I am having trouble figuring out a solution to traversing an array list that's treated as a board with walls and directions given. Basically you are given an array list like so:
xxxxxxx
x-g--xx
x---xxx
x-----x
x--x--x
x---1-x
xxxxxxx
With a given list of moves:
uluudrll
The goal is to use the list of moves and make the according move based on the letter (u for up, d for down, etc.) given while you are traversing this board. You treat the x's as walls and g is your goal. The player is 1. I am using javascript for the code.
if(move === 'd'){
if(maze[row + 1][col] !== 'x'){
maze[row + 1][col] = player;
maze[row][col] = '-';
count++;
} else {
if(move === 'd'){
if(maze[row - 1][col] !== 'x'){
maze[row - 1][col] = player;
maze[row][col] = '-';
count++;
} else if(maze[row][col + 1] !== 'x'){
maze[row][col + 1] = player;
maze[row][col] = '-';
count++;
} else if(maze[row][col - 1] !== 'x'){
maze[row][col - 1] = player;
maze[row][col] = '-';
count++;
}
}
}
}
This is my code for moving down and accommodating for the other movements (for example, if we read in a down movement, d, and it can't move because of a wall, the player will move to the other positions. I don't know whats going on with my code, but when I try to move in any other directions it won't work. Please help I'm pretty confused as to why game isn't working.
Here is a pseudo code example on how to approach your game using Javascript
Take for example this array as your board:
arrayBoard = [["x","x","x","x"],["x","-","-","x"],["x","-","1","x"],["x","x","x","x"]];
If you want to move the player up for example first you need the player position indexOf("1");
in this case is arrayBoard[2][2];
Then you know that up
is the same position but on the second nested array arrayBoard[[1][2];
and so on for the other directions.
To move the player you will have to replace the target postion with "1"
and the previous position with "-"
.
Now you will build your function movement(){}
based on conditions like if index of "1" + 1 !=="x" && === "g" then finish game
So if you write your sequence as an array seq = ["u","u","d","l","u"];
you will have to iterate over it and call your function movement(){}
on each element.
By the way indexOf()
in a multidimensional array will need .map
or a loop to work.