This question already has an answer here:
What does pygame.sprite.Group() do
(1 answer)
Closed 8 months ago.
I'm trying to draw a sprite to the screen using the class Player, but I get a traceback. It seems to be complaining when I draw the object to the screen, I'm not really sure what's causing it. I'm new to pygame so I figure that there is something that I am using wrong, or that I am missing, that I don't quite understand.
Here is my code:
import pygame
from sys import exit
# initilaization
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Bullet hell')
class Player(pygame.sprite.Sprite):
'''The Main player class'''
def __init__(self):
super().__init__()
self.player_image = pygame.image.load('sprites/player/player.png').convert_alpha()
self.player_rect = self.player_image.get_rect(topleft = (0, 0))
# Player
player = pygame.sprite.GroupSingle()
player.add(Player())
# main game loop
while True:
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
player.draw(screen)
pygame.display.update()
It produces this error:
Traceback (most recent call last):
File "/home/linkio/Projects/bullet-hell-game/main.py", line 29, in <module>
player.draw(screen)
File "/home/linkio/.local/lib/python3.10/site-packages/pygame/sprite.py", line 552, in draw
zip(sprites, surface.blits((spr.image, spr.rect) for spr in sprites))
File "/home/linkio/.local/lib/python3.10/site-packages/pygame/sprite.py", line 552, in <genexpr>
zip(sprites, surface.blits((spr.image, spr.rect) for spr in sprites))
AttributeError: 'Player' object has no attribute 'image'
I needed to change my class attribute names. Sprite classes seem to work based on specific keywords as attributes.
class Player(pygame.sprite.Sprite):
'''The Main player class'''
def __init__(self):
super().__init__()
self.image = pygame.image.load('sprites/player/player.png').convert_alpha()
self.rect = self.image.get_rect(topleft = (0, 0))
Related
I can't find the mistake. Trying for hours.
When I run the code, I get the message:
Ballons' object has no attribute 'image'
The message in detail:
Traceback (most recent call last):
File "c:\pythonprogramm\ballon_jagd copy.py", line 47, in
ballon_sprites.draw(spielfeld)
File "C:\Users\chef\AppData\Local\Programs\Python\Python39\lib\site-packages\pygame\sprite.py", line 546, in draw
surface.blits((spr.image, spr.rect) for spr in sprites)
File "C:\Users\chef\AppData\Local\Programs\Python\Python39\lib\site-packages\pygame\sprite.py", line 546, in
surface.blits((spr.image, spr.rect) for spr in sprites)
AttributeError: 'Ballons' object has no attribute 'image'
Here is the code:
class Ballons(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
z_bild = pygame.image.load("Bilder/ballons/ballon1.png")
self.einzel_bild = z_bild
self.rect = self.einzel_bild.get_rect()
self.rect_x = random.randint(100,1800)
self.rect_y = 700
def update(self):
self.rect_y -=5
def draw_bg():
spielfeld.fill(bg)
#Allgemein..............................................
pygame.init()
clock = pygame.time.Clock()
bg = (50,250,50)
#Spielfeld..............................................
bild_breite = 1920
bild_hoehe = 1080
spielfeld = pygame.display.set_mode((bild_breite,bild_hoehe))
#Erstellung Sprite und Group
ballon_sprites = pygame.sprite.Group()
ballon = Ballons()
ballon_sprites.add(ballon)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#Zeichnen
draw_bg()
ballon_sprites.draw(spielfeld)
ballon_sprites.update()
pygame.display.flip()
clock.tick(60)nter code here
pygame.sprite.Group.draw() uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects. See pygame.sprite.Group.draw():
Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]
Therefore a Ballon must have an attribute with the name image:
class Ballons(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Bilder/ballons/ballon1.png")
self.rect = self.image.get_rect()
self.rect_x = random.randint(100,1800)
self.rect_y = 700
def update(self):
self.rect_y -=5
This question already has an answer here:
Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?
(1 answer)
Closed 1 year ago.
I keep getting this error. Here's the full traceback.
Traceback (most recent call last):
File "C:/Users/Luc/PycharmProjects/game_practice/game.py", line 23, in
<module>
run_game()
File "C:/Users/Luc/PycharmProjects/game_practice/game.py", line 13, in
run_game
player = Player(ai_settings, screen)
File "C:\Users\Luc\PycharmProjects\game_practice\player.py", line 8, in
__init__
self.rect.centerx = screen.rect.left
AttributeError: 'pygame.Surface' object has no attribute 'rect'
Here's the code for the "Player" file that's having an issue:
class Player:
def __init__(self, ai_settings, screen):
self.screen = screen
self.screen_rect = screen.get_rect()
self.rect = pygame.Rect((0, 0), (ai_settings.player_width,
ai_settings.player_height))
self.rect.centerx = screen.rect.left
self.rect.centery = screen.rect.ai_settings.screen_height / 2
self.color = ai_settings.player_color
def draw_player(self):
pygame.draw.rect(self.screen, self.color, self.rect)
When I comment these two lines:
self.rect.centerx = screen.rect.left
self.rect.centery = screen.rect.ai_settings.screen_height / 2
The program runs with the rectangle initialized at (0,0) like its supposed to, so I am not really sure why the object has an attribute error when I include the other lines.
The screen is a pygame.Surface which has no rect attribute, but you can get a rect with the size of the surface by calling screen.get_rect() what you already do in this line:
self.screen_rect = screen.get_rect()
Now you just have to use your self.screen_rect instead of screen.rect and your code should work.
# To place the player at the midleft.
self.rect.midleft = self.screen_rect.midleft
Im learning how to use pygame and I'm trying to use multiple images with the same sprite. I want the sprites image to change when i press a button on my keyboard. Whenever i press the right arrow key and attempt to change the sprites image I get the error:
Traceback (most recent call last):
File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 55, in <module>
game.execute()
File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 50, in execute
self.render()
File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 32, in render
self.all.draw(self.screen)
File "C:\Users\theotheo36\Downloads\WinPython-64bit-3.4.4.3Qt5\python-3.4.4.amd64\lib\site-packages\pygame\sprite.py", line 475, in draw
self.spritedict[spr] = surface_blit(spr.image, spr.rect)
TypeError: invalid destination position for blit
Here is my code:
import pygame
from pygame.locals import *
class Camel(pygame.sprite.Sprite):
def __init__(self,x,y):
super().__init__()
self.faceleft=True
self.faceright=False
self.image=pygame.image.load('camel.png').convert()
self.rect=self.image.get_rect()
self.rect.x=x
self.rect.y=y
def look(self):
if self.faceleft==True:
self.image=pygame.image.load('camel.png').convert()
self.rect=self.image.get_rect()
elif self.faceright==True:
self.image=pygame.image.load('camelright.png').convert()
self.rect=self.image.get_rect
class Game(Camel):
def __init__(self):
pygame.init()
self.screen=pygame.display.set_mode((800,800))
self.all=pygame.sprite.Group()
self.camel=Camel(200,200)
self.all.add(self.camel)
self.running=True
def render(self):
self.screen.fill((255,255,255))
self.all.draw(self.screen)
pygame.display.update()
def events(self,event):
if event.type==pygame.QUIT:
self.running=False
if event.type==KEYDOWN:
if event.key==K_RIGHT:
self.camel.faceleft=False
self.camel.faceright=True
self.camel.look()
if event.key==K_LEFT:
self.camel.faceright=False
self.camel.faceleft=True
self.camel.look()
def collisons(self):
pass
def execute(self):
while (self.running):
self.render()
for event in pygame.event.get():
self.events(event)
game=Game()
game.execute()
Don't forget the parentheses after self.rect=self.image.get_rect in your look method. Without parenthesis self.rect is assigned to the function instead of the returned rectangle. Since this rectangle is used to draw the image it will cause this position error.
I'm currently in the process of writing a larger program in python. It is a simple game, but I've got an Error. Can someone help me?
Error
Traceback (most recent call last):
File "C:/Users/kkuja/Desktop/game.py", line 36, in <module>
MainWindow.MainLoop()
File "C:/Users/kkuja/Desktop/game.py", line 17, in MainLoop
self.chicken_sprites.draw(self.screen)
File "C:\Users\kkuja\AppData\Local\Programs\Python\Python35\lib\site-packages\pygame\sprite.py", line 475, in draw
self.spritedict[spr] = surface_blit(spr.image, spr.rect)
AttributeError: 'Chicken' object has no attribute 'rect'
Code
import os, sys
import pygame
class Game:
def __init__(self, width=640, height=480):
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode([self.width, self.height])
def MainLoop(self):
self.ChickenLoad();
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.chicken_sprites.draw(self.screen)
pygame.display.flip()
def ChickenLoad(self):
self.chicken = Chicken()
self.chicken_sprites = pygame.sprite.Group(self.chicken)
class Chicken(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("chic.jpg")
if __name__ == "__main__":
MainWindow = Game()
MainWindow.MainLoop()
Thanks in advance!
In the function self.chicken_sprites.draw(self.screen) in your code chicken.rect is trying to be accessed, but you did not define it.
If you refer to the official documentation you can find this piece of code:
class Block(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, color, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the block, 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(color)
# Fetch the rectangle object that has the dimensions of the image
# Update the position of this object by setting the values of rect.x and rect.y
self.rect = self.image.get_rect()
You do not set self.rect in your Chicken, it should look like this.
class Chicken(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("chic.jpg")
self.rect = self.image.get_rect(); #here rect is created
hello im new to python/pygame and tried to make a basic project. it did not turn out as planned as i don't understand this error if you can tell my why my image is not loading it will very much appreciated. Traceback (most recent call last):
File "C:\Users\Nicolas\Desktop\template\templat.py", line 15, in <module>
screen.fill(background_colour)
NameError: name 'background_colour' is not defined
this is the error i was speaking of however i have fixed now. how ever now the screen opens displayes the background and crashes.
import pygame, sys
pygame.init()
def game():
background_colour = (255,255,255)
(width, height) = (800, 600)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Tutorial 1')
pygame.display.set_icon(pygame.image.load('baller.jpg'))
background=pygame.image.load('path.png')
target = pygame.image.load('Player.png')
targetpos =target.get_rect()
screen.blit(target,targetpos)
screen.blit(background,(0,0))
pygame.display.update()
while True:
screen.blit(background,(0,0))
screen.blit(target,targetpos)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if__name__==('__main__')
game()
You missed the __init__ definition!
While your code does run, it is not what you want. There's an infinite loop inside the definition of the class, which means, however you are running this, there's something missing. You should put this code (most of it at least) inside the __init__ function, and then create an instance of the class.
This is what I assume you want:
import pygame, sys
class game():
width, height = 600,400
def __init__(self):
ball_filename = "Ball.png"
path_filename = "path.png"
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption('Star catcher')
self.background = pygame.image.load(path_filename)
self.screen.blit(self.background,(0,0))
self.target = pygame.image.load(ball_filename)
def run(self):
while True:
self.screen.blit(self.background, (0,0))
targetpos = self.target.get_rect()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if __name__ == "__main__":
# To run this
pygame.init()
g = game()
g.run()
UPDATE:
I made more modifications than what you must do, but they could be useful. I did not test this, but it should be fine.
The error of width and height not being defined is because they are not local/global variables, but bound to the class and/or the instance of the class, therefore in their namespace. So you need to access these either via game.width (per class) or self.width (per instance, only inside a method defined in the class) or g.width (per instance, if you are outside the class definition and g is an instance of game class).
I hope I'm clear. :)