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

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

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

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

目录结构参考下图:

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

1     def load_data(self):
2         # 加载历史最高分
3         file_path = path.join(self.dir, HIGH_SCORE_FILE)
4         if path.exists(file_path):
5             with open(file_path, "r") as f:
6                 try:
7                     self.high_score = int(f.read())
8                 except:
9                     self.high_score = 0
View Code

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

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

 1     def __init__(self):
 2         pg.init()
 3         pg.mixer.init()
 4         self.screen = pg.display.set_mode(SIZE)
 5         pg.display.set_caption(TITLE)
 6         self.clock = pg.time.Clock()
 7         self.running = True
 8         self.playing = False
 9         self.font_name = FONT_NAME
10         # 初始化最高得分
11         self.high_score = 0
12         self.score = 0
13         self.dir = path.dirname(__file__)
14         # 加载历史最高得分
15         self.load_data()
View Code

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

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

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

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

 

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

posted @ 2019-02-17 12:13 菩提树下的杨过 阅读(...) 评论(...) 编辑 收藏