尝试使用 pygame 构建精灵时出现名称错误

Name Error when trying to build a sprite using pygame

我开始使用 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()

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

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 的新手,如果这很明显,请原谅我。

您必须定义颜色 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)