用户分数保存程序

2024-10-02 06:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做一个程序,它将询问用户的名字,然后一系列的问题。每答对一次加分。我试图让它把分数和用户名一起存储到一个文本文件中,这样它在文本文件上看起来是这样的:

Name    Score 

以John为例,如果他得4分,在文本文件中会写下:

^{pr2}$

但我希望这样,如果约翰再参加一次考试,而不是让约翰参加两次考试:

John    4
John    6

我想把它改成:

John    4   6

它不会重写名字和分数,而是将tab和分数写在与John名字相同的行上。在

以下是我目前为止的代码:

import random
name = input("Hello user, what is your name?")
count = (0)
score = (0)
while count != (8):
    count = count + (1)
    symbols = ['+', '-', '*']
    valueF = random.randint(1,10)
    valueS = random.randint(1,10)
    chosensymb = random.choice (symbols)
    question = input("What is %d %s %d ? :"%(valueF, chosensymb, valueS))
    answer = eval(str(valueF) + chosensymb + str(valueS))
    if question == str(answer):            
        score = score + (1)
        print ("Correct")
    else:
        print ("Incorrect")

print("%s, you have scored %d points"%(name,score))
filewrite = open("ScoreSheet.txt","a")
filewrite.write("\n%s\t%d"%(name,score))
filewrite.close()

我不知道怎么做,我是python新手,如果我犯了什么错误,很抱歉,谢谢!在


Tags: nameinputcountrandom名字john分数score
3条回答

文件访问不是这样工作的:在文件中,您不能只在某个地方“插入”新值,将文件的其余部分向后移动;您只能覆盖字符或重写整个文件。在

一般来说,只要你的文件很短,你不会注意到任何性能影响,如果重写整个文件。在

首先,你可以把每个人的分数都储存在字典里。 让我们介绍一个scores对象:

scores = {}

它将名称作为键,分数作为值。像这样:

^{pr2}$

如果您引入了一个新的播放器,我们将在该字典中创建一个新元素,我们将其命名为'John',分数为0

scores['John'] = 0

如果玩家猜对了,我们会增加玩家的分数:

scores['John'] += 1

(如果只想在对象中添加一些内容,可以使用+=运算符。这是一种简短的说法。在

然后魔法开始了!
Python中有一个内置模块,名为pickle,它可以将对象(比如我们制作的字典-scores)存储在文件中,然后将它们从文件中弹出,然后将它们还原!在

这里有a quick manual关于如何使用pickle。简而言之,您可以这样将分数保存到文件中:

import pickle
pickle.dump(scores, open("scores.p", "wb"))

然后像这样加载:

scores = pickle.load(open("scores.p", "rb"))

这并不是存储信息的最佳方式—还有更多类似jsoncsvsqlite的东西,甚至还有手动读/写功能,但你现在还可以:)

只需使用^{}^{}对数据进行serialize。下面是一个使用json序列化分数的示例(将分数存储在^{}-名称和分数之间的映射):

# import the serializing library
import json as serializer

现在我们将创建一个函数,将分数写入给定文件:

^{pr2}$

它的作用是:

  1. 从score文件加载序列化结果对象(dict
  2. 更新分数dict(add key/update value of key)
  3. {{cd4}(更新了^}文件)

在编写write_score函数时,我们缺少了一个read_scores函数,它使我们能够看到当前的分数。我们写下这个read_scores

def read_scores(score_file_name):
    try:
        with open(score_file_name, 'r') as f:
            scores = serializer.load(f)
        return scores
    except IOError:
        # if file does not exist - we have no scores
        return {}

read_scores的作用是:

  1. 读取序列化的dict(使用^{}

现在我们可以测试它是否真的有效。下面是一个小例子:

# set the score file name
SCORES_FILE_NAME = 'scores.txt'

write_score(SCORES_FILE_NAME, 'john', 10)    
print(read_scores(SCORES_FILE_NAME))

write_score(SCORES_FILE_NAME, 'jim', 11)    
print(read_scores(SCORES_FILE_NAME))

# overwrite john's score
write_score(SCORES_FILE_NAME, 'john', 12)
print(read_scores(SCORES_FILE_NAME))

技巧1:在写分数时,您可能需要使用^{},这样john和{}被视为同一个用户。在

技巧2:因为我们将json库作为serializer引用,并且它与pickle具有相同的API,您可以通过将import json as serializer替换为import pickle as serializer在这两者之间进行选择。只需确保删除分数文件,因为它们不会以相同的方式序列化数据。在

将整个代码放在一起:

# import the serializing library
import json as serializer

def write_score(score_file_name, name, score):
    scores = read_scores(score_file_name)
    # add score
    scores[name] = score
    with open(score_file_name, 'w') as f:
        serializer.dump(scores, f)


def read_scores(score_file_name):
    try:
        with open(score_file_name, 'r') as f:
            scores = serializer.load(f)
        return scores
    except IOError:
        # if file does not exist - we have no scores
        return {}

# TESTS

# set the score file name
SCORES_FILE_NAME = 'scores.txt'

write_score(SCORES_FILE_NAME, 'john', 10)
print(read_scores(SCORES_FILE_NAME))

write_score(SCORES_FILE_NAME, 'jim', 11)
print(read_scores(SCORES_FILE_NAME))

# overwrite john's score
write_score(SCORES_FILE_NAME, 'john', 12)
print(read_scores(SCORES_FILE_NAME))

输出:

{u'john': 10}
{u'john': 10, u'jim': 11}
{u'jim': 11, u'john': 12}

要读取特定分数,可以使用现有方法read_scores

def read_score(score_file_name, name):
    return read_scores(score_file_name)[name]

奖金-Closures:

如果您了解闭包,可以使用以下方法使函数特定于文件:

def write_score(score_file_name):
    # create closure specific to 'score_file_name'
    def write_score_specific(name, score):
        scores = read_scores(score_file_name)
        # we're going to make a 'read_scores' with closures as well!
        # so use that one...
        scores_reader = read_scores(score_file_name)
        scores = scores_reader()


        # add score
        scores[name] = score
        with open(score_file_name, 'w') as f:
            serializer.dump(scores, f)

    # return file-specific function
    return write_score_specific

现在,我们只需调用带有file name参数的函数一次,从那时起,我们就可以使用结果来写分数:

# create specific 'write_score' for our file
score_txt_writer = write_score('scores.txt')

# update john's score to 10 without specifying the file
score_txt_writer('john', 10)

read_score也做了同样的处理:

def read_scores(score_file_name):
    # create closure function
    def read_scores_specific():
        try:
            with open(score_file_name, 'r') as f:
                scores = serializer.load(f)
            return scores
        except IOError:
            # if file does not exist - we have no scores
            return {}
    return read_scores_specific

包含闭包的整个代码:

# import the library
import serializer

# CLOSURES

SCORES_FILE = 'scores.txt'
def read_scores(score_file_name):
    # create closure function
    def read_scores_specific():
        try:
            with open(score_file_name, 'r') as f:
                scores = serializer.load(f)
            return scores
        except IOError:
            # if file does not exist - we have no scores
            return {}
    return read_scores_specific

def write_score(score_file_name):
    # create closure specific to 'score_file_name'
    def write_score_specific(name, score):
        scores_reader = read_scores(score_file_name)
        scores = scores_reader()
        # add score
        scores[name] = score
        with open(score_file_name, 'w') as f:
            serializer.dump(scores, f)

    # return file-specific function
    return write_score_specific

# create specific 'write_score' for our file
score_txt_writer = write_score(SCORES_FILE)

# update john's score to 10 without specifying the file
score_txt_writer('john', 10)


score_txt_reader = read_scores(SCORES_FILE)

print score_txt_reader()

输出:

{u'john': 10}

相关问题 更多 >

    热门问题