python使用tkinter实现井字游戏(Tic-Tac-Toe)

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

目录

需求

效果

代码实现

解释代码


需求

使用图形化界面实现双人井字棋游戏

效果

代码实现

import tkinter as tk
from tkinter import messagebox

class TicTacToe:
    def __init__(self, root):
        self.root = root
        self.root.title("井字游戏 (Tic-Tac-Toe)")
        self.current_player = "X"
        self.board = [""] * 9
        self.buttons = []

        for i in range(9):
            button = tk.Button(root, text="", font=('normal', 40), width=5, height=2,
                               command=lambda i=i: self.on_button_click(i))
            button.grid(row=i // 3, column=i % 3)
            self.buttons.append(button)

    def on_button_click(self, index):
        if self.board[index] == "":
            self.board[index] = self.current_player
            self.buttons[index].config(text=self.current_player)
            if self.check_winner():
                messagebox.showinfo("游戏结束", f"玩家 {self.current_player} 获胜!")
                self.reset_board()
            elif "" not in self.board:
                messagebox.showinfo("游戏结束", "平局!")
                self.reset_board()
            else:
                self.current_player = "O" if self.current_player == "X" else "X"

    def check_winner(self):
        win_conditions = [
            [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 condition in win_conditions:
            if self.board[condition[0]] == self.board[condition[1]] == self.board[condition[2]] != "":
                return True
        return False

    def reset_board(self):
        self.board = [""] * 9
        for button in self.buttons:
            button.config(text="")
        self.current_player = "X"

if __name__ == "__main__":
    root = tk.Tk()
    game = TicTacToe(root)
    root.mainloop()

解释代码

  1. 初始化界面

    • 创建主窗口并设置标题。
    • 初始化当前玩家为 "X"。
    • 创建一个长度为 9 的列表 board 来存储棋盘的状态。
    • 使用嵌套循环创建 9 个按钮,并将它们放置在网格布局中。每个按钮都绑定到 on_button_click 方法。
  2. 按钮点击事件

    • 当按钮被点击时,检查该位置是否为空。
    • 如果为空,则更新 board 列表和按钮的文本。
    • 检查是否有玩家获胜或棋盘已满(平局)。
    • 如果游戏未结束,切换当前玩家。
  3. 检查胜利条件

    • 定义所有可能的胜利组合。
    • 遍历这些组合,检查是否有玩家满足胜利条件。
  4. 重置棋盘

    • 将 board 列表清空。
    • 将所有按钮的文本清空。
    • 将当前玩家重置为 "X"。

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

licy__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值