几年来,我一直在研究和开发基于文本的冒险游戏。它最初是作为学习Python的一种方式开始的,然后在我对这种语言感到满意之后,便着手进行与自己的职业更相关的项目。我现在有点称职(仍然是菜鸟,但您知道,进步了),我想回到游戏中添加更复杂的功能。
让我烦恼的一件事是我的开始菜单中出现了视觉错误。下面是代码:
import pygame
from pygame_functions import setBackgroundImage
import gamefile
pygame.init()
display_width = 1500
display_height = 750
startMenu = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("The Woodsman's Tale")
black = (0, 0, 0)
green = (0, 200, 0)
white = (255, 255, 255)
dark_red = (200, 0, 0)
bright_green = (0, 255, 0)
leaf_green = (0, 175, 75)
brown = (102, 51, 0)
red = (255, 0, 0)
clock = pygame.time.Clock()
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()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(startMenu, ac, (x, y, w, h))
if click[0] == 1 and action is not None:
if action == 'play':
gamefile.rungame()
start_menu().intro = False
elif action == 'quit':
pygame.quit()
quit()
else:
pygame.draw.rect(startMenu, ic, (x, y, w, h))
smallText = pygame.font.Font("freesansbold.ttf", 20)
TextSurf, TextRect = text_objects(msg, smallText)
TextRect.center = (x + (w / 2), (y + (h / 2)))
startMenu.blit(TextSurf, TextRect)
def start_menu():
intro = True
while intro:
setBackgroundImage('startScreen.png')
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
largeText = pygame.font.Font('BRADHITC.ttf', 90)
TextSurf, TextRect = text_objects("The Woodsman's Tale", largeText)
TextRect.center = (display_width / 2, display_height / 3)
startMenu.blit(TextSurf, TextRect)
button('Play', 350, 500, 200, 150, green, leaf_green, 'play')
button('Quit', 850, 500, 200, 150, dark_red, red, 'quit')
pygame.display.update()
clock.tick(15)
if __name__ == '__main__':
start_menu()
导入的setbackgroundimage函数是这样的:
def setBackgroundImage(img):
global bgSurface, backgroundImage
surf = loadImage(img)
backgroundImage = surf
screen.blit(surf, [0, 0])
bgSurface = screen.copy()
updateDisplay()
现在,开始菜单效果很好。一切正常。我的问题是,当我单击标题栏(例如移动窗口)时,开始菜单开始出现视觉上的停顿。
确实发生了什么:一旦单击标题栏,开始菜单的“按钮”和游戏的“标题”文本就会消失。释放单击后,按钮和“标题”文本会重新出现,但会迅速停顿。
我不确定自己是否会提供足够的信息让所有人知道发生了什么事情,所以我很抱歉。
第一个问题是setBackgroundImage
似乎可以更新显示(updateDisplay()
)。
在主应用程序循环结束时,显示必须更新一次,并且不应多次更新。导致闪烁。从以下位置删除显示更新setBackgroundImage
:
def start_menu():
intro = True
while intro:
setBackgroundImage('startScreen.png') # draw background but do no update the display
# [...]
pygame.display.update() # the one and only update at the end of the loop
clock.tick(15)
第二个问题是背景图片已加载到中setBackgroundImage
。这导致图像在每帧中连续加载。这会影响性能。
在主循环之前加载图像并将Surface
对象传递给setBackgroundImage
:
def start_menu():
surf = loadImage('startScreen.png')
intro = True
while intro:
setBackgroundImage(surf)
# [...]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句