Reputation: 5
Just making a simple game to practise more than anything where ants start in a nest they leave if they can and find the nearest food that isn't already targeted, so they each have their own path and target. They do this already but whenever I actually move the sprites all the sprites in this group position attributes seem to follow one ants instead of their own path.
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
Upvotes: 0
Views: 105
Reputation: 10959
self.pos = self.world.nest.pos
Copies a reference to the position object, not the object itself!
self.pos += self.direction
Modifies the object inplace, meaning self.world.nest.pos
is modified, too.
Upvotes: 2