My 'Tic Tac Toe' program
May 23, 2012 at 3:22pm UTC
TicTacToe.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
#include <iostream>
using namespace std;
int turn = 1;
class Board
{
public :
char chars [3][3];
Board();
void Clear()
{
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ;
}
void Print()
{
for (int x = 0; x < 3; x++)
{
cout << endl;
for (int y = 0; y < 3; y++)
{
cout << chars[x][y];
}
}
}
bool isUsed(int a, int b)
{
if (a < 0 || a > 3 || b < 0 || b > 3)
{
cout << "\n Invalid coords." ;
return true ;
}
if (chars[a][b] != '#' )
{
return true ;
}
else
{
return false ;
}
}
void Assign(int x, int y)
{
if (isUsed(x, y))
{
return ;
}
else
{
if (turn == 1)
{
chars[x][y] = 'X' ;
turn = 2;
return ;
}
else
{
chars[x][y] = 'O' ;
turn = 1;
}
}
}
bool hasWon()
{
for (int i = 0; i < 3; i++)
{
if ((chars[i][0] + chars[i][1] + chars[i][2]) == 264 || (chars[i][0] + chars[i][1] + chars[i][2]) == 237)
{
return true ;
}
else if ((chars[0][i] + chars[1][i] + chars[2][i]) == 264 || (chars[0][i] + chars[1][i] + chars[2][i]) == 237)
{
return true ;
}
}
if ((chars[0][0] + chars[1][1] + chars[2][2]) == 264 || (chars[0][0] + chars[1][1] + chars[2][2]) == 237)
{
return true ;
}
else if ((chars[0][3] + chars[1][1] + chars[3][0]) == 264 || (chars[0][3] + chars[1][1] + chars[3][0]) == 237)
{
return true ;
}
else
{
return false ;
}
}
};
Board::Board()
{
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
chars[x][y] = '#' ;
}
}
return ;
}
TicTacToe.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include "TicTacToe.h"
int main()
{
int x, y;
Board Board;
while (1)
{
Board.Clear();
Board.Print();
cout << "\n\n Coords of player: " << turn << "'s move\n" ;
cin >> x;
cin >> y;
Board.Assign(x, y);
Board.Print();
if (Board.hasWon())
{
cout << "\n\nPlayer: " << turn << " loses!\n\n\n" ;
break ;
}
}
cout << "Game over!" ;
return 0;
}
I'm looking for feedback on how well I've done, I did it without any help/Google'ing (which, as a noob, I'm proud of).
It is lacking some features (I think I've gotten rid of all bugs, though) for example not detecting when the game is a draw, though this isn't hard I can just change the
while (1)
to a
for (int i = 0; i < 9; i++)
May 23, 2012 at 4:10pm UTC
You have done pretty well for yourself, creating functions and all. The only thing else I would do is create comments, but for a noob you're doing great!
Jun 1, 2012 at 5:58am UTC
Aha thanks :D
Topic archived. No new replies allowed.