我正在尝试为自己的游戏排行榜。
我有一个菜单显示屏幕和一个排行榜按钮,我想要的是让玩家单击该排行榜按钮并查看所有以前的名称和得分的列表,并成为安倍添加最新的得分。
我在网上发现的I have some code可以正常工作,但是当我将其放入代码中时,它的最高得分为600(我没有输入),并且在Python shell中得到了它。
我想要在排行榜按钮内的页面中打开它,有人知道如何帮助我让它显示在游戏中而不是在外壳上吗?
谢谢!
答案 0 :(得分:0)
这是一个简单的例子。高分在[名称,分数]列表列表中。我使用json
模块保存和加载高分(使用json.dump
和json.load
函数)。
当用户键入某些内容时,会将event.unicode
属性添加到字符串变量中以创建名称。按Enter键时,名称和分数将添加到列表中,然后进行排序并保存为json文件。
用for循环将enumerated的名称和分数括起来以得到表格。
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]]