Cannot import name 'Actor' from 'pygame.sprite'

65 Views Asked by At

I have the following python / pygame code:

import pygame
import time

pygame.init()

WIDTH = 800
HEIGHT = 600

from pygame.sprite import Actor

alien = Actor('alien')

def draw():
    alien.draw()

pygame.quit()

When I run it I get the error:

ImportError: cannot import name 'Actor' from 'pygame.sprite'     (/Library/Python/3.9/lib/python/site-packages/pygame/sprite.py)

Do I need my own image? I also have an images/alien.png on the same folder as the code.

How to solve this?

1

There are 1 best solutions below

0
oBrstisf8o On

As @Rabbid76 said, Actor is from Pygame Zero not Pygame. The equivalent code for Pygame would look like this:

# It's unlikely that you need time module,
# it's not a good idea to freeze game by sleeping x seconds
# and if you need time elapsed, pygame already has what you need.
## import time

import pygame
from pygame.sprite import Sprite, Group

pygame.init()

WIDTH = 800
HEIGHT = 600
# We can limit the frame rate of the game
FPS = 60

ALIEN_IMAGE = pygame.image.load("images/alien.png")

# There are many ways of implementing sprites in pygame, but this is the typical one.
# Here I'm creating a new class called "AlienSprite", if I wanted to add logic for an alien, I would add it in the class.
class AlienSprite(Sprite):
    def __init__(self, pos, *groups):
        # This is required for the code to work.
        super().__init__(*groups)
        
        self.image = ALIEN_IMAGE
        self.rect = self.image.get_rect()
        self.rect.center = pos


# We need to create window explicitly.
window = pygame.display.set_mode((WIDTH, HEIGHT))
# For limiting the framerate
clock = pygame.time.Clock()

# You can have multiple aliens using this approach.
sprites = Group()
sprites.add(AlienSprite((200, 200)))
sprites.add(AlienSprite((600, 400)))

# Maing game loop
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # Clear screen
    window.fill((0, 0, 0)) 
    
    # Draw sprites
    sprites.draw(window)
    
    # Apply changes to the screen
    pygame.display.flip()
    
    # Limiting the frame rate to roughly 60 frames a second.
    clock.tick(FPS)

Please forgive me sending the whole program, that contains more than just how to use pygame Sprites - I don't know your experience level, what you are familiar with and with not.