As part of a homework assignment, I'm trying to code an 8-puzzle into Arduino's Serial Monitor. This involves a 3x3 matrix, assigned unique values from 0 to 8, with the 0 value being the 'blank tile' (represented in the printed output as 'b' as part of the assignment). This blank tile can be moved around the puzzle board via an adjacent tile moving into the space it just was. My code so far looks like this:
int a=0;
int b=0;
int g=0;
int w=0;
int c=0;
int d=0;
int e=0;
int BposX=0;
int BposY=0;
int AposX=0;
int AposY=0;
int AposTemp=0;
int dir=0;
int action=0;
int puzzle[3][3];
void SetState(){
BposX=0;
BposY=0;
for (a=3;a>0;a--){
for (b=3;b>0;b--){
puzzle[a][b]=c;
c++;
}
}
}
void printState(){
for (g=3;g>0;g--){
for (w=3;w>0;w--){
if (puzzle[g][w]!=0){
Serial.print(puzzle[g][w]);
}
else{
Serial.print("b");
}
}
Serial.println();
}
}
void Move(int dir){
if (dir=='left'){
if (BposX>0){
AposX=BposX-1;
AposTemp=puzzle[AposX][BposY];
puzzle[AposX][BposY]=0;
puzzle[BposX][BposY]=AposTemp;
}
else{
Serial.println("Invalid move.");
}
}
if (dir='right'){
if(BposX<3){
AposX=BposX+1;
AposTemp=puzzle[AposX][BposY];
puzzle[AposX][BposY]=0;
puzzle[BposX][BposY]=AposTemp;
}
else{
Serial.println("Invalid move.");
}
}
if (dir='up'){
if(BposY>0){
AposY=BposY-1;
AposTemp=puzzle[BposX][AposY];
puzzle[BposX][AposY]=0;
puzzle[BposX][BposY]=AposTemp;
}
else{
Serial.println("Invalid move.");
}
}
if (dir='down'){
if(BposY<3){
AposY=BposY+1;
AposTemp=puzzle[BposX][AposY];
puzzle[BposX][AposY]=0;
puzzle[BposX][BposY]=AposTemp;
}
else{
Serial.println("Invalid move.");
}
}
printState();
}
void setup(){
randomSeed(analogRead(A0));
SetState();
Serial.begin(9600);
printState();
}
void loop(){
if (Serial.available() > 0) {
action = Serial.read();
}
if (action=='1'){
Move('left');
action=0;
}
if (action=='2'){
Move('right');
action=0;
}
}
When I upload this and bring up the Serial Monitor, the initial state looks just fine:
b12
345
678
However, when I attempt to enter '1' or '2' to test these out, I get this response:
(Entering '1')
Invalid move.
Invalid move.
b12
4945
678
(Entering '2')
Invalid move.
b12
5045
678
(Entering '1' twice)
Invalid move.
Invalid move.
b12
4945
678
Invalid move.
Invalid move.
b12
1259345
678
It seems like the code is running the 'Move' function multiple times, but I've no idea why. I know I asked the function to return 'Invalid move.' if the move made was out-of-bounds (e.g. moving the blank tile a space to the right when it was already on the right side of the board), but it seems to think the tile's out-of-bounds even when asking for a move to the right when the tile is on the leftmost side of the board.
Can anyone see what might be going wrong?