Python实现井字棋游戏

Python使用内置库tkinter 实现井字棋游戏

井字棋,也被称为井字游戏、三连棋,是一种非常流行的棋类游戏。它由一个 3 * 3 的方格棋盘组成,玩家轮流在空白的格子中下棋,目标是将自己的棋子连成一条直线,可以是水平、垂直或对角线,先达到这个目标的玩家获胜。
在 Python 中可以使用tkinter来实现界面化的井字棋游戏。如下是代码示例:

from tkinter import Tk,Button,messagebox,NORMAL,DISABLED

current_player = "X"
game_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
game_over = False

def check_win(player):
    # 检查行
    for i in range(0, 9, 3):
        if game_board[i] == game_board[i + 1] == game_board[i + 2] == player:
            return True
    # 检查列
    for i in range(3):
        if game_board[i] == game_board[i + 3] == game_board[i + 6] == player:
            return True
    # 检查对角线
    if game_board[0] == game_board[4] == game_board[8] == player:
        return True
    if game_board[2] == game_board[4] == game_board[6] == player:
        return True
    return False

def check_draw():
    for i in range(9):
        if game_board[i] == " ":
            return False
    return True

def restart_game():
    global current_player, game_board, game_over
    current_player = "X"
    game_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
    game_over = False
    for button in board_buttons:
        button.config(text=" ", state=NORMAL)

def make_move(index):
    global current_player, game_board, game_over
    if game_board[index] == " " and not game_over:
        game_board[index] = current_player
        board_buttons[index].config(text=current_player, state=DISABLED)

        if check_win(current_player):
            messagebox.showinfo("结果", f"玩家 {current_player} 获胜!")
            game_over = True
        elif check_draw():
            messagebox.showinfo("结果", "平局!")
            game_over = True
        else:
            current_player = "O" if current_player == "X" else "X"


# 创建窗口
root = Tk()
root.title("井字棋")
root.resizable(False, False)
# 创建按钮
board_buttons = []
for i in range(9):
    button = Button(root, width=10, height=5, font=("Arial", 20), command=lambda index=i: make_move(index))
    button.grid(row=i // 3, column=i % 3)
    board_buttons.append(button)
# 创建重新开始按钮
restart_button = Button(root, text="重新开始", font=("Arial", 16), command=restart_game)
restart_button.grid(row=3, column=0, columnspan=3)
# 运行窗口主循环
root.mainloop()

上述代码演示了使用tkinter实现井字棋游戏的功能,运行代码后,将会弹出一个窗口,你可以通过点击按钮来进行井字棋游戏。

  • 9
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值