Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I have got this maze game where you have to use the @ symbol to push the o symbols , and it works, but for one little problem : when I try to move the @ symbol then the o symbols moves in wrong strange directions. I think perhaps the coordinates are not put right ( maybe the dy dx are not put right ) but I am not sure can you guys help me out on this one ?

Since you need to see the entire code I shall just show the entire code : ( I know the code is kind of long , but I cannot find any other way to show my problem in the code )




C++
-----------------------------------------------------






#include <iostream>        //for output and input: cout <<, cin >>
 #include <iomanip>         //for output manipulators
 #include <conio.h>         //for getch()
 #include <string>      //for string
 using namespace std;

 //include our own libraries
 #include "ConsoleUtils.h"  //for Clrscr, Gotoxy, etc.


 //---------------------------------------------------------------------------
 //----- define constants
 //---------------------------------------------------------------------------

 //defining the size of the grid
 const int  SIZEY(12);          //vertical dimension
 const int  SIZEX(20);      //horizontal dimension
 //defining symbols used for display of the grid & content
 const char MOUSE('@');     //mouse
 const char TUNNEL(' ');        //tunnel
 const char WALL('#');      //border
 const char APPLE('o');       //apple
 const char STORAGE('+');       //apple storage place
 //defining the command letters to move the mouse on the maze
 const int  UP(72);     //up arrow
 const int  DOWN(80);       //down arrow
 const int  RIGHT(77);      //right arrow
 const int  LEFT(75);       //left arrow
 //defining the other command letters
 const char QUIT('Q');      //to end the game
 //const int SIZE(6);        
 const int MAXAPPLES(6);    //size of apples' array


 struct Item {
int x, y;
const char symbol;
  };

 struct AppleArray
 {
int x,y;
char symbol;
 };


 //---------------------------------------------------------------------------
 //----- run game
 //---------------------------------------------------------------------------

 int main()
 {
int step(0);            // counts movements of a mouse
int storedApps(0);      // counts how many apples have been stored in the storage  
                            //places
//function declarations (prototypes)
void initialiseGame(char g[][SIZEX + 1], char m[][SIZEX + 1], Item& mouse,  
    AppleArray apples[]);
void paintGame(const char g[][SIZEX + 1], string& mess);
bool wantsToQuit(int key);
bool isArrowKey(int k);
int  getKeyPress();
void moveMouse(const char g[][SIZEX + 1], Item& mouse, int key, string& mess, int&    
    step, int& storedApps, AppleArray apples[]);
void updateGrid(char g[][SIZEX + 1], const char m[][SIZEX + 1], Item mouse,  
    AppleArray apples[]);
void endProgram();


//local variable declarations 
char grid[SIZEY + 1][SIZEX + 1];    //grid for display
char maze[SIZEY + 1][SIZEX + 1];    //structure of the maze
Item mouse = { (SIZEX / 2) + 1, (SIZEY / 2) + 1, MOUSE };   //mouse's position  
    //and symbol
//Item apple = { (SIZEX / 2) + 1, (SIZEY / 2) + 1, APPLE }; //[SIZE];
string message("LET'S START...");   //current message to player
AppleArray apples[MAXAPPLES];
apples[0].x = 6;
apples[0].y = 3;
apples[0].symbol = APPLE;
apples[1].x = 6;
apples[1].y = 5;
apples[1].symbol = APPLE;
    apples[2].x = 6;
apples[2].y = 8;
apples[2].symbol = APPLE;
    apples[3].x = 3;
apples[3].y = 8;
apples[3].symbol = APPLE;
    apples[4].x = 8;
apples[4].y = 4;
apples[4].symbol = APPLE;
    apples[5].x = 8;
apples[5].y = 5;
apples[5].symbol = APPLE;


//action...
Clrscr();
initialiseGame(grid, maze, mouse, apples); //initialise grid (incl. walls & mouse)
paintGame(grid, message);   //display game info, modified grid & messages
int key(getKeyPress());     //read in  selected key: arrow or letter command
while (!wantsToQuit(key))       //while user does not want to quit
{
    if (isArrowKey(key))
    {
        int dx(0), dy(0);
 moveMouse(grid, mouse, key, message, step, storedApps, apples); //move mouse in  
                                                                    //that direction
        updateGrid(grid, maze, mouse, apples);  //update grid information
    }
    else
        message = "INVALID KEY!";   //set 'Invalid key' message
    paintGame(grid, message); //display game info, modified grid & messages
    key = getKeyPress();    //display menu & read in next option
}
endProgram();       //display final message
return 0;
    }


 //---------------------------------------------------------------------------
 //----- initialise game state
 //---------------------------------------------------------------------------

 void initialiseGame(char grid[][SIZEX + 1], char maze[][SIZEX + 1], Item& mouse,   
 AppleArray apples[])
 { //initialise grid & place mouse in middle
void setInitialMazeStructure(char g[][SIZEX + 1]);
void setInitialMouseCoordinates(Item& mouse);
void setInitialAppleCoordinates(AppleArray apples[]);
void updateGrid(char g[][SIZEX + 1], const char m[][SIZEX + 1], Item mouse,   
    AppleArray apples[]);

setInitialMazeStructure(maze);  //initialise maze
setInitialMouseCoordinates(mouse);  //initialise mouse's position
updateGrid(grid, maze, mouse, apples);  //prepare grid
   }

   void setInitialMazeStructure(char maze[][SIZEX + 1])
   { //set the position of the walls in the maze
//initialise maze configuration
char initialMaze[SIZEY + 1][SIZEX + 1]  //local array to store the maze structure
    = { { 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',  
    'X', 'X', 'X', 'X', 'X' },
    { 'X', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#',   
    '#', '#', '#', '#' },
    { 'X', '#', '#', '#', '#', '#', ' ', ' ', ' ', '#', '#', '#', '#', '#', '#',  
    '#', '#', '#', '#' },
    { 'X', '#', '#', '#', '#', '#', ' ', ' ', ' ', '#', '#', '#', '#', '#', '#',  
    '#', '#', '#', '#' },
    { 'X', '#', '#', '#', '#', '#', ' ', ' ', ' ', '#', '#', '#', '#', '#', '#',  
    '#', '#', '#', '#' },
    { 'X', '#', '#', '#', ' ', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#', '#', 
    '#', '#', '#', '#' },
    { 'X', '#', '#', '#', ' ', '#', ' ', '#', '#', ' ', '#', '#', '#', '#', '#', 
    '#', '#', '#', '#' },
    { 'X', '#', ' ', ' ', ' ', '#', ' ', '#', '#', ' ', '#', '#', '#', '#', '#', 
    ' ', ' ', '+', '+' },
    { 'X', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 
    ' ', ' ', '+', '+' },
    { 'X', '#', '#', '#', '#', '#', ' ', '#', '#', '#', ' ', '#', ' ', '#', '#', 
    ' ', ' ', '+', '+' },
    { 'X', '#', '#', '#', '#', '#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#', 
    '#', '#', '#', '#' },
    { 'X', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', 
    '#', '#', '#', '#' }, };
// with '#' for wall, ' ' for tunnel and 'X' for unused part of array
//copy into maze structure
for (int row(1); row <= SIZEY; ++row)   //for each row (vertically)
for (int col(1); col <= SIZEX; ++col)   //for each column (horizontally)
    maze[row][col] = initialMaze[row][col];
   }

   void setInitialMouseCoordinates(Item& mouse)
     { //calculate mouse's coordinates at beginning of game
    mouse.y = 3;    //y-coordinate: vertically
    mouse.x = 6;    //x-coordinate: horizontally
     }

     //---------------------------------------------------------------------------
     //----- update grid state
     //---------------------------------------------------------------------------

    void updateGrid(char grid[][SIZEX + 1], const char maze[][SIZEX + 1], Item mouse,  
    AppleArray apples[])
      { //update grid configuration after each move
       void setMaze(char g[][SIZEX + 1], const char m[][SIZEX + 1]);
       void placeMouse(char g[][SIZEX + 1], Item mouse);
       void placeApples(char g[][SIZEX + 1], AppleArray apples[]);

       setMaze(grid, maze); //reset the empty maze configuration into grid
       placeMouse(grid, mouse); //set mouse in grid                                               
       placeApples(grid, apples);  //set all apples in grid 
      }

    void setMaze(char grid[][SIZEX + 1], const char maze[][SIZEX + 1])
       { //reset the empty/fixed maze configuration into grid

       for (int row(1); row <= SIZEY; ++row)    //for each row (vertically)

       for (int col(1); col <= SIZEX; ++col)    //for each column (horizontally)
       grid[row][col] = maze[row][col];
    }

   void placeMouse(char g[][SIZEX + 1], Item m)
   {               //place mouse at its new position in grid
 g[m.y][m.x] = m.symbol;
   }

   void placeApples(char g[][SIZEX + 1], AppleArray apples[])
      {        //place apples at their new positions in grid

           for (int i(0); i < MAXAPPLES; ++i) {
       g[apples[i].y][apples[i].x] = apples[i].symbol;
         }
       }

   //---------------------------------------------------------------------------   
   //----- move the mouse
   //---------------------------------------------------------------------------
   void moveMouse(const char g[][SIZEX + 1], Item& m, int key, string& mess, int& step,   
   int& storedApps, AppleArray apples[])

   {    //move mouse in required direction

  void setKeyDirection(int k, int& dx, int& dy);

  bool moveApple(const char g[][SIZEX + 1], int, int, string&, int&, int&, 
      AppleArray a[], Item& m);
//calculate direction of movement required by key - if any

int dx(0), dy(0);

setKeyDirection(key, dx, dy);   //find direction indicated by key
//check new target position in grid & update mouse coordinates if move is possible

switch (g[m.y + dy][m.x + dx])
{           //...depending on what's on the target position in grid...
case TUNNEL:        //can move
    m.y += dy;      //go in that Y direction
    m.x += dx;      //go in that X direction
    ++step;         //add one to the movement counter
    break;
case WALL:          //hit a wall & stay there
    cout << '\a';   //beep the alarm
    mess = "CANNOT GO THERE!";
    break;
case APPLE:
/*  int i(0);
    while ((apples[i].y != (m.y + dy)) && (apples[i].x != (m.x + dx)))
    {*/
        if (moveApple(g, dx, dy, mess, step, storedApps, apples, m))
        {
         m.y += dy;     //go in that Y direction
         m.x += dx;     //go in that X direction
         ++step;         //add one to the movement counter
        }
        else
        {
                cout << '\a';   //beep the alarm
                mess = "CANNOT GO THERE!";
        }
        //++i;      
    //}
     }
       }

   bool moveApple(const char g[][SIZEX + 1], int dx, int dy, string& mess, int& step,  
     int& storedApps, AppleArray a[] , Item& m)
         { //move apple in required direction

          bool hasMoved = false;


          int i(0);
      while ((a[i].y != (m.y + dy)) && (a[i].x != (m.x + dx)))
    {

  switch (g[a[i].y + dy][a[i].x + dx])
    {             //...depending on what's on the target position in grid...

        case TUNNEL:            //can move
    a[i].y += dy;       //go in that Y direction
    a[i].x += dx;       //go in that X direction
        hasMoved = true;
    break;

        case APPLE:
        case WALL:              //hit a wall OR another apple & stay there
    cout << '\a';               //beep the alarm
    mess = "CANNOT GO THERE!";
    break;

    case STORAGE:
    a[i].y += dy;
    a[i].x += dx;
        hasMoved = true;
    ++storedApps;
    break;
  }
            ++i;        
    }
return hasMoved;



   }
      //---------------------------------------------------------------------------
      //----- process key
      //---------------------------------------------------------------------------
      void setKeyDirection(int key, int& dx, int& dy)
        { //
switch (key)        //...depending on the selected key...
{
case LEFT:      //when LEFT arrow pressed...
    dx = -1;    //decrease the X coordinate
    dy = 0;
    break;
case RIGHT:     //when RIGHT arrow pressed...
    dx = +1;    //increase the X coordinate
    dy = 0;
    break;
case UP:        //when UP arrow pressed...
    dx = 0;
    dy = -1;    //decrease the Y coordinate
    break;
case DOWN:      //when DOWN arrow pressed...
    dx = 0;
    dy = +1;    //increase the Y coordinate
    break;
     }
   }

   int getKeyPress()
  { //get key or command selected by user

int keyPressed;
keyPressed = getch();   //read in the selected arrow key or command letter
while (keyPressed == 224)   //ignore symbol following cursor key
    keyPressed = getch();
return(toupper(keyPressed));    //return it in uppercase 
   }

   bool isArrowKey(int key)
  { //check if the key pressed is an arrow key (also accept 'K', 'M', 'H' and 'P')
return ((key == LEFT) || (key == RIGHT) || (key == UP) || (key == DOWN));
   }

   bool wantsToQuit(int key)
        {   //check if the user wants to quit (when key is 'Q' or 'q')

            return (toupper(key) == QUIT);
         }

   //---------------------------------------------------------------------------
   //----- display info on screen
   //---------------------------------------------------------------------------
   void paintGame(const char gd[][SIZEX + 1], string& mess)
     { //display game title, messages, maze, mouse & apples on screen
    void paintGrid(const char g[][SIZEX + 1]);

//clear screen
Clrscr();

//display game title
SelectTextColour(clYellow);
Gotoxy(0, 0);
cout << "___MOUSE AND APPLES GAME___\n" << endl;
SelectBackColour(clWhite);
SelectTextColour(clRed);
Gotoxy(40, 0);
cout << "P V: March 14";  //PUT YOUR GROUP NUMBER AND NAMES HERE

// display grid contents
paintGrid(gd);

//display menu options available
SelectBackColour(clRed);
SelectTextColour(clYellow);
Gotoxy(40, 3);
cout << "TO MOVE USE KEYBOARD ARROWS ";
Gotoxy(40, 4);
cout << "TO QUIT ENTER 'Q'           ";

//print auxiliary messages if any
SelectBackColour(clBlack);
SelectTextColour(clWhite);
Gotoxy(40, 8);
cout << mess;   //display current message
mess = "";      //reset message to blank
   }

   void paintGrid(const char g[][SIZEX + 1])
   { //display grid content on screen
 SelectBackColour(clBlack);
 SelectTextColour(clWhite);
 Gotoxy(0, 2);
 for (int row(1); row <= SIZEY; ++row)  //for each row (vertically)
   {
    for (int col(1); col <= SIZEX; ++col)   //for each column (horizontally)
        cout << g[row][col];    //output cell content
    cout << endl;
   }
    }

    void endProgram()
   {
SelectBackColour(clRed);
SelectTextColour(clYellow);
Gotoxy(40, 8);
//hold output screen until a keyboard key is hit
cout << "\n";
system("pause");
   }</string></conio.h></iomanip></iostream>
Posted
Updated 7-Apr-14 22:42pm
v2
Comments
[no name] 7-Apr-14 19:19pm    
I see one problem.

<pre lang="c++">char initialMaze[SIZEY + 1][SIZEX + 1] //local array to store the maze structure
= { { 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
'X', 'X', 'X', 'X', 'X' },</pre>

SIZEX is defined as 20. Your array is 21 columns wide but you only have 19 X's.
[no name] 7-Apr-14 19:41pm    
Well.... there are a couple of problems here.
1. This is a repost
2. This code is unformatted, meaning that very few people will bother reading it.
3. This is a repost.
4. You did not give us a description of the problem. "strange directions" does not mean anything.
5. This is a repost
6. No one needs to see your entire codebase. You have already been told this.
Sergey Alexandrovich Kryukov 7-Apr-14 20:28pm    
I can see some code dump, unformatted. And what's the issue?
—SA
pasztorpisti 8-Apr-14 17:12pm    
OK, someone please debug/fix the code and let's put a period at the end of this! :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900