Maze game using 2D array

Can anyone help me get started with this i am not sure how to read from file into array.


The user will be presented with a maze, which is read from a file. The maze has twice as many columns as rows. You should use constants.
For this part, the program will
Prompt the user for a file that contains the maze. Read it into a two-dimensional array
Remember you can use inputStream.get(c) to read the next character from the inputStream. This will read whitespace and non-whitespace characters
Don’t forget to read the newline character at the end of each line
Print the maze to the screen from your array
You should include a ‘*’ in your maze to indicate where the user is located. The initial position is the second row, first column
Prompt the user for a single move
Print the current location as (x,y) and the location after the move is done as (x,y)
For this week, just do the arithmetic, do not worry if the move is bad
Note (0, 0) is the upper left corner. X increases to the right and Y increases down
Use functions as appropriate – you should have more than just main()
Let small_maze.txt contain the following lines (4 rows, 8 columns):
||||||||
||||||
|
||||||||
You could try and do something with this code if you like. It reads the file (maze.txt) and stores either a 1 or a 0 in the appropriate array element, and then prints out the 2-dimensional array.

I'm sure there are many other ways of doing it, but maybe this will help you in the right direction. As for the rest of the problem, I haven't looked at it; see how far you can get on your own, now you have a start.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <fstream>
#include <iostream>

using namespace std;

int main() {
    const int rows=4; const int cols=8;
    int amazed [rows][cols] {0,0};              // define the array

    ifstream mazefile("maze.txt");              // open the file

    int row_counter=0;
    string row;

    while (mazefile >> row) {                   // loop through file
        for (int x=0; x<row.length(); x++)
        {
        // if pipe symbol is present then store the position as a 1, otherwise as 0
        row[x]=='|' ? amazed[row_counter][x]=1 : amazed[row_counter][x]=0;
        }
        row_counter++;
    }

    int myrow, mycolumn;            // this bit is just to print out the array

    for (myrow=0; myrow < rows; myrow++) {
      for (mycolumn=0; mycolumn < cols; mycolumn++)
      {
      cout << amazed[myrow][mycolumn];
      }
    cout << endl;
    }

return 0;
}


Input (maze.txt)
||||||||
||||||
| 
||||||||

Output:
$ ./maze
11111111
11111100
10000000
11111111

Also, you may find this useful:
http://www.cplusplus.com/doc/tutorial/arrays/

Good luck.
Last edited on
Topic archived. No new replies allowed.