Alien class has no rect attribute - python

I'm trying to make a basic shooting game with sprites. I get an error on the line alien.rect.x in my for loop when I try to run. It says that my object Alien has no rect attribute. I thought self.rect = self.image.get_rect () in my Alien class takes care of that? What am I doing wrong? Do I need Sprite lists for this?
#Created by Mark Schaeffler 4/17/18
import pygame
import random
import sys
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
PLAYERMOVERATE = 5
# set up pygame, the window, and the mouse cursor
pygame.init()
clock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Alien Invasion')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.Font(None, 48)
# set up sounds
game_over_sound = pygame.mixer.Sound("gameover.wav")
background_music = pygame.mixer.Sound("Background_Music.ogg")
click_sound = pygame.mixer.Sound("laser5.ogg")
#Terminate
def terminate():
pygame.quit()
sys.exit()
#Class for player
class Player(pygame.sprite.Sprite):
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()
#Load player image
self.image = pygame.image.load("Player1.png").convert()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
def update(self):
# Update the player's position
# Get the current mouse position.
pos = pygame.mouse.get_pos()
# Set the player x, y position
self.rect.x = pos[0]
self.rect.y = pos[0]
#Class for bullets
class Bullet(pygame.sprite.Sprite):
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.Surface([4, 10])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
def update(self):
# Move the bullet
self.rect.y -= 3
#Class for aliens
class Aliens(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Aliensprite1")
self.rect = self.image.get_rect()
def reset_pos(self):
self.rect.y = random.randrange(-300, -20)
self.rect.x = random.randrange(0, WINDOWWIDTH)
def update(self):
# Move alien down one pixel
self.rect.y += 1
# If alien is too far down, reset to top of screen.
if self.rect.y > 610:
self.reset_pos()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: # pressing escape
quits
terminate()
return
# List of every sprite. All aliens, bullets, player
all_sprites_list = pygame.sprite.Group()
# List of each alien in the game
alien_list = pygame.sprite.Group()
# List of each bullet
bullet_list = pygame.sprite.Group()
for i in range(50):
# This represents an alien
alien = Aliens
# Set random location for the aliens
alien.rect.x = random.randrange(WINDOWWIDTH)
# Add aliens to the list of objects
alien_list.add(alien)
all_sprites_list.add(alien)
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# "Start" screen
drawText('Alien Invasion', font, windowSurface, (WINDOWWIDTH / 3),
(WINDOWHEIGHT / 3))
drawText('Press any key to start.', font, windowSurface, (WINDOWWIDTH
/ 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
score = 0
topScore = 0
player.rect.y = 370
background_music.play()
# -------- Main Program Loop -----------

You need to create an instance of the Aliens class, you are missing the brackets:
alien = Aliens()
This invokes the class constructor and creates a new object of Aliens.

Replace alien = Aliens with alien = Aliens() :)

Related

pygame sprite collision ... how can i cheak for sprite collision?

from numpy import place
import pygame, sys ,random as ran
start = True
class Player(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
super().__init__()
self.attack_animation = False
self.sprites_1 = []
self.sprites_1.append(pygame.image.load('crossHair.png'))
self.sprites_1.append(pygame.image.load('crossHair_2.png'))
self.sprites_1.append(pygame.image.load('crossHair_3.png'))
self.sprites_1.append(pygame.image.load('crossHair_4.png'))
self.sprites_1.append(pygame.image.load('crossHair_5.png'))
self.sprites_1.append(pygame.image.load('FIRE.png'))
self.current_sprite = 0
self.image = self.sprites_1[self.current_sprite]
self.image.set_colorkey('white')
for items in self.sprites_1:
items.set_colorkey('white')
self.rect = self.image.get_rect()
self.rect.topleft = [pos_x,pos_y]
def attack(self):
self.attack_animation = True
self.image.set_colorkey('white')
def update(self,speed):
self.image.set_colorkey('white')
if self.attack_animation == True:
self.current_sprite += speed
if int(self.current_sprite) >= len(self.sprites_1):
self.current_sprite = 0
self.attack_animation = False
print('shot')
self.image = self.sprites_1[int(self.current_sprite)]
# self.image = self.sprites_1[int(self.current_sprite)]
mouse = pygame.mouse.get_pos()
self.rect = mouse
class enemy(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
super().__init__()
self.image = pygame.image.load('sp_1.png')
self.rect = self.image.get_rect()
self.rect.center = [pos_x, pos_y]
self.image.set_colorkey((255,255,255))
# General setup
pygame.init()
pygame.mouse.set_visible(0)
clock = pygame.time.Clock()
# Game Screen
screen_width = 400
screen_height = 400
mouse = pygame.mouse.get_pos()
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Sprite Animation")
# Creating the sprites and groups
moving_sprites = pygame.sprite.Group()
crosshair = Player(mouse[0],mouse[1])
enemy_x = ran.randint(18,387)
enemy_y = ran.randint(18,387)
print(enemy_x,enemy_y)
enemy_ = enemy(enemy_x,enemy_y)
moving_sprites.add(enemy_,crosshair)
while True:
# Player.set_pos(*pygame.mouse.get_pos())
globals()['mouse'] = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
crosshair.attack()
enemy.checkCollision(enemy,crosshair,enemy_)
# enemy.attack()
# pygame.sprite.spritecollide(Player,enemy,True)
screen.fill((120,220,150))
#this is causing the problem
get_hit = pygame.sprite.spritecollide(Player,enemy,True)
# Drawing
screen.set_colorkey('white')
moving_sprites.draw(screen)
moving_sprites.update(0.08)
pygame.display.flip()
clock.tick(120)
the movement i check for sprite collision it gives me error sayin' :
File "c:\Users\pc\VS_PYTHON_PY\pyGame.py", line 82, in
get_hit = pygame.sprite.spritecollide(Player,enemy,True)
File "C:\python-py\lib\site-packages\pygame\sprite.py", line 1682, in spritecollide
default_sprite_collide_func = sprite.rect.colliderect
AttributeError: type object 'Player' has no attribute 'rect'
why is that happening can you solve this pls
The arguments of pygame.sprite.spritecollide must be instance objects of Sprite and Group classes. Player and enemy are a classes, however crosshair and enemy_ are objects. Create a Group for the enemies and detect the collisions between the crosshair and the Group of enemies:
crosshair = Player(mouse[0],mouse[1])
enemyGroup = pygame.sprite.Group()
enemy_ = enemy(enemy_x,enemy_y)
enemyGroup.add(enemy_)
while True:
# [...]
get_hit = pygame.sprite.spritecollide(crosshair, enemyGroup, True)
See also How do you program collision in classes? and How do I detect collision in pygame?.
Also see Style Guide for Python Code: Class names should normally use the CapWords convention. The name of the class should be Enemy instead of enemy.

Pygame mask collision only putting damage on base on first collision

I am writing a simple invaders game. To add damage to the bases I figured I could blit a small, black surface on the base at bullet impact, and use a mask to check if the bullet was on the damage or the base, but it isn't working and I feel I am misunderstanding the mask. The first collision is detected but after that it also detects a collision but doesn't put any more damage on the base. I thought because the surface was black the base mask wouldn't include it, but it isn't working. Here is a short test to demo this. Press space (or any key) to fire a bullet at the base. I thought maybe I should generate a new mask for the base but that doesn't work. The mask collide is from the pygame sprite code on github.
import sys, pygame, random
from pygame.locals import *
screenwidth = 600
screenheight = 400
pygame.init()
screen = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption("shoot 'em up")
screenrect = screen.get_rect()
black = (0, 0, 0)
blue = (10, 10, 255)
yellow = (238, 238, 0)
base_width = 80
base_height = 40
bullet_width = 3
bullet_height = 10
class Bullet(pygame.Surface):
def __init__(self, point):
super().__init__((bullet_width, bullet_height), pygame.SRCALPHA)
self.rect = self.get_rect()
self.rect.midbottom = point
self.fill(yellow)
self.velocity = -5
self.alive = True
self.mask = pygame.mask.from_surface(self)
def update(self):
self.rect.top += self.velocity
def draw(self, surf):
surf.blit(self, self.rect)
class Base(pygame.Surface):
def __init__(self, x, y, colour):
super().__init__((base_width, base_height), pygame.SRCALPHA)
self.rect = self.get_rect()
self.rect.x = x
self.rect.y = y
self.fill(colour)
self.alive = True
def add_damage(self, bullet):
width = random.randint(3, 6)
height = random.randint(8, 12)
damage = pygame.Surface((width, height), pygame.SRCALPHA)
damage.fill(black)
rect = damage.get_rect()
rect.x = bullet.rect.x - self.rect.x
rect.y = bullet.rect.top - self.rect.top
self.blit(damage, rect)
#self.mask = pygame.mask.from_surface(self)
def draw(self, surf):
surf.blit(self, self.rect)
class Test(pygame.Surface):
def __init__(self):
super().__init__((600, 400))
self. base = Base(50, 300, blue)
self.bullets = []
def run(self):
while 1:
self.get_events()
self.update()
self.draw()
def get_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
bullet = Bullet((60, 380))
self.bullets.append(bullet)
def update(self):
if self.bullets:
for bullet in self.bullets:
bullet.update()
self.collision_check(bullet)
for bullet in self.bullets:
if not bullet.alive:
self.bullets.remove(bullet)
def collision_check(self, bullet):
if bullet.rect.colliderect(self.base):
if self.collide_mask(bullet, self.base):
print("collide")
self.base.add_damage(bullet)
bullet.alive = False
def collide_mask(self, left, right):
xoffset = right.rect[0] - left.rect[0]
yoffset = right.rect[1] - left.rect[1]
try:
leftmask = left.mask
except AttributeError:
leftmask = pygame.mask.from_surface(left)
try:
rightmask = right.mask
except AttributeError:
rightmask = pygame.mask.from_surface(right)
return leftmask.overlap(rightmask, (xoffset, yoffset))
def draw(self):
self.fill(black)
self.base.draw(self)
for bullet in self.bullets:
bullet.draw(self)
screen.blit(self, (0,0))
pygame.display.flip()
if __name__=="__main__":
t = Test()
t.run()
As you can see this is not using pygame sprites.
if the pygame.Surface object is changed you need to recreate the mask with pygame.mask.from_surface. However, the mask is generated form the Surface's alpha channel. Therefore, you need to make the damaged area transparent. Create a completely transparent rectangle (RGBA = 0, 0, 0, 0) and blit the rectangle using the special flag BLEND_RGBA_MULT (or BLEND_RGBA_MIN). Finally recreate the mask:
damage = pygame.Surface((width, height), pygame.SRCALPHA)
self.blit(damage, rect, special_flags=pygame.BLEND_RGBA_MULT)
self.mask = pygame.mask.from_surface(self)
add_damage Mehtod:
class Base(pygame.Surface):
# [...]
def add_damage(self, bullet):
width = random.randint(3, 6)
height = random.randint(8, 12)
damage = pygame.Surface((width, height), pygame.SRCALPHA)
rect = damage.get_rect()
rect.x = bullet.rect.x - self.rect.x
rect.y = bullet.rect.top - self.rect.top
self.blit(damage, rect, special_flags=pygame.BLEND_RGBA_MULT)
self.mask = pygame.mask.from_surface(self)

How do you move a sprite in pygame?

I know that this question has already been answered in other forms, but I can't seem to make it work for my game. I'm trying to make the sprite move and keep him in the place he moved to. This is part of my code:
class player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
def draw(self, x, y):
player = pygame.image.load("stand_down.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
screen.blit(player, (x, y))
pygame.display.update()
for event in pygame.event.get():
key = pygame.key.get_pressed()
if event.type == KEYDOWN :
if key [K_LEFT] :
player = pygame.image.load("standleft.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
x -= 50
screen.blit(player, (x, y))
pygame.display.update()
pygame.sprite.Sprite.update(player)
if key [K_RIGHT]:
player = pygame.image.load("standright.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
x += 50
screen.blit(player, (x, y))
pygame.display.update()
pygame.sprite.Sprite.update(player)
def update(self):
pygame.sprite.Sprite.update(player)
And then this is part of my main function:
player.draw(screen, x, y)
player.update(screen)
I've tried everything I can think of, but the player just keeps flashing at a different point, then returning to the previous position. If you could help, it would be much appreciated!
I can't test it but I would do this
# --- classes ---
class Player(pygame.sprite.Sprite): # UpperCaseName for class
def __init__(self, x, y):
super().__init__()
temp_image = pygame.image.load("stand_down.png").convert_alpha()
self.image_down = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standleft.png").convert_alpha()
self.image_left = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standright.png").convert_alpha()
self.image_right = pygame.transform.scale(temp_image, (100, 200))
self.image = self.image_down
# keep position and size in pygame.Rect()
# to use it in collision checking
self.rect = self.image.get_rect(x=x, y=y)
def draw(self, screen):
screen.blit(self.image, self.rect)
def handle_event(self):#, event)
self.image = self.image_down
key = pygame.key.get_pressed()
if key[K_LEFT]:
self.rect.x -= 50
self.image = self.image_left
if key[K_RIGHT]:
self.rect.x += 50
self.image = self.image_right
def update(self, enemy):
# check collision with eneny
if self.rect.colliderect(enemy.rect):
print("I'm killed by enemy")
# --- main ---
player = Player(400, 400)
enemy = Enemy(100, 100)
while True:
# - events -
for event in pygame.event.get():
#player.handle_event(event)
player.handle_event()
# - updates -
enemy.update()
player.update(enemy)
# - draws -
screen.fill( (0,0,0) )
player.draw(screen)
enemy.draw(screen)
pygame.display.update()

My game keeps calling a method for the wrong sprite

When i try to run the game the code tries to run a method for the wrong sprite. I think the line "player.handle_keys()" is the problem as when i run it, it says that it can't find a "handle_keys()" method for the "meteor" class. I haven't got a line to run a "meteor.handle_keys()" as this class should not have this method.
Here is the code:
import pygame
import random
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
bg = pygame.image.load("bg1.png")
class space_ship(pygame.sprite.Sprite):
def __init__(self, color, width, height):
super().__init__()
# Create an image of the space_ship1, and fill it with a color.
# This could also be an image loaded from the disk.
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
#draw image
self.image = pygame.image.load("player1.gif").convert()
# Draw the ellipse
#pygame.draw.ellipse(self.image, color, [0, 0, width, height])
# x and y coordinates
self.x = 500
self.y = 450
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 5 # distance moved in 1 frame
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
class asteroid(pygame.sprite.Sprite):
def __init__(self, color, width, height):
super().__init__()
# Create an image of the space_ship1, and fill it with a color.
# This could also be an image loaded from the disk.
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
# Draw the ellipse
#pygame.draw.ellipse(self.image, color, [0, 0, width, height])
self.image = pygame.image.load("ast1.gif").convert()
# x and y coordinates
self.x = random.randint(50,950)
self.y = 10
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
def fall(self):
dist = 5
self.y +=dist
if self.y > 600:
self.x = random.randint(50,950)
self.y = random.randint(-2000, -10)
def respawn(self):
self.y = -10
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width = 1000
screen_height = 600
screen = pygame.display.set_mode([screen_width, screen_height])
# This is a list of 'sprites.' Each sprite in the program is
# added to this list.
# The list is managed by a class called 'Group.'
asteroid_list = pygame.sprite.Group()
# This is a list of every sprite.
# All asteroids and the player as well.
all_sprites_list = pygame.sprite.Group()
player = space_ship(RED, 20, 15)
all_sprites_list.add(player)
asteroid_1 = asteroid(BLACK, 40, 40)
asteroid_list.add(asteroid_1)
all_sprites_list.add(asteroid_1)
asteroid_2 = asteroid(BLACK, 40, 40)
asteroid_list.add(asteroid_2)
all_sprites_list.add(asteroid_2)
asteroid_3 = asteroid(BLACK,40, 40)
asteroid_list.add(asteroid_3)
all_sprites_list.add(asteroid_3)
asteroid_4 = asteroid(BLACK,40, 40)
asteroid_list.add(asteroid_4)
all_sprites_list.add(asteroid_4)
asteroid_5 = asteroid(BLACK,40, 40)
asteroid_list.add(asteroid_5)
all_sprites_list.add(asteroid_5)
asteroid_6 = asteroid(BLACK,40, 40)
asteroid_list.add(asteroid_6)
all_sprites_list.add(asteroid_6)
asteroid_7 = asteroid(BLACK,40, 40)
asteroid_list.add(asteroid_7)
all_sprites_list.add(asteroid_7)
asteroid_8 = asteroid(BLACK,40, 40)
asteroid_list.add(asteroid_8)
all_sprites_list.add(asteroid_list)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
score = 0
# ----------------- Main Program Loop --------------------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#Call upon function
player.handle_keys()
# Clear the screen
screen.fill(WHITE)
#INSIDE OF THE GAME LOOP
screen.blit(bg, (0, 0))
# See if the player space_ship1 has collided with anything.
blocks_hit_list = pygame.sprite.spritecollide(player, asteroid_list, True)
# Check the list of collisions.
for player in blocks_hit_list:
score +=1
print(score)
# Draw all the spites
player.draw(screen)
asteroid_1.draw(screen)
asteroid_1.fall()
asteroid_2.draw(screen)
asteroid_2.fall()
asteroid_3.draw(screen)
asteroid_3.fall()
asteroid_4.draw(screen)
asteroid_4.fall()
asteroid_5.draw(screen)
asteroid_5.fall()
asteroid_6.draw(screen)
asteroid_6.fall()
asteroid_7.draw(screen)
asteroid_7.fall()
asteroid_8.draw(screen)
asteroid_8.fall()
#all_sprites_list.draw(screen)
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
You are overriding player in your for loop
# Check the list of collisions.
for player in blocks_hit_list:
score +=1
print(score)
change it to something else and all will be good
# Check the list of collisions.
for something_else in blocks_hit_list:
score +=1
print(score)
Enjoy

adding sprites to a group

I am trying to display a group of Sprite to the screen, however, my code below displays a blank screen. I've been at this for a while and i dont know why this doesnt work at the logic seems correct. the main problem occurs in the sprite method where i am trying to add the sprites at a random position. The sprites are then drawn in the gameLoop method.
Any suggestions?
import pygame, sys, random
pygame.init()
troll = pygame.image.load("image.png")
black = (0, 0, 0)
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 400
sprite_width = 5
sprite_height = 5
spriteCount = 5
class Sprite(pygame.sprite.Sprite):
pygame.init()
sprite = pygame.sprite.Group()
clock = pygame.time.Clock()
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def __init__(self, Image, pos):
pygame.sprite.Sprite.__init__(self)
self.image =pygame.Surface([0, 0])
self.rect = self.image.get_rect()
self.rect.topleft = pos
#classmethod
def sprite(self):
for i in range(spriteCount):
tmp_x = random.randrange(0, SCREEN_WIDTH)
tmp_y = random.randrange(0, SCREEN_HEIGHT)
# all you have to do is add new sprites to the sprite group
self.sprite.add(Sprite(troll, [tmp_x, tmp_y]))
def update(self):
self.rect.x += 1
self.rect.y += 2
if self.rect.y > SCREEN_HEIGHT:
self.rect.y = -1 * sprite_height
if self.rect.x > SCREEN_WIDTH:
self.rect.x = -1 * sprite_width
#classmethod
def setImage(self,Image):
self.image=pygame.image.load(Image)
#classmethod
def gameLoop(self):
screen = pygame.display.set_mode([640, 400])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(black)
# to update or blitting just call the groups update or draw
# notice there is no for loop
# this will automatically call the individual sprites update method
self.actor.update()
self.actor.draw(screen)
pygame.display.update()
self.clock.tick(20)
Sprite.sprite()
Sprite.setImage("image.png")
Sprite.gameLoop()
#classmethod
def setImage(self,Image):
self.image=pygame.image.load(Image)
Here, you should name the first parameter cls, not self, since it's a class method, not an instance method. Also, parameter-names should be lowercase (image instead of Image).
#classmethod
def gameLoop(self):
screen = pygame.display.set_mode([640, 400])
while True:
...
Same here. Also, I don't know why your gameloop is part of your Sprite class. Also, you should not name your class Sprite in the first place, as it will just create confusion with pygame's Sprite class.
class Sprite(pygame.sprite.Sprite):
...
sprite = pygame.sprite.Group()
...
#classmethod
def sprite(self):
...
Here you have a field called sprite and a class level function sprite. This will not work, as the method will overwrite the field. So whenever you want to access the field sprite, you will access the function sprite instead.
#classmethod
def gameLoop(self):
...
self.actor.update()
Sprite.actor does not exit. You never created such a field.
def __init__(self, Image, pos):
pygame.sprite.Sprite.__init__(self)
self.image =pygame.Surface([0, 0])
self.rect = self.image.get_rect()
self.rect.topleft = pos
Here, you pass an argument called Image. However, you don't use it but an empty Surface .
Here's a running version of your code:
import pygame, sys, random
pygame.init()
troll = pygame.image.load("image.png")
black = pygame.color.Color('black')
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 400
spriteCount = 5
class Sprite(pygame.sprite.Sprite):
actors = pygame.sprite.Group()
clock = pygame.time.Clock()
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def __init__(self, image, pos):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect()
self.rect.topleft = pos
#classmethod
def init(self):
for i in range(spriteCount):
tmp_x = random.randrange(0, SCREEN_WIDTH)
tmp_y = random.randrange(0, SCREEN_HEIGHT)
self.actors.add(Sprite(troll, [tmp_x, tmp_y]))
def update(self):
self.rect.x += 1
self.rect.y += 2
if self.rect.y > SCREEN_HEIGHT:
self.rect.y = -1 * self.rect.height
if self.rect.x > SCREEN_WIDTH:
self.rect.x = -1 * self.rect.width
#classmethod
def gameLoop(self):
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(black)
self.actors.update()
self.actors.draw(screen)
pygame.display.update()
self.clock.tick(20)
Sprite.init()
Sprite.gameLoop()

Categories