帮我用Python写一个完整的井字游戏
时间: 2024-12-11 19:37:11 浏览: 38
井字游戏,也叫Tic Tac Toe,是一个简单的两人对战游戏。我们可以用Python编写一个控制台版的游戏。以下是基本的实现步骤:
```python
# 定义棋盘大小和初始状态
size = 3
board = [[" " for _ in range(size)] for _ in range(size)]
current_player = 'X'
def print_board():
for row in board:
print(" | ".join(row))
print("-" * size)
def check_win():
# 检查行、列和对角线是否有三个连续的标记
for i in range(size):
if all(board[j][i] == current_player for j in range(size)) or \
all(board[i][j] == current_player for j in range(size)):
return True
if board[0][0] == board[1][1] == board[2][2] == current_player or \
board[0][2] == board[1][1] == board[2][0] == current_player:
return True
return False
def play_game():
while not check_win() and not all(' ' not in row for row in board):
print_board()
try:
row, col = map(int, input(f"{current_player} (row, col): ").split())
if board[row][col] != ' ':
print("Invalid move, please try again.")
continue
board[row][col] = current_player
current_player = 'O' if current_player == 'X' else 'X'
except ValueError:
print("Invalid input, please enter a number.")
play_game()
```
在这个代码中,我们首先创建了一个3x3的空棋盘,然后通过`print_board()`函数显示当前的棋局状态。`check_win()`检查是否有人获胜,如果没有,则轮到玩家输入他们想要放置标记的位置。如果输入无效,会提示玩家重新输入。
运行这个程序,你可以开始玩井字游戏了。
阅读全文
相关推荐




















