抽认卡游戏:如何保持分数

时间:2014-02-10 15:06:35

标签: python

我正在尝试在python中为python术语构建一个flashcard游戏。我希望它的一些规格是:

1)程序应将分数存储在文件中 2)分数应跟踪每个单词和/或键,并跟踪猜测正确和不正确的次数 3)每次猜测后,程序应该告诉用户用户正确错误地猜到了该键的次数

我对Python非常陌生,并且非常感谢如何使这项工作最简单的解释(如果可能的话)。

这就是我所拥有的:

from random import choice
import sys

print("Welcome! Please type 'Start' to begin or 'Quit' to leave")

user_answer = raw_input()

if (user_answer == "quit"):
    quit()  

file = []

words = {
    "break": "Stops repeat of a block or loop", 
    "else": "comes after 'if' to offer an alternative option", 
    "if": "informs computer on how to react depending on key response from user",
    "index": "Return the index in the list of the first item whose value is x",
    "dict": "Associates one thing to another no matter what it is",
    "import": "To call a command",
    "def": "to define a word",
    "print": "to send a message to the screen for the user to see",
    "for": "One way to start a loop",
    "while": "Another way to start a loop",
    "elif": "When an 'If'/'Else' situation calls for more than one 'Else'",
    "from": "directs the computer to a location from which to import a command"
}

score = file[]

key = choice(words.keys())
remaining_questions = 3

while remaining_questions > 0:
    print("Which command can accomplish: " + words[key] + "...?")
    user_guess = raw_input()
    print(str(user_guess == key))
    remaining_questions = remaining_questions - 1

2 个答案:

答案 0 :(得分:1)

好吧,让我们从基本开始:您也可以将结果存储在dict中,并使用pickle模块将该dict转储到文件中。所以,dict结构可以是这样的:

answers[word]['correct']
answers[word]['wrong']

如果文件不存在,我将创建一个简单的短代码来启动该dict的默认值(所有单词和猜测为0),如果文件存在则从文件中加载该dict,使用Pickle

from os.path import isfile
from pickle import load

if isfile('answers.bin'):
    # loads the dict from the previously "pickled" file if it exists
    answers = load(open('answers.bin', 'rb'))     
else: 
    # create a "default" dict with 0s for every word
    for word in words.keys():
        answers[word] = {'correct': 0, 'wrong': 0}

然后,我们将构建一个if语句来检查用户是否正确回答:

if key == user_guess: # there's no need to cast the `user_guess` to str
    answers[key]['correct'] += 1
else:
    answers[key]['wrong'] += 1

最后,在while块之后,我们坚持使用pickle来回答dict,所以我们可以在以后加载它:

from pickle import dump
dump(answers, open('answers.bin', 'wb'))

答案 1 :(得分:0)

在文件中保留分数很难 - 这就是数据库(例如sqlite3)可以做得很好的事情。如果您真的想要,可以实现如下Scorer类。您可以毫无困难地添加多个用户。它只有两种你想要调用的方法,即add_score表示某人说得对,get_score看看他们是如何对这个单词做的,如:

user_scores = Scorer()
user_scores.add_score(words[key])
right, wrong = user_scores.get_score(words[key])
print("You've gotten {:s} right {:d} times and wrong {:d} times".format(
    words[key],
    right,
    wrong))

数据将全部存在于some_filename.csv中,所以只要你没有弄乱,你就可以了。

import csv
import os

class Scorer:
    def __init__(self):
        self.filename = 'some_filename.csv'
        self._colnames = ["word","right","wrong"]
        self._data = self._load_data()

    def _load_data(self):
        if not os.path.exists(self.filename):
            with open(self.filename, 'wb') as f:
                f.write(",".join(self._colnames) + "\n")
        with open(self.filename, 'rb') as f:
            reader = csv.DictReader(f)
            data = {row["word"] : row for row in reader}
        return data

    def _save_data(self):
        with open(self.filename,'wb') as f:
            f.write(",".join(self._colnames) + "\n")
            for word_data in self._data.values():
                row_str = ",".join([str(word_data[col]) for col in self._colnames])
                f.write(row_str + "\n")

    def add_score(self, word, was_right):
        if word not in self._data:
            self._data[word] = {"word": word,"right":0,"wrong":0} 
        if was_right:
            self._data[word]["right"] += 1
        else:
            self._data[word]["wrong"] += 1
        self._save_data

    def get_score(self, word):
        right = self._data.get(word, {}).get("right",0)
        wrong = self._data.get(word, {}).get("wrong",0)
        return right, wrong