gpt4 book ai didi

python - 如何让敌人在接触方 block 后随机改变方向

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:15 24 4
gpt4 key购买 nike

糟糕,我想删除它,但它不允许我,抱歉,

最佳答案

它真的想改变方向到非碰撞的方式。 movedirection() 知道它的行进方向,因此可以从选择中删除该方向。

def movedirection(self, x, y):
next_movement = ( x, y ) # no change
self.rect.x = self.rect.x + x
self.rect.y = self.rect.y + y

# If you collide with a wall, move out based on velocity
for block in block_list:
if self.rect.colliderect(block.rect):
if x > 0: # Moving right Hit the left side of the wall
self.rect.right = block.rect.left
directions = [(-2,0),(0,-2),(0,2)] # L, D, U
elif x < 0: # Moving left Hit the right side of the wall
self.rect.left = block.rect.right
directions = [( 2,0),(0,-2),(0,2)] # R, D, U
if y > 0: # Moving down Hit the top side of the wall
self.rect.bottom = block.rect.top
directions = [(-2,0),(2,0),(0,-2)] # L, R, D
elif y < 0: # Moving up Hit the bottom side of the wall
self.rect.top = block.rect.bottom
directions = [(-2,0),(2,0),(0,2)] # L, R, U

# pick a new random direction that does not re-collide
next_movement = random.choice( directions )

# The enemy either continues, or turned
return next_movement

显然,移动逻辑需要更改以合并返回结果:

def move(self, x, y):
return self.movedirection( x, y )

def movmethod(self,godirection,changedirection):
while True:
godirection = move( godirection )

但是 movmethod() 仍然有一个讨厌的无限循环(它永远不会返回)。我会按照 PyGame Sprite 类通常使用 update() 函数处理这个的方式对运动进行建模。这会处理移动和位图更改等。

def update( self ):
x, y = self.godirection # NOTE: now a member variable
self.rect.x = self.rect.x + x
self.rect.y = self.rect.y + y

# If you collide with a wall, move out based on velocity
for block in block_list:
if self.rect.colliderect( block.rect ):
if x > 0: # Moving right Hit the left side of the wall
self.rect.right = block.rect.left
directions = [(-2,0),(0,-2),(0,2)] # L, D, U
elif x < 0: # Moving left Hit the right side of the wall
self.rect.left = block.rect.right
directions = [( 2,0),(0,-2),(0,2)] # R, D, U
if y > 0: # Moving down Hit the top side of the wall
self.rect.bottom = block.rect.top
directions = [(-2,0),(2,0),(0,-2)] # L, R, D
elif y < 0: # Moving up Hit the bottom side of the wall
self.rect.top = block.rect.bottom
directions = [(-2,0),(2,0),(0,2)] # L, R, U

# pick a new random direction that does not re-collide
self.godirection = random.choice( directions )

在主循环中调用 update()

关于python - 如何让敌人在接触方 block 后随机改变方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59035867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com