2016-11-13 44 views
0

我試圖切換這種方法,以允許魚嘗試4個隨機位置爲其下一步移動。我已經嘗試了一些破解,但我還沒有找到一個好方法。試圖將龜對象移動到隨機位置

def tryToMove(self): 
     offsetList = [(-1, 1), (0, 1), (1, 1), 
        (-1, 0)  , (1, 0), 
        (-1, -1), (0, -1), (1, -1)] 
     randomOffsetIndex = random.randrange(len(offsetList)) 
     randomOffset = offsetList[randomOffsetIndex] 
     nextx = self.xpos + randomOffset[0] 
     nexty = self.ypos + randomOffset[1] 
     while not(0 <= nextx < self.world.getMaxX() and 0 <= nexty < self.world.getMaxY()): 
      randomOffsetIndex = random.randrange(len(offsetList)) 
      randomOffset = offsetList[randomOffsetIndex] 
      nextx = self.xpos + randomOffset[0] 
      nexty = self.ypos + randomOffset[1] 

     if self.world.emptyLocation(nextx, nexty): 
      self.move(nextx, nexty) 
+0

順便說一下'randomOffset = random.choice(offsetList)' – furas

+1

是什麼問題?你有錯誤信息嗎?顯示有問題?或者創建最小的工作示例,以便我們可以運行它並查看問題。 – furas

回答

0

我通常不會評論我無法運行的代碼,但我會對此採取措施。以下是我可能如何設計這種方法。

offsetList = [(-1, 1), (0, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)] 

def tryToMove(self): 

    maxX = self.world.getMaxX() 
    maxY = self.world.getMaxY() 

    possibleOffsets = offsetList[:] # make a copy we can change locally 

    while possibleOffsets: 
     possibleOffset = random.choice(possibleOffsets) # ala @furas 

     nextx = self.xpos + possibleOffset[0] 
     nexty = self.ypos + possibleOffset[1] 

     if (0 <= nextx < maxX() and 0 <= nexty < maxY()) and self.world.emptyLocation(nextx, nexty): 
      self.move(nextx, nexty) 
      return True # valid move possible and made 

     possibleOffsets.remove(possibleOffset) # remove invalid choice 

    return False # no valid move possible for various reasons 

我不知道你的意思是:

嘗試多達4個隨機位置對下一步的行動

,因爲有多達8級的可能性,但如果你真的想限制它,然後這裏有一個替代方法,找到所有possibleOffsets,你可以根據需要修剪:

offsetList = [(-1, 1), (0, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)] 

def tryToMove(self): 

    maxX = self.world.getMaxX() 
    maxY = self.world.getMaxY() 

    possibleOffsets = [] 

    for possibleOffset in offsetList: 
     nextx = self.xpos + possibleOffset[0] 
     nexty = self.ypos + possibleOffset[1] 

     if 0 <= nextx < maxX and 0 <= nexty < maxY and self.world.emptyLocation(nextx, nexty): 
      possibleOffsets.append(possibleOffset) 

    if possibleOffsets: 
     offsetX, offsetY = random.choice(possibleOffsets) # ala @furas 
     nextx = self.xpos + offsetX 
     nexty = self.ypos + offsetY 

     self.move(nextx, nexty) 
     return True # valid move possible and made 

    return False # no valid move possible for various reasons 
相關問題