设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: mty1111
打印 上一主题 下一主题

【Python 第41课】 用文件保存游戏(3)

[复制链接]

0

主题

0

好友

8

积分

新手上路

Rank: 1

楼主
发表于 2016-8-5 20:16:37 |显示全部楼层
39.40.41断断续续看了一个星期,终于看完了,虽然不是很熟,但代码总算是都能看懂了,按照课程抄下来运行出一些小问题也都能找到问题出在哪里并且自己解决。
  1. from random import randint

  2. name=raw_input('请输入姓名:')
  3. f=file('text1.txt')
  4. lines=f.readlines()
  5. f.close()
  6. scores={}
  7. for l in lines:
  8.     s=l.split()
  9.     scores[s[0]]=s[1:] #s[0]是姓名,在score中是KEY,为键赋值.
  10. score=scores.get(name) #socre等于在字典scores查找的键
  11. if score is None:
  12.     score=[0, 0, 0] #给不存在的用户赋值创建一个新的字典项
  13.    
  14. game_times=int(score[0])
  15. min_times=int(score[1])
  16. total_times=int(score[2])
  17. if game_times>0:
  18.     avg_times=float(total_times)/game_times
  19. else:
  20.     avg_times=0
  21. print'%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案'%(name,game_times,min_times,\
  22.         avg_times)

  23. num=randint(1,100)
  24. times=0
  25. print'Guess what i think?'
  26. bingo=False
  27. while bingo==False:
  28.     times+=1
  29.     answer = input()
  30.     if num<answer:
  31.         print'too big'
  32.     if num>answer:
  33.         print'too small'
  34.     if num==answer:
  35.         print'bingo'
  36.         bingo=True
  37. if game_times==0 or times<min_times:
  38.     min_times=times
  39. total_times+=times
  40. game_times+=1
  41. scores[name]=[str(game_times),str(min_times),str(total_times)]
  42. result=''
  43. for n in scores: #遍历键
  44.     line=n+' '+' '.join(scores[n])+'\n' #姓名+空格+合并字典值为一个字符串要加空格+换行
  45.     result+=line #把成绩作为一个字符串赋值给result
  46. f=file('text1.txt','w')
  47. f.write(result)
  48. f.close()
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-19 09:45 , Processed in 0.024443 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部