前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python入门(五) 猜随机数小游戏改进(涉及数据和文件的更新)

python入门(五) 猜随机数小游戏改进(涉及数据和文件的更新)

作者头像
星辉
发布2019-01-15 10:06:32
5770
发布2019-01-15 10:06:32
举报
# 猜随机数小游戏代码如下
from random import randint

num = randint(0, 100)
game_times = 0 # 玩家游戏次数
min_times = 0 # 最短次数猜中
total_times = 0 # 共猜测次数
times = 0 # 本次多少轮猜出答案
scores = {} # 记录数据的字典

# import random 可采用引入模块的形式写随机数代码
# num = random.randint(0, 100)


def judge_new(name):#判断新老用户
    global game_times
    global min_times
    global total_times
    try:
        f = open("data.txt")
        lines = f.readlines()  # 读取成为list数据
        f.close()
    except:
        print("文件打开失败.")
    #从列表中读取用户数据

    for l in lines:
        s = l.split()  # 把每一行拆分成list
        scores[s[0]] = s[1:]  # 名字作为key,剩下的为value
    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
        print("%s, 你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案" % (name, game_times, min_times, avg_times))
        print("%s, 请继续您的游戏." % name)
    else:
        avg_times = 0
        print("%s, 请开始您的新游戏." % name)
    #判断结果输出


def judge_game():
    global times
    _yournum = int(input("please input your number:"))
    times = 1
    while _yournum != num:
        if _yournum < num:
            print("这是你的第%d次猜测," % times + "你的数字%d比随机数小." % _yournum)
        else:
            print("这是你的第%d次猜测,你的数字%d比随机数大." % (times, _yournum))
        _yournum = int(input("please input your number:"))
        times = times + 1
    # 此处不能够用for循环,python中for循环不太适用条件循环
    print("这是你的第%d次猜测,你的数字%d与随机数相同." % (times, _yournum))
# 游戏部分


def upgrade(name):
    global game_times
    global min_times
    global total_times
    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: # n取到的为key值
        line = n + " " + " ".join(scores[n]) + "\n"
        result +=  line
    #制作输出字符串

    try:
        f = open("data.txt", "w")
        f.write(result)
        f.close()
    except:
        print("文件打开失败.")
    #结果输出文件


name = input("请输入你的名字:")  # name 用来区分玩家的标志
judge_new(name)
judge_game()
upgrade(name)

以上程序中所用到的知识点如下:

  • 字典

用法:dictionary = { 'key' = value,  ... } #一个键值对的集合 字典查找函数get()

用法:dictionary.get(查找的key值)

#若查找不到,函数返回None

  • 处理异常

用法

try: 引发异常的语句块 except: 处理异常的语句块

#适用情况

#输入不合规定的值 #需要打开的文件不存在

  • python "=="和"is"的区别

#"=="如果如果变量引用的对象值相等,则会返回True

#"is"如果两个变量指向相同的对象,则会返回True

  • python中的"与、或、非"

与:and 或:or 非:not

  • for...in遍历字典

用法

for name in score:

print(score[name])

#遍历的变量中存储的是字典的key

# dir(模块名)

#查看引入的模块中含有的函数和变量

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年02月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档