изображение не падает в меню «Пуск». Pygame - PullRequest
0 голосов
/ 03 сентября 2018

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

Это код:

import pygame
import random

pygame.init()

display_width= 1000
display_height= 600

black = (0,0,0)
white = (255, 255, 255)
blue = (0, 0, 112)

x=0
y=0

gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Name")

clock = pygame.time.Clock()

def text_objects(text, font, color):
    textSurface = font.render(text, True, color)
    return textSurface, textSurface.get_rect()

Stmenpic = pygame.image.load("Start_menu_sky_back_ground.png")

def StartMenPic(x,y):
    gameDisplay.blit(Stmenpic, (x,y) )

def Title_Of_Game(text):
    Title_Text = pygame.font.Font("ARDESTINE.ttf", 115)
    TextSurf, TextRect = text_objects(text, Title_Text, blue)
    TextRect.center = ((500),(100))
    gameDisplay.blit(TextSurf, TextRect)

    pygame.display.update

Baby_1=pygame.image.load("Baby_1.png")

def things(x,y):
    gameDisplay.blit(Baby_1,(x, y ))

x_change = 0

def Title_of_Game():
    Title_Of_Game("Title")

def Start_Menu():

    StartMenu=True
    while StartMenu:
        x = 0
        y = 0
        x_change = 0

        thing_startx = random.randrange(0, display_width)
        thing_starty = -600
        thing_speed = 7
        thing_width= 30
        thing_height=30

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

        Title_of_Game()
        x_change=0

        x+= x_change

        if thing_starty > display_height:
            thing_starty = 0 - thing_height
            thing_startx = random.randrange(0, display_width)

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

StartMenPic(0, 0)
Start_Menu()

pygame.quit()
quit()

Это, наверное, очень очевидно, но я только начинаю, поэтому мне нужна большая помощь. Спасибо за всю помощь в этом вопросе. Теперь у меня проблема с блоком, он всегда появляется в случайных местах, но не выключается.

Это основная часть этого кода:

    pygame.init()

    display_width= 1000
    display_height= 600

    Startmenpic = pygame.image.load("Start_menu_sky_back_ground.png")
    stmenpic = pygame.Surface((30, 50))
def Start_Menu():
    thing_rect = pygame.Rect(random.randrange(display_width), -60, 30, 30)
    thing_speed = 7

    StartMenu = True

    while StartMenu:

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

        Title_of_Game()

        thing_rect.y += thing_speed

        if thing_rect.y > display_height:
            thing_rect.y = 0 - thing_rect.height
            thing_rect.x = random.randrange(display_width)

            gameDisplay.fill((30, 30, 30))
            gameDisplay.blit(stmenpic, thing_rect)
            pygame.display.update()
            clock.tick(60)

    StartMenPic(0, 0)
    pygame.display.update()
    Start_Menu()

    pygame.quit()
    quit()

    stmenpic.fill((0, 200, 50))

1 Ответ

0 голосов
/ 03 сентября 2018

Не определяйте переменные положения и скорости в цикле while, иначе они будут сбрасываться каждый кадр (итерация цикла). Вместо этого определите их вне цикла и измените положения внутри цикла, добавив скорость.

Я также рекомендую использовать объект pygame.Rect вместо отдельных переменных thing_startx, thing_starty, thing_width и thing_height:

# Pass the top left coordinates, the width and the height.
thing_rect = pygame.Rect(random.randrange(display_width), -60, 30, 30)

Затем обновите его y-координату, добавив скорость каждого кадра:

thing_rect.y += thing_speed

Вот минимальный, полный пример:

import pygame
import random


pygame.init()

display_width = 1000
display_height = 600

gameDisplay = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()

stmenpic = pygame.Surface((30, 50))
stmenpic.fill((0, 200, 50))


def start_menu():
    thing_rect = pygame.Rect(random.randrange(display_width), -60, 30, 30)
    thing_speed = 7

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return

        # Move the rect downwards.
        thing_rect.y += thing_speed
        # Reset the position of the rect when it leaves the screen.
        if thing_rect.y > display_height:
            thing_rect.y = 0 - thing_rect.height
            thing_rect.x = random.randrange(display_width)

        gameDisplay.fill((30, 30, 30))
        gameDisplay.blit(stmenpic, thing_rect)  # Blit the image at the rect.
        pygame.display.update()
        clock.tick(60)


start_menu()
pygame.quit()

Если вам нужно несколько падающих объектов, просто добавьте несколько списков в список и используйте петли for, чтобы обновить и нарисовать их.

...