我在GUI中编写奥赛罗游戏。我已经开始研究翻转某些瓷砖的动画了,就在这里。当电路板上的瓷砖数量变大时,我的计算机将开始窒息。我不知道如何简化此代码或使用更少的内存。 (我可以使用自动驾驶键,我可以在没有动画的情况下以光速完成游戏。这很好用。)这是我用来翻转瓷砖的定义。
def animateFlips(self, i):
self._canvas.delete(tkinter.ALL)
column_width = self._canvas.winfo_width()/Othello.COLUMNS
row_height = (self._canvas.winfo_height()-self._scoreBoard)/Othello.ROWS
newBoard = self._game.board
animatedTileCoords = []
color = ''
oppcolor = ''
if self._game.turn == 2:
color = 'black'
oppcolor = 'white'
elif self._game.turn == 1:
color = 'white'
oppcolor = 'black'
for x in range(Othello.COLUMNS):
for y in range(Othello.ROWS):
x1 = x * column_width
y1 = y * row_height
x2 = x1 + column_width
y2 = y1 + row_height
self._canvas.create_rectangle(x1,y1,x2,y2)
if self._game.board[x][y] == 1:
self._canvas.create_oval(x1,y1,x2,y2,fill='black')
elif self._game.board[x][y] == 2:
self._canvas.create_oval(x1,y1,x2,y2,fill='white')
elif self._game.board[x][y] == 3 or self._game.board[x][y] == 4:
animatedTileCoords.append([x,y])
for x, y in animatedTileCoords:
x1 = x * column_width
y1 = y * row_height
x2 = x1 + column_width
y2 = y1 + row_height
if i == 1:
self._canvas.create_oval(x1,y1,x2,y2,fill=oppcolor)
self._canvas.after(50, lambda: self.animateFlips(2))
elif i == 2:
self._canvas.create_oval(x1 + (column_width/4),y1,x1 + (3*column_width/4),y2,fill=oppcolor)
self._canvas.after(50, lambda: self.animateFlips(3))
elif i == 3:
self._canvas.create_oval(x1 + (column_width/2),y1,x1 + (column_width/2),y2,fill=oppcolor)
self._canvas.after(50, lambda: self.animateFlips(4))
elif i == 4:
self._canvas.create_oval(x1 + (column_width/4),y1,x1 + (3*column_width/4),y2,fill=color)
self._canvas.after(50, lambda: self.animateFlips(5))
elif i == 5:
self._canvas.create_oval(x1,y1,x2,y2,fill=color)
newBoard[x][y] = Othello.nextTurn(self._game.turn)
self._game = GameState(board = newBoard, turn = self._game.turn, skipped = 0)
self.displayMoves()
self.displayButtons()
self.displayInfo()
self.displayWinner(self.getWinner())
self._canvas.bind('<Configure>',self.draw_handler)
答案 0 :(得分:2)
最简单的解决方案是不在每次迭代中删除和重新创建游戏片段。绘制一次,然后使用itemconfig
方法改变游戏块的外观。
更好的是创建一个GamePiece
类,以便每个部分由此类表示。然后,在类中移动动画功能。这将使您的主要逻辑更多更容易理解。