I recently wrote a program to generate a tic tac toe game. The program should ask the user to select a number from the 'selection board', and this number will correspond to a spot on the game board. The user is playing against him/herself. I've encountered a pretty glaring bug that I can't seem to fix, though. Every time I enter a designated number it outputs "That spot on the board is taken," even when it is not. Can anyone help me with this? I suspect it's just something small that I missed.
//Tic Tac Toe game
#include <iostream>
using namespace std;
//note: main program placed below function definitions for convenience
int game[9]={1,2,3,4,5,6,7,8,9}; //declares an array for the game board
/////////////////////////////////
//Part 1: Function Definitions//
///////////////////////////////
void TicTacToe() //makes a function for the selection board
{
cout<<"This is the selection board:"<<endl;
cout<<"-----"<<endl;
cout<<"1|2|3"<<endl;
cout<<"-----"<<endl;
cout<<"4|5|6"<<endl;
cout<<"-----"<<endl;
cout<<"7|8|9"<<endl;
cout<<"-----"<<endl;
}
int move(int play,int turn) //puts player's turn in memory
{
game[turn-1]=play;
if (turn==1)
return play+1;
else if (turn==2)
return play-1;
}
int state(int play,int first)
{
if((game[1]&&game[2]&&game[3]==play)||(game[1]&&game[4]&&game[7]==play)||(game[1]&&game[5]&&game[9]==play))
return play;
else if ((game[2]&&game[5]&&game[8]==play)||(game[3]&&game[5]&&game[7]==play)||(game[3]&&game[6]&&game[9]==play))
return play;
else if ((game[4]&&game[5]&&game[6]==play)||(game[7]&&game[8]&&game[9]== play))
return play;
}
void outputBoard() //outputs current state of board
{
for(int x=1;x<=9;x++) //makes a loop for each turn -- x and o
{
if (game[x-1]==1)
cout<<"x";
else if (game[x-1]==2)
cout<<"o";
else
cout<<" ";
cout <<"|";
if (x==3||x==6)
cout<<endl<<"-----"<<endl;
}
cout<<endl;
}
/////////////////////////
//Part 2: Main Program//
///////////////////////
int main ()
{
int won,turn1,turn2,first,move;
TicTacToe();
cout<<endl;
for(int x=1;x<=9;x++) //searches for moves
{
if(first==1)
cout<<turn1<<endl;
else if(first==2)
cout<<turn2<<endl;
}
do //assures that each selection is possible
{
cout<<"Please select a number from the selection board.";
cin>>move;
if(game[move-1]!=0)
cout << "That spot on the board is taken."<<endl;
else if(game[move>9])
cout<<"You cannot select a number over 9."<<endl;
}
while (move<1||move>9||game[move-1]!=0);
first=state(first,move); //calls function with current state of the board
cout<<endl;
outputBoard();
won=state(first,move); //outputs if program finds a winner
if(won==1)
{
cout<<turn2<<"O wins."<<endl;
break;
}
else if(won==2)
{
cout<<turn1<<"X wins."<<endl;
break;
}
}
system ("PAUSE");
return 0;
}