【问题标题】:Name Error when trying to build a sprite using pygame尝试使用 pygame 构建精灵时出现名称错误
【发布时间】:2020-04-21 14:58:21
【问题描述】:

我开始使用 pygame。我的第一个任务是制作一个精灵并让它移动。到目前为止,我做得很好,直到出现错误:

Traceback (most recent call last):
  File "C:\Users\tom\Documents\python\agame.py", line 33, in <module>
    YOU = Player(RED ,20, 30)
NameError: name 'RED' is not defined

到目前为止我的主要代码:

import pygame
import sys
from player import Player
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
init_result = pygame.init()
# Create a game window
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# Set title
pygame.display.set_caption("agame")

#game_running keeps loopgoing
game_running = True
while game_running:
    # Game content
    # Loop through all active events
    YOU = Player(RED ,20, 30)
    for event in pygame.event.get():
            #exit through the X button
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
    #change background colour to white
    game_window.fill((255,255,255))


    #update display
    pygame.display.update()

如您所见,这是制作精灵的开始。 我的精灵类:

import pygame

#creating sprite class
class Player(pygame.sprite.Sprite):
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the Player, and its x and y position, width and height.
        # Set the background color
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        # Draw player (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])

这是在名为player 的.py 文件中创建的。我正在关注HERE 的教程,并在进行过程中进行自己的更改。我不明白这个错误。我对 pygame 很陌生,所以如果这很明显,请原谅我。

【问题讨论】:

    标签: python class pygame sprite


    【解决方案1】:

    您必须定义颜色REDWHITE。例如:

    RED = (255, 0, 0)
    WHITE = (255, 255, 255)
    

    或者创建pygame.Color对象:

    RED = pygame.Color("red")
    WHITE = pygame.Color("white") 
    

    此外,您必须在Player 的构造函数中使用color 参数:

    class Player(pygame.sprite.Sprite):
        def __init__(self, color, width, height):
            # Call the parent class (Sprite) constructor
            super().__init__()
    
            # Pass in the color of the Player, and its x and y position, width and height.
            # Set the background color
            self.image = pygame.Surface([width, height])
            self.image.fill(color)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2020-06-16
      • 1970-01-01
      • 2021-03-05
      • 2018-09-11
      • 1970-01-01
      • 2018-10-20
      相关资源
      最近更新 更多