Pascal Worked Example: Maze Game: Monster Idea

From SwinBrain

Remember to follow the design process when attempting any design exercise.

Data Required

This extension will require some additional data:

  • A value to represent the monster in the maze file. We could use an M to represent this.
  • A value to represent the monster in the maze array within the program. We could use 253 for this (player is 254 and goal is 255 etc.)
  • A character to draw the monster with (suggest a LightRed #2)
  • When we get to moving the monster we would need to store the Monster's location (MonsterRow and MonsterColumn).

Structure

To add the monster you will need to adjust the following routines:

  • LoadMaze - include the ability to load the monster into the array when M is encountered in the input file
  • DrawMaze - draw the Monster character to the console when it is encountered in the maze array

Once this is working you can add the code to move the monster.

  • Refactoring MovePlayer to remove the general code will help
  • We can extract a Move routine and a CanMoveTo function
  • The following structure chart shows an approach for this
The structure chart needed to include the Monster movement


Representation

The basic logic for the MoveMonster code is:

if playerColumn < monsterColumn then
  dColumn := -1;
else if playerColumn > monsterColumn then
  dColumn := 1;
 
if dColumn <> 0 then
  if Move(monsterRow, monsterColumn, 0, dColumn, true) then
    exit //Exit from this routine
 
if playerRow < monsterRow then
  dRow := -1;
else if playerRow > monsterRow then
  dRow := 1;
 
if dRow <> 0 then
  if Move(monsterRow, monsterColumn, dRow, 0, true) then
    exit //Exit from this routine
 
//we cant move toward the player
if Move(monsterRow, monsterColumn, -dRow, 0, true) then
  exit
Move(monsterRow, monsterColumn, 0, -dColumn, true)

The Monster will not be smart but thats ok.

[edit]Maze Game: Overview | Iteration 1 | Iteration 2 | Iteration 3
Sample Code » C | C++ | .NET | Pascal | Perl | T-Sql | XHTML | Python | others to come