Skip to content

Instantly share code, notes, and snippets.

@andrewfhart
Created November 16, 2015 05:10
Show Gist options
  • Save andrewfhart/cb3ce23ed91897f50e37 to your computer and use it in GitHub Desktop.
Save andrewfhart/cb3ce23ed91897f50e37 to your computer and use it in GitHub Desktop.
Tic-tac-toe Tutorial (Step 3)
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
/**
* Draw a 3x3 tic-tac-toe board with row and column labels
* The cell data in board will be interpreted as follows:
* 1 = owned by 'x'
* 2 = owned by 'o'
* all other values = empty
*
* @param int[3][3] board The current state of each board cell
* @return void
*/
void drawBoard(int board[][3]) {
cout << " " << " A B C " << endl;
cout << " " << "+---+---+---+" << endl;
for (int row = 0; row < 3; row++) {
cout << row << " ";
for (int col = 0; col < 3; col++) {
switch (board[row][col]) {
case 1: cout << "| " << "x" << " "; break;
case 2: cout << "| " << "o" << " "; break;
default:cout << "| " << " " << " "; break;
}
}
cout << "|" << endl;
cout << " " << " " << "+---+---+---+" << endl;
}
}
int main (int argc, char* argv[])
{
// State variables
//
// Board:
// 0 1 2
// +---+---+---+
// 0 | | | x | x = board[0][2]
// +---+---+---+
// 1 | | | |
// +---+---+---+
// 2 | | | |
// +---+---+---+
//
// Each board square will be in one of three possible
// states: 0=empty, 1=owned by 'x', 2=owned by 'o'.
int board[3][3] = {};
// Flag to determine whether or not the game is finished
// false: game should end: someone has won or there are no more valid moves
// true: game may continue
bool gameIsValid = true;
// Flag to determine whose turn it is
// false: it is the computer's turn to make a move
// true: it is the player's turn to make a move
bool playerTurn = true;
/* Game Flow */
// 1. determine who goes first
playerTurn = rand() % 2; // coin flip
// 2. Enter the main game "loop"
while (gameIsValid) {
// a. draw the board
drawBoard(board);
// b. current player makes a move
// c. check if the current player has just won
// d. swap current player
}
// 3. print final game result message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment