Recommended Posts
- Get link
- X
- Other Apps
import numpy as np
def create_board():
"""Creates a 3x3 NumPy array representing an empty Tic-Tac-Toe board."""
return np.zeros((3, 3), dtype=str) # Initialize with empty strings
def display_board(board):
"""Displays the Tic-Tac-Toe board in a user-friendly format."""
for row in board:
print("| " + " | ".join(row) + " |")
print("-" * 11)
def place_mark(board, row, col, mark):
"""Places a mark ('X' or 'O') on the board at the specified row and column."""
if board[row, col] == "": # Check if the cell is empty
board[row, col] = mark
return True
else:
print("That spot is already taken!")
return False
def check_winner(board):
"""Checks if there is a winner on the board."""
# Check rows
for row in board:
if row[0] == row[1] == row[2] != "":
return row[0]
# Check columns
for col in range(3):
if board[0, col] == board[1, col] == board[2, col] != "":
return board[0, col]
# Check diagonals
if board[0, 0] == board[1, 1] == board[2, 2] != "":
return board[0, 0]
if board[0, 2] == board[1, 1] == board[2, 0] != "":
return board[0, 2]
return None # No winner
# Main game loop
board = create_board()
current_player = "X"
while True:
display_board(board)
try:
row = int(input(f"Player {current_player}, enter row (0-2): "))
col = int(input(f"Player {current_player}, enter column (0-2): "))
except ValueError:
print("Invalid input. Please enter numbers between 0 and 2.")
continue
if 0 <= row <= 2 and 0 <= col <= 2:
if place_mark(board, row, col, current_player):
winner = check_winner(board)
if winner:
display_board(board)
print(f"Player {winner} wins!")
break
elif np.all(board != ""): # Check for a draw
display_board(board)
print("It's a draw!")
break
else:
# Switch players
current_player = "O" if current_player == "X" else "X"
else:
continue # Ask for input again
else:
print("Invalid row or column. Please enter numbers between 0 and 2.")
-
Explanation:
- create_board(): Creates a 3x3 NumPy array filled with empty strings (""). This represents the empty Tic-Tac-Toe board. The dtype=str is important to store 'X' and 'O' characters.
- display_board(): Prints the board to the console in a readable format.
- place_mark(): Places the player's mark ('X' or 'O') on the board at the specified row and column. It checks if the cell is already occupied.
- check_winner(): Checks all possible winning combinations (rows, columns, diagonals) to determine if there's a winner.
- Main Game Loop:
- Initializes the board and sets the starting player to "X".
- Continuously displays the board and prompts the current player for their move.
- Validates the player's input (row and column).
- Places the mark on the board if the cell is empty.
- Checks for a winner or a draw after each move.
- Switches to the other player if no winner or draw is detected.
How to Run:
- Save the code as a Python file (e.g., tic_tac_toe.py).
- Run the file from your terminal: python tic_tac_toe.py
This example demonstrates how NumPy arrays can be used to represent game boards and how NumPy's array indexing and manipulation capabilities can be used to implement game logic. It's a good starting point for exploring more complex game development projects with NumPy.
Comments
Post a Comment