# 猜随机数小游戏代码如下
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: 处理异常的语句块
#适用情况
#输入不合规定的值 #需要打开的文件不存在
#"=="如果如果变量引用的对象值相等,则会返回True
#"is"如果两个变量指向相同的对象,则会返回True
与:and 或:or 非:not
用法
for name in score:
print(score[name])
#遍历的变量中存储的是字典的key
# dir(模块名)
#查看引入的模块中含有的函数和变量