Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- //initialize a globally used grid with *'s
- char grid[3][3] = {{'*','*','*'},{'*','*','*'},{'*','*','*'}};
- //acts as a bool, only 'x' or 'o' is used
- char turn = 'o';
- void displayBoard()
- {
- //display ALL of the board! _o/
- cout << "\n 1 2 3"
- <<"\n1 " << grid[0][0] << " | " << grid[0][1] << " | " << grid[0][2] << endl
- << " ---------" << endl
- << "2 " << grid[1][0] << " | " << grid[1][1] << " | " << grid[1][2] << endl
- << " ---------" << endl
- << "3 " << grid[2][0] << " | " << grid[2][1] << " | " << grid[2][2] << endl;
- }
- bool checkWin(){
- if( grid[0][0] == turn && grid[0][1] == turn && grid[0][2] == turn){
- return true;//row 1
- } else if( grid[1][0] == turn && grid[1][1] == turn && grid[1][2] == turn){
- return true;//row 2
- } else if( grid[2][0] == turn && grid[2][1] == turn && grid[2][2] == turn){
- return true;//row 3
- } else if( grid[0][0] == turn && grid[1][0] == turn && grid[2][0] == turn){
- return true;//col 1
- } else if( grid[0][1] == turn && grid[1][1] == turn && grid[2][1] == turn){
- return true;//col 2
- } else if( grid[2][0] == turn && grid[2][1] == turn && grid[2][2] == turn){
- return true;//col 3
- } else if( grid[0][0] == turn && grid[1][1] == turn && grid[2][2] == turn){
- return true;//diagonal 1
- } else if( grid[0][2] == turn && grid[1][1] == turn && grid[2][0] == turn){
- return true;//diagonal 1
- }
- return false;
- }
- //check if the input is between upper and lower
- bool inBounds(int i, int lower, int upper)
- {
- if(i>=lower&&i<=upper) return true;
- else return false;
- }
- void move()
- {
- int x,y;
- cout << "\nEnter your move Player "<<turn<<": ";
- cout << "\nEnter Row: ";
- cin >> x;
- cout << "\nEnter Col: ";
- cin >> y;
- //check if it's a * and if the x and y are between 1 and 3
- if(grid[x-1][y-1] == '*' && inBounds(x, 1, 3) && inBounds(y, 1, 3)){
- grid[x-1][y-1] = turn;
- }
- else
- move();//recursion if invalid move
- displayBoard();//refresh the board
- }
- int main()
- {
- displayBoard();
- //has someone won yet? if not keep playing
- while(!checkWin())
- {
- if(turn == 'x') turn = 'o';
- else turn = 'x';
- move();
- //swap players
- }
- //all done! call the winner!
- cout << turn << " Wins!!!!";
- cin >> turn;//dummy input
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement