Pygame报TypeError: decoding str is not supported错误 如何正确解码渲染字符串
错误原因
你遇到的TypeError: decoding str is not supported错误由以下几个代码问题共同导致:
- 构造字符串
STR_xo时错误使用了str()多参数构造方式:str("You ARE \n" , Character)的写法是错误的,str()传入第二个参数时会被识别为编码格式,你传入了字符串类型的Character自然会触发解码报错。 - 给
Character赋值时错误使用了比较运算符==,导致Character始终是空字符串,没有正确赋值为X或O。 - 代码开头未导入依赖库
pygame和random。 pygame.font.render原生不支持\n换行符,直接传入换行文本会导致渲染异常。- 画布绘制逻辑错误放在了事件遍历循环内部,只有触发事件时才会更新画面内容。
修复后的完整代码
import pygame import random # 初始化pygame pygame.init() # 创建窗口 win = pygame.display.set_mode((500, 500)) # 加载字体 font = pygame.font.Font('freesansbold.ttf', 32) # 颜色变量 Blackk = (0, 0, 0) Redd = (255, 0, 0) Bluee = (0, 0, 255) Character = "" # 随机分配X或O x_o = random.randint(0, 1) if x_o == 1: Character = "X" else: Character = "O" # 拼接提示文本,去掉不支持的换行符 STR_xo = f"You ARE {Character}" # 渲染文本 You_R = font.render(STR_xo, True, Blackk, (240, 240, 240)) # 获取文本矩形区域并居中 textRect = You_R.get_rect() textRect.center = (250, 50) # 放在顶部居中位置 # 设置窗口标题 pygame.display.set_caption("Tic Tac Toe") # 主游戏循环 RunNow = True while RunNow: # 事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: RunNow = False # 画布绘制逻辑移到事件循环外 win.fill((240, 240, 240)) # 绘制井字棋网格 pygame.draw.rect(win, Blackk, pygame.Rect(150, 0, 20, 500)) pygame.draw.rect(win, Blackk, pygame.Rect(335, 0, 20, 500)) pygame.draw.rect(win, Blackk, pygame.Rect(0, 150, 500, 20)) pygame.draw.rect(win, Blackk, pygame.Rect(0, 335, 500, 20)) # 绘制提示文本 win.blit(You_R, textRect) pygame.display.update() pygame.quit()
额外优化说明
如果需要展示两行提示文本,单独渲染两行文本分别放置即可,无需尝试让render支持换行。
内容的提问来源于stack exchange,提问作者Harsshavardhan Kannan
相关产品推荐
相关产品推荐

