Кнопка go не работает из-за проблем в основном цикле - PullRequest
0 голосов
/ 14 марта 2020
def game_controls(): # First page of controls #################################  
    gcont = True
    global intro

    gameDisplay.fill(white)

    while gcont:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_e:
                        pygame.quit()
                        quit()

                if event.type == pygame.KEYDOWN:
                   if event.key == pygame.K_c:
                       game_controls1()

        message_to_screen("Cystal Caves", green,-100, size="large")
        message_to_screen("Created by 'Alan Benoy'", black, 10)
        message_to_screen("--  --  --  --  --  Press  -C-  to continue along screens  --  --  --  --  --", yellow, 250)


def game_controls1():  # Page 1 of controls ###################################
    gcont1 = True
    global intro

    gameDisplay.fill(white)

    while gcont1:

        message_to_screen("Welcome to Crystal Caves!",green,-100,size="large")
        message_to_screen("Journey through different caverns and explore the caves mysteries!",black,10)
        message_to_screen("Find the caves hidden treasures and become rich!",black,50)
        message_to_screen("But BEWARE... Danger lurks around every corner with monster hiding in dark!",black,90)

        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_e:
                        pygame.quit()
                        quit()

                if event.type == pygame.KEYDOWN:
                   if event.key == pygame.K_c:
                       game_controls2()


def game_controls2():  # Page 2 of controls ###################################
    gcont2 = True
    global intro

    gameDisplay.fill(white)

    while gcont2:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_e:
                        pygame.quit()
                        quit()

                if event.type == pygame.KEYDOWN:
                   if event.key == pygame.K_c:
                       game_controls3()

        message_to_screen("Controls:",green,-100,size="large")
        message_to_screen("Press the right arrow key to movie right",black,10)
        message_to_screen("Press the left arrow key to move left",black,50)
        message_to_screen("Press the up arrow key to jump up",black,90)
        message_to_screen("Press  -E-  to exit the game whenever",black,130)   
        message_to_screen("Press  -P-  to pause the game",black,170)   
        message_to_screen("Press  -C-  to unpause and continue the game",black,210)   
        message_to_screen("Press  -R-  to restart the game (to Main Menu)",black,250)           


def game_controls3():  # Final page of controls ###############################
    gcont3 = True
    global intro

    gameDisplay.fill(white)

    while gcont3:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_e:
                        pygame.quit()
                        quit()

                if event.type == pygame.KEYDOWN:
                   if event.key == pygame.K_c:
                       game_intro() # Leads user back to game intro screen

        message_to_screen("Now it's Time to Play:",green,-100,size="large")
        message_to_screen("Enter the cave to begin your adventure... IF YOU DARE!!!",black,10)


######################## Message to Screen Variables ##########################

def text_objects(text, color,size = "small"):
    if size == "small":
        textSurface = smallfont.render(text, True, color)
    if size == "medium":
        textSurface = medfont.render(text, True, color)
    if size == "large":
        textSurface = largefont.render(text, True, color)
    return textSurface, textSurface.get_rect()

def message_to_screen(msg,color, y_displace = 0, size = "small"):
    textSurf, textRect = text_objects(msg,color,size)
    textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
    gameDisplay.blit(textSurf, textRect)

    pygame.display.update()


########################## Game Intro Buttons #################################

def button(msg,x,y,w,h,ic,ac, action = None ):
    global intro

    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    #print(click)
    #print(mouse)

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            if action == "play": 
                intro = False
                redrawGameWindow()

        if click[0] == 1 and action != None:          
            if action == "controls":
                game_controls()

        if click[0] == 1 and action != None:        
            if action == "quit":
                pygame.quit()
                quit()

    else:
        pygame.draw.rect(gameDisplay, ic,(x, y, w, h))

    font = pygame.font.SysFont('calbri', 30)
    text = font.render(msg, 1, (255, 255, 255))
    position = ( ((x+8)+((w-100)/2)), ((y+40)+((h-100)/2)) )
    win.blit(text, position)


########################## Game Intro Function ################################

def game_intro():

    intro = True


    while intro:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_c:
                        intro = False

                    elif event.key == pygame.K_e:
                        pygame.quit()
                        quit()

            win.fill((0, 255, 255))
            font = pygame.font.SysFont('Bahnschrift Light', 60)
            text = font.render('Cystal Caves', 1, (0, 0, 255))
            win.blit(text, (424, 60))

            button('    Go!',(150+160),450,100,50,(0, 255, 0),(0, 200, 0), "play") 
            button("Controls",(350+160),450,100,50,(249, 166, 2), (255, 255, 0), "controls")
            button('   Quit?',(550+160),450,100,50,(255, 0, 0),(200, 0, 0), "quit")

            pygame.display.update()
            clock.tick(15)   

Это проблема, так как она не активирует кнопку go, я пытался использовать перерисованное игровое окно и переменные, но, похоже, ничего не работает. Мне действительно нужно это исправить, так как это часть очень большого задания, которое должно скоро произойти, и у меня психические расстройства. Я получил кнопку c для работы, и она входит в игру, и я попробовал кнопку go, но она не работает, и я просто не знаю почему. ПОЖАЛУЙСТА, ПОМОГИТЕ !!!!

1 Ответ

1 голос
/ 14 марта 2020

Я полагаю, что это проблема вашей глобальной вступительной переменной. Ключевое слово global следует использовать, когда вы хотите присвоить новое значение глобальной переменной внутри функции, а глобальная переменная должна быть инициализирована вне функции.

Так что если вы инициализируете переменную intro вне какой-либо функции например,

intro = true

def game_controls(): # First page of controls #################################  
    gcont = True
    global intro

    gameDisplay.fill(white)
    ...

и затем измените вашу функцию game_intro () на

def game_intro():

    global intro


    while intro:
    ...

, тогда ваша проблема должна быть решена (или, по крайней мере, проблема должна быть решена).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...