qmya00 发表于 2017-5-2 10:45:53

Python实现简单文件读写:BINGOGame

  程序的主要功能:
  一个随机猜数字的游戏,会记录每个用户的一些基本信息,本存入文本的数据库当中并实时更新
  代码如下:

#-------------------------------------------------------------------------------
# Name:      BINGOGame
# Created:   27/11/2015
# Copyright:   (c) xiao5_zju 2015
#-------------------------------------------------------------------------------
from random import randint
name = input("请输入你的名字:")    #输入玩家的名字
f = open("D:\python\pyscripter\game.txt")
lines = f.readlines()
f.close()
scores = {}   #初始化一个空的字典
for i in lines:
s = i.split()       #把每一行的数据拆分成list
scores] = s    #第一项作为key,剩下的作为value
score = scores.get(name)    #查找当前玩家的数据
if score is None:       #玩家数据没找到
score =    #没找到初始化的数据
game_times = int(score)
min_times = int(score)
total_times = int(score)
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)
times = 0
bingo = False
print("Guess what I think: ")
while bingo == False:
times += 1#轮数加 1
answer = int(input())
if answer < num:
print('Too small')
if answer > num:
print('Too big')
if answer == num:
print('BINGO')
bingo = True
#如果是第一次玩,或者轮数比最小轮数少,则更新最小轮数
if game_times == 0 or times < min_times:
min_times = times
total_times += times    #总游戏轮数增加
game_times += 1   #游戏次数增加
#成绩更新到对应的玩家的数据当中去
scores =
result = '' #初始化一个空的字符串用来储存数据
for n in scores:
line = n + ' ' + ' '.join(scores) + '\n'
result += line
f = open('D:\python\pyscripter\game.txt', 'w')
f.write(result)
f.close()
页: [1]
查看完整版本: Python实现简单文件读写:BINGOGame