我编写了一个基于GUI的奥赛罗游戏。重新调整游戏板的大小有点麻烦。这是我到目前为止的代码:
BOXWIDTH=60
BOXHEIGHT=60
class player:
"""Make a user player to play the game via a GUI."""
def __init__(self,row,column):
# create the GUI state variables
self.alive = True
self.move = None
self.move_played = False
# create the GUI windows and handlers
self.root = tkinter.Tk()
self.root.wm_title('Othello')
self.root.protocol("WM_DELETE_WINDOW", self.quit)
# create a button to get the No move command from the user
tkinter.Button(self.root, text="No Move", command = self.nomove).pack()
# create a label for displaying the next player's name
self.movemesg = tkinter.StringVar()
tkinter.Label(self.root, textvariable=self.movemesg).pack()
self.canvas = tkinter.Canvas(self.root, bg="darkgreen",
height = BOXHEIGHT*row,
width = BOXWIDTH*column)
self.canvas.bind("<Button-1>", self.click)
# create a box for highlighting the last move
self.lastbox = self.canvas.create_rectangle(0, 0, BOXWIDTH*column,
BOXHEIGHT*row,
outline="red")
# draw the game canvas
for i in range(1,row):
# horizontal lines
self.canvas.create_line(0, i*BOXHEIGHT,
BOXWIDTH*column, i*BOXHEIGHT)
for i in range(1,column):
# vertical lines
self.canvas.create_line(i*BOXWIDTH, 0,
i*BOXWIDTH, BOXHEIGHT*row)
# the board will store the widgets to be displayed in each square
self.board = [[None for y in range(row)]
for x in range(column)]
# display the window
self.canvas.pack()
self.canvas.focus_set()
self.root.update()
def draw_board(self, game, last_move):
"""Draw an othello game on the board."""
ws = str(sum(x.count(1) for x in game.board))
bs = str(sum(x.count(-1) for x in game.board))
if game.player == -1:
self.movemesg.set("Black to play "+'\nSCORE: White = '+ws+' Black = ' + bs)
else:
self.movemesg.set("White to play "+'\nSCORE: White = '+ws+' Black = ' + bs)
for i in range(game.column):
for j in range(game.row):
color = game.get_color((i,j))
if color == -1:
board_color = "black"
elif color == 1:
board_color = "white"
else:
if self.board[i][j] is not None:
self.canvas.delete(self.board[i][j])
self.board[i][j] = None
continue
if self.board[i][j] is None:
self.board[i][j] = self.canvas.create_oval(
i*BOXWIDTH+2, j*BOXHEIGHT+2, (i+1)*BOXWIDTH-2,
(j+1)*BOXHEIGHT-2, fill = board_color)
else:
self.canvas.itemconfig(self.board[i][j], fill=board_color)
我希望游戏板调整大小,即它必须使绘制板的区域相应地改变大小,重新绘制游戏板以填充可用空间。对此的任何帮助都会很棒。
答案 0 :(得分:0)
你的第一个问题是当主窗口增长时画布没有被告知要增长。将您的包语句更改为:
self.canvas.pack(fill="both", expand=True)
接下来,您需要创建一个在画布调整大小时调用的绑定。您可以通过绑定到<Configure>
来完成此操作。例如:
self.canvas.bind("<Configure>", self.on_configure)
最后,您需要创建一个除了重绘电路板之外什么都不做的功能。您将从on_configure
方法调用此方法。