猜数字小游戏

本文介绍了一个基于Python的猜数字游戏,游戏会记录玩家的名字、游戏次数、最少猜数次数及平均猜数次数,并在每次游戏结束后更新这些记录。通过读取和写入本地文件,实现了游戏数据的持久化存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from random import randint
times = 0
name = input('请输入你的名字:')
f=open('game.txt')
lines=f.readlines()
f.close()
#将文本数据一行一行的获取出来


scores={}#定义一个空的字典
for l in lines:
    s = l.split()
    scores[s[0]]=s[1:]
    #将每一行的数据写入字典
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))


num = randint(1,100)
print("guess what i think?")
bingo = False
while bingo == False:
    answer = int(input())
    times += 1 
    if answer < num:
        print("%s is toot small" % answer)
    if answer > num:
        print("%s is toot big" % answer)
    if answer == num:
        print("bingo! %s is the right answer" % answer)
        break
    if answer == 1:
        break    #随机获取值,然后输入数字进行判断,开始猜数字游戏


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  #定义一个空的字符串,然后将新成绩取出来格式化(使用字符串join方式)例如 ‘gg 1 2 3’
    

f = open('game.txt', 'w') #将玩的真是次数写入文本中
f.write(result)
f.close()

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值