Untitled
unknown
plain_text
2 years ago
2.5 kB
7
Indexable
# Initialize the game board
board = [[' ' for _ in range(3)] for _ in range(3)]
# Initialize the scores
player_1_score = 0
player_2_score = 0
# Function to draw the game board
def draw_board():
for row in board:
print(" | ".join(row))
print("-" * 5)
# Function to handle a player's turn
def player_turn(player):
global board
while True:
row = int(input(f"Player {player}, enter the row (1-3) for your move: ")) - 1
col = int(input(f"Player {player}, enter the column (1-3) for your move: ")) - 1
if board[row][col] == ' ':
board[row][col] = f'P{player}'
break
# Function to check if there is a winner
def check_winner():
global board, player_1_score, player_2_score
for row in board:
if row[0] == row[1] == row[2] != ' ':
if row[0] == 'P1':
player_1_score += 1
return True
elif row[0] == 'P2':
player_2_score += 1
return True
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] != ' ':
if board[0][col] == 'P1':
player_1_score += 1
return True
elif board[0][col] == 'P2':
player_2_score += 1
return True
if board[0][0] == board[1][1] == board[2][2] != ' ':
if board[0][0] == 'P1':
player_1_score += 1
return True
elif board[0][0] == 'P2':
player_2_score += 1
return True
if board[0][2] == board[1][1] == board[2][0] != ' ':
if board[0][2] == 'P1':
player_1_score += 1
return True
elif board[0][2] == 'P2':
player_2_score += 1
return True
return False
# Main game loop
while True:
draw_board()
player_turn(1)
if check_winner():
print(f"Player 1 wins! Player 1 score: {player_1_score}, Player 2 score: {player_2_score}")
if player_1_score == 3:
print("Player 1 wins the game!")
break
board = [[' ' for _ in range(3)] for _ in range(3)]
continue
draw_board()
player_turn(2)
if check_winner():
print(f"Player 2 wins! Player 1 score: {player_1_score}, Player 2 score: {player_2_score}")
if player_2_score == 3:
print("Player 2 wins the game!")
break
board = [[' ' for _ in range(3)] for _ in range(3)]Editor is loading...
Leave a Comment