2014-02-10 2 views
0

저는 파이썬 용어로 파이썬에서 플래시 카드 게임을 만들려고합니다. 내가 원했던 사양 중 일부는 다음과 같습니다.Flashcard Game : 점수를 유지하는 방법

1) 프로그램은 점수에 파일을 저장해야합니다. 2) 점수는 각 단어 및/또는 키를 추적하고 추측 된 횟수를 추적해야합니다 정확하고 잘못된 각 추측 후 사용자에게해야 프로그램이 얼마나 많은 시간을 사용자가 정확하게 해당 키를 추측했다 3) 잘못

는 파이썬에 아주 새로운 해요이를 만드는 방법에 대한 간단한 설명을 부탁드립니다 가능하다면 일하십시오.

여기에 내가 가진 무엇 :

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

이 프로그램을 작성하기 전에 정의를 올바르게 가져야합니다. "def : 단어를 정의하는"? "가져 오기 : 명령을 호출하려면"? 이렇게하면 많은 도움이되며 코딩을 시작할 기초를 마련합니다. – Hyperboreus

+0

저장된 파일을 사람이 읽을 수 있도록 하시겠습니까? –

+0

각 게임의 시작 부분에 점수를 표시하여 사용자가 자신의 기록을 볼 수있게하고 싶습니다. 나는이 함수에 대해 csv를 사용하여 언급했지만 답변과 세 가지 접근법을 비교해보고있다. – cocog

답변

1

글쎄,의 기본적인 시작하자 : 당신이뿐만 아니라 딕셔너리에 결과를 저장하고 파일에 그 DICT를 덤프 pickle 모듈을 사용할 수 있습니다. 그래서, DICT 구조는 다음과 같이 할 수있다 :

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

내가 파일이 존재하지 않는 경우 기본 값 (모든 단어와 추측에 대한 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 

가 마지막으로 잠시 블록 후에, 우리는 답변 피클과 DICT 것을 지속, 그래서 필요하다면 우리가 나중에로드 할 수 있습니다 : 파일에 점수를 유지

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

그냥 덤프 호출을 사람이 읽을 수 있도록하려면 open ('ansers.bin', 'w'). write (json.dumps (answers))로 바꿉니다. –

+0

그냥'import json'을 사용하고'open ('answers.bin'). read (json.loads (answers))'를 사용하여 파일을 읽습니다. –

0

가 힘든 -이 (예를 들어, sqlite3) 어떤 데이터베이스입니다 아주 잘 할 수 있습니다. 정말로 원한다면 아래처럼 Scorer 클래스를 구현할 수 있습니다. 별다른 문제없이 여러 사용자를 추가 할 수 있습니다.

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에 살고있는 것이다 : 그것은 당신이 같이 오른쪽 get_score 그들은 그 단어에했던 방식을 볼 수, 전화, 즉 add_score 사람이 단어를 가지고 말하고 싶은 것이 두 가지 방법이있다 그러니 너가 그걸로 어지럽 혀지지 않으면, 너는 괜찮을거야.

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 
관련 문제