设为首页收藏本站

Crossin的编程教室

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

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

[复制链接]

0

主题

0

好友

8

积分

新手上路

Rank: 1

91#
发表于 2018-11-9 15:17:34 |只看该作者
本帖最后由 吃土小华 于 2018-11-9 15:18 编辑
吃土小华 发表于 2018-11-8 21:00
from random import randint

f = open('game.txt')

之前的问题已经解决了,可能是因为文本后面空白行的原因。
新的问题是这个
from random import randint

f = open('game.txt')
lines = f.readlines()
f.close()


scores = {}
for l in lines:
   s = l.split()

   scores[s[0]] = s[1:]

   
name  = input('请输入你的名字:')
score = scores.get(name)
if score is None:
    score = [0,0,0]

game_time = int(score[0])
min_time = int(score[1])
total_time = int(score[2])
if game_time>0:
    avg_times = float(total_time)/game_time
else:
    avg_times = 0

print('%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案。'%(name,game_time,min_time,avg_times))

num = randint(1,100)
time=0
bingo= False
print('Guess what I think.')
while bingo==False:
    answer=int(input())
    time+=1
    if answer<num:
        print('too small')
    if answer>num:
        print('too big')
    if answer==num:
        print('bingo')
        bingo=True

total_time +=time
if game_time==0 or time<min_time:
    min_time=time
game_time+=1
print(game_time,min_time,total_time)
game_times=str(game_time)
mins=str(min_time)
total=str(total_time)
scores[name] = {game_times,mins,total}
print(scores[name])
result=''
for n in scores:
    line = n +' '+' '.join(scores[n])+'\n'#line为字符串
    result += line


#f=open('game.txt','w')
#f.write(result)
#f.close()
这样写完后显示
请输入你的名字:小华
小华,你已经玩了0次,最少0轮猜出答案,平均0.00轮猜出答案。
Guess what I think.
50
too big
60
too big
25
too small
35
too small
40
too small
45
too small
48
too small
49
bingo
1 8 8
{'1', '8'}
>>>
其中小华的所有数值无法写入到字典里,只能显示两个值,文本文档中的内容和公众号一致,非常疑惑这是为什么,求大神解答,非常感谢。
回复

使用道具 举报

174

主题

45

好友

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

92#
发表于 2018-11-9 22:44:47 |只看该作者
吃土小华 发表于 2018-11-9 15:17
之前的问题已经解决了,可能是因为文本后面空白行的原因。
新的问题是这个
from random import randint

scores[name] = [game_times,mins,total]
这里是列表不是字典
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

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

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

GMT+8, 2024-5-19 07:30 , Processed in 0.029508 second(s), 21 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部