A typical approach to storing "old school" game boards is to use a char
or int
multidimensional array. Using Matt's excellent little graphic you can see there are 21 by 21 squares in the board:
int board[21][21] = {{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1},
/* ... and so on, for all 21 lines .. */ }};
It doesn't really matter which numbers you pick for walls and pathways. The "pathway" positions initially contain a code for "contains a dot". As paccy consumes the dots, store a new value into the board at the position to indicate that the dot has been consumed but it is still a pathway square. Matt recommended -1
for walls, 0
for no dot, and 1
for a dot -- that's a pretty plan, as it lets your "wall collision" routines simply look for
if (board[pac.x][pac.y] > 0) {
/* still in bounds */
} else {
/* collided against a wall */
}
The downside is the -1
is more awkward looking in your array initializer.
If this were done in C, it'd be easy enough to "improve" this using char board[21][21]
instead of int board[21][21]
and store the game board as a C string:
char board[21][21] = " XXXXXXXXXXXXXXXXXXX "
" X X X "
" X XX XXX X XXX XX X "
" X X "
" X XX X XXXXX X XX X "
" X X X X X "
" XXXX XXX X XXX XXXX "
" X X X X "
"XXXXX X XXXXX X XXXXX"
" X X "
"XXXXX X XXXXX X XXXXX"
" X X X X "
" XXXX X XXXXX X XXXX "
" X X X "
" X XX XXX X XXX XX X "
" X X X X "
" XX X X XXXXX X X XX "
" X X X X X "
" X XXXXXX X XXXXXX X "
" X X "
" XXXXXXXXXXXXXXXXXXX";
This is far easier to read in the source code, takes less memory, and your wall-collision routines can look like this:
if (board[pac.x][pac.y] == 'X') {
/* collided with a wall */
} else {
/* still in bounds */
}
(Though the trailing NUL
that the compiler will insert at the end of the string means that lower-right-hand square can never be used for pathway or wall -- a little more effort can work around that, but it isn't as beautiful.)
I don't remember enough Java to make this work in Java -- but I'm sure you can figure out something if this looks compelling enough.