设为首页收藏本站

Crossin的编程教室

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

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

[复制链接]

0

主题

0

好友

96

积分

注册会员

Rank: 2

楼主
发表于 2016-12-15 15:38:28 |显示全部楼层
  1. #-*-coding:utf-8-*-
  2. a = 1
  3. while a == 1:
  4.     from random import randint
  5.     name = raw_input('请输入你的名字')#输入名字
  6.    
  7.     f = open('jifen.txt')
  8.     lines = f.readlines()#读取文件内容并制成list
  9.     f.close()
  10.     scores = {}#建立一个字典
  11.     for i in lines:#遍历lines
  12.         s = i.split()#通过空格隔开制成list
  13.         scores[s[0]] = s[1:]#从list提出元素并在字典里赋值,名字是KEY,数据是VALUE


  14.     score = scores.get(name)#在字典中查找输入的名字
  15.     if score is None:
  16.         score = [0, 0, 0]
  17.    
  18.     game_times = int(score[0])#总游戏数
  19.     min_times = int(score[1])#最少轮数
  20.     total_times = int(score[2])#总轮数
  21.     if game_times > 0:
  22.         avg_times = float(total_times)/game_times
  23.     else:
  24.         avg_times = 0
  25.     print ' 你已经玩%d了次,最少%d轮猜出答案,平均%.2f轮猜出答案 '%(game_times,min_times,avg_times)

  26.     num = randint(1 , 100)
  27.     times = 0
  28.     print ' 请猜一个100以内的数字'
  29.     bingo = False
  30.     while bingo == False:
  31.         times += 1
  32.         answer = input()
  33.         if answer < num:
  34.             print 'too small'
  35.         if answer > num:
  36.             print 'too big'
  37.         if answer == num:
  38.             print 'bingo'
  39.             bingo = True
  40.    
  41.     if game_times == 0 or times < min_times:
  42.         min_times = times
  43.     total_times += times
  44.    
  45.     game_times += 1


  46.     scores[name] = [str(game_times),str(min_times),str(total_times)]#由于是新玩家 没有数据 给新玩家赋值
  47.     result = ' '
  48.     for n in scores:#遍历scores的KEY
  49.         line = n + ' ' +' '.join(scores[n]) + '\n'
  50.         #n是scores中的key也就是名字 scores[n] 是value 也就是数据

  51.         result += line#将遍历出来的元素加进result字符组

  52.         f = open ('jifen.txt','w')
  53.         f.write(result)
  54.         f.close
  55.         
复制代码
老师,请帮我看下后面的注解对不对,想了好长时间
回复

使用道具 举报

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

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

GMT+8, 2024-5-19 07:29 , Processed in 0.028557 second(s), 24 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部