基本上我有这个乒乓球游戏。我运行开始菜单,在开始菜单中,我有一个矩形的图像,该矩形是用户选择一个还是两个玩家的选择框。现在,我正在检查矩形的Y坐标,然后定义一个名为“ gamechoice”的值,然后根据gamechoice的值确定是单人游戏还是两名玩家。问题是,在我的主菜单中的while循环中定义了gamechoice之后,它不会继承该值,并表示未定义gamechoice
我在互联网上找不到任何有关此的信息
def game_intro():
intro = True
rect_x = 340
rect_y = 130
gamechoice = 0
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
backgroundimage = pygame.image.load('background.jpg')
screen.blit(backgroundimage,(0,0))
#-----------------------------------------------------------------
# you ended here trying to make
# a selection rectangle you need to make it hollow
#-----------------------------------------------------------------
#selection rectangle
rect = pygame.image.load('rect.png')
screen.blit(rect,(rect_x,rect_y))
#Text size for title
screenText = pygame.font.Font('freesansbold.ttf',60)
#text size for selection
screenText2 = pygame.font.Font('freesansbold.ttf',25)
#Display Title "Pong"
TextSurf, TextRect = text_objects("Pong", screenText)
TextRect = ((360),(65))
gameDisplay.blit(TextSurf, TextRect)
#Display selection "Single Player"
TextSurf2, TextRect2 = text_objects("Single Player", screenText2)
TextRect2 = ((350),(135))
gameDisplay.blit(TextSurf2, TextRect2)
#Display selection "Two Player"
TextSurf3, TextRect3 = text_objects("Two Player", screenText2)
TextRect3 = ((370),(175))
gameDisplay.blit(TextSurf3, TextRect3)
if event.type == KEYDOWN:
if event.key == K_UP:
rect_y = 130
elif event.key == K_DOWN:
rect_y = 170
if event.type == KEYDOWN:
if event.key == K_SPACE:
intro = False
if rect_y == 130:
gamechoice = 1
if rect_y == 170:
gamechoice = 2
pygame.display.update()
clock.tick(15)
它将使用gamechoice的值来确定是单人游戏还是多人游戏
答案 0 :(得分:2)
如果在代码的另一部分中使用game_intro
方法,则最好返回gamechoice
的值:
def game_intro():
# ... the first part of your method
pygame.display.update()
clock.tick(15)
return gamechoice
if __name__ == '__main__':
choice = game_intro()
if choice == 1:
# do stuff
# ... rest of the program