试图将龟对象移动到随机位置

时间:2016-11-13 02:22:42

标签: python random methods turtle-graphics

我正试图改变这种方法,让鱼可以尝试最多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)

1 个答案:

答案 0 :(得分: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