1

I am starting to use pygame. My first task is to make a sprite and to make it move. So far I am doing fine until I get the error:

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

My main code so far:

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()

As you can see this is the very start of making a sprite. My sprite 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])

This has been made in the .py file called player. I am following the tutorials HERE and making my own changes as I go along. I do not understand this error. I am very new to pygame so forgive me if this is obvious.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
Thomas
  • 1,214
  • 4
  • 18
  • 45

1 Answers1

1

You have to define the colors RED and WHITE. For instance:

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

Or create pygame.Color objects:

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

Furthermore you have to use the color argument in the constructor of Player:

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)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174