我的Pygame中cake类的__init__方法有何问题?如何修正?
Here are the key issues in your code and their solutions:
1. Pygame Initialization Order
pygame.init() must be called before any other pygame operations (like creating the display screen). Move it to the top of your code, right after imports.
2. Invalid Arguments in pygame.transform.scale
The scale function expects a tuple of integers, but you passed ([width], 80) (a list inside a tuple). Replace [width] with width to make it (width, 80).
3. Incorrect Rect Attribute Assignment
self.rect.bottom is a single integer (the y-coordinate of the rect's bottom edge). You tried to assign a tuple (750, [pos_y]), which is invalid. Since you want to position the pancake's midbottom at (750, pos_y), use self.rect.midbottom = (750, pos_y) instead. Also, [pos_y] is unnecessary—just use the integer pos_y.
4. Sprite Image Attribute Mismatch
Your Sprite subclass needs a self.image attribute (the surface to draw). You stored the scaled pancake in self.pancake instead of updating self.image. Assign the scaled surface directly to self.image.
Corrected Code
import pygame from sys import exit pygame.init() # Moved to top of execution num = 3 class Cake(pygame.sprite.Sprite): # Follow Python CamelCase class naming convention def __init__(self, pos_y, width): super().__init__() # Modern way to call parent constructor original_image = pygame.image.load('Pancake.png').convert_alpha() self.image = pygame.transform.scale(original_image, (width, 80)) # Assign scaled image to required Sprite attribute self.rect = self.image.get_rect() self.rect.midbottom = (750, pos_y) # Correctly position the sprite's midbottom screen = pygame.display.set_mode((1500, 800)) pygame.display.set_caption('Pancake House') clock = pygame.time.Clock() background = pygame.Surface((2000, 1000)) background.fill('#96e2fc') pancake = Cake(550, 200) pancakes = pygame.sprite.GroupSingle() pancakes.add(pancake) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() screen.blit(background, (0, 0)) pancakes.draw(screen) pygame.display.update() clock.tick(60)
Additional Notes
super().__init__()is preferred over directly callingpygame.sprite.Sprite.__init__(self)as it works better with inheritance hierarchies.- The class name was renamed to
Caketo follow standard Python class naming conventions. - The original image is stored in a temporary variable to avoid overwriting it before scaling.
内容的提问来源于stack exchange,提问作者AJAI ARJUN G BTech_ME

