Nag
Nag

Reputation: 19

Trying to draw a pygame sprite in a class but error comes

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.

Upvotes: 1

Views: 382

Answers (4)

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 50))  # Placeholder for player image
        self.image.fill(BLUE)
        self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2))
        self.speed = PLAYER_SPEED
        self.health = 100
        self.ammo = {'AK47': 30, 'M16A4': 30, 'MP5K': 30, 'Pistol1': 15, 'Pistol2': 15}
        self.weapon = 'AK47'
        self.bullets = []
        self.knife_equipped = False

    def update(self, keys):
        # Handle movement
        if keys[pygame.K_LEFT] and self.rect.left > 0:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT] and self.rect.right < WIDTH:
            self.rect.x += self.speed
        if keys[pygame.K_UP] and self.rect.top > 0:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN] and self.rect.bottom < HEIGHT:
            self.rect.y += self.speed

    def shoot(self):
        """Shoot bullets."""
        if self.weapon != 'Knife' and self.ammo[self.weapon] > 0:
            bullet = Bullet(self.rect.centerx, self.rect.top, self.weapon)
            self.bullets.append(bullet)
            self.ammo[self.weapon] -= 1
            return bullet
        return None

    def switch_weapon(self, weapon):
        """Switch weapons."""
        if weapon in WEAPONS:
            self.weapon = weapon

    def use_knife(self):
        """Switch to knife mode."""
        self.weapon = 'Knife'
        self.knife_equipped = True

    def draw_health(self):
        """Draw the player's health bar on the screen."""
        health_bar = pygame.Rect(10, 10, HEALTH_BAR_WIDTH * (self.health / 100), HEALTH_BAR_HEIGHT)
        pygame.draw.rect(screen, RED, health_bar)

    def draw_ammo(self):
        """Display ammo count."""
        ammo_text = font.render(f"Ammo: {self.ammo[self.weapon]}", True, BLACK)
        screen.blit(ammo_text, (10, 40))

Upvotes: -1

xxSirFartAlotxx
xxSirFartAlotxx

Reputation: 404

You are missing a () after convert, change it to:

self.image = pygame.image.load("Pacman_Player.tiff").convert()

and change:

self.draw = screen.blit(self.rect, 200, 200)

to

self.draw = lambda: screen.blit(self.image, (200, 200))

this way, you can just call self.draw(), whenever you wanna draw the sprite.

Here’s the 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 = lambda: screen.blit(self.image, (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()

    

Upvotes: 0

Red
Red

Reputation: 27567

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)

Upvotes: 2

Erling Olsen
Erling Olsen

Reputation: 740

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()

Upvotes: 0

Related Questions