class Game(Questions, Dblinker): def __init__(self): self.questions = Questions() self.player1 = Dblinker() def calculate_score(self, n): return n * n def play(self): nickname = input("Enter your player name> ") print("Welcome, {}! Let the game begin!".format(nickname)) points_counter = 0 while True: print(self.questions.generate_question()) correct_answer = self.questions.solve_question() player_answer = int(input()) if player_answer == correct_answer: points_counter += 1 points = (self.calculate_score(points_counter)) print("Correct!") else: print("Incorrect! Ending game. You score is: {}".format(points)) break self.player1.update_table(nickname, points)
def run_quiz(): questions = Questions(QUESTIONS_PATH) user_progress = {KEY_PROGRESS_SUCCESSES: 0, KEY_PROGRESS_MISTAKES: 0} available_questions = {question['id']: 1 for question in questions.list} print('Welcome! Let the game begin!\n') question = questions.get_random_question(available_questions) need_repeat = False while True: question.display() answer = Answer(question) if answer.user_answer == 'q': print('\nGoodbye! We\'ll miss you :(\n') break else: if answer.is_correct: question = questions.get_random_question(available_questions) if not need_repeat: user_progress[answer.is_correct] += 1 need_repeat = not answer.is_correct answer.display() print(render_user_progress(user_progress, available_questions)) exit()
class Game(Questions, Dblinker): def __init__(self): self.questions = Questions() self.player1 = Dblinker() def calculate_score(self, n): return n * n def play(self): nickname = input("Enter your player name> ") print("Welcome, {}! Let the game begin!".format(nickname)) points_counter = 0 while True: print(self.questions.generate_question()) correct_answer = self.questions.solve_question() player_answer = int(input()) if player_answer == correct_answer: points_counter += 1 points = (self.calculate_score(points_counter)) print("Correct!") else: print( "Incorrect! Ending game. You score is: {}".format(points)) break self.player1.update_table(nickname, points)
def __init__(self, socket, player_id): self.questions = Questions() self.WinnerChosen = False self.socketGUI = socket self.playerId = player_id self.thread_scores = threading.Thread(target=self.update_scoreboard, args=()) self.thread_scores.daemon = True
def __init__(self, *a, **kw): sys.setrecursionlimit(0x100000) self.questions = Questions() cozmo.setup_basic_logging() # cozmo.connect_with_tkviewer(self.startResponding) cozmo.connect(self.startResponding)
def __init__(self, client, scoreboard): self._client = client self._scoreboard = scoreboard self._questions = Questions() self._questions.load() self._collectedAnswers = {} self._priority = util.mtime() self._lastHeartbeatSeen = util.mtime() self._minPrioritySeen = sys.maxsize self._lastQuestionSend = 0
def score_questions(): rq = Questions() quest_num = request.args.get('order') answer = request.args.get('answer') category = request.args.get('category') correct = request.args.get('correct') if quest_num and answer and category and correct: scores = rq.score_questions(quest_num, answer, category, correct) session['scores'] = scores return "OK" else: return "Problem with your data"
def __init__(self, socket, address, id, name, signal): threading.Thread.__init__(self) self.socket = socket self.address = address self.id = id self.name = name self.signal = signal self.score = 0 self.questions = Questions() self.askedQuestionCtg = "" self.askedQuestionNum = "" self.askedQuestionCode = ""
def pickcategory(*args): global catid, qlist, question, stv, selector catid = d[stv.get()] qlist = Questions(catid) question = qlist.next() stv = "" selector.destroy() stv = tk.StringVar(F) stv.trace("w", answer) selector = tk.OptionMenu(F, stv, "") selector.grid(row=0, column=1) display()
def test_category_tally(self, mock_get_points_per_question): mock_get_points_per_question.return_value = 16.67 exp_result = { 'Monitoring and Reporting': 33.34, 'Storage and Management': 33.34 } results = { 'results': [{ "quest_num": 1, "result": 1, "correct": 1, "right_or_wrong": 1, "category": 'Monitoring and Reporting' }, { "quest_num": 2, "result": 2, "correct": 3, "right_or_wrong": 0, "category": 'Monitoring and Reporting' }, { "quest_num": 3, "result": 3, "correct": 3, "right_or_wrong": 1, "category": 'Monitoring and Reporting' }, { "quest_num": 4, "result": 1, "correct": 1, "right_or_wrong": 1, "category": 'Storage and Management' }, { "quest_num": 5, "result": 2, "correct": 3, "right_or_wrong": 0, "category": 'Storage and Management' }, { "quest_num": 6, "result": 3, "correct": 3, "right_or_wrong": 1, "category": 'Storage and Management' }] } rq = Questions() cat_result = rq.category_tally(results) self.assertTrue(TestQuestions.compare_dict(exp_result, cat_result))
def get_next_question(): if questions and len(questions): quest = str(Questions.get_question_raw_json(questions)) quest = eval(quest) return render_template( 'question.html', title="QUIZ", order=quest['order'], question_text=quest["question_text"], type=quest['answers']['type'], answers=quest['answers']['answer'], category=quest['category'], correct=quest['answers']['correct'], remain=len(questions), ) else: rq = Questions() total = rq.final_tally(session['scores']) cat_totals = rq.category_tally(session['scores']) cat_quest_numbers = Questions.get_number_of_questions_by_category( Questions.load_questions()) return render_template('end_of_questions.html', title="QUIZ", total=total, cat_totals=cat_totals, num_per_cat=cat_quest_numbers)
def test_final_tally(self, mock_get_points_per_question): results = { 'results': [{ "quest_num": 1, "result": 1, "correct": 1, "right_or_wrong": 1, "category": 'Monitoring and Reporting' }, { "quest_num": 2, "result": 2, "correct": 3, "right_or_wrong": 0, "category": 'Monitoring and Reporting' }, { "quest_num": 3, "result": 3, "correct": 3, "right_or_wrong": 1, "category": 'Monitoring and Reporting' }, { "quest_num": 4, "result": 1, "correct": 1, "right_or_wrong": 1, "category": 'Storage and Management' }, { "quest_num": 5, "result": 2, "correct": 3, "right_or_wrong": 0, "category": 'Storage and Management' }, { "quest_num": 6, "result": 3, "correct": 3, "right_or_wrong": 1, "category": 'Storage and Management' }] } rq = Questions() mock_get_points_per_question.return_value = 16.67 final = rq.final_tally(results) exp_result = 66.68 self.assertEqual(final, exp_result)
class User(): # name = 'Honey' # email = '' # address = '' basicQuestions = Questions([ 'What shall I call you honey? (Your sweet name please :)', 'What\'s your internet address? (Email Id!)', 'And where do you live on the earth? (Your address! Please type in one line only)' ], [validateString, validateString, validateString], ['Honey', '', ''])
def __init__(self, master, filename): super(Frame, self).__init__(master) self.qs = Questions(filename) # 初始化 self.init_question() self.init_interactive() self.init_buttons() self.init_indicate() self.reset_question() # 添加部件 self.add_question() self.add_interactive() # self.add_buttons() # self.add_indicate() # 添加键盘事件 self.bind('<Key>', self.key)
def init(self): Help(intro='The following modules are loaded. To find out more, do ' + '".help <module>."', outro='If you have any questions about me or a module, ' + 'please direct them to arctem.').register(self) Link(ArcBot.links_file).register(self) Markov(ArcBot.markov_dat_file).register(self) TheFucking().register(self) WordSwap().register(self) Coercion().register(self) Questions().register(self) UserTracker().register(self) Admin().register(self) LastMessage().register(self) FactoidPlugin().register(self) LearnerPlugin().register(self) BandPlugin().register(self) SmartVariables().register(self) ArcUserVariables().register(self) for cmd in phrase_commands.get_phrase_commands(): cmd.register(self)
['Sausage roll', 'Pork pie', 'Scotch egg', 'Potato crisp'], 2) q4 = Question("Which of these is not one of the American Triple Crown horse races?", [ 'Arlington Million', 'Belmont Stakes', 'Kentucky Derby', 'Preakness Stakes'], 1) q5 = Question("Who is the patron saint of Spain?", ['St James', 'St John', 'St Benedict', 'St Peter'], 1) q6 = Question("The young of which creature is known as a squab?", ['Salmon', 'Horse', 'Pigeon', 'Octopus'], 3) q7 = Question("In Welsh, what does ‘afon’ mean?", ['Fort', 'Meadow', 'Pool', 'River'], 4) q8 = Question("Where does a cowboy wear chaps?", ['On his head', 'On his arms', 'On his legs', 'On his hands'], 3) q9 = Question("Which of these phrases refers to a brief success?", ['Blaze in the pot', 'Spark in the tub', 'Flare in the jug', 'Flash in the pan'], 4) q10 = Question("Which of these have to pass a test on ‘The Knowledge’ to get a licence?", ['Taxi drivers', 'Bus drivers', 'Police officers', 'Ambulance drivers'], 1) questions = Questions([q1, q2, q3, q4, q5, q6, q7, q8, q9, q10]) player = Player("Maniek") game = Game(player, questions, Gui) game.play()
from questions import Questions question_prompts = [ "How do you solve an argument in the classroom?\n a) Scream at your colleague\n b) Talk rationally c)\n Walk away\n", "Can you teach writing to the children?\n a) Yes, in secret\n b) No, it is illegal \n c) Yes, in moderation\n", "What do you do when you are late?\n a) Keep quiet\n b) Panic\n c) Text a head teacher\n" ] question = [ Questions(question_prompts[0], "b"), Questions(question_prompts[1], "b"), Questions(question_prompts[2], "c") ] def run_test(questions): score = 0 for question in questions:
def __init__(self): self.questions = Questions() self.player1 = Dblinker()
import os import random from questions import Questions from flask import Flask, render_template, session, request app = Flask(__name__) app.secret_key = os.urandom(24) app.session_cookie_name = 'quiz-WebSession' app.config['DEBUG'] = False # Data to persist is Scores # Difference between results and scores questions = Questions.load_questions() random.shuffle(questions) @app.route('/') def main(): return 'The quiz is up and running' @app.route('/favicon.ico') def favico(): return 'The quiz is up and running' @app.route('/get_next_question/') def get_next_question(): if questions and len(questions): quest = str(Questions.get_question_raw_json(questions)) quest = eval(quest)
def __init__(self): self.questions = Questions() self.car_list = [] self.sort = Sort()
class IceBreaker(WOC): theFace = None def __init__(self): self._isCompleted = False self._face = None self._newRound = True self._questions = Questions() async def run(self, coz_conn: cozmo.conn.CozmoConnection): await Common.wochelper.initFaceHandlers(coz_conn, self.onFaceObserved, self.onFaceAppeared, self.onFaceDisappeared) self._robot = await coz_conn.wait_for_robot() self._initPose = self._robot.pose self._cube = None # start with the "next question button" cube placed in front of cozmo try: self._cube = await self._robot.world.wait_for_observed_light_cube(timeout=30) print("Found cube: %s" % self._cube) except asyncio.TimeoutError: print("Didn't find a cube") while True: if not self._face: # first spin fast, then spin slower to seek human face await self.crazySpin() await self.spin() else: # find a face, do interaction await self.moveCloser() await self.coreInteraction() await self.waitFinishInteraction() await self.afterInteraction() await asyncio.sleep(0.1) # spin to find any human face async def spin(self): # start spin if not self._robot.is_moving: # head up so that Cozmo can see faces spinAction = self._robot.set_head_angle(MAX_HEAD_ANGLE, in_parallel=True) await self._robot.drive_wheels(-TURN_SPEED, TURN_SPEED) await spinAction.wait_for_completed() cozmo.logger.info("spinAction = %s", spinAction) # close up to human whose face is just seen by Cozmo async def moveCloser(self): # turn to human Cozmo saw await self._robot.turn_towards_face(self._face).wait_for_completed() # move closer action1 = self._robot.drive_straight(distance_mm(DISTANCE_HUMAN), speed_mmps(STRAIGHT_SPEED), should_play_anim=False, in_parallel=True) action2 = self._robot.set_lift_height(0.0, accel=1.0, in_parallel=True) await action1.wait_for_completed() cozmo.logger.info("action1 = %s", action1) await action2.wait_for_completed() cozmo.logger.info("action2 = %s", action2) # ask ice breaking question async def coreInteraction(self): self._question = self._questions.getRandomQuestion() (pitch, self._duration) = await self.customizeSpeech(self._question) print(self._question) print("pitch = %s, durationScalar = %s" % (pitch, self._duration)) await self._robot.say_text(self._question, use_cozmo_voice=True, in_parallel=True, voice_pitch=pitch, duration_scalar=self._duration).wait_for_completed() # repeat question if repeating button is pressed async def repeatInteraction(self): pitch = random.uniform(MIN_PITCH, MAX_PITCH) await self._robot.say_text(self._question, use_cozmo_voice=True, in_parallel=True, voice_pitch=pitch, duration_scalar=self._duration).wait_for_completed() # use cubes to finish interaction with human async def waitFinishInteraction(self): finishConfirmed = False while not finishConfirmed: cube = None await self._robot.set_head_angle(degrees(0), in_parallel=True).wait_for_completed() await self._robot.play_anim_trigger(cozmo.anim.Triggers.MeetCozmoGetIn).wait_for_completed() # wait to see a cube try: cube = await self._robot.world.wait_for_observed_light_cube(timeout=30) print("Found cube: %s" % cube) except asyncio.TimeoutError: print("Didn't find a cube") finally: pass # found ANY cube if cube: # set cube flashing light cube.set_lights(CUBE_READY_LIGHT) # Cozmo being curious await self._robot.play_anim_trigger(cozmo.anim.Triggers.BlockReact).wait_for_completed() await asyncio.sleep(1) # finishConfirmed = True tapped = None # wait this cube to be tapped try: tapped = await cube.wait_for_tap(timeout=30) print("Cube tapped: %s" % tapped) except asyncio.TimeoutError: print("Didn't tap the cube") if tapped: # show the cube is tapped cube.set_lights(cozmo.lights.green_light) # the tapped cube is the cube of "next question" if cube == self._cube: finishConfirmed = True await self._robot.play_anim_trigger(cozmo.anim.Triggers.BuildPyramidSuccess).wait_for_completed() # other cube else: await self.repeatInteraction() cube.set_lights_off() else: # didn't find cube await self._robot.play_anim_trigger(cozmo.anim.Triggers.DriveStartAngry).wait_for_completed() # return to spin position to start next round async def afterInteraction(self): await self._robot.go_to_pose(self._initPose).wait_for_completed() ## await self._robot.turn_in_place(TURN_ANGLE_AFTER_INTERACTION).wait_for_completed() self._newRound = True ## await self._robot.drive_straight(distance_mm(-DISTANCE_HUMAN), ## speed_mmps(STRAIGHT_SPEED), ## should_play_anim=False).wait_for_completed() # customize speech voice pitch and length async def customizeSpeech(self, question): pitch = random.uniform(MIN_PITCH, MAX_PITCH) length = len(question) - question.count(' ') duration = log_mapping(10, MIN_DURATION, 100, MAX_DURATION, length, 10) return (pitch, duration) # fast spin, don't care about faces async def crazySpin(self): if self._newRound: t = random.uniform(MIN_CRAZY_SPIN_TIME, MAX_CRAZY_SPIN_TIME) await self._robot.drive_wheels(-TURN_SPEED_FAST, TURN_SPEED_FAST) await asyncio.sleep(t) self._robot.stop_all_motors() await asyncio.sleep(0.5) self._newRound = False async def onFaceObserved(self, evt: cozmo.faces.EvtFaceObserved, obj=None, **kwargs): if self._face and self._face == evt.face: pass async def onFaceAppeared(self, evt: cozmo.faces.EvtFaceAppeared, obj=None, **kwargs): if not self._face: self._face = evt.face self._robot.stop_all_motors() print("Find a face, start tracking") if not self.theFace: self.theFace = evt.face async def onFaceDisappeared(self, evt: cozmo.faces.EvtFaceDisappeared, obj=None, **kwargs): if self._face and self._face == evt.face: self._face = None print("Lose tracking face")
def __init__(self, _query, _actual_ids): self.query = _query self.actual_ids: List[int] = list(map(int, _actual_ids)) self.predicted_ids: List[int] = list(map(int, Questions().result_ids(_query)))
class CozmoQuiz(WOC): cl = None exit_flag = False audioThread = None curEvent = None idleAnimations = [ 'anim_sparking_idle_03', 'anim_sparking_idle_02', 'anim_sparking_idle_01' ] attractAttentionAnimations = [ 'anim_keepaway_pounce_02', 'reacttoblock_triestoreach_01' ] numMap = { 'CustomObjectTypes.CustomType00': '0', 'CustomObjectTypes.CustomType01': '1', 'CustomObjectTypes.CustomType02': '2', 'CustomObjectTypes.CustomType03': '3', 'CustomObjectTypes.CustomType04': '4', 'CustomObjectTypes.CustomType05': '5', 'CustomObjectTypes.CustomType06': '6', 'CustomObjectTypes.CustomType07': '7', 'CustomObjectTypes.CustomType08': '8', 'CustomObjectTypes.CustomType09': '9' } animCtr = 0 face = None lookingForFace = False buzzerWinner = None timeToAnswer = 15 currentPlayer = 0 numPlayers = 2 #get input later from command line turnsCompleted = 0 numList = [] answerGiven = False questions = None currentQuestion = None questionAsked = False playerTries = [] startPose = None totalQuestions = 4 questionsAsked = [] playerScores = [] points = [10, 5] questionNum = 0 def __init__(self, *a, **kw): sys.setrecursionlimit(0x100000) self.questions = Questions() cozmo.setup_basic_logging() # cozmo.connect_with_tkviewer(self.startResponding) cozmo.connect(self.startResponding) def startResponding(self, coz_conn): asyncio.set_event_loop(coz_conn._loop) self.coz = coz_conn.wait_for_robot() self.coz.world.define_custom_cube(CustomObjectTypes.CustomType00, CustomObjectMarkers.Circles2, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType01, CustomObjectMarkers.Diamonds2, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType02, CustomObjectMarkers.Hexagons2, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType03, CustomObjectMarkers.Circles3, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType04, CustomObjectMarkers.Diamonds3, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType05, CustomObjectMarkers.Hexagons3, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType06, CustomObjectMarkers.Circles4, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType07, CustomObjectMarkers.Diamonds4, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType08, CustomObjectMarkers.Hexagons4, 100, 90, 90, False) self.coz.world.define_custom_cube(CustomObjectTypes.CustomType09, CustomObjectMarkers.Circles5, 100, 90, 90, False) self.startPose = self.coz.pose look_around = self.coz.start_behavior( cozmo.behavior.BehaviorTypes.LookAroundInPlace) try: self.cubes = self.coz.world.wait_until_observe_num_objects( self.numPlayers, object_type=cozmo.objects.LightCube, timeout=60) except asyncio.TimeoutError: print("Didn't find a cube :-(") return finally: look_around.stop() for i in range(0, len(self.cubes)): self.cubes[i].set_lights(Colors.WHITE) self.playerScores.append(0) self.coz.go_to_pose(self.startPose).wait_for_completed() self.coz.say_text("Welcome to Math Buzz", duration_scalar=1.5, voice_pitch=-1, in_parallel=False).wait_for_completed() self.coz.play_anim('anim_greeting_happy_01').wait_for_completed() self.coz.say_text("Let's start!!", duration_scalar=1, voice_pitch=-1, in_parallel=False).wait_for_completed() self.askNextQuestion() while not self.exit_flag: asyncio.sleep(0) self.coz.abort_all_actions() def on_object_tapped(self, event, *, obj, tap_count, tap_duration, tap_intensity, **kw): if self.questionAsked is True: if obj not in self.playerTries: self.playerTries.append(obj) for i in range(0, len(self.cubes)): self.cubes[i].set_lights_off() if obj == self.cubes[i]: self.currentPlayer = i self.coz.go_to_object( obj, cozmo.util.distance_mm(250), in_parallel=False).wait_for_completed() self.startTimerAndWaitForAnswer() obj.set_lights(Colors.BLUE) def startTimerAndWaitForAnswer(self): #Set up event handlerss self.coz.world.add_event_handler(cozmo.objects.EvtObjectAppeared, self.foundMarker) self.coz.world.add_event_handler(cozmo.objects.EvtObjectDisappeared, self.removeMarker) Timer(self.timeToAnswer, self.checkAnswer).start() def checkAnswer(self): self.numList.sort(key=lambda c: c.pose.position.y) num = "" for i in range(0, len(self.numList)): num += self.numMap[str(self.numList[i].object_type)] print("The number is ") if num == '': num = '0' print(num) if int(num) == int(self.currentQuestion['answer']): self.playerScores[self.currentPlayer] += self.points[ len(self.playerTries) - 1] self.coz.say_text("Right Answer! You win " + str(self.points[len(self.playerTries) - 1]) + " points", duration_scalar=1.5, voice_pitch=-1, in_parallel=False).wait_for_completed() self.coz.play_anim( 'anim_rtpkeepaway_playeryes_02').wait_for_completed() self.askNextQuestion() else: self.coz.play_anim( 'anim_keepaway_losegame_01').wait_for_completed() self.playerScores[self.currentPlayer] -= 10 print(self.playerScores) self.goToNextPlayer() def goToNextPlayer(self): self.numList = [] self.coz.say_text("You are wrong.. You lose 10 points", duration_scalar=1.5, voice_pitch=-1, in_parallel=False).wait_for_completed() self.turnsCompleted += 1 if self.turnsCompleted < self.numPlayers - 1: for i in range(0, len(self.cubes)): self.cubes[i].set_lights_off() if i != self.currentPlayer and i not in self.playerTries: self.cubes[i].set_lights(Colors.WHITE.flash()) self.buzzerWinner = None else: self.askNextQuestion() def askNextQuestion(self): self.questionNum += 1 if self.questionNum < self.totalQuestions: self.coz.go_to_pose(self.startPose).wait_for_completed() allPlayerScores = ' '.join( str(score) for score in self.playerScores) if self.questionNum > 1: self.coz.say_text("End of Round " + str(self.questionNum - 1) + ". The scores are " + allPlayerScores, duration_scalar=1.75, voice_pitch=-1, in_parallel=False).wait_for_completed() self.coz.say_text("Round " + str(self.questionNum), duration_scalar=1.75, voice_pitch=-1, in_parallel=False).wait_for_completed() self.playerTries = [] self.currentPlayer = 0 self.buzzerWinner = None self.questionAsked = False for i in range(0, len(self.cubes)): self.cubes[i].set_lights_off() self.coz.world.add_event_handler(cozmo.objects.EvtObjectTapped, self.on_object_tapped) self.turnsCompleted = 0 self.currentPlayer = 0 #go to next question while (True): self.currentQuestion = self.questions.getRandomQuestion() if self.currentQuestion in self.questionsAsked: continue else: self.questionsAsked.append(self.currentQuestion) break self.coz.say_text("What is " + self.currentQuestion['question'], duration_scalar=1.75, voice_pitch=-1, in_parallel=False).wait_for_completed() self.coz.say_text("GO", duration_scalar=1, voice_pitch=-1, in_parallel=False).wait_for_completed() for i in range(0, len(self.cubes)): self.cubes[i].set_lights(Colors.WHITE.flash()) self.questionAsked = True else: self.findWinner() def findWinner(self): for i in range(0, len(self.cubes)): self.cubes[i].set_lights_off() self.coz.go_to_pose(self.startPose).wait_for_completed() self.coz.say_text("Game over", duration_scalar=1.75, voice_pitch=-1, in_parallel=False).wait_for_completed() index, value = max(enumerate(self.playerScores), key=operator.itemgetter(1)) print("The winner is " + str(index)) self.cubes[index].set_lights(Colors.YELLOW.flash()) self.coz.go_to_object( self.cubes[index], cozmo.util.distance_mm(150)).wait_for_completed() self.coz.play_anim( 'anim_memorymatch_successhand_cozmo_04').wait_for_completed() self.coz.say_text("You win! Congratulations!!", duration_scalar=1.75, voice_pitch=-1, in_parallel=False).wait_for_completed() def foundMarker(self, event, *, image_box, obj, pose, updated, **kw): if self.questionAsked == True: if 'Custom' in str(type(obj)): if obj not in self.numList: self.numList.append(obj) print(len(self.numList)) def removeMarker(self, event, *, obj): if self.questionAsked == True: if obj in self.numList: self.numList.remove(obj) def playIdle(self): if self.lookingForFace == False: self.coz.play_anim( self.idleAnimations[self.animCtr]).wait_for_completed() self.playIdle()
class Leader: """ This class represents the quiz "leader". The leader is one priviliged client amongst all quiz players which is responsible for publishing new questions and calculate the score of the quiz players, based on their answers. """ def __init__(self, client, scoreboard): self._client = client self._scoreboard = scoreboard self._questions = Questions() self._questions.load() self._collectedAnswers = {} self._priority = util.mtime() self._lastHeartbeatSeen = util.mtime() self._minPrioritySeen = sys.maxsize self._lastQuestionSend = 0 def _sendHeartbeat(self): self._client.send({ "type": config.Message.HEARTBEAT, }) def _sendPriority(self): self._client.send({ "type": config.Message.PRIORITY, "priority": self._priority, }) def _resetPriority(self): self._minPrioritySeen = sys.maxsize def _processAnswers(self): if self._client.activeQuestion != None: correctAnswer = self._client.activeQuestion.getCorrectAnswer() self._scoreboard.deltaUpdate(self._collectedAnswers, correctAnswer) self._collectedAnswers = {} self._client.send(self._scoreboard.toDict(), True) def _publishQuestion(self): q = self._questions.random() self._client.send(q.toDict(), True) self._lastQuestionSend = util.mtime() def isLeader(self): """ Whether this client is currently the leader (which is responsible for score calculation and question publishing) """ return self._lastHeartbeatSeen < util.mtime() - config.TAKEOVER_TIMEOUT_MS and \ self._priority < self._minPrioritySeen def dispatchPriority(self, msg): """ Gets called whenever a client is announcing his priority. This message is important during the leader election process. The client with the highest priority (=>lowest value) will take the leadership. """ if not self.isLeader(): self._minPrioritySeen = min(self._minPrioritySeen, int(msg.getMeta("priority"))) def dispatchHeartbeat(self, msg): """ Gets called whenever a heartbeat signal is received. A heartbeat signals the presence of a leader. """ self._resetPriority() self._lastHeartbeatSeen = util.mtime() def dispatchAnswer(self, msg): """ Gets called whenever an answer from a client received. If we are leader, we process the answer in order to calculate the scores. """ if (not self.isLeader() or self._client.activeQuestion == None): return activeQuestionId = int(self._client.activeQuestion.getQuestionId()) answerQuestionId = int(msg.getMeta("questionId")) if answerQuestionId == activeQuestionId: self._collectedAnswers[msg.getMeta("username")] = msg.getMeta("answer") def tick(self): """ Gets called from the main event loop of tkinter. It basically takes care to perform the duty of the leader. If we are not the leader, there is not much work to be done here. """ if not self._client.hasSubscribers(): self._lastHeartbeatSeen = util.mtime() self._resetPriority() return if self.isLeader(): self._resetPriority() self._sendHeartbeat() if self._lastQuestionSend + config.QUESTION_TIME_MS < util.mtime(): self._processAnswers() self._publishQuestion() elif self._lastHeartbeatSeen < util.mtime() - config.ELECTION_TIMEOUT_MS: self._sendPriority()
from flask import Flask, request, jsonify, render_template from werkzeug.utils import secure_filename import os from users import Users from questions import Questions from ohqueue import OHQueue from controller import Controller import debug app = Flask(__name__) app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True IMAGE_UPLOAD_FOLDER = "static/question_assets" users = Users() questions = Questions() ohqueue = OHQueue() controller = Controller() # ========= # DEBUG # ========= # def add_debug_data(): # users.create_user_if_doesnt_exist(88, "David Xiong", "*****@*****.**") # users.create_user_if_doesnt_exist(89, "Jiewen Lai", "*****@*****.**") # users.create_user_if_doesnt_exist(90, "Zoey Cao", "*****@*****.**") # users.create_user_if_doesnt_exist(91, "Peng Gu", "*****@*****.**") # users.create_user_if_doesnt_exist(92, "Sundi Xiao", "*****@*****.**") # users.create_user_if_doesnt_exist(93, "James Student", "*****@*****.**") # users.create_user_if_doesnt_exist(94, "Oski Bear", "*****@*****.**") # users.create_user_if_doesnt_exist(95, "Carol Christ", "*****@*****.**")
from questions import Questions # created the entire quiz all_questions = [ 'What color are strawberries?\na) Red\nb) Yellow\nc) Green\n>>', 'What color are bananas?\na) Teal\nb) Magenta\nc) Yellow\n>>', 'What color are apples?\na) Blue\nb) Red\nc) Pink\n>>' ] # arranged an array question_answer = [ Questions(all_questions[0], 'a'), Questions(all_questions[1], 'c'), Questions(all_questions[2], 'b') ] def quiz(questions: list): """ Run the quiz GAME It takes an array using classes to store 'prompt and answer' :param questions: each single element of the array is a class :return: score (correct answers out of the questions) checked between the user input and the class.answer """ score = 0 for question in questions: answer = input(question.prompt) if answer == question.answer: score += 1 print(f'You got {score}/{len(questions)} correct')
def test_get_points_per_question(self, mock_get_number_of_questions): mock_get_number_of_questions.return_value = 49 expected_result = round(100 / 49, 2) self.assertEqual(Questions.get_points_per_question(), expected_result)
from questions import Questions if __name__ == '__main__': q = Questions() df = q.initDataframe() q.askQuestion(df, 'How does the len() function work?', q.getStudentNum(), 24) q.askQuestion(df, 'How do I add a list to a dataframe?', q.getStudentNum()) q.askQuestion(df, 'How can I find the sum of a list?', q.getStudentNum(), 4) q.askQuestion(df, 'What is abstraction?', q.getStudentNum(), 2) q.askQuestion(df, 'What are the 4 pillars of Object Oriented Programming?', q.getStudentNum(), 4) q.askQuestion(df, 'How do you compare a list of characters?', q.getStudentNum(), 2) studentNums = df['studentNum'].tolist() q.upvoteQuestion(df, studentNums[0]) q.upvoteQuestion(df, studentNums[0]) q.upvoteQuestion(df, studentNums[0]) q.upvoteQuestion(df, studentNums[1]) print(df)
from urllib.request import urlopen import json import mlab from questions import Questions mlab.connect() url = "https://opentdb.com/api.php?amount=50" conn = urlopen(url) ### Fetch the content into a string raw_data = conn.read() page_content = raw_data.decode("utf8") # print(type(page_content)) ### Convert it into a dict d1 = json.loads(page_content) results = d1["results"] for result in results: for i in range (len(results)): result = Questions(category = results[i]["category"], types = results[i]["type"], difficulty = results[i]["difficulty"], question = results[i]["question"], correct_answer = results[i]["correct_answer"], incorrect_answers = results[i]["incorrect_answers"]) result.save()
class Ui_MainWindow(object): def __init__(self, socket, player_id): self.questions = Questions() self.WinnerChosen = False self.socketGUI = socket self.playerId = player_id self.thread_scores = threading.Thread(target=self.update_scoreboard, args=()) self.thread_scores.daemon = True # self.answered_questions_t = threading.Thread(target=self.answered_questions, args=()) # self.answered_questions_t.daemon = True # self.answered_questions_t.start() # each second asks for new scores def update_scoreboard(self): while True: new_scores = self.socketGUI.send("get_scores") print("New scores from server: ", new_scores) self.team1_score_lbl.setText(str(new_scores.get("p0"))) self.team2_score_lbl.setText(str(new_scores.get("p1"))) self.team3_score_lbl.setText(str(new_scores.get("p2"))) sleep(1) # def answered_questions(self): # while True: #answered = self.socketGUI.send("get_answered") #print(answered) # print("New scores from server: ", new_scores) # self.team1_score_lbl.setText(str(new_scores.get("p0"))) # self.team2_score_lbl.setText(str(new_scores.get("p1"))) # self.team3_score_lbl.setText(str(new_scores.get("p2"))) #sleep(1) def openQuestion(self, btn): rcv = self.socketGUI.send("q_" + btn.objectName()) # ex. cat1.100 dialog = QuestionDialog(rcv) ret_status = dialog.exec_() if ret_status == QtWidgets.QDialog.Accepted: print("Answered = ", dialog.getAnswer()) #check answer answ = json.dumps({ "question": "cat1.100", "answer": dialog.getAnswer() }) print("Data back to server", answ) print(type(answ)) rcv = self.socketGUI.send(answ) print("Received back (is correct): ", rcv.get("a")) btn.setEnabled(False) def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(608, 392) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.cat1_100den = QtWidgets.QPushButton(self.centralwidget) self.cat1_100den.setGeometry(QtCore.QRect(30, 50, 101, 41)) self.cat1_100den.setAutoFillBackground(True) self.cat1_100den.setCheckable(True) self.cat1_100den.setChecked(False) self.cat1_100den.setAutoRepeat(False) self.cat1_100den.setAutoExclusive(False) self.cat1_100den.setAutoDefault(True) self.cat1_100den.setDefault(False) self.cat1_100den.setFlat(False) self.cat1_100den.setObjectName("cat1.100") self.cat1_100den.clicked.connect( lambda: self.openQuestion(self.cat1_100den)) #self.buttons.append(self.cat1_100den) self.cat2_100den = QtWidgets.QPushButton(self.centralwidget) self.cat2_100den.setGeometry(QtCore.QRect(140, 50, 101, 41)) self.cat2_100den.setAutoFillBackground(True) self.cat2_100den.setCheckable(True) self.cat2_100den.setChecked(False) self.cat2_100den.setAutoRepeat(False) self.cat2_100den.setAutoExclusive(False) self.cat2_100den.setAutoDefault(True) self.cat2_100den.setDefault(False) self.cat2_100den.setFlat(False) self.cat2_100den.setObjectName("cat2.100") self.cat2_100den.clicked.connect( lambda: self.openQuestion(self.cat2_100den)) self.cat3_100den = QtWidgets.QPushButton(self.centralwidget) self.cat3_100den.setGeometry(QtCore.QRect(250, 50, 101, 41)) self.cat3_100den.setAutoFillBackground(True) self.cat3_100den.setCheckable(True) self.cat3_100den.setChecked(False) self.cat3_100den.setAutoRepeat(False) self.cat3_100den.setAutoExclusive(False) self.cat3_100den.setAutoDefault(True) self.cat3_100den.setDefault(False) self.cat3_100den.setFlat(False) self.cat3_100den.setObjectName("cat3.100") self.cat3_100den.clicked.connect( lambda: self.openQuestion(self.cat3_100den)) self.cat4_100den = QtWidgets.QPushButton(self.centralwidget) self.cat4_100den.setGeometry(QtCore.QRect(360, 50, 101, 41)) self.cat4_100den.setAutoFillBackground(True) self.cat4_100den.setCheckable(True) self.cat4_100den.setChecked(False) self.cat4_100den.setAutoRepeat(False) self.cat4_100den.setAutoExclusive(False) self.cat4_100den.setAutoDefault(True) self.cat4_100den.setDefault(False) self.cat4_100den.setFlat(False) self.cat4_100den.setObjectName("cat4.100") self.cat4_100den.clicked.connect( lambda: self.openQuestion(self.cat4_100den)) self.cat5_100den = QtWidgets.QPushButton(self.centralwidget) self.cat5_100den.setGeometry(QtCore.QRect(470, 50, 101, 41)) self.cat5_100den.setAutoFillBackground(True) self.cat5_100den.setCheckable(True) self.cat5_100den.setChecked(False) self.cat5_100den.setAutoRepeat(False) self.cat5_100den.setAutoExclusive(False) self.cat5_100den.setAutoDefault(True) self.cat5_100den.setDefault(False) self.cat5_100den.setFlat(False) self.cat5_100den.setObjectName("cat5.100") self.cat5_100den.clicked.connect( lambda: self.openQuestion(self.cat5_100den)) self.cat4_200den = QtWidgets.QPushButton(self.centralwidget) self.cat4_200den.setGeometry(QtCore.QRect(360, 100, 101, 41)) self.cat4_200den.setAutoFillBackground(True) self.cat4_200den.setCheckable(True) self.cat4_200den.setChecked(False) self.cat4_200den.setAutoRepeat(False) self.cat4_200den.setAutoExclusive(False) self.cat4_200den.setAutoDefault(True) self.cat4_200den.setDefault(False) self.cat4_200den.setFlat(False) self.cat4_200den.setObjectName("cat4.200") self.cat4_200den.clicked.connect( lambda: self.openQuestion(self.cat4_200den)) self.cat3_200den = QtWidgets.QPushButton(self.centralwidget) self.cat3_200den.setGeometry(QtCore.QRect(250, 100, 101, 41)) self.cat3_200den.setAutoFillBackground(True) self.cat3_200den.setCheckable(True) self.cat3_200den.setChecked(False) self.cat3_200den.setAutoRepeat(False) self.cat3_200den.setAutoExclusive(False) self.cat3_200den.setAutoDefault(True) self.cat3_200den.setDefault(False) self.cat3_200den.setFlat(False) self.cat3_200den.setObjectName("cat3.200") self.cat3_200den.clicked.connect( lambda: self.openQuestion(self.cat3_200den)) self.cat2_200den = QtWidgets.QPushButton(self.centralwidget) self.cat2_200den.setGeometry(QtCore.QRect(140, 100, 101, 41)) self.cat2_200den.setAutoFillBackground(True) self.cat2_200den.setCheckable(True) self.cat2_200den.setChecked(False) self.cat2_200den.setAutoRepeat(False) self.cat2_200den.setAutoExclusive(False) self.cat2_200den.setAutoDefault(True) self.cat2_200den.setDefault(False) self.cat2_200den.setFlat(False) self.cat2_200den.setObjectName("cat2.200") self.cat2_200den.clicked.connect( lambda: self.openQuestion(self.cat2_200den)) self.cat5_200den = QtWidgets.QPushButton(self.centralwidget) self.cat5_200den.setGeometry(QtCore.QRect(470, 100, 101, 41)) self.cat5_200den.setAutoFillBackground(True) self.cat5_200den.setCheckable(True) self.cat5_200den.setChecked(False) self.cat5_200den.setAutoRepeat(False) self.cat5_200den.setAutoExclusive(False) self.cat5_200den.setAutoDefault(True) self.cat5_200den.setDefault(False) self.cat5_200den.setFlat(False) self.cat5_200den.setObjectName("cat5.200") self.cat5_200den.clicked.connect( lambda: self.openQuestion(self.cat5_200den)) self.cat1_200den = QtWidgets.QPushButton(self.centralwidget) self.cat1_200den.setGeometry(QtCore.QRect(30, 100, 101, 41)) self.cat1_200den.setAutoFillBackground(True) self.cat1_200den.setCheckable(True) self.cat1_200den.setChecked(False) self.cat1_200den.setAutoRepeat(False) self.cat1_200den.setAutoExclusive(False) self.cat1_200den.setAutoDefault(True) self.cat1_200den.setDefault(False) self.cat1_200den.setFlat(False) self.cat1_200den.setObjectName("cat1.200") self.cat1_200den.clicked.connect( lambda: self.openQuestion(self.cat1_200den)) self.cat4_400den = QtWidgets.QPushButton(self.centralwidget) self.cat4_400den.setGeometry(QtCore.QRect(360, 200, 101, 41)) self.cat4_400den.setAutoFillBackground(True) self.cat4_400den.setCheckable(True) self.cat4_400den.setChecked(False) self.cat4_400den.setAutoRepeat(False) self.cat4_400den.setAutoExclusive(False) self.cat4_400den.setAutoDefault(True) self.cat4_400den.setDefault(False) self.cat4_400den.setFlat(False) self.cat4_400den.setObjectName("cat4.400") self.cat4_400den.clicked.connect( lambda: self.openQuestion(self.cat4_400den)) self.cat4_300den = QtWidgets.QPushButton(self.centralwidget) self.cat4_300den.setGeometry(QtCore.QRect(360, 150, 101, 41)) self.cat4_300den.setAutoFillBackground(True) self.cat4_300den.setCheckable(True) self.cat4_300den.setChecked(False) self.cat4_300den.setAutoRepeat(False) self.cat4_300den.setAutoExclusive(False) self.cat4_300den.setAutoDefault(True) self.cat4_300den.setDefault(False) self.cat4_300den.setFlat(False) self.cat4_300den.setObjectName("cat4.300") self.cat4_300den.clicked.connect( lambda: self.openQuestion(self.cat4_300den)) self.cat2_400den = QtWidgets.QPushButton(self.centralwidget) self.cat2_400den.setGeometry(QtCore.QRect(140, 200, 101, 41)) self.cat2_400den.setAutoFillBackground(True) self.cat2_400den.setCheckable(True) self.cat2_400den.setChecked(False) self.cat2_400den.setAutoRepeat(False) self.cat2_400den.setAutoExclusive(False) self.cat2_400den.setAutoDefault(True) self.cat2_400den.setDefault(False) self.cat2_400den.setFlat(False) self.cat2_400den.setObjectName("cat2.400") self.cat2_400den.clicked.connect( lambda: self.openQuestion(self.cat2_400den)) self.cat3_300den = QtWidgets.QPushButton(self.centralwidget) self.cat3_300den.setGeometry(QtCore.QRect(250, 150, 101, 41)) self.cat3_300den.setAutoFillBackground(True) self.cat3_300den.setCheckable(True) self.cat3_300den.setChecked(False) self.cat3_300den.setAutoRepeat(False) self.cat3_300den.setAutoExclusive(False) self.cat3_300den.setAutoDefault(True) self.cat3_300den.setDefault(False) self.cat3_300den.setFlat(False) self.cat3_300den.setObjectName("cat3.300") self.cat3_300den.clicked.connect( lambda: self.openQuestion(self.cat3_300den)) self.cat2_300den = QtWidgets.QPushButton(self.centralwidget) self.cat2_300den.setGeometry(QtCore.QRect(140, 150, 101, 41)) self.cat2_300den.setAutoFillBackground(True) self.cat2_300den.setCheckable(True) self.cat2_300den.setChecked(False) self.cat2_300den.setAutoRepeat(False) self.cat2_300den.setAutoExclusive(False) self.cat2_300den.setAutoDefault(True) self.cat2_300den.setDefault(False) self.cat2_300den.setFlat(False) self.cat2_300den.setObjectName("cat2.300") self.cat2_300den.clicked.connect( lambda: self.openQuestion(self.cat2_300den)) self.cat1_400den = QtWidgets.QPushButton(self.centralwidget) self.cat1_400den.setGeometry(QtCore.QRect(30, 200, 101, 41)) self.cat1_400den.setAutoFillBackground(True) self.cat1_400den.setCheckable(True) self.cat1_400den.setChecked(False) self.cat1_400den.setAutoRepeat(False) self.cat1_400den.setAutoExclusive(False) self.cat1_400den.setAutoDefault(True) self.cat1_400den.setDefault(False) self.cat1_400den.setFlat(False) self.cat1_400den.setObjectName("cat1.400") self.cat1_400den.clicked.connect( lambda: self.openQuestion(self.cat1_400den)) self.cat5_300den = QtWidgets.QPushButton(self.centralwidget) self.cat5_300den.setGeometry(QtCore.QRect(470, 150, 101, 41)) self.cat5_300den.setAutoFillBackground(True) self.cat5_300den.setCheckable(True) self.cat5_300den.setChecked(False) self.cat5_300den.setAutoRepeat(False) self.cat5_300den.setAutoExclusive(False) self.cat5_300den.setAutoDefault(True) self.cat5_300den.setDefault(False) self.cat5_300den.setFlat(False) self.cat5_300den.setObjectName("cat5.300") self.cat5_300den.clicked.connect( lambda: self.openQuestion(self.cat5_300den)) self.cat5_400den = QtWidgets.QPushButton(self.centralwidget) self.cat5_400den.setGeometry(QtCore.QRect(470, 200, 101, 41)) self.cat5_400den.setAutoFillBackground(True) self.cat5_400den.setCheckable(True) self.cat5_400den.setChecked(False) self.cat5_400den.setAutoRepeat(False) self.cat5_400den.setAutoExclusive(False) self.cat5_400den.setAutoDefault(True) self.cat5_400den.setDefault(False) self.cat5_400den.setFlat(False) self.cat5_400den.setObjectName("cat5.400") self.cat5_400den.clicked.connect( lambda: self.openQuestion(self.cat5_400den)) self.cat3_400den = QtWidgets.QPushButton(self.centralwidget) self.cat3_400den.setGeometry(QtCore.QRect(250, 200, 101, 41)) self.cat3_400den.setAutoFillBackground(True) self.cat3_400den.setCheckable(True) self.cat3_400den.setChecked(False) self.cat3_400den.setAutoRepeat(False) self.cat3_400den.setAutoExclusive(False) self.cat3_400den.setAutoDefault(True) self.cat3_400den.setDefault(False) self.cat3_400den.setFlat(False) self.cat3_400den.setObjectName("cat3.400") self.cat3_400den.clicked.connect( lambda: self.openQuestion(self.cat3_400den)) self.cat1_300den = QtWidgets.QPushButton(self.centralwidget) self.cat1_300den.setGeometry(QtCore.QRect(30, 150, 101, 41)) self.cat1_300den.setAutoFillBackground(True) self.cat1_300den.setCheckable(True) self.cat1_300den.setChecked(False) self.cat1_300den.setAutoRepeat(False) self.cat1_300den.setAutoExclusive(False) self.cat1_300den.setAutoDefault(True) self.cat1_300den.setDefault(False) self.cat1_300den.setFlat(False) self.cat1_300den.setObjectName("cat1.300") self.cat1_300den.clicked.connect( lambda: self.openQuestion(self.cat1_300den)) self.cat3_500den = QtWidgets.QPushButton(self.centralwidget) self.cat3_500den.setGeometry(QtCore.QRect(250, 250, 101, 41)) self.cat3_500den.setAutoFillBackground(True) self.cat3_500den.setCheckable(True) self.cat3_500den.setChecked(False) self.cat3_500den.setAutoRepeat(False) self.cat3_500den.setAutoExclusive(False) self.cat3_500den.setAutoDefault(True) self.cat3_500den.setDefault(False) self.cat3_500den.setFlat(False) self.cat3_500den.setObjectName("cat3.500") self.cat3_500den.clicked.connect( lambda: self.openQuestion(self.cat3_500den)) self.cat2_500den = QtWidgets.QPushButton(self.centralwidget) self.cat2_500den.setGeometry(QtCore.QRect(140, 250, 101, 41)) self.cat2_500den.setAutoFillBackground(True) self.cat2_500den.setCheckable(True) self.cat2_500den.setChecked(False) self.cat2_500den.setAutoRepeat(False) self.cat2_500den.setAutoExclusive(False) self.cat2_500den.setAutoDefault(True) self.cat2_500den.setDefault(False) self.cat2_500den.setFlat(False) self.cat2_500den.setObjectName("cat2.500") self.cat2_500den.clicked.connect( lambda: self.openQuestion(self.cat2_500den)) self.cat4_500den = QtWidgets.QPushButton(self.centralwidget) self.cat4_500den.setGeometry(QtCore.QRect(360, 250, 101, 41)) self.cat4_500den.setAutoFillBackground(True) self.cat4_500den.setCheckable(True) self.cat4_500den.setChecked(False) self.cat4_500den.setAutoRepeat(False) self.cat4_500den.setAutoExclusive(False) self.cat4_500den.setAutoDefault(True) self.cat4_500den.setDefault(False) self.cat4_500den.setFlat(False) self.cat4_500den.setObjectName("cat4.500") self.cat4_500den.clicked.connect( lambda: self.openQuestion(self.cat4_500den)) self.cat5_500den = QtWidgets.QPushButton(self.centralwidget) self.cat5_500den.setGeometry(QtCore.QRect(470, 250, 101, 41)) self.cat5_500den.setAutoFillBackground(True) self.cat5_500den.setCheckable(True) self.cat5_500den.setChecked(False) self.cat5_500den.setAutoRepeat(False) self.cat5_500den.setAutoExclusive(False) self.cat5_500den.setAutoDefault(True) self.cat5_500den.setDefault(False) self.cat5_500den.setFlat(False) self.cat5_500den.setObjectName("cat5.500") self.cat5_500den.clicked.connect( lambda: self.openQuestion(self.cat5_500den)) self.cat1_500den = QtWidgets.QPushButton(self.centralwidget) self.cat1_500den.setGeometry(QtCore.QRect(30, 250, 101, 41)) self.cat1_500den.setAutoFillBackground(True) self.cat1_500den.setCheckable(True) self.cat1_500den.setChecked(False) self.cat1_500den.setAutoRepeat(False) self.cat1_500den.setAutoExclusive(False) self.cat1_500den.setAutoDefault(True) self.cat1_500den.setDefault(False) self.cat1_500den.setFlat(False) self.cat1_500den.setObjectName("cat1.500") self.cat1_500den.clicked.connect( lambda: self.openQuestion(self.cat1_500den)) self.category1_lbl = QtWidgets.QLabel(self.centralwidget) self.category1_lbl.setGeometry(QtCore.QRect(40, 20, 81, 16)) self.category1_lbl.setAlignment(QtCore.Qt.AlignCenter) self.category1_lbl.setIndent(0) self.category1_lbl.setObjectName("category1_lbl") self.category1_lbl.setText(self.questions.GetCategoryName(0)) self.category2_lbl = QtWidgets.QLabel(self.centralwidget) self.category2_lbl.setGeometry(QtCore.QRect(150, 20, 81, 16)) self.category2_lbl.setAlignment(QtCore.Qt.AlignCenter) self.category2_lbl.setIndent(0) self.category2_lbl.setObjectName("category2_lbl") self.category2_lbl.setText(self.questions.GetCategoryName(1)) self.category3_lbl = QtWidgets.QLabel(self.centralwidget) self.category3_lbl.setGeometry(QtCore.QRect(260, 20, 81, 16)) self.category3_lbl.setAlignment(QtCore.Qt.AlignCenter) self.category3_lbl.setIndent(0) self.category3_lbl.setObjectName("category3_lbl") self.category3_lbl.setText(self.questions.GetCategoryName(2)) self.category4_lbl = QtWidgets.QLabel(self.centralwidget) self.category4_lbl.setGeometry(QtCore.QRect(370, 20, 81, 16)) self.category4_lbl.setAlignment(QtCore.Qt.AlignCenter) self.category4_lbl.setIndent(0) self.category4_lbl.setObjectName("category4_lbl") self.category4_lbl.setText(self.questions.GetCategoryName(3)) self.category5_lbl = QtWidgets.QLabel(self.centralwidget) self.category5_lbl.setGeometry(QtCore.QRect(480, 20, 81, 16)) self.category5_lbl.setAlignment(QtCore.Qt.AlignCenter) self.category5_lbl.setIndent(0) self.category5_lbl.setObjectName("category5_lbl") self.category5_lbl.setText(self.questions.GetCategoryName(4)) self.result_lbl = QtWidgets.QLabel(self.centralwidget) self.result_lbl.setGeometry(QtCore.QRect(30, 300, 61, 16)) font = QtGui.QFont() font.setPointSize(10) self.result_lbl.setFont(font) self.result_lbl.setObjectName("result_lbl") self.team1_txt_lbl = QtWidgets.QLabel(self.centralwidget) self.team1_txt_lbl.setGeometry(QtCore.QRect(30, 320, 41, 16)) font = QtGui.QFont() font.setPointSize(10) self.team1_txt_lbl.setFont(font) self.team1_txt_lbl.setObjectName("team1_txt_lbl") self.team2_txt_lbl = QtWidgets.QLabel(self.centralwidget) self.team2_txt_lbl.setGeometry(QtCore.QRect(30, 340, 41, 16)) font = QtGui.QFont() font.setPointSize(10) self.team2_txt_lbl.setFont(font) self.team2_txt_lbl.setObjectName("team2_txt_lbl") self.team3_txt_lbl = QtWidgets.QLabel(self.centralwidget) self.team3_txt_lbl.setGeometry(QtCore.QRect(30, 360, 41, 16)) font = QtGui.QFont() font.setPointSize(10) self.team3_txt_lbl.setFont(font) self.team3_txt_lbl.setObjectName("team3_txt_lbl") self.team1_score_lbl = QtWidgets.QLabel(self.centralwidget) self.team1_score_lbl.setGeometry(QtCore.QRect(80, 320, 41, 16)) font = QtGui.QFont() font.setPointSize(10) self.team1_score_lbl.setFont(font) self.team1_score_lbl.setObjectName("team1_score_lbl") self.team2_score_lbl = QtWidgets.QLabel(self.centralwidget) self.team2_score_lbl.setGeometry(QtCore.QRect(80, 340, 41, 16)) font = QtGui.QFont() font.setPointSize(10) self.team2_score_lbl.setFont(font) self.team2_score_lbl.setObjectName("team2_score_lbl") self.team3_score_lbl = QtWidgets.QLabel(self.centralwidget) self.team3_score_lbl.setGeometry(QtCore.QRect(80, 360, 41, 16)) font = QtGui.QFont() font.setPointSize(10) self.team3_score_lbl.setFont(font) self.team3_score_lbl.setObjectName("team3_score_lbl") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle( _translate( "MainWindow", "Џеопарди (Jeopardy) | Player: {}".format(str(self.playerId)))) self.cat1_100den.setText(_translate("MainWindow", "100 ден.")) self.cat2_100den.setText(_translate("MainWindow", "100 ден.")) self.cat3_100den.setText(_translate("MainWindow", "100 ден.")) self.cat4_100den.setText(_translate("MainWindow", "100 ден.")) self.cat5_100den.setText(_translate("MainWindow", "100 ден.")) self.cat4_200den.setText(_translate("MainWindow", "200 ден.")) self.cat3_200den.setText(_translate("MainWindow", "200 ден.")) self.cat2_200den.setText(_translate("MainWindow", "200 ден.")) self.cat5_200den.setText(_translate("MainWindow", "200 ден.")) self.cat1_200den.setText(_translate("MainWindow", "200 ден.")) self.cat4_400den.setText(_translate("MainWindow", "400 ден.")) self.cat4_300den.setText(_translate("MainWindow", "300 ден.")) self.cat2_400den.setText(_translate("MainWindow", "400 ден.")) self.cat3_300den.setText(_translate("MainWindow", "300 ден.")) self.cat2_300den.setText(_translate("MainWindow", "300 ден.")) self.cat1_400den.setText(_translate("MainWindow", "400 ден.")) self.cat5_300den.setText(_translate("MainWindow", "300 ден.")) self.cat5_400den.setText(_translate("MainWindow", "400 ден.")) self.cat3_400den.setText(_translate("MainWindow", "400 ден.")) self.cat1_300den.setText(_translate("MainWindow", "300 ден.")) self.cat3_500den.setText(_translate("MainWindow", "500 ден.")) self.cat2_500den.setText(_translate("MainWindow", "500 ден.")) self.cat4_500den.setText(_translate("MainWindow", "500 ден.")) self.cat5_500den.setText(_translate("MainWindow", "500 ден.")) self.cat1_500den.setText(_translate("MainWindow", "500 ден.")) self.result_lbl.setText(_translate("MainWindow", "Резултат:")) self.team1_txt_lbl.setText(_translate("MainWindow", "ТИМ 1: ")) self.team2_txt_lbl.setText(_translate("MainWindow", "ТИМ 2:")) self.team3_txt_lbl.setText(_translate("MainWindow", "ТИМ 3: ")) self.team1_score_lbl.setText(_translate("MainWindow", "0")) self.team2_score_lbl.setText(_translate("MainWindow", "0")) self.team3_score_lbl.setText(_translate("MainWindow", "0")) self.thread_scores.start()
class Leader: """ This class represents the quiz "leader". The leader is one priviliged client amongst all quiz players which is responsible for publishing new questions and calculate the score of the quiz players, based on their answers. """ def __init__(self, client, scoreboard): self._client = client self._scoreboard = scoreboard self._questions = Questions() self._questions.load() self._collectedAnswers = {} self._priority = util.mtime() self._lastHeartbeatSeen = util.mtime() self._minPrioritySeen = sys.maxsize self._lastQuestionSend = 0 def _sendHeartbeat(self): self._client.send({ "type": config.Message.HEARTBEAT, }) def _sendPriority(self): self._client.send({ "type": config.Message.PRIORITY, "priority": self._priority, }) def _resetPriority(self): self._minPrioritySeen = sys.maxsize def _processAnswers(self): if self._client.activeQuestion != None: correctAnswer = self._client.activeQuestion.getCorrectAnswer() self._scoreboard.deltaUpdate(self._collectedAnswers, correctAnswer) self._collectedAnswers = {} self._client.send(self._scoreboard.toDict(), True) def _publishQuestion(self): q = self._questions.random() self._client.send(q.toDict(), True) self._lastQuestionSend = util.mtime() def isLeader(self): """ Whether this client is currently the leader (which is responsible for score calculation and question publishing) """ return self._lastHeartbeatSeen < util.mtime() - config.TAKEOVER_TIMEOUT_MS and \ self._priority < self._minPrioritySeen def dispatchPriority(self, msg): """ Gets called whenever a client is announcing his priority. This message is important during the leader election process. The client with the highest priority (=>lowest value) will take the leadership. """ if not self.isLeader(): self._minPrioritySeen = min(self._minPrioritySeen, int(msg.getMeta("priority"))) def dispatchHeartbeat(self, msg): """ Gets called whenever a heartbeat signal is received. A heartbeat signals the presence of a leader. """ self._resetPriority() self._lastHeartbeatSeen = util.mtime() def dispatchAnswer(self, msg): """ Gets called whenever an answer from a client received. If we are leader, we process the answer in order to calculate the scores. """ if (not self.isLeader() or self._client.activeQuestion == None): return activeQuestionId = int(self._client.activeQuestion.getQuestionId()) answerQuestionId = int(msg.getMeta("questionId")) if answerQuestionId == activeQuestionId: self._collectedAnswers[msg.getMeta("username")] = msg.getMeta( "answer") def tick(self): """ Gets called from the main event loop of tkinter. It basically takes care to perform the duty of the leader. If we are not the leader, there is not much work to be done here. """ if not self._client.hasSubscribers(): self._lastHeartbeatSeen = util.mtime() self._resetPriority() return if self.isLeader(): self._resetPriority() self._sendHeartbeat() if self._lastQuestionSend + config.QUESTION_TIME_MS < util.mtime(): self._processAnswers() self._publishQuestion() elif self._lastHeartbeatSeen < util.mtime( ) - config.ELECTION_TIMEOUT_MS: self._sendPriority()
class Frame(tk.Frame): def __init__(self, master, filename): super(Frame, self).__init__(master) self.qs = Questions(filename) # 初始化 self.init_question() self.init_interactive() self.init_buttons() self.init_indicate() self.reset_question() # 添加部件 self.add_question() self.add_interactive() # self.add_buttons() # self.add_indicate() # 添加键盘事件 self.bind('<Key>', self.key) def init_question(self): '添加问题变量' self.Q = tk.StringVar() def add_question(self): '添加问题对应的widget.' tk.Label(self, textvariable=self.Q, font=(FONT['family'], FONT['size'] + 2), wraplength=600, justify=tk.LEFT, anchor=tk.W, ).grid(row=0, column=0, columnspan=4, sticky='w', padx=(20, 0), pady=(10, 10), ) def init_interactive(self): '初始化交互部件变量,如选项(选择题),空格(填空题)' pass def add_interactive(self): '添加选项、空格对应的widget' pass def init_buttons(self): '初始化操作按钮部件' self.hint_button = tk.Button(self, text='提示(h)', command=self.hint, width=10, font=(FONT['family'], FONT['size'] - 2), ) self.redo_button = tk.Button(self, text='重做(r)', command=self.redo, width=10, font=(FONT['family'], FONT['size'] - 2), ) self.next_question_button = tk.Button(self, text='下一题(n)', command=self.next, width=10, font=(FONT['family'], FONT['size'] - 2), ) self.confirm_button = tk.Button(self, text='确定(Enter)', command=self.check, width=10, font=(FONT['family'], FONT['size'] - 2), ) def add_buttons(self, row): '添加按钮部件' self.hint_button.grid(row=row, column=0, padx=(10, 0), pady=(0, 0), sticky='w', ) self.redo_button.grid(row=row, column=1, padx=(0, 0), pady=(0, 0), sticky='w', ) self.next_question_button.grid(row=row, column=2, padx=(0, 0), pady=(0, 0), sticky='w', ) self.confirm_button.grid(row=row, column=3, padx=(0, 0), pady=(0, 0), sticky='w', ) def init_indicate(self): '初始化正确/错误提示部件' self.indicate = tk.StringVar() def add_indicate(self, row): '添加正确/错误提示部件' tk.Label(self, textvariable=self.indicate, font=(FONT['family'], FONT['size'] + 1), ).grid(row=row, column=0, columnspan=4, sticky='w', pady=(20, 20), padx=(20, 0), ) def reset_question(self, index=0): '''初始化问题,即获取当前问题,并将问题和提示 变量至于初始状态 ''' self.qs.index += index question = self.qs.get_question() self.Q.set('{}/{}.{}'.format(self.qs.index + 1, self.qs.total, question.get('Q'))) self.reset_interactive(index) self.indicate.set('') def reset_interactive(self, index=0): '重置交互,如选择状态,填空' pass def key(self, event): '按键捕捉回调函数' char = event.char.lower() # print('!!!') if char == 'h': self.hint() if char == 'r': self.redo() if char == 'n': self.next() if char == '\r': self.check() # # 逻辑部分 # def hint(self): self.indicate.set(self.qs.get_question().get('A')) # print(self.qs.get_question().get('A')) def redo(self): self.reset_question(0) def next(self): self.reset_question(1) def check(self): pass def show_correct(self): self.indicate.set("正确") def show_incorrect(self): self.indicate.set("错误")
def __init__(self): self._isCompleted = False self._face = None self._newRound = True self._questions = Questions()
class Application(object): def __init__(self): self.questions = Questions() self.car_list = [] self.sort = Sort() def main_menu(self): print("What would you like to do?") print("1 - practice sorting") print("2 - quit") def sorting_menu(self): print("1 - Sort by time entered") print("2 - Sort by ranking") print("3 - Sort by year (newest to oldest)") print("4 - Sort alphabetically by make") print("5 - Random") print("6 - End") def run(self): while True: self.main_menu() user_input = input() if user_input == "1": i = 0 print( "Please answer the following questions for your top 5 dream cars" ) while len(self.car_list) < 5: i += 1 print(f"Car #{i}") make = self.questions.make() model = self.questions.model() year = self.questions.year() color = self.questions.color() rank = self.questions.rank() self.car_list.append( Car(make=make, model=model, year=year, color=color, rank=rank)) user_input = None while user_input != "6": self.sorting_menu() user_input = input() if user_input == "1": self.sort.sort_by_entry(car_list=self.car_list) elif user_input == "2": self.sort.sort_by_ranking(car_list=self.car_list) elif user_input == "3": self.sort.sort_by_year(car_list=self.car_list) elif user_input == "4": self.sort.sort_by_make(car_list=self.car_list) elif user_input == "5": self.sort.random_sort(car_list=self.car_list) elif user_input == "6": break else: print('try again') elif user_input == "2": break else: print("Not an option, try again") print(self.car_list)