```python
import random
def create_board():
return [[" " for _ in range(3)] for _ in range(3)]
def draw_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
检查所有可能的获胜组合
win_combinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], 横向
[0, 3, 6], [1, 4, 7], [2, 5, 8], 竖向
[0, 4, 8], [2, 4, 6] 对角线
]
for combination in win_combinations:
if all(board[row][col] == player for row, col in zip(combination, combination[1:])):
return True
return False
def is_full(board):
return all(cell != " " for row in board for cell in row)
def get_move(board, player):
while True:
move = input(f"玩家{player},请输入你的移动(1-9):")
if move.isdigit() and 1 <= int(move) <= 9:
row, col = divmod(int(move) - 1, 3)
if board[row][col] == " ":
return row, col
else:
print("该位置已有棋子,请重新输入。")
def make_move(board, row, col, player):
board[row][col] = player
def computer_move(board):
available_moves = [(row, col) for row in range(3) for col in range(3) if board[row][col] == " "]
return random.choice(available_moves)
def play_game():
board = create_board()
current_player = "X"
while True:
draw_board(board)
row, col = get_move(board, current_player)
make_move(board, row, col, current_player)
if check_winner(board, current_player):
draw_board(board)
print(f"玩家{current_player}获胜!")
break
if is_full(board):
draw_board(board)
print("平局!")
break
if current_player == "X":
row, col = computer_move(board)
make_move(board, row, col, "O")
current_player = "O"
else:
current_player = "X"
if __name__ == "__main__":
play_game()
```
这个代码实现了井字棋的基本功能,包括创建棋盘、绘制棋盘、检查获胜条件、获取玩家输入、执行移动、电脑随机移动等。你可以运行这个脚本来体验井字棋游戏。