2016-03-06 222 views
3

我在GUI中編寫一個黑白棋遊戲。我已經開始研究翻轉某些瓷磚的動畫,這是在這裏。當電路板上的瓦片數量變大時,我的電腦將開始窒息。我不知道該怎麼做才能簡化這段代碼或使用更少的內存。 (我可以使用一個automove鍵,我已經能夠以光速完成遊戲,沒有動畫效果。)這是我用來翻轉拼圖的定義。Python Tkinter - 如何使某些代碼使用更少的內存

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

這跟這個[tag:processing]語言有什麼關係嗎? –

回答

2

最簡單的解決方案是在每次迭代時不刪除並重新創建遊戲塊。繪製一次,然後使用itemconfig方法更改遊戲塊的外觀。

更好的辦法是創建一個GamePiece類,以便每一塊都由這個類表示。然後,在該類中移動動畫功能。這將使你的主要邏輯很多更容易理解。