I'm new to C++ and programming in general, and this is my first 'project'. I'm sorry if this is not an applicable question, tell me and I will delete it right away.
I want to build a 8 puzzle game, but instead of sliding tiles, the user swaps the number adjacent to '0', where '0' is the blank tile.
This is the code I've so far:
#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;
int grid[]= {1,2,3,4,5,6,7,8,0};
void shuffle()
{
random_shuffle(&grid[0],&grid[9]);
}
void print_puzzle()
{
shuffle();
int a=grid[0];
int b=grid[1];
int c=grid[2];
int d=grid[3];
int e=grid[4];
int f=grid[5];
int g=grid[6];
int h=grid[7];
int i=grid[8];
cout<<endl;
cout<<" "<<a<<" "<<b<<" "<<c<<endl;
cout<<" "<<d<<" "<<e<<" "<<f<<endl;
cout<<" "<<g<<" "<<h<<" "<<i<<endl;
}
bool check()
{
if (grid[0]==1&&grid[1]==2&&grid[2]==3&&grid[3]==4&&grid[4]==5&&grid[6]==7&&grid[7]==8&&grid[8]==0)
{
return true;
}
else{return false;}
}
void swap_puzzle()
{
print_puzzle();
int temp=0;
cout<<"Enter the number adjacent to '0' that you want to be swapped with '0'."<<endl;
cin>> temp;
while(check==false)
{
for(int i=0; i<9; i++)
{
if(grid[i]==temp)
{
int pos_num=i;
for(int j=0; j<9; j++)
{
if(grid[j]==0)
{
int pos_0=j;
swap(grid[pos_num], grid[pos_0]);
break;
}
}
}
}
print_puzzle();
}
}
int main()
{
srand ( time(NULL) );
cout<<"The Rules:"<<endl;
cout<<"There will be a shuffled 3x3 grid with numbers from 1-8, with one blank space denoted by '0'. You can swap '0' only with adjacent numbers. The goal of this game is to rearrange the numbers in the grid in ascending order."<<endl;
cout<<endl;
cout<<"The Shuffled Grid: "<<endl;
swap_puzzle();
return 0;
}
After swapping the number that the enter user with '0', the grid just shuffles instead of swapping them as I intended. I tried fixing this problem by breaking the code into smaller functions, but that didn't help.
Any advice would be appreciated.
Aucun commentaire:
Enregistrer un commentaire