[ad_1]
I’m trying to get a turtle sprite to chase a falling algae sprite utilising Pygame’s inbuilt functionality. I have spent many hours reviewing questions and answers and suspect I’m missing some foundational logic as a beginner.
Below is the full code pared down to essential lines only.
No errors are displayed, yet the turtle sprite does not move.
import pygame
import random
from random import randint
#GLOBAL VARIABLES
BACKGROUND_COLOR = pygame.Color('black')
screen_width = 1400
screen_height = 1000
win = pygame.display.set_mode((screen_width, screen_height))
display_surface = pygame.display.get_surface()
display_rect = display_surface.get_rect()
clock = pygame.time.Clock()
class Turtle(pygame.sprite.Sprite):
def __init__(self):
super(Turtle, self).__init__()
self.image = pygame.image.load('T10.png').convert_alpha()
self.x = random.randrange(60, (screen_width - 60), 1)
self.y = random.randrange(60, (screen_height - 60), 1)
self.pos = pygame.Vector2(self.x, self.y)
self.rect = self.image.get_rect()
self.rect.x = self.x
self.rect.y = self.y
self.velocity = 5
def move(self):
self.pos.move_towards_ip(algae.pos, self.velocity)
def update(self):
self.move()
class Algae(pygame.sprite.Sprite):
def __init__(self):
super(Algae, self).__init__()
self.width = 20
self.height = 20
self.surf = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
self.rect = self.surf.get_rect()
self.x = -5
self.y = -5
self.pos = pygame.Vector2(self.x, self.y)
pygame.draw.circle(self.surf, pygame.Color('green'), (10, 10), 4)
self.list = []
pygame.init()
pygame.display.set_caption("EvoSim")
turtle = Turtle()
algae = Algae()
turtle_group = pygame.sprite.Group(turtle)
algae_group = pygame.sprite.Group(algae)
all_sprites = pygame.sprite.Group()
collide_list = pygame.sprite.Group(algae) #not currently in use
algae_spawn = pygame.USEREVENT + 1 #algae spawn event
pygame.time.set_timer(algae_spawn, randint(0, 10000)) #algae spawn timer
def main():
while True:
clock.tick(15)
bg = pygame.image.load('bg.png')
win.blit(bg, (0, 0))
turtle.rect.clamp_ip(pygame.display.get_surface().get_rect())
turtle_group.draw(win)
turtle_group.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == algae_spawn: #falling algae spawn on random timer
algae.x = random.randrange(10, win.get_width()-10)
algae.list.append(pygame.Rect(algae.x, -20, 20, 20))
collide_list.add(algae)
for algae.rect in algae.list[:]:
algae.rect.y += 1
if algae.rect.top > win.get_height():
algae.list.remove(algae.rect)
for algae.rect in algae.list:
win.blit(algae.surf, algae.rect)
pygame.display.update()
if __name__ == '__main__':
main()
[ad_2]