还需能够将成绩保存到一个txt文件中
时间: 2024-03-23 14:42:53 浏览: 14
好的,以下是新增了将成绩保存到txt文件中的代码:
```python
import random
import time
# 定义游戏时间(单位:秒)
game_time = 60
# 定义玩家历史成绩字典
player_scores = {}
# 生成随机数
number = random.randint(1, 100)
# 定义猜数字的函数
def guess_number():
start_time = time.time() # 记录游戏开始时间
remaining_time = game_time # 初始化剩余时间
# 循环猜数字,直到时间到或猜对为止
while True:
guess = input("请输入一个1到100之间的整数:")
if guess.isdigit():
guess = int(guess)
if guess == number:
end_time = time.time() # 记录游戏结束时间
score = remaining_time + (game_time - (end_time - start_time)) # 计算得分
print(f"恭喜你,猜对了!你的得分是{score:.2f}分。")
player_name = input("请输入你的姓名:")
if player_name in player_scores:
player_scores[player_name].append(score)
else:
player_scores[player_name] = [score]
break
else:
if guess < number:
print("猜的数字太小了,请再试一次。")
else:
print("猜的数字太大了,请再试一次。")
else:
print("输入有误,请输入一个整数。")
# 更新剩余时间
remaining_time = game_time - (time.time() - start_time)
if remaining_time <= 0:
print("时间到了,游戏结束。")
break
else:
print(f"还剩{remaining_time:.2f}秒。")
# 调用猜数字的函数
guess_number()
# 输出历史成绩
print("历史成绩:")
for player, scores in player_scores.items():
print(f"{player}: {scores}")
# 保存成绩到txt文件中
with open("scores.txt", "w") as f:
for player, scores in player_scores.items():
f.write(f"{player}: {scores}\n")
```
在这个代码中,我们使用了一个`with`语句打开了一个名为`scores.txt`的文件,并以只写模式写入成绩。在`for`循环中,我们遍历了`player_scores`字典中的每个玩家及其成绩,并将其写入文件中。每个玩家的成绩占一行,格式为“姓名: 成绩”。
这样,当我们运行程序并结束游戏后,程序会自动将历史成绩保存到`scores.txt`文件中。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)