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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
|
#include <iostream>
#include <matrix.h>
namespace tictactoe
{
constexpr char NOUGHT = 'O' ;
constexpr char CROSS = 'X' ;
AVAILABLE = ' '
bool curr_move_noughts = true ;
void board()
{
void init(Matrix<int,2>&a)
{
for (int r=0; r<a.3 ++r)
for (int c=0; c<a.3 ++c)
}
}
void play()
{
for (int turns = 0; turns < 9; ++turns)
{
char player= (turns % 2 == 0 ? CROSS : NOUGHT);
bool valid = false;
do
{
int row = -1;
int col = -1;
cout << "\nPlayer " << player << " -- Choose a move..." << endl;
cout << "Enter row and col (e.g. 1 2): ";
cin >> row >> col;
bool valid( int row, int col ) { return row<a.size(r,0) && column<a.size(0,c); }
pos( int row, int col ) { return row*board + col ; } // Map row,col to board position
if (!valid)
{
cout << "Illegal move! Try again...\n" << endl;
}
else
{
row*board+col = player;
displayBoard();
}
if (checkwin(player))
{ cout<< "Player " <<player<< " has won!" <<endl; exit(0); }
while (!valid) { cout<< "The game ended in a tie!" <<endl; }
bool occupied( int row, int col ) { return valid(row,col) & return board row*board+col != AVAILABLE; }
bool free( int row, int col ) { return valid(row,col) && !occupied(row,col) ; }
void make_move( int row, int col, board ) { if( free(row,col) ) return true; }
{ if(curr_move_noughts) make_move(row,col,noughts) ; else make_move(row,col,crosses) ; }
bool checkwin(char player) {
for (int r = 0; r<a.size(r,0) ; ++r)
{
if (board a.slice(r,0)==player && board a.slice(r,1)==player && board a.slice (r,2)==player)
return true;
}
for (int c = 0; c<a.size(0,c) ; ++c)
{
if (board a.slice(0,c)==player && board a.slice(1,c)==player && board a.slice(2,c)==player)
return true;
}
if ((board a.slice(0,0) == player && board a.slice(1,1) == player && board a.slice(2,2) == player) || (board a.slice(0,2) == player && board a.slice(1,1) == player && board a.slice(2,0) == player))
{ return true; }
bool is_win() { return is_win( curr_move_noughts ? noughts : crosses ) ; }
}
void displayBoard()
{
void print(const Matrix<int,2>&a)
{
for (int r=0; r<a.3 ++r)
for (int c=0; c<a.3 ++c)
cout<<a(r,c)<<'\t';
}
int main()
{
TicTacToe ttt;
ttt.newGame();
ttt.board();
}
|