Python code for Tic-Tac-Toe Game
Tic Tac Toe is a two-player paper-and-pencil game. The game is played on a 3×3 grid, and the goal is to place three of your symbols (usually “X” or “O”) in a row, either horizontally, vertically, or diagonally, before your opponent does the same. If all the spaces on the grid are filled and neither player has achieved three in a row, the game is considered a draw.
Code for Tic-Tac-Toe
board = [" " for x in range(9)]
def print_board():
row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
row2 = "| {} | {} | {} |".format(board[3], board[4], board[5])
row3 = "| {} | {} | {} |".format(board[6], board[7], board[8])
print()
print(row1)
print(row2)
print(row3)
print()
def player_move(icon):
if icon == "X":
number = 1
elif icon == "O":
number = 2
print("Your turn player {}".format(number))
choice = int(input("Enter your move (1-9): ").strip())
if board[choice - 1] == " ":
board[choice - 1] = icon
else:
print()
print("That space is already taken!")
def is_victory(icon):
if (board[0] == icon and board[1] == icon and board[2] == icon) or \
(board[3] == icon and board[4] == icon and board[5] == icon) or \
(board[6] == icon and board[7] == icon and board[8] == icon) or \
(board[0] == icon and board[3] == icon and board[6] == icon) or \
(board[1] == icon and board[4] == icon and board[7] == icon) or \
(board[2] == icon and board[5] == icon and board[8] == icon) or \
(board[0] == icon and board[4] == icon and board[8] == icon) or \
(board[2] == icon and board[4] == icon and board[6] == icon):
return True
else:
return False
def is_draw():
if " " not in board:
return True
else:
return False
while True:
print_board()
player_move("X")
print_board()
if is_victory("X"):
print("X wins! Congratulations!")
break
elif is_draw():
print("It's a draw!")
break
player_move("O")
if is_victory("O"):
print_board()
print("O wins! Congratulations!")
break
elif is_draw():
print("It's a draw!")
break
In this code, the game board is represented by a list of 9 spaces. The print_board function formats the board and displays it to the console. The player_move function allows the player to make a move by entering a number between 1 and 9, which corresponds to the positions on the board. The is_victory function checks if a player has won by matching the icon with 3 consecutive spaces in a row, column, or diagonal. The is_draw function checks if the game has ended in a draw
Explanation of Code
The code implements the Tic Tac Toe game using a list called board that represents the 3×3 game board. The board is initialized with 9 spaces represented as empty strings. The print_board function formats the board and displays it to the console. The player_move function allows the player to make a move by entering a number between 1 and 9, which corresponds to the positions on the board. The is_victory function checks if a player has won by matching the icon with 3 consecutive spaces in a row, column, or diagonal. The is_draw function checks if the game has ended in a draw.
Unit Test
import unittest
class TestTicTacToe(unittest.TestCase):
def test_print_board(self):
board = ["X", "O", "X", "X", "O", " ", " ", " ", " "]
expected_output = "| X | O | X |\n| X | O | |\n| | | |\n"
self.assertEqual(print_board(board), expected_output)
def test_player_move(self):
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
player_move("X", board)
self.assertEqual(board, ["X", " ", " ", " ", " ", " ", " ", " ", " "])
def test_is_victory(self):
board = ["X", "X", "X", " ", " ", " ", " ", " ", " "]
self.assertTrue(is_victory("X", board))
def test_is_draw(self):
board = ["X", "O", "X", "X", "O", "O", "O", "X", "X"]
self.assertTrue(is_draw(board))
if __name__ == "__main__":
unittest.main()
GUI for the program
import tkinter as tk
class TicTacToe(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("Tic Tac Toe")
self.geometry("300x325")
self.board = [" " for x in range(9)]
self.buttons = []
for i in range(9):
button = tk.Button(self, text=" ", font=("Helvetica", 24), width=3, height=1,
command=lambda i=i: self.button_click(i))
button.grid(row=i//3, column=i%3)
self