Мой начальный экран не запускается, когда я нажимаю Run! кнопка - PullRequest
1 голос
/ 07 августа 2020

Так что с тех пор, как я добавил свой стартовый экран для своей игры, и когда я нажимал кнопку «Выполнить!» / «Старт», экран просто зависал, и я не мог ничего нажимать. Мой Sit / quit работает отлично, но мой Run / Start не будет

https://gyazo.com/f0dfef5bc4be1875e6928d79a0b792fd

Как вы можете видеть из моей короткой демонстрации, если я нажму Run / Кнопка «Пуск» моя игра просто зависнет и перестанет работать. Я попытался переписать свой код, но это все еще не работает, я думаю, что мне чего-то не хватает, но я не знаю что.

Вот где у меня проблемы

##############################################
# START MENUE
def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    #print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(window, ac,(x,y,w,h))

        if click[0] == 1 and action != None:
            action()         
    else:
        pygame.draw.rect(window, ic,(x,y,w,h))

    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    window.blit(textSurf, textRect)

def quitgame():
    pygame.quit()


def game_intro():

    intro = True

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

        largeText = pygame.font.Font('freesansbold.ttf',95)
        TextSurf, TextRect = text_objects("Lava Runer", largeText)
        TextRect.center = ((500/2),(500/2))
        window.blit(TextSurf, TextRect)


        button("Run!",100,350,100,50,darkgreen,green,main_loop)
        button("Sit!",300,350,100,50,darkred,red,quitgame)

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

        bg = pygame.image.load("Sky2.jpg")
        window.blit(bg,(0,0))


        
############################################

Это это мой Полный код

import pygame
pygame.font.init()
pygame.init()

#set screen
window = pygame.display.set_mode((500,500))

#set Name
pygame.display.set_caption("Noob")



class player:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.speed = 0
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.topleft = (self.x,self.y)

class Floor:
    def __init__ (self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)


class Coin():
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)
    


white = (255,255,255)

green = (0,255,0)

red = (255,0,0)

darkred = (200,0,0)

darkgreen = (0,200,0)

black = (0,0,0)
 
player1 = player(50,400,40,40,white)

coin1 = Coin(100,300,30,30,red)

coin2 = Coin(200,300,30,30,red)

floor1 = Floor(0,0,1000,30,green)
floor2 = Floor(0,400,1000,30,green)


coins = [coin1,coin2]
floors = [floor1,floor2]




fps = (30)

clock = pygame.time.Clock()

##############################################
# START MENUE
def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    #print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(window, ac,(x,y,w,h))

        if click[0] == 1 and action != None:
            action()         
    else:
        pygame.draw.rect(window, ic,(x,y,w,h))

    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    window.blit(textSurf, textRect)

def quitgame():
    pygame.quit()


def game_intro():

    intro = True

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

        largeText = pygame.font.Font('freesansbold.ttf',95)
        TextSurf, TextRect = text_objects("Lava Runer", largeText)
        TextRect.center = ((500/2),(500/2))
        window.blit(TextSurf, TextRect)


        button("Run!",100,350,100,50,darkgreen,green,main_loop)
        button("Sit!",300,350,100,50,darkred,red,quitgame)

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

        bg = pygame.image.load("Sky2.jpg")
        window.blit(bg,(0,0))


        
############################################

def main_loop():
    #window
    def redrawwindow():
        window.fill((0,0,0))    

        #draw plyer
        player1.draw()
        for Coin in coins:
            Coin.draw()

        for Floor in floors:
            Floor.draw()
    



        # the score draw it on the screen
        window.blit(text,textRect)


    # Font for coin   
    font  = pygame.font.Font("freesansbold.ttf",30)
    score = 0
    text = font.render("Coins = "+str(score),True,(255,255,255))
    textRect = text.get_rect()
    textRect.center = ((100,40))

                    
    run = True
    while run:
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False


        # coin collisions
        for Coin in coins:
            for one in range(len(coins)-1-1-1):
                if player1.rect.colliderect(coins[one].rect):
                    del coins[one]
                    score += 1
                    text = pygame.font.Font("comicsansms",30)
                    textRect.center = (100,40)



        # Keys for player
        keys = pygame.key.get_pressed()

        if keys[pygame.K_a]and player1.x > player1.speed:
            player1.x -= player1.speed

        if keys[pygame.K_d]and player1.x <500 - player1.height - player1.speed:
            player1.x += player1.speed

        if keys[pygame.K_w]and player1.y > player1.speed:
            player1.y -= player1.speed

        if keys[pygame.K_s]and player1.y <500 - player1.width - player1.speed:
            player1.y += player1.speed


        # Fall
        if not player1.isJump:
            player1.y += player1.fall
            player1.fall += 1
            player1.isJump = False



            # Collide with Floor
            collide = False
            for Floor in floors:
                if player1.rect.colliderect(Floor.rect):
                    collide = True
                    player1.isJump = False
                    player1.y = Floor.rect.top - player1.height + 1
                    if player1.rect.right > Floor.rect.left and player1.rect.left > Floor.rect.right - player1.width:
                        player1.x = Floor1.rect.left - player1.width
                    if player1.rect.left < Floor.rect.right and player1.rect.right > Floor.rect.left + player1.width:
                        player1.x = Floor.rect.right


                if player1.rect.bottom >= 500:
                    collide = True
                    player1.isJump = False
                    player1.JumpCount = 10
                    player1.y = 500 - player1.height

                if collide:
                    if keys[pygame.K_SPACE]:
                        player1.isJump = True
                        player1.fall = 0

                else:
                    if player1.JumpCount >= 0:
                        player1.y -= (player1.JumpCount*abs(player1.JumpCount))*0.3
                        player1.JumpCount -= 1
                    else:
                        player1.JumpCount = 10
                        player1.isJump = False
                    
                    
        redrawwindow()
    pygame.display.update()
    pygame.quit()
game_intro()
main_loop()

1 Ответ

2 голосов
/ 07 августа 2020

Итак, именно здесь вы правильно начинаете свою игру .?

    button("Run!",100,350,100,50,darkgreen,green,main_loop)
    button("Sit!",300,350,100,50,darkred,red,quitgame)

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

button("Run!",100,350,100,50,darkgreen,green,main_loop_state_turn_on)

Затем приступайте к оценке ее положения относительно кнопок.

event_i = False

def main_loop_state_turn_on():
    global event_i = true

def main_loop_state_turn_off():
    global event_i = false

внутри основного l oop обеспечьте выполнение, пока l oop, если эти глобальные переменные истинны.

def main_loop():
      if event_i:
         print 'Begin'
         #your code is going on here

для большего понимания вы можете найти это

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