write me tic tac toe game in python version 311
Sure! Here's an example of a Tic Tac Toe game in Python 3.11:
# Tic Tac Toe
# Create a board
board = [' ' for _ in range(9)]
# Function to display the Tic Tac Toe board
def display_board():
print('-------------')
print('|', board[0], '|', board[1], '|', board[2], '|')
print('-------------')
print('|', board[3], '|', board[4], '|', board[5], '|')
print('-------------')
print('|', board[6], '|', board[7], '|', board[8], '|')
print('-------------')
# Function to check if any player has won
def check_win(player):
# Check rows
for i in range(0, 9, 3):
if board[i] == board[i + 1] == board[i + 2] == player:
return True
# Check columns
for i in range(3):
if board[i] == board[i + 3] == board[i + 6] == player:
return True
# Check diagonals
if board[0] == board[4] == board[8] == player:
return True
if board[2] == board[4] == board[6] == player:
return True
return False
# Function to check if the board is full
def is_board_full():
return ' ' not in board
# Main game loop
def play_game():
current_player = 'X'
while True:
display_board()
position = int(input(f"Player {current_player}, choose a position (1-9): ")) - 1
if board[position] == ' ':
board[position] = current_player
else:
print("Invalid move. Try again.")
continue
if check_win(current_player):
display_board()
print(f"Congratulations! Player {current_player} wins!")
break
elif is_board_full():
display_board()
print("It's a tie!")
break
current_player = 'O' if current_player == 'X' else 'X'
# Start the game
play_game()
You can run this code in Python 3.11 to play the Tic Tac Toe game
原文地址: https://www.cveoy.top/t/topic/hXzc 著作权归作者所有。请勿转载和采集!