【Python】猜数小游戏(文件操作)

人生苦短,我用Python

关键词

1.多用户
2.字典记录所有成绩
3.每次游戏轮数&总游戏次数&平均每次游戏需要多少轮
字典Dictionary、列表List、元组Tuple差异化理解

from random import randint

name = input('请输入你的名字:')#输入玩家名字
#读取文件中的数据
f = open('game.txt')
lines = f.readlines()
f.close()

scores = { }#Initialize an empty directory
for l in lines:
    s = l.split() # split (拆分)each line data to list
    scores[s[0]] = s[1:] #把第一项作为key,剩下的作为value
score = scores.get(name) # 查找当前玩家的数据
if score is  None:#如果没找到该玩家
    score = [0,0,0] #初始化数据,new
    
# 分别存入变量中
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

#输出成绩信息,平均轮数保留2位小数
print ('%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案'%(name,game_times,min_times,avg_times))

num = randint(1,100)
times = 0 #记录本轮游戏次数

print ('Guess what I think?')
bingo = False
while bingo == False:
    times += 1 
    answer = int(input())
    if answer < num:
        print ('too small')
    if answer > num:
        print ('too big')
    if answer==num:
        print ('Bingo!')
        bingo = True
#如果是第一次玩,或者本轮游戏次数比最小次数少,则更新最小次数
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:
    line = n + ' ' + ' '.join(scores[n])+'\n' # 输出key 和value
    result += line
    

f = open('game.txt','w')  # 相对路径,同一文件夹下
f.write(result)
f.close()

1143923-20170815153825646-406217370.jpg
1143923-20170815153823350-918693441.jpg

转载于:https://www.cnblogs.com/Neo007/p/7365439.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值