December 12, 2013, 01:58:31 PM
 News: Welcome!
 Forum Home Help Search Forum Login Register
Pages: [1]   Go Down
 Send this topic  |  Print
 Author Topic: Tic Tac Toe  (Read 566 times)
GiveMeLife
Newbie

Posts: 8

 « on: July 07, 2012, 01:35:15 PM »

Code:
#include <cstdlib>
#include <iostream>
using namespace std;

int printboard(char array[],char alph,int x=0,int y=0)
{

for(alph='a';array[x]!=false;){
if(array[x]!=alph)
{
alph++;
}
if(array[x]==alph)
{
x++;
}
};

for(y=x,x=0;x!=y;x++){
cout<<""<<array[x]<<" ";
if(x==2||x==5)
{
cout<<"\n         \n";
}
};
cout<<"\n";
return x;
}

//Tic Tac Toe?
int main()
{

char array[]="123456789";
int x=0;
int y=0;
int c=0;
char alph;
char player1='x';
char player2='o';
int quest;
int round=1;
int turn=0;
do{
retry:
c = printboard(array,alph,x,y);
cout<<"\nPlayer "<<round<<". Turn "<<turn<<"/"<<c<<". Enter(1-9): ";
cin>>quest;
quest--;
if(quest<=-1||quest>=9)
{
cout<<"\nInvalid input\n\n";goto retry;
}

turn++;

if(array[quest]=='x'||array[quest]=='o')
{
cout<<"\nInvalid Maneuver. Location occupied by "<<array[quest]<<"\n\n";turn--;
goto retry;
}
cout<<"\n";
if(round==1)
{
array[quest]=player1;
}
if(round==2)
{
array[quest]=player2;
}

round++;

if(round>=3)
{
round=1;
}

}while(quest>-1&&quest<9&&(array[quest]=='x'||array[quest]=='o'));

cout<<"\n\n";
system("PAUSE");
return EXIT_SUCCESS;
}

This is my way of coding tic tac toe. As you can see, it is missing a win condition.
I could just add a if statement for every win condition, but then i would not learn anything.
Is it possible for anyone to give me some advices on how to make a win condition, without having to write a if statement for every possible win?

Edit: I have started using hungarian notation. Unfortunately that was after i made this code, so i appologize if it's useless to read.
 « Last Edit: July 07, 2012, 02:12:31 PM by GiveMeLife » Logged
Michael Hall
Hero Member

Posts: 934

 « Reply #1 on: July 08, 2012, 11:03:10 AM »

Well, there are 8 ways to win. You can go along each of those and check each entry as long as they are equal. If you find one that isn't equal, you know it isn't a win. If you get to the third entry and they are all equal it is a win. Since you didn't have win with the previous move, the winner is the last person to play (or you can check the symbols for x or o).

Mike
 Logged
Pages: [1]   Go Up
 Send this topic  |  Print