Python 用文件保存游戏(2)

来源:互联网 发布:油漆调色软件下载 编辑:程序博客网 时间:2024/06/07 11:31
from random import randint#读取文件中的成绩数据f=open('game.txt')#注意文件名要正确score=f.read().split()f.close()#分别存入变量中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_timeselse:    avg_times=0    #输出成绩信息,平均轮数保留2位小数print '你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案'%(game_times,min_times,avg_times)num=randint(1,100)times=0 #记录本次游戏次数print 'Guess what I think?'bingo =Falsewhile bingo==False:    answer = input()    if answer<num:        print '%d is too small!'%answer #这里代的是answer    if answer>num:        print '%d is too big!'%answer    if answer==num:        print 'Bingo,%d is the right answer!'%num        bingo=True#如果是第一次玩,或者轮数比最小轮数少,则更新最小轮数if game_times==0 or times<min_times:    min_times=timestotal_times+=timesgame_times+=1result='%d %d %d' %(game_times,min_times,total_times)f=open('game.txt','w')f.write(result)f.close()


结果:


你已经玩了3次,最少5轮猜出答案,平均10.33轮猜出答案(game.txt 文件中把默认为3 5 10)
Guess what I think?
56
56 is too big!
49
49 is too big!
45
45 is too big!
25
25 is too small!
35
35 is too small!
4
4 is too small!
40
40 is too big!
37
Bingo,37 is the right answer!

0 0
原创粉丝点击