做一个井字棋游戏,可以直接运行
- User
做一个井字棋游戏,可以直接运行
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
做一个井字棋游戏,可以直接运行
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
以下是一个可以直接运行的井字棋(Tic-Tac-Toe)游戏 Python 实现:
def print_board(board):
print("\n")
print(f"{board[0]} | {board[1]} | {board[2]}")
print("--+---+--")
print(f"{board[3]} | {board[4]} | {board[5]}")
print("--+---+--")
print(f"{board[6]} | {board[7]} | {board[8]}")
print("\n")
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 combo in win_combinations:
if board[combo[0]] == board[combo[1]] == board[combo[2]] == player:
return True
return False
def is_draw(board):
return all(cell in ['X', 'O'] for cell in board)
def tic_tac_toe():
board = ['1','2','3','4','5','6','7','8','9']
current_player = 'X'
while True:
print_board(board)
try:
move = int(input(f"玩家 {current_player} 请输入位置 (1-9): ")) - 1
if move < 0 or move > 8:
print("无效输入!请输入 1-9 之间的数字。")
continue
if board[move] in ['X', 'O']:
print("该位置已被占用!请选择其他位置。")
continue
board[move] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"恭喜玩家 {current_player} 获胜!")
break
if is_draw(board):
print_board(board)
print("平局!")
break
# 切换玩家
current_player = 'O' if current_player == 'X' else 'X'
except ValueError:
print("请输入有效的数字!")
if __name__ == "__main__":
tic_tac_toe()
tic_tac_toe.pypython tic_tac_toe.py1 | 2 | 3
--+---+--
4 | 5 | 6
--+---+--
7 | 8 | 9
玩家 X 请输入位置 (1-9):
你可以随时改进它,比如添加AI对手、图形界面或网络对战功能!