Hello everyone. I'm having troubles implementing a certain function so I hope you can help me out. Will try to be simple and quick.
Ok, so not that long ago I posted a couple of doubts regarding a "Slidding Puzzle" code. I am now trying to make the code shorter by not having to test every possibility, considering I'm willing to implement a 3x3, 4x4 and 5x5 board.
This is what I got so far:
Code:
#include <iostream>
#include <algorithm>
//Checks end game conditions (Working)
bool Verif(int array[], int ArraySize)
{
int counter = 0;
for (int i = 0; i < (ArraySize - 1); i++)
{
if (array[i] == (i + 1) && array[ArraySize - 1] == 0)
{
counter = counter + 1;
}
else
{
counter = counter;
}
}
if (counter == (ArraySize - 1))
{
return true;
std::cout<<"You win!";
}
}
//Validates a move (Not working)
bool ValidatesMove(int Move, int array[], int ArraySize)
{
int n;
switch (ArraySize)
{
case 9:
if (Move = array[n])
{
if (array[n - 1] == 0)
{
std::swap(array[n], array[n - 1]);
return true;
}
else if (array[n - 3] == 0)
{
std::swap(array[n], array[n - 3]);
return true;
}
else if (array[n + 1] == 0)
{
std::swap(array[n], array[n + 1]);
return true;
}
else if (array[n + 3] == 0)
{
std::swap(array[n], array[n + 3]);
return true;
}
else
{
return false;
}
}
break;
default:
break;
}
}
int main()
{
while (true)
{
int GameBoard[9];
GameBoard[0] = 1; GameBoard[1] = 2; GameBoard[2] = 3; GameBoard[3] = 4; GameBoard[4] = 5; GameBoard[5] = 0; GameBoard[6] = 7; GameBoard[7] = 8; GameBoard[8] = 6;
std::cout<<std::endl <<std::endl <<std::endl;
std::cout<<" " <<GameBoard[0] <<" | " <<GameBoard[1] <<" | " <<GameBoard[2] <<std::endl;
std::cout<<"-----+-----+-----" <<std::endl;
std::cout<<" " <<GameBoard[3] <<" | " <<GameBoard[4] <<" | " <<GameBoard[5] <<std::endl;
std::cout<<"-----+-----+-----" <<std::endl;
std::cout<<" " <<GameBoard[6] <<" | " <<GameBoard[7] <<" | " <<GameBoard[8] <<std::endl <<std::endl;
int Play;
std::cin >> Play;
//If the piece selected is next to "0" then it should swap with it. If not, then the move is invalid.
ValidatesMove(Play, GameBoard, 9);
//Checks for end game conditions
if (Verif(GameBoard, 9) == true)
{
break;
}
}
std::cin.ignore();
std::cin.get();
}
A move is supposed to be valid when the piece selected is next to a zero:
1 2 3
4 5 0
7 8 6
6
1 2 3
4 5 6
7 8 0
You win!
^That's what it is supposed to work but the pieces won't swap.