【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 directory for l in lines:s = l.split() # split (拆分)each line data to listscores[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 = 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()轉載于:https://www.cnblogs.com/Neo007/p/7365439.html
總結
以上是生活随笔為你收集整理的【Python】猜数小游戏(文件操作)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于key/value+Hadoop H
- 下一篇: 如何使用CPU来加速你的Linux命令