【发布时间】:2020-06-02 00:44:06
【问题描述】:
我正在制作一个 High_Name_Score(玩家姓名和高分)列表,以在游戏结束屏幕 (show_go_screen) 期间显示。我能够保存和加载列表,按分数对其进行排序并将其传送到屏幕上,但我有两个问题:
1) 它显示在一条线上,我希望每个玩家/得分都在新线上
2) 它显示括号和引号,例如高分 ['3580 AABBCC', '3508 CCBBAA'] 我希望它更干净
我在网上搜索过,但还没有告诉我该怎么做
import pygame
import random
import sys
import json
from pygame.locals import *
def (main):
try:
with open('High_Name_Score.txt', 'r') as file:
High_Name_Score = json.load(file)
High_Name_Score.sort()
except FileNotFoundError:
High_Name_Score = []
High_Score = 0
PURPLE = (139, 0, 139)
arial = pygame.font.match_font('arial')
pygame.init()
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
pygame.display.set_caption("Racing Fury")
def events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
def draw_text(surf, text, size, x, y, fonts, color):
font = pygame.font.Font(fonts, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
def high_name():
High_Name = ""
Enter_Name = True
while Enter_Name:
DS.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYUP:
if event.key == K_a:
High_Name += 'A'
if event.key == K_b:
High_Name += 'B'
if event.key == K_c:
High_Name += 'C'
if event.key == K_RETURN:
High_Name_Score.append(str(High_Score) + " " + High_Name)
with open('High_Name_Score.txt', 'w') as file:
json.dump(High_Name_Score, file)
main()
draw_text(DS, "HIGH SCORE: " + str(High_Name), 18, W / 2, 700, arial, PURPLE)
pygame.display.flip()
def show_go_screen():
DS.fill(WHITE)
Bckgrnd = [Summer, Winter, Desert, Space]
Bckgrnd_Img = random.choice(Bckgrnd)
if Bckgrnd_Img == Space:
color = WHITE
else:
color = BLACK
DS.blit(Bckgrnd_Img, (0, 0))
for i in range(3):
draw_text(DS, "RACING FURY!", 64, W / 2 + (i + 1), H / 4 - 60 + (i + 1), bodoni, color)
draw_text(DS, "RACING FURY!", 64, W / 2, (H / 4 - 60), bodoni, PURPLE)
draw_text(DS, "Summer Track (S)", 18, W / 2, (HH - 70), arial, color)
draw_text(DS, "Winter Track (W)", 18, W / 2, (HH + 0), arial, color)
draw_text(DS, "Desert Track (D)", 18, W / 2, (HH + 70), arial, color)
for i in High_Name_Score:
draw_text(DS, "HIGH SCORE: " + str(High_Name_Score), 18, W / 2, (H / 4 - 160), arial, PURPLE)
pygame.display.flip()
waiting = True
while waiting:
global TRACK
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keystate = pygame.key.get_pressed()
if keystate[pygame.K_s]:
TRACK = 1
waiting = False
这是我认为所需的所有代码部分。不用说,当越过终点线时,会计算 High_Score,然后调用 high_name() 来输入玩家姓名。一切正常,玩家姓名和分数被保存,并放入列表中,只是当我将它放到屏幕上时,我得到了我不想看到的括号和引号,它们都显示在一行上
任何建议将不胜感激
【问题讨论】:
-
使用 JSON 存储分数数据的代码,但没有打包或解包。你期望这会发生什么?为什么不把乐谱文件写成纯文本呢?或其他一些易于解析的格式(如 CSV)。
-
所以您是说保存和检索的 .txt 文件不是我可以从中提取每个索引信息的“列表”?我可以在加载它之后对其进行排序,所以我不能通过调用每个索引来将它blit /打印到屏幕上,例如索引0将具有最高玩家得分和名称,而索引1将是第二名,索引2将是第三名,等等.?如果您可以提供示例代码供我参考,根据您对使用简单 CSV 的评论,我可以如何做到这一点?