我从早期的脚本中复制了大部分代码,但是当我加载游戏时,几乎所有的元素都在闪烁。 这是最小的完整可验证示例:
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和按钮函数时,它们都会开始闪烁(除了调用的第一个函数之外的所有内容)。更改功能的顺序会改变哪一个会停止闪烁。其他一切都很好。当光标位于它们上方时,按钮会改变颜色,仍然可以单击它们并具有功能
答案 0 :(得分:1)
不要在游戏循环的每次迭代中多次调用pygame.display.update()
。它会导致你看到的屏幕闪烁。
只需移除pygame.display.update()
和message_to_screen
功能中的text_to_button
来电即可。