设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: mty1111
打印 上一主题 下一主题

【Python 第41课】 用文件保存游戏(3)

[复制链接]

0

主题

0

好友

8

积分

新手上路

Rank: 1

楼主
发表于 2017-11-20 08:52:54 |显示全部楼层

请教老师,这是哪里出问题了

name=input('请输入你的名字:')
f1=open('d:\py\game.txt')
lines=f1.readlines()   #读取文件。与之前不同,我们用readlines把每组成绩分开来
f1.close()

scores={}              #再用一个字典来记录所有的成绩
for i in lines:
    s=i.split()
    scores[s[0]]=s[1:] #每一项的key是玩家的名字,value是一个由剩下的数据组成的数组。把成绩赋值给键
score=scores.get(name) #查找当前玩家数据
if score is None: #没有找到该玩家数据,说明是新玩家,给他初始化一组成绩:
    socre=[0,0,0]

from random import randint #用random模块中的randint这个方法产生随机数
game_times=int(score[0])  #玩游戏次数
min_times=int(score[1])   #最快猜出的轮数
total_times=int(score[2]) #猜过的总轮数
if game_times>0:         #分母不能为0,所以加了个判断
    avg_times=float(total_times)/game_times  #平均数可能是小数,所以在之前加个float
else:
    avg_times=0
print('%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案' %(
    name,game_times,min_times,avg_times))

num=randint(1,100)
times=0            #记录本次游戏轮数
print('gusee what i think?')
bingo=False  #先让循环动起来!
while bingo==False:
    times+=1       #每进行一次就记录一次轮数
    answer=int(input())
    if answer<num:
        print('%.2f is too small!' %answer)
    if answer>num:
        print('%.2f is too big!'%answer)
    if answer<0:
        print('exit game')
        break             #输入负数提前结束游戏
    if answer==num:
        print('bingo,%.2f is the right answer!'%answer)
        bingo=True  
  
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)] #把成绩更新到scores中,如果没有这一项,会自动生成新条目
result=''    #初始化一个空字符串
for n in scores:
    line=n+''+' '.join(scores[n])+'\n' #把成绩按照“game_times,min_times,total_times”格式化
    result+=line  #添加到result中

f1=open('d:\py\game.txt','w')
f1.write(result)    #把结果输入到文件中
f1.close()
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-5 07:42 , Processed in 0.027473 second(s), 24 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部