我正在尝试进行模拟。
我的兔子本应随机移动,但是我希望它们保持相同方向更长的时间,因此,为什么我使用if randomnum == 1
只将方向更改1/10次。
但是当我运行代码时,兔子似乎一举一动都改变了方向。我在做什么错了?
class Rabbit(pygame.sprite.Sprite):
def __init__(self,x,y):
super().__init__()
self.image = pygame.Surface([10,10])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.xchange = 0
self.ychange = 0
self.hp = 100
for rabbit in rabbits:
randomnum = random.randint(1,10)
if randomnum == 1:
xdir = random.randint(-5,5)
ydir = random.randint(-5,5)
rabbit.xchange = xdir
rabbit.ychange = ydir
else:
continue
if rabbit.rect.x+xdir > 10 and rabbit.rect.x+xdir < 390 and rabbit.rect.y+ydir > 10 and rabbit.rect.y+ydir < 390:
rabbit.rect.x += rabbit.xchange
rabbit.rect.y += rabbit.ychange
else:
continue
答案 0 :(得分:0)
将实例属性steps
添加到类Rabbit
并将其初始化为0。该属性说明兔子在当前方向上必须走的步骤。它是在控制兔子的循环中设置和更新的:
class Rabbit(pygame.sprite.Sprite):
def __init__(self,x,y):
# [...]
self.steps = 0
当steps
的数量为0时,创建一个新的随机移动方向并设置steps
的随机数。兔子移动时减少step
的数量。
每次执行循环时,兔子都必须移动。如果兔子碰到了边界,则设置steps = 0
,这将导致在下一帧中设置新的随机方向:
for rabbit in rabbits:
# new direction and number of steps if steps is zero
if self.steps <= 0:
rabbit.xchange = random.randint(-5,5)
rabbit.ychange = random.randint(-5,5)
rabbit.steps = random.randint(1,10)
# decrement the number of steps
rabbit.steps -= 1
# verify if the rabbit is in bounds and move
xdir, ydir = rabbit.xchange, rabbit.ychange
if rabbit.rect.x+xdir > 10 and rabbit.rect.x+xdir < 390 and rabbit.rect.y+ydir > 10 and rabbit.rect.y+ydir < 390:
rabbit.rect.x += rabbit.xchange
rabbit.rect.y += rabbit.ychange
else:
rabbit.steps = 0
答案 1 :(得分:0)
它是continue
。他们跳过了循环主体的其余部分,这在这里是不需要的:
if
中,只要兔子的方向不变,它也不会移动。continue
跳过第二个if
并前进到下一个兔子if
中,continue只是使循环继续进行到下一个兔子,它仍然会这样做修复:删除它们。
for rabbit in rabbits:
randomnum = random.randint(1,10)
if randomnum == 1:
xdir = random.randint(-5,5)
ydir = random.randint(-5,5)
rabbit.xchange = xdir
rabbit.ychange = ydir
if rabbit.rect.x+xdir > 10 and rabbit.rect.x+xdir < 390 and rabbit.rect.y+ydir > 10 and rabbit.rect.y+ydir < 390:
rabbit.rect.x += rabbit.xchange
rabbit.rect.y += rabbit.ychange
备注:
if
-s:仅仅因为兔子到达屏幕的左侧,它不必完全停止移动(y坐标仍可以更新)。