找回密码
 中文实名注册
搜索
查看: 663|回复: 0

井字棋--丁彦辰

[复制链接]

15

主题

55

回帖

2143

积分

金牌会员

积分
2143
发表于 2025-6-15 17:13:28 | 显示全部楼层 |阅读模式
[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import messagebox
import random

class TicTacToe:
    def __init__(self, root):
        self.root = root
        self.root.title("井字棋游戏")
        self.current_player = "X"
        self.board = [""] * 9
        self.buttons = []
        
        # 创建游戏界面
        self.create_board()
        
    def create_board(self):
        # 创建3x3的按钮网格
        for i in range(3):
            for j in range(3):
                button = tk.Button(
                    self.root, 
                    text="", 
                    font=('Arial', 30), 
                    width=5, 
                    height=2,
                    command=lambda row=i, col=j: self.on_click(row, col)
                )
                button.grid(row=i, column=j)
                self.buttons.append(button)
        
        # 添加重置按钮
        reset_button = tk.Button(
            self.root, 
            text="重新开始", 
            font=('Arial', 14), 
            command=self.reset_game
        )
        reset_button.grid(row=3, column=0, columnspan=3, sticky="we")
    
    def on_click(self, row, col):
        index = 3 * row + col
        
        # 检查格子是否为空
        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_game()
            elif "" not in self.board:
                messagebox.showinfo("游戏结束", "平局!")
                self.reset_game()
            else:
                # 切换玩家
                self.current_player = "O" if self.current_player == "X" else "X"
    
    def check_winner(self):
        # 检查所有可能的获胜组合
        winning_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 winning_combinations:
            if (self.board[combo[0]] == self.board[combo[1]] == self.board[combo[2]] != ""):
                # 高亮显示获胜的格子
                for index in combo:
                    self.buttons[index].config(bg="light green")
                return True
        return False
    
    def reset_game(self):
        # 重置游戏状态
        self.current_player = "X"
        self.board = [""] * 9
        for button in self.buttons:
            button.config(text="", bg="SystemButtonFace")

# 创建主窗口并启动游戏
root = tk.Tk()
game = TicTacToe(root)
root.mainloop()

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 中文实名注册

本版积分规则

快速回复 返回顶部 返回列表