Мерцание кнопок и текста - PullRequest
0 голосов
/ 05 июня 2018

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

import pygame

pygame.init()

displayWidth = 1280
displayHeight = 720

gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Grow')

black = (0, 0, 0)
brown = (100, 100, 0)
green = (0, 200, 0)
lightGreen = (0, 255, 0)
red = (200, 0, 0)
lightRed = (255, 0, 0)

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)

clock = pygame.time.Clock()
FPS = 60

def gameIntro():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        gameDisplay.fill(brown)
        message_to_screen('Welcome to Tanks', green, -100, 'large')
        message_to_screen('The objective is to shoot and destroy', black, -30)
        message_to_screen('Shoot and destroy the enemy tank before they destroy you', black, 10)
        message_to_screen('The more enemies you destroy, the harder they get', black, 50)

        button('quit', 500, 500, 100, 50, red, lightRed, action = 'quit')
        button('play', 200, 500, 100, 50, green, lightGreen, action = 'play')
        pygame.display.update()
        clock.tick(0)

def gameLoop():
    pygame.quit()
    quit()

def button(text, x, y, width, height, inactive_color, active_color, action = None):
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x + width > cur[0] > x and y + height > cur[1] > y:
        pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
        if click[0] == 1 and action != None:
            if action == 'quit':
                pygame.quit()
                quit()
            if action == 'play':
                gameLoop()
    else:
        pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
    text_to_button(text, black, x, y, width, height)

def text_to_button(msg, colour, buttonx, buttony, buttonwidth, buttonheight, size = 'small'):
    textSurf, textRect = text_objects (msg, colour, size)
    textRect.center = ((buttonx + (buttonwidth/2)), buttony + (buttonheight/2))
    gameDisplay.blit(textSurf, textRect)
    pygame.display.update()

def message_to_screen(msg, colour, y_displace = 0, size = 'small'):
    textSurf, textRect = text_objects (msg, colour, size)
    textRect.center = (displayWidth / 2), (displayHeight / 2) + y_displace
    gameDisplay.blit(textSurf, textRect)
    pygame.display.update()

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

gameIntro()

По какой-то причине в функции gameIntro, когда я вызываю функции message_to_screen и button, все они начинают мигать (все, кроме первой вызванной функции).Изменение порядка функций приводит к изменению, которое перестает мигать.Все остальное работает отлично.Кнопки меняют цвет, когда курсор находится над ними, и они все еще могут быть нажаты и имеют функциональность

1 Ответ

0 голосов
/ 05 июня 2018

Не вызывайте pygame.display.update() несколько раз в каждой итерации игрового цикла.Это приведет к мерцанию экрана.

Просто удалите вызовы pygame.display.update() в функциях message_to_screen и text_to_button.

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