我试图了解如何在pygame中定义退出。我正在制作汽车游戏,你必须避免障碍物与汽车接触。
我的错误是
line 71, in <module>
while not gameExit:
NameError: name 'gameExit' is not defined
我的代码是
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255, 255, 255)
red = (255,0,0)
car_width = 73
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Hi There Fucker")
clock = pygame.time.Clock()
carImg = pygame.image.load("mycar.png")
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, black)
gameDisplay.blit(text, (0,0))
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def car(x,y):
gameDisplay.blit(carImg, (x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font("freesansbold.ttf", 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display("You crashed")
def game_loop():
x = (display_width * 0.1)
y = (display_height * 0.3)
x_change = 0
thing_starx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
答案 0 :(得分:0)
thing_height = 100
# this doesn't define it at a global scope.
gameExit = False
## gameExit is not defined
while not gameExit:
问题是您尚未定义该值gameExit
。考虑在全球范围内更早地定义它。
pygame.init()
gameExit=False
display_width = 800
答案 1 :(得分:0)
这是一个范围问题。您的变量gameExit
仅在使用它的函数内定义。
解决此问题的最简单方法是在程序开始时将其声明为False
,并将global gameExit
置于设置它的所有函数的顶部,从而确保它们可以访问它的全球版本并没有重新定义它。
为了您的目的,我确定这很好,但您可能想查看top answer on this question。