简单井字格游戏python代码
以下是一个简单的井字格游戏 Python 代码示例:
# 定义井字格游戏的棋盘
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# 定义当前玩家
current_player = "X"
# 定义游戏是否结束的标志
game_over = False
# 定义游戏胜利的可能组合
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)]
# 打印游戏棋盘
def print_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
# 玩家走一步
def play_game():
global game_over
while not game_over:
print_board()
handle_turn(current_player)
check_if_game_over()
flip_player()
if current_player == "X" or current_player == "O":
print(current_player + " 赢了!")
else:
print("平局!")
# 处理玩家输入
def handle_turn(player):
print(player + " 的回合。")
position = input("请选择一个位置(1-9):")
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("请选择一个位置(1-9):")
position = int(position) - 1
if board[position] == "-":
valid = True
else:
print("这个位置已经被占了,请选择另一个位置。")
board[position] = player
print_board()
# 检查游戏是否结束
def check_if_game_over():
check_if_win()
check_if_tie()
# 检查是否有玩家获胜
def check_if_win():
global game_over
for combination in win_combinations:
pos1 = combination[0]
pos2 = combination[1]
pos3 = combination[2]
if board[pos1] == board[pos2] == board[pos3] != "-":
game_over = True
return board[pos1]
return None
# 检查是否为平局
def check_if_tie():
global game_over
if "-" not in board:
game_over = True
return True
else:
return False
# 切换玩家
def flip_player():
global current_player
if current_player == "X":
current_player = "O"
else:
current_player = "X"
# 开始游戏
play_game()
``
原文地址: https://www.cveoy.top/t/topic/hvcJ 著作权归作者所有。请勿转载和采集!