设为首页收藏本站

Crossin的编程教室

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

【Python 第40课】 用文件保存游戏(2)

[复制链接]

0

主题

2

好友

72

积分

注册会员

Rank: 2

楼主
发表于 2018-4-12 15:19:54 |显示全部楼层
  1. #读取文件中的成绩数据
  2. f=open('D:\game.txt')
  3. score=f.read().split()
  4. f.close()
  5. #分别存入变量中
  6. game_times=int(score[0])
  7. min_times=int(score[1])
  8. total_times=int(score[2])
  9. times=0
  10. #计算游戏的平均轮数,注意浮点数和避免除零错误
  11. if game_times>0:
  12.     avg_times=float(total_times)/game_times
  13. else:
  14.     avg_times=0
  15. print(game_times,min_times,avg_times)
  16. import random
  17. num=random.randint(1,5)
  18. guess=eval(input('guess what I think?'))
  19. #猜数过程
  20. def compare(x,y):
  21.     if x<y:
  22.         print('%d is too small' %x)
  23.     elif x>y:
  24.         print('%d is too big' %x)
  25.     else:
  26.         print('bingo')
  27.     return x==y

  28. #开始猜数
  29. while num!=guess:
  30.     compare(guess,num)
  31.     guess=eval(input('guess what I think?'))
  32.     times+=1
  33. print('bingo')
  34. if game_times==0 or times<min_times:
  35.     min_times=times
  36. total_times+=times
  37. game_times+=1
  38. result='%d %d %d' %(game_times,min_times,total_times)
  39. f=open('D:\game.txt','w')
  40. f.write(result)
  41. f.close()


  42.    

复制代码
回复

使用道具 举报

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

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

GMT+8, 2024-5-7 19:44 , Processed in 0.027249 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部