只要制作一个简单的游戏就可以实践更多的蚂蚁,如果蚂蚁可以的话,它们会离开并在巢中找到最近的尚未瞄准的食物,因此它们都有自己的路线和目标。他们已经这样做了,但是每当我实际移动精灵时,该组位置属性中的所有精灵似乎都遵循一个蚂蚁而不是它们自己的路径。
import pygame
import settings
import random
vec = pygame.math.Vector2
class Ant(pygame.sprite.Sprite):
def __init__(self, world):
self.world = world
pygame.sprite.Sprite.__init__(self, self.world.ants, self.world.all_sprites)
self.image = pygame.Surface((settings.ANT_RADIUS*2, settings.ANT_RADIUS*2))
self.draw()
self.rect = self.image.get_rect()
self.pos = self.world.nest.pos
self.rect.center = self.pos
self.in_nest = True
self.image.set_colorkey((0, 0, 0))
self.target = False
def update(self):
if self.in_nest:
self.try_leave_nest()
else:
if self.target != False:
self.move_to_food()
else:
self.target = self.find_food()
def draw(self):
pygame.draw.circle(self.image, settings.ANT_COLOUR,
(settings.ANT_RADIUS, settings.ANT_RADIUS), settings.ANT_RADIUS)
def move_to_food(self):
self.direction = vec(self.target.pos-self.pos).normalize()
self.pos += self.direction
self.rect.center = self.pos
print(self.pos)
def find_food(self):
self.closest = settings.WINDOW_WIDTH
self.closest_food = False
for food in self.world.food:
if not food.taken:
self.distance = self.pos.distance_to(food.pos)
if self.distance <= self.closest:
self.closest = self.distance
self.closest_food = food
self.closest_food.taken = True
return self.closest_food
def try_leave_nest(self):
leave_chance = settings.ANT_LEAVE_CHANCE
leave_num = random.random()
if leave_num < leave_chance:
self.in_nest = False
答案 0 :(得分:2)
self.pos = self.world.nest.pos
复制对位置对象的引用,而不是对象本身!
self.pos += self.direction
就地修改对象,这意味着self.world.nest.pos
也被修改。