Reputation: 33
I'm attempting to write a program using pygame to create a class called Dot()
that allows me to implement Dot objects, which will be small, 2 pixel radius circles. I'm trying to create them within my main game loop, but I keep getting the error message "name 'x' is not defined". I'm not sure why that would be the case. If it were going to throw such an error I would expect it to first say that color isn't defined, since it's listed first in the list of parameters. I'm not sure if my error is caused by the way I wrote the class itself or if it's something in my implementation of the class (I'm almost positive I did this wrong, but I've tried it a few different ways as well and keep getting the same error), or if it's or both.
#!/usr/bin/env python
import random, pygame, sys
from random import randint
from pygame.locals import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((700, 700), 0, 32)
pygame.display.set_caption('Version02')
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
class Dot():
def __init__(self, color, x, y):
self = pygame.draw.circle(DISPLAYSURF, color, (x, y), 2, 0)
self.color = getDotColor()
self.x = getDotX()
self.y = getDotY()
def getDotColor():
color = random.choice([RED, GREEN, BLUE])
return color
def getDotX():
x = randint(0, 700)
return x
def getDotY():
y = randint(0, 700)
return y
while True: #main game loop
DISPLAYSURF.fill(WHITE)
dot = Dot(color, x, y)#I'm not exactly sure how to implement this correctly
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
Upvotes: 0
Views: 45
Reputation: 7361
dot = Dot(color, x, y)#I'm not exactly sure how to implement this correctly
You do not define a x or y value before. Your error comes from here. Same for the color.
If you want color and dot coordinates to be randomly created each time you create a Dot object (at least I understand this is what you are looking for) you have to rewrite the __init__
method:
class Dot():
def __init__(self):
self.color = getDotColor()
self.x = getDotX()
self.y = getDotY()
self = pygame.draw.circle(DISPLAYSURF, self.color, (self.x, self.y), 2, 0)
Upvotes: 1