- 帖子
- 12
- 精华
- 0
- 积分
- 60
- 阅读权限
- 20
- 注册时间
- 2017-10-24
- 最后登录
- 2017-12-12
|
- from random import randint
- name = input('请输入你的名字:')
- f = open('game.txt')
- lines = f.readlines()
- f.close()
- scores = {} # 初始化字典
- for l in lines :
- s = l.split() # 把每一行的数据拆分成list
- scores[s[0]] = s[1:] # 第一项作为key,剩下的作为value
- score = scores.get(name) # 查找当前玩家数据
- if score is None:
- score = [0,0,0] # 如果查不到score,就初始化score
- # 游戏主代码
- game_times = int(score[0])
- min_times = int(score[1])
- total_times = int(score[2])
- if game_times > 0:
- avq_times = float(total_times) / game_times
- else:
- avq_times = 0
- print('%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案'%(
- name,game_times,min_times,avq_times)) # 加了个名字name,在括号处换行.
- num = randint(1,10)
- times = 0 # 记录本次游戏轮数
- print('猜猜我想啥?')
- bingo = False
- while bingo == False:
- times += 1 #轮数+1
- answer = int(input())
- if answer > num:
- print('太大了')
- if answer < num:
- print('太小了')
- if answer == num:
- print('bingo')
- bingo = True
- if answer < 0:
- print('Exit game...')
- break
- # 如果是第一次玩,或者轮数比最小轮数少,则更新最小轮数。
- if game_times ==0 or times < min_times:
- min_times = times
- total_times += times # 总游戏轮数增加
- game_times += 1
- # 把成绩更新到对应玩家当中
- # 加上str转化为字符串,为后面的格式做准备
- scores[name] = [str(game_times),str(min_times),str(total_times)]
- result = '' # 初始化一个空字符串用来存储
- for n in scores: # 把成绩按照'name,game_times,min_times,total_times',结尾要加上\n换行
- line = n +' '+' '.join(scores[n])+'\n'
- result += line
- f = open('game.txt','w')
- f.write(result)
- f.close()
复制代码 |
|