You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import random
from datetime import datetime
def generate_target_num():
"""生成1-100的随机目标数字"""
return random.randint(1, 100)
def guess_game():
target_num = generate_target_num()
guess_count = 0
guess_history = []
print("欢迎来到猜数字游戏目标数字范围1-100")
while True:
try:
user_guess = int(input("请输入你猜测的数字:"))
guess_count += 1
guess_history.append(user_guess)
if user_guess > target_num:
print("猜大了!再试试~")
elif user_guess < target_num:
print("猜小了!再试试~")
else:
print(f"恭喜你,猜对了!你一共猜了{guess_count}次")
return guess_count, guess_history, target_num
except ValueError:
print("输入错误!请输入1-100之间的整数。")
def save_game_record(guess_count, guess_history, target_num):
"""将游戏记录保存到game_record.txt文件"""
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
record = (
f"游戏时间:{current_time}\n"
f"目标数字:{target_num}\n"
f"猜测次数:{guess_count}\n"
f"猜测历史:{guess_history}\n"
"-------------------------\n"
)
with open("game_record.txt", "a", encoding="utf-8") as f:
f.write(record)
print("游戏记录已保存到game_record.txt")
if __name__ == "__main__":
count, history, target = guess_game()
save_game_record(count, history, target)