pygame-KidsCanCode系列jumpy-part8-记录历史最高分

通常在多玩家的游戏中,每个玩家都会有自己的得分,最高分数会成为该游戏的最佳记录。这一篇,学习下如何记录最高得分:(为了简化代码,本文采用文件方式,仅记录本机得分,明白原理后,可以将得分保存在云端或数据库中,就可能支持多玩家了)。

首先要在settings.py中新建一个常量:

HIGH_SCORE_FILE = "../data/high_score.txt"

目录结构参考下图:
pygame-KidsCanCode系列jumpy-part8-记录历史最高分

然后main.py中,定义一个load_data函数,加载这个文件的内容:

     def load_data(self):
# 加载历史最高分
file_path = path.join(self.dir, HIGH_SCORE_FILE)
if path.exists(file_path):
with open(file_path, "r") as f:
try:
self.high_score = int(f.read())
except:
self.high_score = 0

注意这里要做好异常处理(因为文件有可能被锁定,或不存在)

初始化时,调用该函数,加载历史最高得分:

     def __init__(self):
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode(SIZE)
pg.display.set_caption(TITLE)
self.clock = pg.time.Clock()
self.running = True
self.playing = False
self.font_name = FONT_NAME
# 初始化最高得分
self.high_score = 0
self.score = 0
self.dir = path.dirname(__file__)
# 加载历史最高得分
self.load_data()

启动画面,加上历史最高得分显示:

     def show_start_screen(self):
self.screen.fill(BG_COLOR)
self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT * 0.4)
self.draw_text("Arrows to move, Space to jump", 22, WHITE, WIDTH / 2, HEIGHT * 0.55)
self.draw_text("Press a key to play", 20, WHITE, WIDTH / 2, HEIGHT * 0.7)
# 显示最高得分
self.draw_text("High Score: " + str(self.high_score), 20, WHITE, WIDTH / 2, 15)
pg.display.update()
self.wait_for_key()

游戏结束时,如果出现得分新记录,保存到文件中:

     def show_go_screen(self):
self.screen.fill(BG_COLOR)
self.draw_text("GAME OVER", 48, WHITE, WIDTH / 2, HEIGHT * 0.4)
self.draw_text("Score: " + str(self.score), 22, WHITE, WIDTH / 2, HEIGHT * 0.55)
self.draw_text("Press a key to play again", 20, WHITE, WIDTH / 2, HEIGHT * 0.7)
# 如果得分出现新记录,保存下来
if self.score > self.high_score:
self.high_score = self.score
self.draw_text("New High Score: " + str(self.high_score), 28, WHITE, WIDTH / 2, 25)
with open(path.join(self.dir, HIGH_SCORE_FILE), "w") as f:
f.write(str(self.high_score))
else:
self.draw_text("High Score: " + str(self.high_score), 20, WHITE, WIDTH / 2, 15) pg.display.update()
self.wait_for_key()

pygame-KidsCanCode系列jumpy-part8-记录历史最高分

pygame-KidsCanCode系列jumpy-part8-记录历史最高分

github源码地址: https://github.com/yjmyzz/kids-can-code/tree/master/part_08

上一篇:Sending Signals to Processes with kill, killall, and pkill


下一篇:oracle学习----统计信息