python - 如何在 pygame 的屏幕顶部显示分数?
问题描述
我试图在屏幕顶部显示平台游戏的分数,但每次运行它时都会收到此错误:“文本必须是 Unicode 或字节”我已经在网站上查看过,代码看起来就像我写的一样,但我仍然遇到同样的错误。到目前为止,这是我的代码:
def __init__(self):
#this has all the things needed to initialise the game but the only relevant one to my problem is this line
self.font_name = pygame.font.match_font(FONT_NAME)
def draw(self):
self.screen.fill(BLACK)
self.all_sprites.draw(self.screen)
self.draw_text(self.score, 22, WHITE, WIDTH / 2, 15)
pygame.display.flip()
def draw_text(self, text, size, colour, x, y):
font = pygame.font.Font(self.font_name, size)
text_surface = font.render(text, True, colour)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
self.screen.blit(text_surface, text_rect)
所有大写的东西都在另一个我称为设置的文件中被赋予了值,然后导入到这个文件中。
问题似乎与 text_surface 线有关,但我不知道问题是什么。
解决方案
的第一个参数render
必须是一个字符串,看起来你试图传递一个数字。
从文档:
文本只能是单行:不呈现换行符。空字符 ('x00') 引发 TypeError。接受 Unicode 和 char(字节)字符串。
str
首先使用以下函数将您的值转换为字符串:
font.render(str(text), True, colour)
推荐阅读
- objective-c - 来自 dispatch_async 全局的 C 函数调用崩溃但在主队列上工作
- php - PHP - 检查数据库列是否为空
- mysqli - Mysql- SELECT Column 'A' 即使有 NULLS
- javascript - 根据文本框值选中或取消选中复选框 Adobe Acrobat Stamp Javascript
- vba - 运行时错误“5”无效的过程调用或参数
- dart - 超类型的静态成员必须由定义类型的名称限定
- c# - IE 和 Chrome 中的 ASP.NET 日期格式不起作用
- python - 通常将 For 循环转换为列表理解
- python - Google App Engine - Python 3 - ModuleNotFoundError:没有名为“pytz”的模块
- r - 使用向量化或应用从矩阵中提取值以绑定一个向量