用文件保存遊戲
from random import randint
name = input('請輸入你的名字:') #輸入玩家名字
f = open('011.txt') #打開文件011.txt,讀取文件中的成績數據
lines = f.readlines() #把內容按行讀取,存入lines的列表中
f.close()
scores = {} #初始化一個叫scores的字典
for i in lines: #將多行列表lines中的數據賦值給i
s = i.split() #把每一行的數據切割,得到新的列表s
scores[s[0]] = s[1:] #將第一項作爲key,第二項開始作爲value
score = scores.get(name) #查找當前玩家(name)的數據
if score is None: #如果沒有找到(返回值是None)
score = [0, 0, 0] #新建一個數據score
game_times = int(score[0]) #score中的第一個元素定義爲game_times(遊戲次數)
min_times = int(score[1]) #score中的第二個元素定義爲min_times(最少次數)
total_times = int(score[2]) #score中的第三個元素定義爲total_times(總次數)
if game_times > 0:
avg_times = float(total_times) / game_times #平均次數
else:
avg_times = 0
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 Big!')
if answer < num:
print ('Too small!')
if answer == num:
print ('Bingo!!!')
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)] #把成績更新到對應玩家的數據中。。加str轉換成字符串,爲後面格式化做準備
result = '' #初始化一個空字符串,用來存儲數據
for n in scores:
line = n + ' ' + ' '.join(scores[n]) + '\n' #把成績按照“name game_times min_times total_times”格式化。。。結尾加上\n換行
result += line #添加到result中
f = open('011.txt', 'w')
f.write(result)
f.close()