在 pygame 中显示文本时遇到问题

编程入门 行业动态 更新时间:2024-10-28 04:15:56
本文介绍了在 pygame 中显示文本时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是 pygame 和 python 的新手.我昨天开始了一个简单的直升机游戏项目,但我不知道为什么我无法显示消息.

I am a nubie in pygame and python overall. I started a simple helicopter game project yesterday but i cant figure out why i cant display a message.

我尝试使用不同的代码格式,也尝试在这里和那里移动几行,但仍然无法使其工作.

I tried using different code formats and also tried moving a few lines here and there but still could not get it to work.

def display_gameover(): pygame.font.init() font = pygame.font.SysFont(None, 100) text = font.render("GAME OVER", True, red) extRect = text.get_rect() screen.blit(text,(screen_height//2, screen_width//2)) pygame.display.update() time.sleep(2) if x > screen_width - heli_width or x < 0 or y > screen_height - heli_height or y < 0: display_gameover() game_loop()

我定义了 display_gameover 并如上所示调用它.但是,当我尝试运行代码时,一切正常,除了在 2 秒的等待时间内没有显示任何内容.

I defined display_gameover and called it as shown above. However when i try to run the code, everything works fine, apart from the fact that during the 2 second wait time, nothing is displayed.

推荐答案

调用 pygame.display.update() 是不够的,您还必须处理事件(例如通过pygame.event.pump()).此外,我建议使用 pygame.time.wait() 而不是 time.sleep().请注意,pygame.time.wait() 的时间单位是毫秒.

It is not sufficient to call pygame.display.update(), you've to handle the events, too (e.g. by pygame.event.pump()). Further I recommend to use pygame.time.wait() rather than time.sleep(). Be aware that the time unit for pygame.time.wait() is milliseconds.

def display_gameover(): pygame.font.init() font = pygame.font.SysFont(None, 100) text = font.render("GAME OVER", True, red) extRect = text.get_rect() screen.blit(text,(screen_height//2, screen_width//2)) pygame.display.update() pygame.event.pump() pygame.time.wait(2000) # 2000 milliseconds == 2 seconds

此外,您必须确保与显示器关联的 Surface 已初始化(pygame.display.set_mode()).这意味着如果 pygame 被 pygame.quit() 终止,那么它必须被 pygame.init() 重新初始化并且 screen 必须重新初始化在调用 display_gameover() 之前由 pygame.display.set_mode() 设置.或者不要终止 pygame.

Furthermore you've to ensure that the Surface which is associated to the display is initialized (pygame.display.set_mode()). This means if pygame was terminated by pygame.quit(), then it has to be reinitialized by pygame.init() and screen has to be set by pygame.display.set_mode() before the call to display_gameover(). Alternatively don't terminate pygame.

更多推荐

在 pygame 中显示文本时遇到问题

本文发布于:2023-07-03 21:55:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1012503.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   pygame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!