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

Trying to move turtle object to random location

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

我通常不会评论我不能评论的代码 运行 但我会尝试一下。下面是我可能如何设计这种方法。

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

我不明白你的意思:

try up to 4 random locations for its next move

因为最多有 8 种可能性,但如果你真的想限制它,那么这里有一个替代方法可以找到所有 possibleOffsets,你可以根据需要 trim:

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