如何从一个while循环到另一个while循环获取值?

2024-06-16 21:04:16 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我有这个乒乓球游戏。我运行“开始”菜单,在“开始”菜单中有一个矩形的图像,它是用户选择单人还是双人的选择框。现在我正在检查矩形的Y坐标,然后定义一个叫做“gamechoice”的值,根据gamechoice的值来决定它是单人游戏还是双人游戏。问题是,在我的主菜单中定义gamechoice之后,while loop并没有携带值,并且说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的值来决定是不是它的单个玩家还是多个玩家


Tags: textrecteventforiftypedisplay菜单
1条回答
网友
1楼 · 发布于 2024-06-16 21:04:16

如果在代码的另一部分中使用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

相关问题 更多 >