1
基本上我試圖讓敵人隨機在地圖上移動。我已經實現了這一點,然而隨機移動只發生在牆壁上(使它看起來更自然)。有沒有更好的方法來做到這一點?或者我應該移動我的地圖,讓角色更頻繁地撞牆?PyGame Sprite隨機運動
def update(self, walls, player):
# Check if moving left/right caused a collision
self.rect.x += self.x_speed
walls_hit = pygame.sprite.spritecollide(self, walls, False)
for wall in walls_hit:
if self.x_speed > 0:
self.rect.right = wall.rect.left
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.x_speed = 0
self.y_speed = 3
else:
self.x_speed = 0
self.y_speed = -3
else:
self.rect.left = wall.rect.right
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.x_speed = 0
self.y_speed = 3
else:
self.x_speed = 0
self.y_speed = -3
# Check if moving up/down caused a collision
self.rect.y += self.y_speed
walls_hit = pygame.sprite.spritecollide(self, walls, False)
for wall in walls_hit:
if self.y_speed > 0:
self.rect.bottom = wall.rect.top
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.y_speed = 0
self.x_speed = 3
else:
self.y_speed = 0
self.x_speed = -3
else:
self.rect.top = wall.rect.bottom
tmp = random.randint(0, 1)
print(tmp)
if tmp == 0:
self.y_speed = 0
self.x_speed = 3
else:
self.y_speed = 0
self.x_speed = -3
如果它有助於下面的代碼是我的地圖(1的牆壁= 0的地板=)
GRID = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
任何幫助,將不勝感激!