基于tkinter的五子棋游戏

五子棋游戏

想参考网友的博客使用Python写了一个简单的五子棋游戏,使用类的方法。但对于我来说,参考的代码写得太好了,所以基本上都是大段的搬过来。

代码

直接上代码吧

from tkinter import *

class GoBang():
    def __int__(self):
        self.window = Tk()
        self.window.title("五子棋")
        self.window.iconbitmap('./gobang.ico')
        self.window.geometry("500x560")
        self.window.canvas = Canvas(self.window, width=480, height=480, bg='peachpuff')
        self.window.canvas.pack()
        for num in range(1, 16):
            if num == 1 or num == 15:
                self.window.canvas.create_line(num * 30, 30,
                                               num * 30, 450,
                                               width=2)
            else:
                self.window.canvas.create_line(num * 30, 30,
                                               num * 30, 450,
                                               width=1)
        for num in range(1, 16):
            if num == 1 or num == 15:
                self.window.canvas.create_line(30, num * 30,
                                               450, num * 30,
                                               width=2)
            else:
                self.window.canvas.create_line(30, num * 30,
                                               450, num * 30,
                                               width=1)

        self.window.canvas.create_oval(8 * 30 - 2, 8 * 30 - 2, 8 * 30 + 2,
                                       8 * 30 + 2, fill='black')
        self.window.canvas.create_oval(5 * 30 - 2, 5 * 30 - 2, 5 * 30 + 2,
                                       5 * 30 + 2, fill='black')
        self.window.canvas.create_oval(5 * 30 - 2, 11 * 30 - 2, 5 * 30 + 2,
                                       11 * 30 + 2, fill='black')
        self.window.canvas.create_oval(11 * 30 - 2, 5 * 30 - 2, 11 * 30 + 2,
                                       5 * 30 + 2, fill='black')
        self.window.canvas.create_oval(11 * 30 - 2, 11 * 30 - 2, 11 * 30 + 2,
                                       11 * 30 + 2, fill='black')
        self.startBtn = Button(self.window, text='Start', bg="DeepSkyBlue", width=8, height=1, command=self.chessGo)
        self.quitBtn = Button(self.window, text='Quit', bg="OrangeRed", width=8, height=1, command=self.window.quit)
        self.withDrawBtn = Button(self.window, text='Withdraw', bg="cyan", width=8, height=1, command=self.withDraw)
        self.startBtn.place(relx=0.2, rely=0.89)
        self.quitBtn.place(relx=0.6, rely=0.89)
        self.withDrawBtn.place(relx=0.4, rely=0.89)

        self.game_print = StringVar()
        self.labelInfo = Label(self.window, width=12, textvariable=self.game_print, font=("Arial", 10, "bold"),
                               justify="center")
        self.labelInfo.place(relx=0.36, rely=0.95)
        self.window.canvas.bind("<Button-1>", self.place)
        self.game_print.set("请开始新局")
        self.chess = [([0] * 15) for i in range(15)]
        # 悔棋用的顺序列表
        self.order = []

        # 棋子颜色
        self.color_count = 0
        self.color = 'black'

        self.flag_win = 0
        self.flag_go = 0

        self.window.mainloop()

    def chessGo(self):
        if self.startBtn['text'] == "Start":
            #
            self.flag_go = 1
            self.startBtn['text'] = "Going"
            self.game_print.set('请black落子')
            self.labelInfo['fg'] = 'black'

        elif self.startBtn['text'] == "New":
            self.startBtn['text'] = "Start"
            self.newGame()

    def newGame(self):
        self.window.canvas.delete("chessman")
        self.chess = [([0] * 15) for i in range(15)]
        self.order = []
        self.color_count = 0
        self.color = 'black'
        self.flag_win = 0
        self.flag_go = 0
        self.game_print.set('请开始新局')
        self.labelInfo['fg'] = 'black'

    def withDraw(self):
        if len(self.order) == 0 or self.flag_win == 1:
            self.game_print.set("Can't Withdraw")
            self.labelInfo['fg'] = 'sandybrown'
            return
        else:
            self.window.canvas.delete("chessman")
            xylist = self.order.pop()
            self.chess[xylist[0]][xylist[1]] = 0
            self.color_count = 0
            for xylist in self.order:
                y = xylist[0]
                x = xylist[1]
                if self.color_count == 0:
                    self.chess[y][x] = 1
                    self.color = 'black'

                elif self.color_count == 1:
                    self.chess[y][x] = 2
                    self.color = 'white'
                self.color_count = 1 - self.color_count
                self.window.canvas.create_oval((x + 1) * 30 - 12, (y + 1) * 30 - 12, (x + 1) * 30 + 12,
                                               (y + 1) * 30 + 12, fill=self.color,
                                               tags="chessman")
            if self.color_count:
                self.color = 'white'
            else:
                self.color = 'black'
            self.game_print.set("请" + self.color + "落子")
            self.labelInfo['fg'] = 'black'

    def place(self, event):
        if (self.flag_win == 0 and self.flag_go == 1):
            print("enter place")
            x, y = event.x, event.y
            x = round(x / 30 - 1)
            y = round(y / 30 - 1)
            if x < 0 or x > 14 or y < 0 or y > 14:
                #            tkinter.messagebox.INFO('提示', '请在棋盘上落子!')
                self.game_print.set('越界落子!')
                self.labelInfo['fg'] = "darkorange"
                return
            if self.chess[y][x] == 0:
                print("enter paint oval")
                if self.color_count == 0:
                    self.chess[y][x] = 1
                    self.color = 'black'

                elif self.color_count == 1:
                    self.chess[y][x] = 2
                    self.color = 'white'
                self.color_count = 1 - self.color_count
                self.window.canvas.create_oval((x + 1) * 30 - 12, (y + 1) * 30 - 12, (x + 1) * 30 + 12,
                                               (y + 1) * 30 + 12, fill=self.color,
                                               tags="chessman")
                self.order.append([y, x])
            else:
                #            tkinter.messagebox.INFO('提示', '此处已有棋子!')
                self.game_print.set('请别处落子!')
                self.labelInfo['fg'] = "darkorange"
                return

            if self.win(x, y):
                self.flag_win = 1
                self.startBtn['text'] = "New"
                if self.color_count == 1:
                    self.color = 'black'

                else:
                    self.color = 'white'
                    # self.messagebox.INFO('提示', '白棋胜!')
                self.game_print.set(self.color + "胜!")
                self.labelInfo['fg'] = "red"

            else:
                if self.color_count:
                    self.color = 'white'
                else:
                    self.color = 'black'

                self.game_print.set("请" + self.color + "落子")
                self.labelInfo['fg'] = "black"

    def win(self, x, y):
        count = 1
        # -计算
        for i in range(-1, -5, -1):
            if x + i < 0:
                break
            else:
                if self.chess[y][x + i] == self.chess[y][x]:
                    count += 1
                else:
                    break
        for i in range(1, 5, 1):
            if x + i > 14:
                break
            else:
                if self.chess[y][x + i] == self.chess[y][x]:
                    count += 1
                else:
                    break
        if count >= 5:
            return True
        # |计算
        count = 1
        for i in range(-1, -5, -1):
            if y + i < 0:
                break
            else:
                if self.chess[y + i][x] == self.chess[y][x]:
                    count += 1
                else:
                    break
        for i in range(1, 5, 1):
            if y + i > 14:
                break
            else:
                if self.chess[y + i][x] == self.chess[y][x]:
                    count += 1
                else:
                    break
        if count >= 5:
            return True
        # /计算
        count = 1
        for i in range(-1, -5, -1):
            if y + i < 0 or x + i < 0:
                break
            else:
                if self.chess[y + i][x + i] == self.chess[y][x]:
                    count += 1
                else:
                    break
        for i in range(1, 5, 1):
            if y + i > 14 or x + i > 14:
                break
            else:
                if self.chess[y + i][x + i] == self.chess[y][x]:
                    count += 1
                else:
                    break
        if count >= 5:
            return True
        # \计算
        count = 1
        for i in range(-1, -5, -1):
            if y + i < 0 or x - i > 14:
                break
            else:
                if self.chess[y + i][x - i] == self.chess[y][x]:
                    count += 1
                else:
                    break
        for i in range(1, 5, 1):
            if y + i > 14 or x - i < 0:
                break
            else:
                if self.chess[y + i][x - i] == self.chess[y][x]:
                    count += 1
                else:
                    break
        if count >= 5:
            return True


if __name__ == "__main__":
    myBang = GoBang()
    myBang.__int__()

运行结果

在这里插入图片描述
在这里插入图片描述

问题

  1. 创建了类,按说实体化的时候会自动调用__int__,但是我这里要显示调用,很费解。
  2. 想用messagebox弹出消息的,但是不知道在类里这个怎么用。
    后续研究,再把功能丰富丰富。

引用

Python tkinter制作单机五子棋游戏

tkinter 实现的五子棋UI界面 import tkinter as tk from tkinter import messagebox from chessboard import ChessBoard ChessBoard = ChessBoard() class GUI(object): def __init__(self): self.counter = 0 self.winner = 0 self.is_start = False self.is_surrender = False self.window = tk.Tk() # 窗口对象(首字母大写) self.window.title('Gobang') self.window.geometry('800x540') self.window.resizable(width = False, height = False) # 画布对象 棋盘 self.canvas = tk.Canvas(self.window, height = 540, width = 540) self.chessboard = tk.PhotoImage(file = 'Gobang_chessboard/chessboard.gif') self.blackpoint = tk.PhotoImage(file = 'Gobang_chessboard/blackpoint.gif') self.whitepoint = tk.PhotoImage(file = 'Gobang_chessboard/whitepoint.gif') self.canvas.create_image(0, 0, anchor = 'nw', image = self.chessboard) self.canvas.bind("", self.get_point) self.start_point = 10 # 起始点位置 self.step = 35 # 每个格子的跨度 self.canvas.place(x = 0, y = 0) # 标签对象 self.l_info = tk.Label(self.window, text = 'Not started', font=('Arial', 12), width = 25, height = 2) self.l_info.place(x = 545, y = 0) # 文本框对象 self.t = tk.Text(self.window, height = 15) self.t.place(x = 540, y = 40) # 按钮对象 self.f_header = tk.Frame(self.window, highlightthickness=0) self.b_start = tk.Button(self.f_header, text = 'start', command = self.start) self.b_restart = tk.Button(self.f_header, text = 'restart', command = self.restart) self.b_regret = tk.Button(self.f_header, text = 'regret', command = self.regret) self.b_surrender = tk.Button(self.f_header, text = 'surrender', command = self.surrender) self.f_header.place(x = 545, y = 250) self.b_start.pack(side='left', padx=10) self.b_restart.pack(side = 'left') self.b_surrender.pack(side = 'right') self.b_regret.pac
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值