from random import randint
times = 0
name = input('请输入你的名字:')
f=open('game.txt')
lines=f.readlines()
f.close()
#将文本数据一行一行的获取出来
scores={}#定义一个空的字典
for l in lines:
s = l.split()
scores[s[0]]=s[1:]
#将每一行的数据写入字典
score = scores.get(name)
if score is None:
score = [0,0,0]#如果字典中没用用户名(也就是新用户)就定义一个空的字典给这个用户
game_times = int(score[0])
min_times = int(score[1])
total_times = int(score[2])#取出字典中的值
if game_times > 0:
avg_times = float(total_times)/game_times
else:
avg_times = 0
print ('%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案'%(name,game_times,min_times,avg_times))
num = randint(1,100)
print("guess what i think?")
bingo = False
while bingo == False:
answer = int(input())
times += 1
if answer < num:
print("%s is toot small" % answer)
if answer > num:
print("%s is toot big" % answer)
if answer == num:
print("bingo! %s is the right answer" % answer)
break
if answer == 1:
break #随机获取值,然后输入数字进行判断,开始猜数字游戏
if game_times == 0 or times < min_times:
min_times = times #如果是新用户第一次玩,或者玩的次数小于现有的最小次数,就重新赋值
total_times += times #总次数相加
game_times += 1 #玩的次数加一次
scores[name] = [str(game_times), str(min_times), str(total_times)] #更新新的成绩
result = ''
for n in scores:
line = n + ' ' + ' '.join(scores[n]) + '\n'
result += line #定义一个空的字符串,然后将新成绩取出来格式化(使用字符串join方式)例如 ‘gg 1 2 3’
f = open('game.txt', 'w') #将玩的真是次数写入文本中
f.write(result)
f.close()