试图将乌龟物体移动到随机位置

2024-04-19 03:31:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试切换这个方法,让鱼尝试多达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)

Tags: 方法selfworldlendefrandomrandrange办法
1条回答
网友
1楼 · 发布于 2024-04-19 03:31:08

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

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,您可以根据需要进行调整:

^{pr2}$

相关问题 更多 >