Python初学者求助:射箭游戏如何实现最高分存储与结束时展示
解决turtle射箭游戏的最高分存储与展示问题
先修复你代码里的基础问题:重复导入turtle模块、t.pendown缺少调用括号、代码结构零散。然后在此基础上实现最高分存储功能——核心思路是用文本文件持久化保存最高分,游戏结束时读取文件对比当前分数,更新并展示。
完整实现代码
import turtle import random # 初始化游戏屏幕 screen = turtle.Screen() screen.bgcolor("red") screen.title("简易射箭游戏") # 绘制箭靶及对应分数映射 target_turtle = turtle.Turtle() target_turtle.pensize(4) target_turtle.speed(5) r = 180 # 最大环半径 y = -r # 从外到内的环对应分数 score_map = {"white": 10, "grey": 20, "blue": 30, "red": 40, "yellow": 50} for color in ["white", "grey", "blue", "red", "yellow"]: target_turtle.penup() target_turtle.goto(0, y) target_turtle.pendown() # 修复原代码的括号缺失问题 target_turtle.color(color) target_turtle.fillcolor(color) target_turtle.begin_fill() target_turtle.circle(r) target_turtle.end_fill() r -= 50 y = -r target_turtle.hideturtle() # 射箭并计算当前得分 def shoot_arrow(): arrow = turtle.Turtle() arrow.shape('arrow') arrow.penup() # 随机生成射箭起始位置 start_x = random.randint(-100, 0) start_y = random.randint(0, 100) arrow.goto(start_x, start_y) # 朝靶心方向移动 arrow.setheading(arrow.towards(0, 0)) arrow.speed(3) arrow.forward(300) # 根据箭头落点计算得分 final_x, final_y = arrow.pos() distance = ((final_x ** 2) + (final_y ** 2)) ** 0.5 current_score = 0 # 从内到外判断命中的环 if distance <= 30: current_score = score_map["yellow"] elif distance <= 80: current_score = score_map["red"] elif distance <= 130: current_score = score_map["blue"] elif distance <= 180: current_score = score_map["grey"] elif distance <= 230: current_score = score_map["white"] arrow.hideturtle() return current_score # 读取本地存储的最高分 def load_high_score(): try: with open("high_score.txt", "r") as f: return int(f.read().strip()) except (FileNotFoundError, ValueError): # 文件不存在或内容无效时,默认最高分为0 return 0 # 将新最高分写入本地文件 def save_high_score(score): with open("high_score.txt", "w") as f: f.write(str(score)) # 游戏主流程 current_score = shoot_arrow() high_score = load_high_score() # 更新并判断是否刷新最高分 if current_score > high_score: high_score = current_score save_high_score(high_score) result_text = f"新纪录!当前得分:{current_score},最高分:{high_score}" else: result_text = f"当前得分:{current_score},最高分:{high_score}" # 在屏幕底部展示结果 text_turtle = turtle.Turtle() text_turtle.hideturtle() text_turtle.color("white") text_turtle.penup() text_turtle.goto(0, -250) text_turtle.write(result_text, align="center", font=("Arial", 16, "bold")) screen.exitonclick()
关键功能说明
- 基础问题修复:补全
t.pendown()的调用括号,合并重复的箭头生成代码,优化整体结构。 - 得分逻辑:通过计算箭头落点到靶心的距离,判断命中的环数并匹配对应分数。
- 最高分持久化:
load_high_score():读取本地的high_score.txt文件,首次运行文件不存在时默认最高分0。save_high_score():当当前得分超过历史最高分时,将新分数写入文件,确保下次打开游戏仍能读取历史最高分。
- 结果展示:用turtle的文本绘制功能,在屏幕底部清晰显示当前得分与最高分,刷新纪录时给出明确提示。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

