转载于:https://www.cnblogs.com/Neo007/p/7365439.html
【Python】猜数小游戏(文件操作),壹购网(python 猜数游戏)
0evadmin
编程语言
15
文件名:【Python】猜数小游戏(文件操作),壹购网
【Python】猜数小游戏(文件操作)
人生苦短,我用Python 关键词 1.多用户 2.字典记录所有成绩 3.每次游戏轮数&总游戏次数&平均每次游戏需要多少轮 字典Dictionary、列表List、元组Tuple差异化理解 from random import randintname = input('请输入你的名字:')#输入玩家名字#读取文件中的数据f = open('game.txt')lines = f.readlines()f.close()scores = { }#Initialize an empty directoryfor l in lines:s = l.split() # split (拆分)each line data to listscores[s[0]] = s[1:] #把第一项作为key,剩下的作为valuescore = 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_timeselse: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 = Falsewhile 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 = timestotal_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 和valueresult += linef = open('game.txt','w') # 相对路径,同一文件夹下f.write(result)f.close()
同类推荐
-

【Python Flask+Nginx】实现HTTP、WS (两步实现,简单易懂),8800诺基亚
查看 -

【Python 千题 —— 基础篇】进制转换:十进制转二进制,惠普笔记本型号大全
查看 -

【PythonRS】植被显示增强(多光谱、正射、照片等),东芝as100
查看 -

【Python】Locust持续优化:InfluxDB与Grafana实现数据持久化与可视化分析,诺基亚lumia1000
查看 -

【Python】Python爬虫使用代理IP的实现,硕美科g927(python爬取代理ip)
查看 -

【Python】Selenium自动化测试框架,Benjamin Ling
查看 -

【Python】comtypes模块Windows环境下使用批量转换成PDF文件,lg gd300s
查看 -

【Python】上市公司数据进行经典OLS回归实操,花王论坛(python ols回归)
查看 -

【Python】使用execute(sql)执行insert之后没有插入数据,网吧版迅雷
查看