This function takes two arguments: `row` and `col`, which represent the row and column where the player wants to place their X or O (we’ll use ‘X’ for one player and ‘O’ for the other):
def update_board(board, row, col):
"""
This function updates the game board with the player's move and switches to the other player for the next move.
Args:
board (list): The current game board.
row (int): The row where the player wants to place their X or O.
col (int): The column where the player wants to place their X or O.
Returns:
bool: True if the move was successful, False if the spot is already taken.
"""
# check if the spot is already taken
if board[row * 3 + col] != 0:
print("Spot already taken!")
return False
# mark the chosen spot with either 'X' or 'O' depending on whose turn it is
if current_player == "X":
board[row * 3 + col] = 'X' # use string instead of integer to represent player's move
else:
board[row * 3 + col] = 'O' # use string instead of integer to represent player's move
# switch to the other player for the next move
global current_player
current_player = "O" if current_player == "X" else "X" # use ternary operator for shorter code
return True
Now, let’s define a function that checks whether there is a winner:
# Define a function that checks whether there is a winner
def check_winner(board):
# Check rows for three in a row (horizontal)
for i in range(3):
# Check if the current row has three consecutive "X" values
if board[i] == 1 and board[i + 3] == 1 and board[i + 6] == 1:
return "X"
# Check if the current row has three consecutive "O" values
elif board[i] == -1 and board[i + 3] == -1 and board[i + 6] == -1:
return "O"
# Check columns for three in a row (vertical)
for j in range(3):
# Check if the current column has three consecutive "X" values
if board[j] == 1 and board[j + 1 * 3] == 1 and board[j + 2 * 3] == 1:
return "X"
# Check if the current column has three consecutive "O" values
elif board[j] == -1 and board[j + 1 * 3] == -1 and board[j + 2 * 3] == -1:
return "O"
# Check diagonals for three in a row (diagonal)
# Check if the top left to bottom right diagonal has three consecutive "X" values
if board[0] == 1 and board[4] == 1 and board[8] == 1:
return "X"
# Check if the top right to bottom left diagonal has three consecutive "O" values
elif board[2] == -1 and board[4] == -1 and board[6] == -1:
return "O"
# If no winner is found, the game continues
return None
Finally, let’s define a function that prints out the current state of the board:
# Define a function that prints out the current state of the board
def print_board(board):
# Loop through the rows of the board
for i in range(3):
# Loop through the columns of the board
for j in range(3):
# Check if the current position on the board is occupied by a player's piece
if board[i * 3 + j] == 1:
# If the position is occupied by a 1, print "X" to represent player 1's piece
print("X", end=" ")
elif board[i * 3 + j] == -1:
# If the position is occupied by a -1, print "O" to represent player 2's piece
print("O", end=" ")
else:
# If the position is not occupied, print "-" to represent an empty space
print("- ", end=" ")
# Move to the next line after printing each row
print()
Now, let’s put it all together in a main function that runs the game loop:
def play_game():
global board, current_player # declare global variables
# initialize variables and board
board = [0] * 9 # create a list of 9 elements, representing the game board
current_player = "X" # set the current player to "X"
while True: # start a loop that will continue until a winner is found
print("Current Board:")
print_board(board) # call the print_board function to display the current state of the board
row = int(input("Enter the row (1-3): ")) - 1 # convert input to integer and subtract 1 for Python indexing
col = int(input("Enter the column (1-3): ")) - 1 # convert input to integer and subtract 1 for Python indexing
if update_board(board, row, col) == False: # call the update_board function to update the board with the player's move
continue # if the spot is already taken, skip the turn and continue the loop
winner = check_winner(board) # call the check_winner function to check if there is a winner
if winner != None: # if a winner is found, exit the loop
break
print("Congratulations! " + current_player + " wins!") # print a congratulatory message for the winner
And that’s it! You can run this script by saving it as `tic-tac-toe.py`, opening up your terminal or command prompt, and running the following commands:
1. Navigate to the directory where you saved the file (using `cd`)
2. Run the Python interpreter with `python`
3. Type in `import tic_tac_toe` (assuming that’s what your script is called) and press enter
4. Call the main function by typing in `play_game()` and pressing enter
5. Follow the instructions to play a game of tic-tac-toe!