目次
1.调用外部库
2.代码实现
3.游戏实测
1.调用外部库
pygame库
2.代码实现
1.根本功能实现
(1条消息) python小游戏——贪吃蛇游戏_timberman666的博客-CSDN博客 https://blog.csdn.net/timberman666/article/details/129778682?spm=1001.2014.3001.55022.更新功能2.0版本
(1条消息) python小游戏——贪吃蛇游戏2.0版本の得分功能实现_timberman666的博客-CSDN博客 https://blog.csdn.net/timberman666/article/details/129782005?spm=1001.2014.3001.5502
3.汗青最高得分记录功能实现
为贪吃蛇游戏添加汗青最高分记录功能,可以在游戏竣事后将当前得分与汗青最高分举行比较,如果当前得分高于汗青最高分,则更新汗青最高分。可以在游戏竣事后表现汗青最高分。
首先,我们必要在游戏开始前读取汗青最高分,可以将汗青最高分生存在一个文件中,每次游戏开始前读取该文件即可。可以在代码中添加以下代码:
- # 读取历史最高分
- try:
- with open('high_score.txt', 'r') as f:
- high_score = int(f.read())
- except FileNotFoundError:
- high_score = 0
- # 定义得分
- score = 0
复制代码
这里利用了try-except语句,如果文件不存在,则会捕捉FileNotFoundError非常,然后将汗青最高分设置为0。
然后,在游戏竣事后,将当前得分与汗青最高分举行比较,如果当前得分高于汗青最高分,则更新汗青最高分,并将其生存到文件中。可以在代码中添加以下代码:
- # 判断是否更新历史最高分
- if score > high_score:
- high_score = score
- # 保存历史最高分
- with open('high_score.txt', 'w') as f:
- f.write(str(high_score))
复制代码 末了,在游戏竣事后,表现汗青最高分。可以在代码中添加以下代码:
- # 创建一个字体对象
- font = pygame.font.Font(None, 36)
- # 创建一个文本对象
- score_text = font.render("Score: " + str(score), 1, white)
- high_score_text = font.render("High Score: " + str(high_score), 1, white)
- # 绘制文本对象
- screen.blit(score_text, (width/2 - score_text.get_width()/2, height/2 - score_text.get_height()))
- screen.blit(high_score_text, (width/2 - high_score_text.get_width()/2, height/2))
复制代码 这样,就完成了为贪吃蛇游戏添加汗青最高分记录功能的利用
3.游戏实测
来源:https://blog.csdn.net/timberman666/article/details/129791187
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |