Pygame renvoie une erreur lorsque vous cliquez sur une image-objet avec un autre sprite qui n'est pas dans la liste

0

La question

Je suis juste de faire un écran titre pour un futur projet, et quand je le lance le "PLAY" et "QUITTER" boutons beau travail assez, mais lorsque vous cliquez sur l'entourant d'arrière-plan ou le titre de l'image, le jeu se fige et renvoie le message d'erreur "AttributeError: 'liste' de l'objet n'a pas d'attribut "sprites" j'ai essayé en ajoutant un espace fichier audio séparé de l' "si le jeu == 0:" dans le cas où il est juste confus quand il n'avait rien à faire, mais le problème est resté.

import pygame
 
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255,255,0)
score = 0
play = 0

class Sprite(pygame.sprite.Sprite):
    def __init__(self,filename):
        super().__init__()
        self.image = pygame.image.load(filename).convert()
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
class Player(Sprite):
    def update(self):
        """ Method called when updating a sprite. """
 
        # Get the current mouse position. This returns the position
        # as a list of two numbers.
        pos = pygame.mouse.get_pos()
 
        # Now see how the mouse position is different from the current
        # player position. (How far did we move?)
        diff_x = self.rect.x - pos[0]
        diff_y = self.rect.y - pos[1]
 
        # Loop through each block that we are carrying and adjust
        # it by the amount we moved.
 
        # Now wet the player object to the mouse location
        self.rect.x = pos[0]
        self.rect.y = pos[1]
 
class Block(pygame.sprite.Sprite):

    def __init__(self, color, width, height):

        # Call the parent class (Sprite) constructor
        super().__init__()
 
        # 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
        # image.
        # Update the position of this object by setting the values
        # of rect.x and rect.y
        self.rect = self.image.get_rect()

# Initialize Pygame
pygame.init()
 
# Set the height and width of the screen
screen_width = 750
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])

pygame.display.set_caption("LARP")
 
# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()
quit_block = pygame.sprite.Group()
start_block = pygame.sprite.Group()

title_image = pygame.image.load("title.png").convert_alpha()
quit_image = pygame.image.load("quit.png").convert_alpha()
logo_image = pygame.image.load("logo.png").convert_alpha()
player_image = pygame.image.load("player.png").convert_alpha()
background_image = pygame.image.load("title_screen.png").convert_alpha()
bomp = pygame.mixer.Sound("bump.wav")
# This is a list of every sprite.
# All blocks and the player block as well.
player_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
 
#for i in range(50):
     #This represents a block
    #block = Block(BLACK, 20, 15)
 
     #Set a random location for the block
    #block.rect.x = random.randrange(screen_width)
    #block.rect.y = random.randrange(screen_height)
 
     #Add the block to the list of objects
    #block_list.add(block)
    #all_sprites_list.add(block)


title = Sprite("title.png")
title.rect.x = 340
title.rect.y = 230
all_sprites_list.add(title)
start_block.add(title)
quitg = Sprite("quit.png")
quitg.rect.x = 340
quitg.rect.y = 350
all_sprites_list.add(quitg)
quit_block.add(quitg)
logo = Sprite("logo.png")
logo.rect.y = 90
logo.rect.x = 310
all_sprites_list.add(logo)
block_list.add(logo)
player = Player("player.png")
player_list.add(player)
all_sprites_list.add(player)


 
# Loop until the user clicks the close button.
done = False
 
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
 
# Hide the mouse cursor
pygame.mouse.set_visible(False)
 
# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
 
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # When the mouse button is pressed, see if we are in contact with
            # other sprites:
            if play == 0:         
                start_block = pygame.sprite.spritecollide(player, start_block, True)
                if len(start_block) >= 1:
                    play += 1    

                quit_block = pygame.sprite.spritecollide(player, quit_block, True)
                if len(quit_block) >= 1:
                    done = True
            #print(score)
            #blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
            #if len(blocks_hit_list) >= 1:
                #score +=1


            # Set the list of blocks we are in contact with as the list of
            # blocks being carried.
            #player.carry_block_list = blocks_hit_list
 
        elif event.type == pygame.MOUSEBUTTONUP:
            # When we let up on the mouse, set the list of blocks we are
            # carrying as empty.
            player.carry_block_list = []

 
    all_sprites_list.update()
    
 
    # Clear the screen
    screen.fill(WHITE)
 
    # Draw all the spites
    if play == 0:
        screen.blit(background_image, [0,0])
        all_sprites_list.draw(screen)
    screen.blit(player_image, [player.rect.x, player.rect.y])
 
    # 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()
list pygame pygame-surface python
2021-11-24 22:09:37
1

La meilleure réponse

1

start_block et quit_block sont pygame.sprite.Group(). Cependant, pygame.sprite.spritecollide(). Par conséquent, l'instruction:

start_block = pygame.sprite.spritecollide(player, start_block, True)

n'a pas de sens parce que le groupe start_block est remplacée par la liste start_block

Changer le nom de la variable la obtient la valeur de retour. par exemple:

start_block_hit = pygame.sprite.spritecollide(player, start_block, False)

Remarque, vous n'avez pas besoin de stocker les valeurs de retour, à tous. Le doKill argument doit être Falsesinon votre bouton sera détruit lorsque vous cliquez dessus:

if pygame.sprite.spritecollide(player, start_block, False):
    play += 1    

if pygame.sprite.spritecollide(player, quit_block, False):
    done = True
2021-11-24 22:22:22

Dans d'autres langues

Cette page est dans d'autres langues

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................