How to Create a Tic-Tac-Toe Game in Python
Submitted by Yorkiebar on Wednesday, March 12, 2014 - 08:57.
Introduction:
This tutorial is going to cover how to create a simple, text based tic-tac-toe (three in a row) game in Python.
The Variables:
First we need to create some variable that will be used throughout the game. The constants are used to hold the board size, and the character value of each possible state of one field within the board...
Next we need some variables which may change throughout the game...
The Main Game Loop:
Next we will start with the main game loop. First we ask if the human wants to go first, if they do, we set their value to O and set the current player to human, otherwise we perform the opposite and set the player value to X.
Once we have done that, we create a new variable list named board which will be our game board to hold all of the field values (character moves), and set up the board.
Then we show the instructinos to the player, checks it the board is setup correctly, then begin the main loop which runs while there are spare spaces on the board.
Within the main game loop, we allow the user (or computer) to take their turn, draw the new board, check for any wins, and if they have, end the game/loop...
Show Instructions:
This function is simple, we display the text instructions to the user...
Check Win:
The Check Win function gets all the possible combination of moves to win the game, and checks if either the player or computer has all their pieces in all the places... if so, they've won!...
DrawBoard:
Up next we have the draw board function, which simply runs through each place on the board and outputs the equvilient character...
Switch and Take Turn:
The switch turn function simply swaps the current turn variable from player to computer, or vice versa.
While the take turn function allows the human to select and enter a place to move a piece to, or the computer gets a list of legal moves/empty board places and moves to the first one within the list...
Will Win:
This function checks if the computer is able to win by placing their piece in any certain places on the board...
Win:
The win function simply returns a final result string for the winner...
In Game and Legal Move:
In Game function checks whether there are any more spaces left on the board.
Legal moves function returns where there are spaces left on the board for the computer to move to...
Setup Board and Yes No:
The SetupBoard function simply sets each of the fields on the empty board list to our EMPTY variable to specify a blank space, ready to hold a human/computer piece.
The yes no function simply asks the human for a yes/no answer to a question and returns the input...
Finally...
Finally we start the main, game loop and then once it is over (the game has ended) we output the message "Thank you for playing!"...
- X = "X";
- O = "O";
- EMPTY = " ";
- SIZE = 9;
- turn = "";
- human = "";
- computer = "";
- def main():
- if (yes_no("Would you like to go first?") == "y"):
- human = X;
- computer = O;
- turn = human;
- else:
- human = O;
- computer = X;
- turn = computer;
- board = [];
- setup_board(board);
- showInstructions();
- isInGame = inGame(board);
- while (isInGame):
- takeTurn(turn, board, human, computer);
- drawBoard(board, human, computer);
- if (checkWin(board, human, computer) == "human"):
- print("\n"+win("human"));
- break;
- elif (checkWin(board, human, computer) == "computer"):
- print("\n"+win("computer"));
- break;
- turn = switchTurn(turn, human, computer);
- temp = inGame(board);
- if (temp == "yes"):
- isInGame = "yes";
- else:
- break;
- return "";
- def showInstructions():
- sep = " | ";
- print("\n 0 " + sep + " 1 " + sep + " 2 ");
- print(" 3 " + sep + " 4 " + sep + " 5 ");
- print(" 6 " + sep + " 7 " + sep + " 8 \n");
- def checkWin(b, h, c):
- combinations = ([0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]);
- for comb in combinations:
- if (b[comb[0]] == h and b[comb[1]] == h and b[comb[2]] == h):
- return "human";
- if (b[comb[0]] == c and b[comb[1]] == c and b[comb[2]] == c):
- return "computer";
- return "no";
- def drawBoard(b, h, c):
- sep = " | ";
- print("\n"+b[0]+sep+ b[1]+sep+b[2]);
- print(b[3]+sep+b[4]+sep+b[5]);
- print(b[6]+sep+b[7]+sep+b[8]+"\n");
- print("---KEY---\nPlayer - " + h + "\nComputer - " + c);
- def switchTurn(turn, h, c):
- if (turn == h):
- return c;
- else:
- return h;
- def takeTurn(t, b, h, c):
- if (t == h):
- legal = legalMoves(b);
- index = int(input("\nWhere would you like to go?\n"));
- while (index not in legal):
- index = int(input("That is not a legal move, please try again. The legal moves are:\n" + str(legal)));
- b[index] = h;
- else:
- legal = legalMoves(b);
- index = legal[0];
- print("Computer taking the position of: " + str(index));
- b[index] = c;
- return;
- def willWin(space, h, b):
- combinations = ([0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]);
- for combination in combinations:
- if (space in combination):
- for com in combination:
- if (com != space):
- if (b[com] == h):
- return "no";
- return "yes";
- def win(winner):
- if (winner == "human"):
- return "You win! Congratulations.";
- elif (winner == "computer"):
- return "You lose.";
- else:
- return "Huh?";
- def inGame(b):
- if(len(legalMoves(b)) > 0):
- return "yes";
- return "no";
- def legalMoves(b):
- legal = [];
- c = 0;
- for square in b:
- if (square == EMPTY):
- legal.append(c);
- c += 1;
- return legal;
- def setup_board(b):
- counter = 0;
- while (counter < SIZE):
- b.append(EMPTY);
- counter += 1;
- return;
- def yes_no(q):
- i = input("\n" + q + " (y/n)\n");
- while (i is not "y" and i is not "Y" and i is not "N" and i is not "n"):
- i = input("\n" + q + "(y/n)\n");
- return i.lower();
- main();
- print("Thank you for playing.");
Add new comment
- 415 views