用Python完成猜隨機數的遊戲
阿新 • • 發佈:2019-02-01
from random import randint print '輸入你的名字:' name = raw_input() f = open('game.txt') lines = f.readlines() scores = {}#初始化一個空字典 for l in lines: s = l.split() scores[s[0]] = s[1:] #print s[:]-----------------['yaoxiaokui', '1', '6', '6'] score = scores.get(name) if score is None: score = [0, 0, 0] 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 print '%s,你已經玩了%d次,最少%d輪猜出答案,平均%.2f輪猜出答案' %(name, game_times, min_times,avg_times) print '輸入數值的最大值' max = input() num = randint(1, max) times = 0#記錄本次遊戲輪數 print 'Guess what i think?' answer = input() while answer!=num: times += 1 if answer > num: print 'too large' if answer < num: print 'too small' answer = input() print 'You Win!' 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)] result = '' for n in scores: line = n + ' ' + ' '.join(scores[n]) + '\n' result += line f = file('game.txt', 'w') f.write(result) f.close()