You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的Pygame中cake类的__init__方法有何问题?如何修正?

Fixes for Your Pancake Sprite Class

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 calling pygame.sprite.Sprite.__init__(self) as it works better with inheritance hierarchies.
  • The class name was renamed to Cake to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:30:29