import random import os.path from datetime import datetime def guide_page(guide_word): print("*"*30, guide_word, "*"*30) def all_num(n): while True: if n.isdigit(): return int(n) n = input("您输入的不是数字,请重新输入:") def check_num_legal(n, a, b): if a <= n <= b: return True return False if __name__ == '__main__': guide_page("欢迎进入数字猜猜猜小游戏") begin = all_num(input("请输入数字起始值:")) end = all_num(input("请输入数字终止值:")) if begin == end: print("您输入的数字相同!!请重新启动程序。") else: v = random.randint(begin, end) times = 0 base_path = os.path.dirname(os.path.abspath(__file__)) record_path = os.path.join(base_path, 'record') with open(record_path, 'w', encoding='utf-8') as f: s = all_num(input("请输入您猜测的数字:")) f.write("{0} 您第1次猜测的值为:{1} ".format(str(datetime.now()), s)) while True: times += 1 if check_num_legal(s, begin, end): if s < v: print("Lower than the answer") elif s > v: print("Higher than the answer") else: print("恭喜您!只用了{0}次就赢得了游戏".format(times)) f.write("恭喜您!只用了{0}次就赢得了游戏".format(times)) break else: print("您输入的数字不在指定区间,请您输入合法数字。") print("*"*50) s = all_num(input("请继续输入您猜测的数字:")) f.write("{0} 您第{2}次猜测的值为:{1} ".format(str(datetime.now()), s, times+1))