Pygame 如何让我的排行榜在游戏中而不是在python shell上?
我正在努力为我的游戏制作排行榜 我有一个菜单显示屏和一个排行榜按钮,我想让玩家点击排行榜按钮,看到所有以前的名字和分数的列表,并添加他们最近的分数 我在网上发现这是可行的,但当我把它放到代码中时,它会得到600分的高分(我还没有输入),它会在Python shell中显示出来 我想让它在排行榜按钮内的页面中打开,有人知道如何帮助我在游戏中而不是在外壳上显示它吗Pygame 如何让我的排行榜在游戏中而不是在python shell上?,pygame,Pygame,我正在努力为我的游戏制作排行榜 我有一个菜单显示屏和一个排行榜按钮,我想让玩家点击排行榜按钮,看到所有以前的名字和分数的列表,并添加他们最近的分数 我在网上发现这是可行的,但当我把它放到代码中时,它会得到600分的高分(我还没有输入),它会在Python shell中显示出来 我想让它在排行榜按钮内的页面中打开,有人知道如何帮助我在游戏中而不是在外壳上显示它吗 谢谢大家! 这是一个极简主义的例子。高分在[姓名,分数]列表中。我使用模块保存并加载高分(使用json.dump和json.load函数
谢谢大家! 这是一个极简主义的例子。高分在[姓名,分数]列表中。我使用模块保存并加载高分(使用
json.dump
和json.load
函数)
当用户键入某个内容时,会将event.unicode
属性添加到字符串变量中以创建名称。当按下enter键时,名称和分数将附加到列表中,然后列表将被排序并保存为json文件
使用for循环将名称和分数输入表格
import json
from operator import itemgetter
import pygame as pg
from pygame import freetype
pg.init()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
FONT = freetype.Font(None, 24)
def save(highscores):
with open('highscores.json', 'w') as file:
json.dump(highscores, file) # Write the list to the json file.
def load():
try:
with open('highscores.json', 'r') as file:
highscores = json.load(file) # Read the json file.
except FileNotFoundError:
highscores = [] # Define an empty list if the file doesn't exist.
# Sorted by the score.
return sorted(highscores, key=itemgetter(1), reverse=True)
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
score = 150 # Current score of the player.
name = '' # The name that is added to the highscores list.
highscores = load() # Load the json file.
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
elif event.type == pg.KEYDOWN:
if event.key == pg.K_RETURN:
# Append the name and score and save the sorted the list
# when enter is pressed.
highscores.append([name, score])
save(sorted(highscores, key=itemgetter(1), reverse=True))
name = ''
elif event.key == pg.K_BACKSPACE:
name = name[:-1] # Remove the last character.
else:
name += event.unicode # Add a character to the name.
screen.fill((30, 30, 50))
# Display the highscores.
for y, (hi_name, hi_score) in enumerate(highscores):
FONT.render_to(screen, (100, y*30+40), f'{hi_name} {hi_score}', BLUE)
FONT.render_to(screen, (100, 360), f'Your score is: {score}', BLUE)
FONT.render_to(screen, (100, 390), f'Enter your name: {name}', BLUE)
pg.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
pg.quit()
然后,highscores.json
文件将如下所示:
[["Sarah", 230], ["Carl", 120], ["Joe", 50]]
为了得到一个有用的答案,请将您尝试过的代码直接发布在这里,然后清楚地解释您的预期以及实际发生的情况。当然!我在游戏中的代码与我附加的链接相同。