使用python制作一个简单的井字棋游戏
# 初始化一个空白的棋盘
board = [" " for _ in range(9)]
# 定义一个函数来绘制棋盘
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print("---------")
print(board[3] + " | " + board[4] + " | " + board[5])
print("---------")
print(board[6] + " | " + board[7] + " | " + board[8])
# 定义一个函数来检查胜利条件
def check_win(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 play_game():
current_player = "X"
while True:
display_board()
move = input(f"玩家 {current_player},请选择一个位置 (1-9): ")
if not move.isdigit() or int(move) < 1 or int(move) > 9 or board[int(move) - 1] != " ":
print("无效的选择,请重新选择。")
continue
board[int(move) - 1] = current_player
if check_win(current_player):
display_board()
print(f"玩家 {current_player} 获胜!")
break
if " " not in board:
display_board()
print("游戏平局。")
break
current_player = "X" if current_player == "O" else "O"
# 开始游戏
if __name__ == "__main__":
play_game()