コード例 #1
0
    def test_init(self):
        with self.assertRaises(AssertionError):
            Quiz(["Player1"])

        players = ["Player1", "Player2"]
        quiz = Quiz(players)
        self.assertEqual(quiz.players, players)
        self.assertEqual(quiz.current_round, 1)
コード例 #2
0
ファイル: controller.py プロジェクト: clark-ethan9595/CS108
 def __init__(self):
     
     #Create a window and give it a title.
     self.window = Tk()
     self.window.title('Simple Quiz')
     
     #Create an instance of the quiz class.
     self.quiz = Quiz()
     
     #Labels for the question to appear on the screen.
     self.question_text = Text(self.window, font="arial 16", width = 40, height = 4, wrap = WORD)
     self.question_text.insert(1.0, self.quiz.ask_current_question())
     self.question_text.pack()
     
     #Variable and entry for the user to put in his or her answer.
     self.answer = StringVar()
     self.answerEntry = Entry (self.window, textvariable = self.answer)
     self.answerEntry.pack(side = LEFT)
     
     #Bind the return key to enter the answer in the entry.
     self.answerEntry.focus_set()
     self.answerEntry.bind("<Return>", self.check_answer)
     
     #Label for the instructions for the quiz.
     self.instructions = StringVar()
     self.instructions.set('\u21D0 Enter your answer here')
     self.instrLabel = Label(self.window, textvariable = self.instructions)
     self.instrLabel.pack(side = LEFT)
     
     #Main loop to loop through the initialization method.
     self.window.mainloop()
コード例 #3
0
ファイル: controller.py プロジェクト: mjond/cs108
    def __init__(self):
        self.window = Tk()
        self.window.title('Simple Quiz')

        self.quiz = Quiz()
        #setting the text box
        self.question_text = Text(self.window,
                                  font="arial 16",
                                  width=40,
                                  height=4,
                                  wrap=WORD)
        self.question_text.insert(1.0, self.quiz.ask_current_question())
        self.question_text.pack()
        #making the text entry and binding the 'enter' button to it
        self.answer = StringVar()
        self.answerEntry = Entry(self.window, textvariable=self.answer)
        self.answerEntry.pack(side=LEFT)
        self.answerEntry.focus_set()
        self.answerEntry.bind("<Return>", self.check_answer)
        #label
        self.instructions = StringVar()
        self.instructions.set('\u21D0 Enter your answer here')
        self.instrLabel = Label(self.window, textvariable=self.instructions)
        self.instrLabel.pack(side=LEFT)

        self.window.mainloop()
コード例 #4
0
ファイル: generate.py プロジェクト: bigmolemushroom/Junyi
def initQuizInfo(input_file, sectionDict):
  quizList = [{} for _ in range(len(sectionDict))]
  with open(input_file, newline = '', encoding = 'utf-8') as csvfile:
    rows = csv.reader(csvfile)
    for row in rows:
      idx = sectionDict[row[1]]
      quizList[idx][row[0]] = Quiz(quizId = row[0], sectionId = idx, difficulty = row[2])

  return quizList
コード例 #5
0
def run():
    flashcard_loader = FlashcardLoader()
    flashcard_loader.load_flashcards('data')
    quiz = Quiz()
    user_continuing = True
    while quiz.get_next_flashcard(True) or user_continuing:
        next_card = quiz.get_next_flashcard()
        correct_choice = raw_input()

        quiz.answer_question(next_card, correct_choice)
コード例 #6
0
def main():
    init(autoreset=True)
    # file_path = os.path.join(os.getcwd(), 'src', 'day_17', 'data.txt')
    quiz_data = get_questions_data_from(
        "https://opentdb.com/api.php?amount=48&category=18")

    question_objects = get_questions_from(quiz_data)
    remove_unreadable_parts_from_list(question_objects)

    quiz = Quiz(question_objects)
    run_quiz(quiz)
コード例 #7
0
def setup(base, conf_fn):
    print '\n**** service initialization ****\n'
    global room, courseobj, categoryobj, userobj, announcementobj, discussionobj, quizobj, messageobj
    room = Room(base, conf_fn)
    courseobj = Course()
    categoryobj = Category()
    userobj = Users()
    announcementobj = Announcement()
    discussionobj = Discussion()
    quizobj = Quiz()
    messageobj = Message()
コード例 #8
0
def main():
    print(
        "Would you like to have the pokemon's type displayed? (makes the game easier)"
    )
    show_types = validate_input()
    print(
        "Would you like to have to guess all correct answers? (makes the game harder)"
    )
    all_answers = validate_input()
    quiz = Quiz(show_types, all_answers)
    quiz.run()
コード例 #9
0
ファイル: app.py プロジェクト: steve7158/stop-the-bleed
def quizes():
    result = Quiz()
    print result
    print type(result)
    print len(result)

    if len(result) > 0:
        return render_template('quizes.html', quizes=result)
    else:
        msg = "No quizes found right now"
        return render_template('quizes.html', msg=msg)
コード例 #10
0
ファイル: app.py プロジェクト: steve7158/stop-the-bleed
def quiz(id):
    print colored(id, 'white', 'on_red')
    id = int(id)
    quizes = Quiz()
    for quiz in quizes:
        if (quiz.get('id') == id):
            result = quiz
            questions = result['question']
            break

        # return redirect(url_for('index'))
    return render_template('quiz.html', quiz=result, question=questions)
コード例 #11
0
def play_quiz():
    play = True
    while play:
        question_count, max_number = get_quiz_preference()
        new_quiz = Quiz(0, 0)

        if (not question_count) and (not max_number):
            new_quiz = Quiz()
        elif question_count and max_number:
            new_quiz = Quiz(question_count=question_count, max_num=max_number)
        else:
            new_quiz = Quiz(
                question_count=question_count) if question_count else Quiz(
                    max_num=max_number)

        new_quiz.take_quiz()

        if input("Play again? <Enter> to play again, QUIT to exit: ").upper(
        ) == "QUIT":
            print("Bye now!")
            play = False
        else:
            clear_screen()
コード例 #12
0
def initialise_quiz() -> Quiz:
    """Retrieves quiz parameters from the user and returns a Quiz object based on those parameters."""
    try:
        num_players = int(input("Enter number of players: "))
        players = []
        for i in range(num_players):
            player_name = input(f"Enter player {i+1} name: ")
            players.append(player_name)

        num_rounds = int(input("Enter number of rounds: "))
        round_length = int(input("Enter number of questions in each round: "))
        quiz = Quiz(players, num_rounds, round_length)
    except Exception:
        print("Got an error trying to initialise the quiz. Please try again.")
        return initialise_quiz()
    else:
        return quiz
コード例 #13
0
def ask():
    quiz = Quiz(
        initiator=ANONYMOUS_USER_ID,
        category_id=SPA_GAME_CATEGORY_ID,
        room_id=SPA_ROOM_ID,
        backend=BACKEND
    )
    img, answers, question_id, question = quiz.ask_image_type()

    try:
        image = Image(img, quiz.room_id, question_id, convert_svg=False)
        image = str(image).split('/')[-1]
        return jsonify(url=f'/media/{image}', question_id=question_id,
                       question=question)
    except (FileTypeError, NotFoundError) as e:
        return e.msg, e.code
    except AttributeError:
        return "Image not found", 404
コード例 #14
0
 def test_remove_quizzes_not_from_multiple_choices(self):
     """
     Removing questions NOT in the list of multiple choices shouldn't 
     change multiple choice list.
     """
     self.mock_listener.expects(never()).question_changed()
     self.quiz = Quiz(self.QUIZ_POOL[:])
     old_multi_choices = self.quiz.multi_choices[:]
     old_question = self.quiz.question[:]
     quiz_list = self.QUIZ_POOL[:]
     for quiz in old_multi_choices:
         quiz_list.remove(quiz)
     for quiz in quiz_list:
         self.quiz.remove_quizzes([quiz])
         assert self.quiz.multi_choices == old_multi_choices, \
                 "Multiple choice options changed after removing other "\
                 "quizzes. " "New: %s; Old: %s; Removed: %s." % \
                 (self.quiz.multi_choices, old_multi_choices, quiz)
     self.mock_listener.verify()
コード例 #15
0
 def __init__(self, window):
     ''' Create a quiz and GUI frontend for that quiz '''
     
     self.quiz = Quiz()
     
     self.question_text = Text(window, font="arial 16", width = 40, height = 4, wrap = WORD)
     self.question_text.insert(1.0, self.quiz.ask_current_question())
     self.question_text.pack()
     
     self.answer = StringVar()
     self.answerEntry = Entry (window, textvariable = self.answer)
     self.answerEntry.pack(side = LEFT)
     self.answerEntry.focus_set()
     self.answerEntry.bind("<Return>", self.check_answer)
     
     self.instructions = StringVar()
     self.instructions.set('\u21D0 Enter your answer here')
     self.instrLabel = Label(window, textvariable = self.instructions)
     self.instrLabel.pack(side = LEFT)
コード例 #16
0
ファイル: main.py プロジェクト: tt-n-walters/python-tuesday
from url import URL
from quiz import Quiz

url_generator = URL()
url_generator.choose_category()
url_generator.choose_type()
url_generator.choose_difficulty()
url_generator.choose_number_of_questions()
# url_generator.number_of = 5
# url_generator.category = "any"
# url_generator.difficulty = "any"
# url_generator.type = "any"

api_url = url_generator.generate()

quiz = Quiz(api_url)
quiz.ask_question()
quiz.get_user_answer()
コード例 #17
0
    def handle(self):
        r = self.socket.recv(3)
        if r != b'':
            headerType, size = HeaderParser.decode(r)
            data = Protocol.decode(self.socket.recv(size))
            h, p = None, None

            if headerType == Header.DIS:
                raise socket.error('Disconnect')
            elif headerType == Header.ALI:
                r = requests.get(URL.local + 'quizzes-categories')

                if r.status_code == 200:
                    j = r.json()
                    l = []
                    for x in j:
                        l.append(x['category_name'])
                    h, p = Protocol.encode(Header.LIS, quizes=l)
                    Logger.log('Category request')
                else:
                    h, p = Protocol.encode(Header.ERR,
                                           msg='Cant get categories')
                    Logger.log('Category request failed')
            elif headerType == Header.STR:
                if data['category'] == []:
                    r = requests.get(URL.local + 'quizzes-categories')
                    r2 = requests.get(URL.local + 'stats',
                                      params={'userid': self.dbID})

                    if r.status_code == 200 and r2.status_code == 200:
                        cat = r.json()
                        stat = r2.json()

                        ret = []
                        for x in stat:
                            for y in cat:
                                if x['quizid'] == y['id']:
                                    print('abc')
                                    ret.append({
                                        'category': y['category_name'],
                                        'score': x['score']
                                    })
                                    break

                        if ret != []:
                            h, p = Protocol.encode(Header.STA, stats=ret)
                        else:
                            h, p = Protocol.encode(Header.ERR, msg='empty')
                        Logger.log('Stats request ' + str(self.dbID))
                    else:
                        Logger.log('Stats request failed' + str(self.dbID))
                else:
                    r = requests.get(URL.local + 'top-stats',
                                     params={'category': data['category']})

                    if r.status_code == 200:
                        stat = r.json()

                        if stat != []:
                            h, p = Protocol.encode(Header.STA, stats=stat)
                        else:
                            h, p = Protocol.encode(Header.ERR, msg='empty')
                        Logger.log('Stats request ' + str(self.dbID))
                    else:
                        Logger.log('Stats request failed' + str(self.dbID))

            elif headerType == Header.QUI:
                r = requests.get(URL.local + 'quizzes',
                                 params={'category_name': data['category']})

                if r.status_code == 200 and self.quiz == None:
                    j = r.json()
                    qq = []
                    for x in j:
                        q = x['Question']['question']
                        cor = None
                        a = x['Answers']
                        for y in a:
                            if y['id'] == x['Question']['correct_answer']:
                                cor = y['answer']

                        b = []
                        for i in range(4):
                            b.append(str(a[i]['answer']))
                        qq.append(Question(q, b, str(cor)))

                    self.quiz = Quiz(qq, j[0]['Question']['quizid'])
                    question = self.quiz.next()
                    h, p = Protocol.encode(Header.QUE,
                                           question=question.question,
                                           answers=question.answers,
                                           correct=question.correct)
                    Logger.log('Quiz begin' + str(self.dbID))
                else:
                    h, p = Protocol.encode(Header.ERR, msg='Cant begin quiz')
                    Logger.log('Quiz request fail ' + str(self.dbID))
            elif headerType == Header.NXT:
                if self.quiz != None:
                    question = self.quiz.next()
                    h, p = Protocol.encode(Header.QUE,
                                           question=question.question,
                                           answers=question.answers,
                                           correct=question.correct)
                    Logger.log('next question ' + str(self.dbID))
                else:
                    h, p = Protocol.encode(Header.ERR, msg='Invalid request')
                    Logger.log('next question fail ' + str(self.dbID))
            elif headerType == Header.END:
                if self.quiz != None:
                    r = requests.patch(URL.local + 'stats',
                                       json={
                                           'userid': self.dbID,
                                           'quizid': self.quiz.quizid,
                                           'score': data['score']
                                       })

                    self.quiz = None

                    h, p = Protocol.encode(Header.ACK, msg='Quiz completed')
                    Logger.log('Quiz end ' + str(self.dbID))
                else:
                    h, p = Protocol.encode(Header.ERR,
                                           msg='Invalid end request')
                    Logger.log('Quiz end request fail ' + str(self.dbID))
            if h != None and p != None:
                self.transfer(h, p)

        return None
コード例 #18
0
ファイル: main.py プロジェクト: oliver-bevan/vqm
    master_gui = tk.Tk()

    master_gui.title("VQM")
    master_gui.geometry("800x600")

    gui = OperatorGUI(master_gui, show)
    gui.pack()

    master_gui.mainloop()


print("--Volani Quiz Master: Main Menu--")
quizzes = []
quizzes.append(
    Quiz("Test Quiz", [
        Question("Test Question, B is Correct?",
                 ["Incorrect", "Correct", "Inccorect"], 2, 10)
    ], r"^[1-3]$"))
while True:

    choice = present_menu_get_response(["Create Quiz", "Run Show"])

    if choice == 1:
        print("Enter quiz title: ")
        title = input()
        print("Enter answer regex: ")
        answer_regex = input()

        input_valid = False

        questions = []
コード例 #19
0
ファイル: exam.py プロジェクト: marwahaha/ortho
            self.exam.answers.append(answer)
        print "Fin de l'examen."

    def get_score(self):
        """
        Correct the exam and print the score.
        """
        self.exam.correct()
        print u"Ton score est de %d sur %d" % (self.exam.score,
                                               self.quiz.length)
        if self.exam.score != self.quiz.length:
            print u"Tu t'es trompé sur les mots suivants:"
            for index in self.exam.mistakes:
                answer = self.exam.answers[index]
                word = self.quiz.words[index].word
                print "%25s --> %s" % (word, answer)
        else:
            print u"Magnifique %s!" % self.exam.student


if __name__ == "__main__":
    import os
    from lesson import Lesson
    quiz = Quiz("test", 15)
    lesson = Lesson('mots17', os.path.normpath(os.getcwdu() + '/../mots17'))
    quiz.add_lesson(lesson)
    quiz.generate()
    exam_runner = ExamRunner(u"Eléa", quiz)
    exam_runner.do_exam()
    exam_runner.get_score()
コード例 #20
0
from question import Question
from quiz import Quiz

if __name__ == '__main__':
    q1 = Question('En iyi programlama dili?',['C#','Python','Java','Javascript'],'Python')
    q2 = Question('En sevilen programlama dil?',['C#','Python','Java','Javascript'],'Java')
    q3 = Question('En kolay programlama dil?',['C#','Python','Java','Javascript'],'C#')

    questions = [q1,q2,q3]

    quiz = Quiz(questions)
    quiz.load_question()
コード例 #21
0
    file = "packs/" + file_name if file_name else "packs/example.json"

    if not os.path.isfile(file):
        print(f"Error: The file {file} does not exist.")
        continue

    if file.endswith(".json"):
        file_type = "json"
    else:
        print("Error: Must be a json file.")
        continue

    try:
        with open(file, encoding='utf8') as file:
            data = json.load(file)
        break
    except IOError:
        print("Error: Something went wrong when trying to open the file.")

card_objects = []

for dictionary in data:
    card_objects.append(Card(dictionary))

# TODO - Display valid categories, and prompt user until two valid categories are chosen.
show = input("Which side do you want to see? ")
guess = input("Which side do you want to guess? ")

quiz = Quiz(card_objects, show, guess)
quiz.start()
コード例 #22
0
ファイル: play.py プロジェクト: annec22/learningpython
from questions import Question
from questions import Add
from questions import Multiply
from quiz import Quiz

quizzie = Quiz(3, 10)

quizzie.take_quiz()

#for question in quizzie.questions:
#	print("Question: {}".format(question["question"]))
#	print("Answer: {}".format(question["answer"]))
#	print("Mark: {}".format(question["marks"]))
#	print("Time: {}".format(question["time_elapsed"]))
	
コード例 #23
0
objectsOfTheRooms = myStimuli.combiObjectsOfTheRooms
#################################################

#################################################
#            Creating our Experiment            #
#################################################
# Creating our experiment object #
myExperiment = Experiment(window=windowPsychoPy,
                          stimuliClass=myStimuli,
                          experimentalSetUp=experimentSetUp
                          )  # This is where you set the experiment set-up

# We also create our beginning quiz object #
# We launch this, and then it will launch our experiment, and when it is all done it will close the window:
myQuiz = Quiz(window=windowPsychoPy,
              stimuliClass=myStimuli,
              quiz100=quiz100,
              experiment=myExperiment)
myQuiz.launchWholeQuiz()
windowPsychoPy.close()
#################################################

#################################################
#               Generating Results              #
#################################################

# Get all the information from our experiment that we need for the results: #
quizAttempts = myQuiz.numberOfAttempts  # how many times the participant had to do the quiz to get 100% accuracy
randomWalk = myExperiment.randomWalk  # random gaussian walk of the room probabilities
experimentResults = myExperiment.results  # participant's results

# Create a result recorder object and launch it so it creates all the CSVs and PNGs necessary for keeping the results: #
コード例 #24
0
from converters.images import Image
from quiz import Quiz

if __name__ == '__main__':
    # quick example
    ROOM_ID = 8888
    quiz = Quiz(category_id=1, initiator=123, room_id=ROOM_ID, backend='api')
    img, answers, question_id, question = quiz.ask_image_type()
    image = str(Image(img, quiz.room_id, question_id))
    print(Quiz.get_answers(ROOM_ID))
    print(image)
コード例 #25
0
ファイル: chat.py プロジェクト: hectorbennett/bobby
 def start_quiz(self):
     self.quiz_mode = True
     self.quiz = Quiz(rounds=10)
     return self.quiz.current_question
コード例 #26
0
def main():
    q = Quiz()
    q.interval_guess(3)
コード例 #27
0
from question import Question
from data import question_data
from quiz import Quiz

question_bank = []
for question in question_data:
    question_bank.append(
        Question(question["question"], question["correct_answer"]))

new_quiz = Quiz(question_bank)

while new_quiz.is_still_has_question():
    new_quiz.next_question()

print("You've finished the quiz")
print(f"Total score is: {new_quiz.score}/{new_quiz.question_number}")
コード例 #28
0
from quiz import Quiz
from database import Question as DBQ

if __name__ == '__main__':
    quiz = Quiz()

    for q in quiz.get_all_quiz():
        qdb = DBQ.get_or_none(DBQ.json_file == q.short_filepath)

        if qdb is None:
            quiz.publish(q)
        else:
            if q.checksum != qdb.last_checksum:
                # Удаляем сообщения из канала
                quiz.delete_messages(qdb.message_id)
                # Удаляем запись из БД
                qdb.delete_instance()
                quiz.publish(q)
コード例 #29
0
from quiz import Quiz

questions_prompt = [
    "What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n",
    "What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n",
    "What color are strawberries?\n(a) Yellow\n(b) Red\n(c) blue\n\n"
]

questions = [
    Quiz(questions_prompt[0], "a"),
    Quiz(questions_prompt[1], "c"),
    Quiz(questions_prompt[2], "b"),
]


def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score += 1
    print("You got " + str(score) + "/" + str(len(questions)) + "correct")


run_test(questions)
コード例 #30
0
def classFactory(iface):
    # load Quiz class from file quiz
    from quiz import Quiz
    return Quiz(iface)