如何在pygame窗口中显示pickled .txt文件中的文本

时间:2017-10-09 18:15:08

标签: python-3.x pygame pickle

我已经构建了一个游戏,使用pickle将用户得分记录并保存到文本文件中。当他们的生命被用尽时,他们输入他们的名字,他们的名字和分数被保存到文本文件中。目前,如果"高分"在主菜单上选择了一个部分,只需在python shell中打印高分(如果他们正在使用它,则为CMD)。我想创建一个单独的窗口来显示高分。窗口只显示分数,每次打开时都会刷新。

目前我有代码加载pickle文件并创建一个新窗口。如果我输入静态文本它工作正常,但当我尝试显示文本文件内容时,我收到以下错误:

追踪(最近一次通话):   文件" C:\ LearnArabic \ Program \ Test1.py",第22行,in     textsurface = myfont.render(high_scores,False,(0,0,0)) TypeError:text必须是unicode或bytes

这是我的代码:

import pygame
from operator import itemgetter
import pickle

pygame.font.init()

high_scores = []

with open("C:\\LearnArabic\\HighScores\\HighScores.txt", 'rb') as f:
    high_scores = pickle.load(f)

#Background color 
background_color = (255,255,255)
(width, height) = (400, 500)

HighScoreScreen = pygame.display.set_mode((width, height))
pygame.display.set_caption('High Scores')
HighScoreScreen.fill(background_color)

#Displaying text on window
myfont = pygame.font.SysFont('Comic Sans MS', 30)
textsurface = myfont.render(high_scores, False, (0, 0, 0))
HighScoreScreen.blit(textsurface,(0,0))

pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            running = False

渲染中是否有一个不同的函数可以让我以表格形式显示结果?

我对编程比较新,并且正在使用python 3.感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你可以将高分数点到另一个表面,然后将这个冲浪点到屏幕上。要对高分列表进行blit,请使用for循环并枚举列表,以便将y偏移量乘以i。要切换高分数表面,您只需添加变量highscores_visible = False,然后执行highscores_visible = not highscores_visible,然后在主循环中选中if highscores_visible: # blit the surf(按' h'进行更新和切换下面示例中的高分表。当然,您需要确保名称和高分能够适应表面。

import pygame


pygame.font.init()

screen = pygame.display.set_mode((400, 500))
clock = pygame.time.Clock()

high_scores = [
    ('Carrie', 350),
    ('Arthur', 200),
    ('Doug', 100),
    ]

background_color = (255, 255, 255)

highscore_surface = pygame.Surface((300, 400))
highscore_surface.fill((90, 100, 120))

myfont = pygame.font.SysFont('Comic Sans MS', 30)
highscores_visible = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_h:
                highscores_visible = not highscores_visible
                if highscores_visible:
                    highscore_surface.fill((90, 100, 120))
                    for i, (name, score) in enumerate(high_scores):
                        text = myfont.render('{} {}'.format(name, score), True, (0, 0, 0))
                        highscore_surface.blit(text, (50, 30*i+5))

    screen.fill(background_color)
    if highscores_visible:
        screen.blit(highscore_surface, (50, 50))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

关于TypeError,您无法将列表传递给myfont.render字符串或字节字符串,因此您必须转换列表,例如str(high_scores)。但是,如果您在传递之前将high_scores列表转换为字符串,则pygame会将整个列表呈现为一行。如果你想要几行文字,你需要使用for循环。