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
Related
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))
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
I'm trying to make a sprite using pygame, but when I try running the main game loop the error that comes up is
AttributeError: 'Paddle' object has no attribute 'rect'
however, to me it looks like I've already used self.rect = self.paddle.get_rect() so it should mean that I've already initialized it? Here's the code:
import pygame
class Paddle(pygame.sprite.Sprite):
def __init___(self, screen):
pygame.sprite.Sprite.__init__(self)
self.paddle = pygame.Surface((100, 40))
self.paddle = self.paddle.convert()
self.paddle.fill((0, 0, 0))
self.rect = self.paddle.get_rect()
self.rect.left = 200
self.rect.top = 400
self.__screen = screen
self.__dx = 0
def change_direction(self, xy_change):
self.__dx = xy_change[0]
def update(self):
if ((self.rect.left > 0) and (self.__dx > 0)) or ((self.rect.left < self.__screen.get_width()) and (self.__dx < 0)):
self.rect.left -= (self.__dx*5)
Any help is appreciated!
In init you have 3 underscores after the word init, so it is never called, there should be 2 either side of the word init (__init__())
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
I have a program that is simply made to move an image around. I try to state the self.rect as part of a load_png() call, but it simply does not like it. THe reason I think this will work is from http://www.pygame.org/docs/tut/tom/games6.html, saying that this should work:
def __init__(self, side):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('bat.png')
screen = pygame.display.get_surface()
self.area = screen.get_rect()
self.side = side
self.speed = 10
self.state = "still"
self.reinit()
Here is my code, which according to the pygame tutorial from its own website, should work:
def _init_(self):
pygame.sprite.Sprite._init_(self)
self.state = 'still'
self.image = pygame.image.load('goodGuy.png')
self.rect = self.image.get_rect()
screen = pygame.display.getSurface()
And it gives me this error:
Traceback (most recent call last):
File "C:\Python25\RPG.py", line 37, in <module>
screen.blit(screen, Guy.rect, Guy.rect)
AttributeError: 'goodGuy' object has no attribute 'rect'
If you guys need all of my code, comment blew and I will edit it.
You don't have a load_png function defined.
You need to create the pygame image object before you can access its rect property.
self.image = pygame.image.load(file)
Then you can assign the rect value using
self.rect = self.image.get_rect()
Or you could create the load_png function as per the example you linked.
There is no load_png function built-in to python or pygame. I imagine that the tutorial you are referring to defined it manually somewhere. What you want is pygame.image.load(filename) and then you can call get_rect() on the returned Surface object. The complete code would be as follows:
self.image = pygame.image.load('bat.png')
self.rect = self.image.get_rect()
Your second problem is that you've defined the function _init_, but you need double underscores: __init__.
Also, you need to post the code where the error is actually occurring.