Я пытаюсь закодировать счастливое лицо, чтобы отскакивать от стен и случайным образом менять цвет, когда оно падает на стену. В настоящее время я установил цвета и код, чтобы он отражался от стены и менял цвет. Но мой код не работает, так как он говорит: «NameError: имя 'xPos' не определено", даже если я его определил.
color = GREEN
color2 = BLUE
color3 = RED
# funtion to draw a the "happy face"
# it has 4 parameters passed to it xPos, yPos, radius, and colour
# notice all the shapes are drawn "relative" to the xPos and yPos and the radius
def drawHappy(xPos,yPos,r,colour):
pygame.draw.circle(screen,colour,(xPos,yPos),r,1)
eyeRadius = int(1/6*r)
eyeX = int(xPos-1/3*r)
eyeY = int(yPos- 1/3*r)
pygame.draw.circle(screen,colour,(eyeX,eyeY),eyeRadius,1)
eyeX = int(xPos + 1/3*r)
pygame.draw.circle(screen,colour,(eyeX,eyeY),eyeRadius,1)
wMouth = 1.5*r
xMouth = xPos - 3/4*r
yMouth = yPos - 3/4*r
pygame.draw.arc(screen,colour,(xMouth,yMouth,wMouth,wMouth),math.pi,2*math.pi,1)
def random_color():
random_number = random.randint(1,3)
if random_number == 1:
return GREEN
elif random_number ==2:
return BLUE
else:
return RED
# set up clock to control frames per second
clock = pygame.time.Clock()
FPS = 120
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type == pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
xPos = xPos + dxPos
yPos = yPos + dyPos
if x >= 750:
dx = -abs(dx)
color = random_color()
elif x <=50:
dx = abs(dx)
color = random_color()
if y <= 50:
dy = abs(dy)
color = random_color()
elif y >=550:
dy = -abs(dy)
color = random_color()
if x2 >= 775:
dx2 = -abs(dx2)
color2 = random_color()
elif x2 <= 25:
dx2 = abs(dx2)
if y2 <= 25:
dy2 = abs(dy2)
color2 = random_color()
elif y2 >= 575:
dy2 = -abs(dy2)
color2 = random_color()
if x3 >=700:
dx3 = -abs(dx3)
color3 = random_color()
elif x3 <= 100:
dx3 = abs(dx3)
color3 = random_color()
if y3 <= 100:
dy3 = abs(dy3)
color3 = random_color()
elif y3 >= 500:
dy3 = -abs(dy3)
color3 = random_color()