Pygame - Как равномерно распределить случайно сгенерированные платформы? - PullRequest
0 голосов
/ 25 января 2019

Итак, в моем предыдущем вопросе я получил ответ, который помог сориентировать платформы так, как я хотел.Тем не менее, есть новая проблема, которую я не могу обойти.Как заставить платформы появляться с достаточным пространством между ними?(нажмите 1, чтобы начать игру)

# For the program, it was necessary to import the following.
import pygame, sys, random
import pygame.locals as GAME_GLOBALS
import pygame.event as GAME_EVENTS
import pygame.time as GAME_TIME

pygame.init() # To initialise the program, we need this command. Else nothing will get started.

StartImage = pygame.image.load("Assets/Start-Screen.png")
GameOverImage = pygame.image.load("Assets/Game-Over-Screen.png")

# Window details are here
windowWidth = 1000
windowHeight = 400

surface = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption('GAME NAME HERE')

oneDown = False

gameStarted = False
gameEnded = False

gamePlatforms = []
platformSpeed = 2
platformDelay = 2000
lastPlatform = 0


gameBeganAt = 0
timer = 0

player = {
    "x": 10,
    "y": 200,
    "height": 25,
    "width": 10,
    "vy": 5
}


def drawingPlayer():
    pygame.draw.rect(surface, (248, 255, 6), (player["x"], player["y"], player["width"], player["height"]))


def movingPlayer():
    pressedKey = pygame.key.get_pressed()
    if pressedKey[pygame.K_UP]:
        player["y"] -= 5
    elif pressedKey[pygame.K_DOWN]:
        player["y"] += 5


def creatingPlatform():
    global lastPlatform, platformDelay
    platformX = windowWidth
    gapPosition = random.randint(0, windowWidth)
    verticalPosition = random.randint(0, windowHeight)
    gamePlatforms.append({"pos": [platformX, verticalPosition], "gap": gapPosition}) # creating platforms
    lastPlatform = GAME_TIME.get_ticks()
    if platformDelay > 800:
        platformDelay -= 50

def movingPlatform():
    for idx, platform in enumerate(gamePlatforms):
        platform["pos"][0] -= platformSpeed
        if platform["pos"][0] < -10:
            gamePlatforms.pop(idx)

def drawingPlatform():
    global platform
    for platform in gamePlatforms:
        pygame.draw.rect(surface, (214, 200, 253), (platform["pos"][0], platform["pos"][1], 20, 80))


def gameOver():
    global gameStarted, gameEnded, platformSpeed

    platformSpeed = 0
    gameStarted = False
    gameEnded = True


def quitGame():
    pygame.quit()
    sys.exit()


def gameStart():
    global gameStarted
    gameStarted = True


while True:
    surface.fill((95, 199, 250))
    pressedKey = pygame.key.get_pressed()
    for event in GAME_EVENTS.get():
        if event.type == pygame.KEYDOWN:
            # Event key for space should initiate sound toggle
            if event.key == pygame.K_1:
                oneDown = True
                gameStart()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_1:
                oneDown = False
                #KEYUP for the space bar
        if event.type == GAME_GLOBALS.QUIT:
            quitGame()

    if gameStarted is True:
        drawingPlayer()
        movingPlayer()
        creatingPlatform()
        movingPlatform()
        drawingPlatform()

    elif gameEnded is True:
        surface.blit(GameOverImage, (0, 0))

    else:
        surface.blit(StartImage, (0, 0))



    pygame.display.update()

Я пытался увеличить значение переменной platformDelay, но безрезультатно.Я также пытался повозиться с creatingPlatform().Независимо от того, что я делаю, они всегда появляются в глыбах!Мне бы хотелось, чтобы это была игра, в которой платформы постоянно приближаются к игроку, поэтому на самом деле это играбельно, но затем скорость приближения платформ со временем увеличится, что увеличит сложность игры.Как бы я поступил так?Спасибо!:)

1 Ответ

0 голосов
/ 25 января 2019

Я рекомендую использовать pygame.time.get_ticks(), чтобы получить количество миллисекунд, в течение которых работает программа.Обратите внимание, поскольку время указывается в миллисекундах, значение 1000 будет равно 1 секунде.

Инициализируйте переменную newPlatformTimePoint на 0 и определите интервал между интервалами, в которых появляются новые платформы

newPlatformTimePoint = 0
newPlatformInterval = 200 # 0.2 seconds

Когда игра была запущена. Установите текущий момент времени в основном цикле и установите время.точка для первой платформы, когда игра была запущена:

timePoint = pygame.time.get_ticks()
if event.key == pygame.K_1:
    oneDown = True
    gameStart()
    newPlatformTimePoint = timePoint + 1000 # 1 second after start

Добавьте новую платформу, когда превышен момент времени, и установите инкремент для следующего момента времени, увеличив его на newPlatformInterval.Не интервал может быть изменен (ускорен) во время игры.

if gameStarted is True: 
    drawingPlayer()
    movingPlayer()
    if timePoint > newPlatformTimePoint:
        newPlatformTimePoint = timePoint + newPlatformInterval
        creatingPlatform()
    movingPlatform()
    drawingPlatform()

Код основного цикла, с примененными предложениями:

newPlatformTimePoint = 0
newPlatformInterval = 200 # 0.2 seconds
while True:
    timePoint = pygame.time.get_ticks()

    surface.fill((95, 199, 250))
    pressedKey = pygame.key.get_pressed()
    for event in GAME_EVENTS.get():
        if event.type == pygame.KEYDOWN:
            # Event key for space should initiate sound toggle
            if event.key == pygame.K_1:
                oneDown = True
                gameStart()
                newPlatformTimePoint = timePoint + 1000 # 1 second after start

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_1:
                oneDown = False
                #KEYUP for the space bar
        if event.type == GAME_GLOBALS.QUIT:
            quitGame()

    if gameStarted is True: 
        drawingPlayer()
        movingPlayer()
        if timePoint > newPlatformTimePoint:
            newPlatformTimePoint = timePoint + newPlatformInterval
            creatingPlatform()
        movingPlatform()
        drawingPlatform()

    elif gameEnded is True:
        surface.blit(GameOverImage, (0, 0))

    else:
        surface.blit(StartImage, (0, 0))

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