要将棋盘设置为19x19并添加边框,可以对代码进行一些修改。首先,在draw_board函数中,将棋盘的绘制范围从50450改为30470,这样边框就会被包含在内。然后,在__init__函数中,将widthheight参数修改为570,以便为边框留出空间。最后,在place_stone函数中,将xy的计算公式改为(event.x - 30) // 40(event.y - 30) // 40,这样棋盘上的坐标就会根据边框进行调整。

修改后的代码如下:

import tkinter as tk

class GoGame:
    def __init__(self, size):
        self.size = size
        self.board = {}
        self.current_player = 'B'
        self.root = tk.Tk()
        self.canvas = tk.Canvas(self.root, width=570, height=570)
        self.canvas.grid(row=0, column=0, padx=10, pady=10)
        self.canvas.bind("<Button-1>", self.place_stone)
        self.draw_board()
        self.root.mainloop()

    def draw_board(self):
        self.canvas.delete("all")
        for i in range(self.size):
            self.canvas.create_line(30, 30+i*30, 470, 30+i*30)
            self.canvas.create_line(30+i*30, 30, 30+i*30, 470)
        for pos, stone in self.board.items():
            x, y = pos
            fill = "black" if stone == 'B' else "white"
            self.canvas.create_oval(10+x*30, 10+y*30, 50+x*30, 50+y*30, fill=fill)
    
    def place_stone(self, event):
        x = (event.x - 30) // 30
        y = (event.y - 30) // 30
        if x >= 0 and x < self.size and y >= 0 and y < self.size and (x, y) not in self.board:
            self.board[(x, y)] = self.current_player
            self.current_player = 'W' if self.current_player == 'B' else 'B'
            self.draw_board()

if __name__ == '__main__':
    game = GoGame(19)

这样,代码会创建一个19x19的棋盘,并在棋盘周围添加了边框

import tkinter as tkclass GoGame def __init__self size selfsize = size selfboard = selfcurrent_player = B selfroot = tkTk selfcanvas = tkCanvasselfroot width=500

原文地址: https://www.cveoy.top/t/topic/h3Yd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录