I'm trying to draw a sprite in pygame inside a class however I get an error.
Here is my code:
import pygame
# Initiate Pygame
pygame.init()
# Set The Screen Size
screen = pygame.display.set_mode([800, 600])
# Set The Window Title & Icon
pygame.display.set_caption("Pacman")
# Player
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Pacman_Player.tiff").convert
self.rect = self.image.get_rect()
self.draw = screen.blit(self.rect, 200, 200)
# Background Image
backImg_1 = pygame.image.load("maze.png").convert()
backImg = pygame.transform.scale(backImg_1, (800, 600))
# Game Loop
running = True
while running:
# Player
Player = Player()
# Background Image
screen.blit(backImg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
Here is the error message I get when I try to run this code:
File "/Users/nagz/Pacman/Pacman.py", line 34, in <module>
Player = Player()
File "/Users/nagz/Pacman/Pacman.py", line 19, in __init__
self.rect = self.image.get_rect()
AttributeError: 'builtin_function_or_method' object has no attribute 'get_rect'
The error message says that there is no get_rect
method in pygame, however in pygame there is a get_rect
method.
CodePudding user response:
You'll need to call the Surface.convert()
function at
self.image = pygame.image.load("Pacman_Player.tiff").convert
to be
self.image = pygame.image.load("Pacman_Player.tiff").convert()
See the documentation for Surface.convert()
.
For the new error (provided by the OP in the comments),
File "/Users/nagz/Pacman/Pacman.py", line 34, in <module>
Player = Player() File "/Users/nagz/Pacman/Pacman.py", line 20, in __init__
self.draw = screen.blit(self.rect, 200, 200)
TypeError: argument 1 must be pygame.Surface, not pygame.Rect
Simply replace
screen.blit(self.rect, 200, 200)
with
color = 255, 0, 0
pygame.draw.rect(screen, color 200, 200, self.rect.w, self.rect.h)
CodePudding user response:
import pygame
# Initiate Pygame
pygame.init()
# Set The Screen Size
screen = pygame.display.set_mode([800, 600])
# Set The Window Title & Icon
pygame.display.set_caption("Pacman")
# Player
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Pacman_Player.tiff").convert()
self.rect = self.image.get_rect()
self.draw = screen.blit(self.rect, 200, 200)
# Background Image
backImg_1 = pygame.image.load("maze.png").convert()
backImg = pygame.transform.scale(backImg_1, (800, 600))
# Game Loop
running = True
while running:
# Player
Player = Player()
# Background Image
screen.blit(backImg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()