Exemplo n.º 1
0
class TriviaTests:
    def __init__(self):
        self.t = Trivia()

    def test_questions_loaded(self):
        assert(len(self.t.questions) > 0)

    def test_is_correct_answer_simple(self):
        self.t.q = Question("Test category",
                            "Test question?",
                            "Test answer",
                            None)
        assert(self.t.is_correct_answer("Test answer"))

    def test_is_correct_answer_substring(self):
        self.t.q = Question("Test category",
                            "Test question?",
                            "Test #answer#",
                            None)
        assert(self.t.is_correct_answer("answer"))

    def test_is_correct_answer_regex(self):
        self.t.q = Question("Test category",
                            "Test question?",
                            "Test regex answer",
                            "Test regex(p)? answer")

        assert(self.t.is_correct_answer("Test regex answer"))
        assert(self.t.is_correct_answer("test regexp answer"))
Exemplo n.º 2
0
    def test_trivia_get_category_id_valid(self):
        return_val = {
            "trivia_categories": [{
                "name": "cat1",
                "id": 1
            }, {
                "name": "cat2",
                "id": 2
            }, {
                "name": "cat3",
                "id": 3
            }]
        }

        with patch("trivia.Trivia.get_category_dict",
                   return_value=return_val) as mock_dict:
            self.assertEqual(Trivia.get_category_id("cat1"), 1)
            self.assertEqual(Trivia.get_category_id("cat2"), 2)
            self.assertEqual(Trivia.get_category_id("cat3"), 3)
            self.assertEqual(Trivia.get_category_id("cAT1"), 1)
            self.assertEqual(Trivia.get_category_id("CaT2"), 2)
            self.assertEqual(Trivia.get_category_id("cAt3"), 3)

            self.assertEqual(Trivia.get_category_id("Any"), 0)
            self.assertEqual(Trivia.get_category_id(None), 0)
            self.assertEqual(Trivia.get_category_id(""), 0)
Exemplo n.º 3
0
    def test_trivia_fetch_question_success(self):
        query = BotQuery()
        trivia_command = TriviaCommand(query, ["/trivia"])
        trivia_mock = Trivia()
        trivia_mock.formatted_response = lambda: "trivia question"

        with patch("trivia.Trivia.fetch_question", return_value=trivia_mock):
            trivia_command.handle_normal_query = Mock()
            trivia_command.execute()
            trivia_command.handle_normal_query.assert_called_once_with(
                "trivia question")
Exemplo n.º 4
0
    def test_trivia_get_category_dict(self):
        with patch("trivia.requests.get") as mock_get:
            mock_get.return_value.ok = True
            mock_get.return_value.json = lambda: {"cat1": 1, "cat2:": 2}
            self.assertEqual(Trivia.category_dict, dict())

            # Fetch categories
            Trivia.get_category_dict()
            self.assertEqual(Trivia.category_dict, {"cat1": 1, "cat2:": 2})

            # Already fetched
            Trivia.get_category_dict()
            self.assertEqual(Trivia.category_dict, {"cat1": 1, "cat2:": 2})
Exemplo n.º 5
0
    def run(self):
        self.maxPlayers = 3
        self.minPlayers = 2
        self.totalRounds = 2
        self.round = 0
        self.spins = 0
        self.delay_before_question = 2000

        self.maxSpins = 50

        # game config
        self.geometry_width = 6
        self.geometry_height = 5
        self.triviadb = Trivia(loglevel=self.loglevel,
                               min_questions=self.geometry_height)

        if len(self.triviadb) < (self.totalRounds * self.geometry_width):
            raise Exception(
                "Insufficient trivia exists to complete a game with",
                self.totalRounds, "rounds and", " a geometry of width = ",
                self.geometry_width)

        self.current_trivia = list()
        self.utilized_categories = []

        # Determine
        #   Potentially difficulty?
        #   How many players are playing?
        #   Gather information about each player?

        self.MSG_controller = messaging.MessageController(
            loglevel=self.loglevel,
            msg_controller_name="GameLogic",
            listen_port=self.game_port,
            target_port=self.hmi_port)
        self.MSG_controller.start()

        self.currentPlayerIndex = None
        self.wheel_map = None
        if not self.use_predetermined_players:
            self.enrollPlayers()
        #self.logger.debug(self.players)
        if self.use_predetermined_startingplayer is None:
            self.currentPlayerIndex = self.selectRandomFirstPlayer()
        else:
            self.currentPlayerIndex = self.use_predetermined_startingplayer
        self.players[self.currentPlayerIndex].setActive()

        # Once all setup is completed, start the show
        self.gameLoop()
Exemplo n.º 6
0
    def test_trivia_fetch_question_valid(self):
        question_json = {
            "response_code":
            0,
            "results": [{
                "category": "cat1",
                "type": "multiple",
                "difficulty": "easy",
                "question": "What is the first letter of the alphabet?",
                "correct_answer": "A",
                "incorrect_answers": ["D", "C", "B"]
            }]
        }

        with patch("trivia.requests.get") as mock_get:
            mock_get.return_value.ok = True
            mock_get.return_value.json = lambda: question_json

            question = Trivia.fetch_question()
            self.assertEqual(question.category, "cat1")
            self.assertEqual(question.type, "multiple")
            self.assertEqual(question.difficulty, "easy")
            self.assertEqual(question.question,
                             "What is the first letter of the alphabet?")
            self.assertEqual(question.correct_answer, "A")
            self.assertListEqual(question.answers, ["A", "B", "C", "D"])
Exemplo n.º 7
0
    def test_trivia_get_category_id_invalid(self):
        return_val = {"trivia_categories": [{"name": "science", "id": 1}]}

        with patch("trivia.Trivia.get_category_dict",
                   return_value=return_val) as mock_dict:
            self.assertEqual(Trivia.get_category_id("Science"), 1)
            self.assertRaises(BotError, Trivia.get_category_id, "bad")
Exemplo n.º 8
0
def main():
    logging.basicConfig(format='%(asctime)s %(levelname)s - %(message)s', datefmt='%Y-%m-%d %I:%M:%S', level=logging.DEBUG)
    # TODO: config special word for pwd
    changed = parse_arguments()

    # Parse config file
    parse_config(changed)
    logging.info("Parsed Arguments")

    # Connect to server
    try:
        socket = connect_to_server()
        logging.info("Connected")
    except ssl.SSLError as e:
        logging.info("Unable to connect.  Are you banned?: {}".format(e))
        return sys.exit(1)

    # TODO: debug message for adding user
    # TODO: Handle non-ascii characters
    conn = Connection(socket)
    conn.start()

    try:
        while conn.current_channel is None:
            time.sleep(1)

        # Add services here
        trivia = Trivia(conn)
        conn.addService(trivia)
        trivia.start()

        # TODO: multiple tokens
        while conn.is_alive():
            time.sleep(5)

    except KeyboardInterrupt:
        pass

    logging.info("Closing down")
    # close everything down!
    conn.stop()
    socket.close()
    sys.exit(0)
Exemplo n.º 9
0
class TriviaTests:
    def __init__(self):
        self.t = Trivia()

    def test_questions_loaded(self):
        assert (len(self.t.questions) > 0)

    def test_is_correct_answer_simple(self):
        self.t.q = Question("Test category", "Test question?", "Test answer",
                            None)
        assert (self.t.is_correct_answer("Test answer"))

    def test_is_correct_answer_substring(self):
        self.t.q = Question("Test category", "Test question?", "Test #answer#",
                            None)
        assert (self.t.is_correct_answer("answer"))

    def test_is_correct_answer_regex(self):
        self.t.q = Question("Test category", "Test question?",
                            "Test regex answer", "Test regex(p)? answer")

        assert (self.t.is_correct_answer("Test regex answer"))
        assert (self.t.is_correct_answer("test regexp answer"))
Exemplo n.º 10
0
    def execute_get_new_question(self):
        category = None
        difficulty = None

        if len(self.command_arguments) > 1:
            category = self.command_arguments[1]
            if category.lower() == "help":
                self.handle_normal_query(Trivia.get_help_text())
                return
                
            if len(self.command_arguments) > 2:
                difficulty = self.command_arguments[2]

        try:
            self.trivia = Trivia.fetch_question(category, difficulty)
        except BotError as bot_err:
            print(f"TriviaCommand Error (Checked):\n\t{bot_err}")
            self.handle_normal_query(str(bot_err))
        except Exception as err:
            print(f"TriviaCommand Error (Unchecked):\n\t{err}")
            self.handle_normal_query(TRIVIA_BASE_ERROR_MESSAGE)
        else:
            self.handle_normal_query(self.trivia.formatted_response())
Exemplo n.º 11
0
def main():
    parser = argparse.ArgumentParser('Just a simple command line trivia')

    parser.add_argument("-a", "--amount", type=int, default=5,
                        help="amount of questions (default 5, max 10)")
    parser.add_argument("-l", "--level", type=int, default=1,
                        help="set difficulty level (default 1, max 3)")

    args = parser.parse_args()

    if args.amount is not None:
        if args.amount == 0 or args.amount > 10:
            parser.error("Amount should be between 1 and 10 (inclusive)")

    if args.level is not None:
        if args.level == 0 or args.level > 3:
            parser.error("Level should be between 1 and 3 (inclusive)")

    difficulty = ["easy", "medium", "hard"]
    level = difficulty[args.level - 1]
    print(f"Difficulty level: {level}")

    trivia = Trivia(args.amount, level)
    trivia.begin()
Exemplo n.º 12
0
def trigger(event, context):
    msg_key = "message"
    data = json.loads(event["body"])
    if "inline_query" in data:
        return handle_inline_query(data)

    if "callback_query" in data:
        return handle_callback_query(data)

    # don't care about edited messages or event does not contain relevant text data
    if "edited_message" in data or "text" not in data[msg_key]:
        return {"statusCode": 200}

    message = str(data[msg_key]["text"])
    chat_id = data[msg_key]["chat"]["id"]
    user_id = data[msg_key]["from"]["id"]
    parse_mode = None
    other_params = None

    if message.startswith("/start"):
        if data[msg_key]["chat"]["type"] == "private":
            response = "Hello {}! Welcome to the DAS bot!".format(
                data[msg_key]["chat"]["first_name"])
        elif data[msg_key]["chat"]["type"] == "group":
            response = "Hello {}! I am the DAS Bot, {} has summoned me here!".format(
                data[msg_key]["chat"]["title"],
                data[msg_key]["from"]["first_name"])
        else:
            response = "Hello"
    elif message.startswith("/help"):
        response = "You have invoked the help command!"
    elif message.startswith("/debug"):
        response = str(data)
    elif message.startswith("/joke"):
        r = requests.get("https://icanhazdadjoke.com/",
                         headers={"Accept": "text/plain"})
        response = r.content.decode(
        ) if r.ok else "Oops! Can't fetch joke right now."
    elif message.startswith("/fact"):
        r = requests.get("https://www.mentalfloss.com/api/facts")
        response = str(r.json()[0]['headline']
                       ) if r.ok else "Oops! Can't fetch fact right now."
        parse_mode = "HTML"
    elif message.startswith("/clear"):
        response = "Entry cleared!" if clearUser(
            user_id) else "Nothing to clear!"
    elif message.startswith("/get"):
        response = getUser(user_id) or "Nothing to get! Use /store to set"
    elif message.startswith("/store"):
        index = message.strip().find(" ")
        if index < 0:
            response = "Nothing to store!"
        else:
            result = setUser(user_id, message[index + 1:])
            response = "You stored \"{}\". Use /get to fetch it".format(
                result) if result else "Failed to store!"
    elif message.startswith("/trivia"):
        parse_mode = "Markdown"
        args = message.strip().split(" ")
        category, difficulty = None, None

        if len(args) > 1:
            category = args[1]
            if len(args) > 2:
                difficulty = args[2]

        try:
            trivia = Trivia(category, difficulty)
        except BotError as err:
            response = str(err)
        else:
            response = trivia.formatted_response()
            correct_ans = chr(trivia.correct_answer_index() + 65)
            buttons = [{
                "text": chr(i + 65),
                "callback_data": "{}{}".format(chr(i + 65), correct_ans)
            } for i in range(4)]

            other_params = {
                "reply_markup": {
                    "inline_keyboard": [[buttons[0], buttons[1]],
                                        [buttons[2], buttons[3]]],
                }
            }
    else:
        response = "Sorry, I don't understand. Try /help"

    data = {"chat_id": chat_id, "text": response}

    if parse_mode:
        data["parse_mode"] = parse_mode
    if other_params:
        data.update(other_params)

    url = BASE_URL + "/sendMessage"
    res = requests.post(url, json=data)
    if not res.ok:
        print(res.status_code)
        print(res.text)

    return {"statusCode": 200}
Exemplo n.º 13
0
class Feduquiz(App):
    title = 'Feduquiz'

    bg_col = ListProperty([0, 0, 0])

    trivia = Trivia(USE_SAMPLE_DATA)

    curr_question = StringProperty()
    curr_author = StringProperty()
    curr_type = StringProperty()
    curr_difficulty = StringProperty()
    curr_category = StringProperty()
    curr_correct = StringProperty()
    curr_wrong = ListProperty([])
    curr_btn_labels = ListProperty([])
    curr_score = NumericProperty(0)
    curr_round = NumericProperty(0)
    curr_total_rounds = NumericProperty(0)
    curr_verdict = StringProperty()

    opt_api = StringProperty('opentdb')
    opt_difficulty = StringProperty('')
    opt_category = NumericProperty(0)
    opt_amount = NumericProperty(10)
    opt_instant_fb = BooleanProperty(True)
    opt_type = StringProperty('')

    categories = ListProperty([['All', 0]])
    backends = ListProperty([["Open Trivia DB", "opentdb"],["Feduquiz DB", "feduquizdb"]])
    
    instruction_text = StringProperty(INSTRUCTION_TEXT)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.categories = get_categories()
        self.bind(opt_api=self.update_categories)
        self.fps_event = Clock.schedule_interval(self.print_fps, 1/2.0)
        self.sm = None
        self.bg_anim = (Animation(bg_col=[1,0,0], duration=2) +
                Animation(bg_col=[1,1,0], duration=2) +
                Animation(bg_col=[0, 1, 1], duration=2) +
                Animation(bg_col=[0, 0, 1], duration=2) +
                Animation(bg_col=[1, 0, 1], duration=2))
        self.bg_anim.repeat = True

        self.snd_machine = SoundMachine()
        #self.bg_anim.start(self)   # Will be started by first screen (Intro)

        self.callbacks = []

        # Register EXIT and SCREENSHOT handler
        self.add_callback(CEC_CMD_MAP["EXIT"], "ALL", lambda: App.get_running_app().stop())

        # Set window size if instructed
        if SET_SIZE:
            Window.size = (1920, 1080)
            Window.left = 0
            Window.top = 1

        # Get keyboard
        #self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        Window.bind(on_key_down=self._on_keyboard_down)

        # initialise libCEC
        if not DISABLE_CEC:
            from cec_control import pyCecClient
            self.lib = pyCecClient()
            self.lib.SetCommandCallback(lambda cmd: self.command_callback(cmd, 'cec'))

            # initialise libCEC and enter the main loop
            self.lib.InitLibCec()

    def build(self):
        self.sm = ScreenManager(transition=NoTransition())
        self.sm.add_widget(Intro(name='intro'))
        self.sm.add_widget(Game(name='game'))
        self.sm.add_widget(Score(name='score'))
        self.sm.add_widget(Options(name='options'))
        self.sm.add_widget(Instructions(name='instructions'))
        self.sm.add_widget(Credits(name='credits'))
        return self.sm

    def update_categories(self, property, api):
        self.categories = BACKENDS[api]["categories"]

    def load_game(self, anim=None, widget=None):
        self.trivia.new_game(BACKENDS[self.opt_api]["url"], self.opt_difficulty, self.opt_category, self.opt_amount, self.opt_type)
        Clock.schedule_once(self.check_switch_screen)

    def check_switch_screen(self, dt=None):
        if not self.trivia.running:
            Clock.schedule_once(self.check_switch_screen)
            return
        self.sm.current = 'game'
        self.snd_machine.mode_game()

    def goto_screen(self, dt=None, s_name=None):
        if s_name:
            self.sm.current = s_name
            self.snd_machine.mode_menu()

    @mainthread
    def command_callback(self, cmd, origin):
        """Callback function for the CEC module"""
        print("{} command received: {}".format(origin, cmd))
        current = self.sm.current
        match = False
        for callback in self.callbacks:
            if cmd in callback[0] and (callback[1] == "ALL" or current == callback[1]):
                callback[2]()
                match = True
                print("Callback executed")
        return match


    def add_callback(self, cmd, screen, callback):
        """Adds a callback within the app."""
        print("Adding callback " + str(callback) + " for screen " + screen + " for command " + str(cmd))
        self.callbacks.append([cmd, screen, callback])


    def _on_keyboard_down(self, window, keycode, scancode, text, modifiers, **kwargs):
        print('The key {} {} {} has been pressed'.format(keycode, 'with text '+text if text else '', 'and modifiers '+str(modifiers) if len(modifiers)>0 else ''))

        # Call callback
        return self.command_callback(keycode, 'keyboard')

        # Return True to accept the key. Otherwise, it will be used by
        # the system.
        #return True
        
    def print_fps(self, *args):
        fps = Clock.get_fps()
        print("{} Fps    ".format(int(fps)), end='\r')
Exemplo n.º 14
0
def play():
    # the play function, input your name
    name = input('Enter your name: ')
    player = Trivia() # call Trivia class
    print(name, 'answer these 5 questions:')
    for i in range(5): # loop for 5 questions
        player.set_question()
        player.get_answer()
        player.set_answer(input('Your answer: '))
        print()
    print('Correct answers: ', player.show()) # print number of correct answer
    print()
    correct = player.show() # assign correct answers to correct
    player.clear() # clear player data
    return correct, name # return the number of correct answers and the name
Exemplo n.º 15
0
class Game(QThread):
    def __init__(self,
                 parent=None,
                 loglevel=logging.INFO,
                 hmi_port=None,
                 game_port=None,
                 predetermined_spins=None,
                 predetermined_players=None,
                 predetermined_startingplayer=None):
        super(Game, self).__init__(parent)
        self.logger = logs.build_logger(__name__, loglevel)
        self.loglevel = loglevel
        self.hmi_port = hmi_port
        self.game_port = game_port
        self.logger.debug("selected hmi_port=%s" % (self.hmi_port))
        self.logger.debug("selected game_port=%s" % (self.game_port))

        self.predetermined_spins = queue.Queue()
        if predetermined_spins is not None:
            [self.predetermined_spins.put(x) for x in predetermined_spins]
        self.players = list()
        self.use_predetermined_players = False
        if predetermined_players is not None:
            self.logger.debug("using predetermined players")
            self.use_predetermined_players = True
            for playerName in predetermined_players:
                playerIndex = len(self.players)
                self.players.append(Player(id=playerIndex, name=playerName))
        self.use_predetermined_startingplayer = predetermined_startingplayer
        self.logger.debug("predetermined_startingplayer = %s" %
                          predetermined_startingplayer)

    def run(self):
        self.maxPlayers = 3
        self.minPlayers = 2
        self.totalRounds = 2
        self.round = 0
        self.spins = 0
        self.delay_before_question = 2000

        self.maxSpins = 50

        # game config
        self.geometry_width = 6
        self.geometry_height = 5
        self.triviadb = Trivia(loglevel=self.loglevel,
                               min_questions=self.geometry_height)

        if len(self.triviadb) < (self.totalRounds * self.geometry_width):
            raise Exception(
                "Insufficient trivia exists to complete a game with",
                self.totalRounds, "rounds and", " a geometry of width = ",
                self.geometry_width)

        self.current_trivia = list()
        self.utilized_categories = []

        # Determine
        #   Potentially difficulty?
        #   How many players are playing?
        #   Gather information about each player?

        self.MSG_controller = messaging.MessageController(
            loglevel=self.loglevel,
            msg_controller_name="GameLogic",
            listen_port=self.game_port,
            target_port=self.hmi_port)
        self.MSG_controller.start()

        self.currentPlayerIndex = None
        self.wheel_map = None
        if not self.use_predetermined_players:
            self.enrollPlayers()
        #self.logger.debug(self.players)
        if self.use_predetermined_startingplayer is None:
            self.currentPlayerIndex = self.selectRandomFirstPlayer()
        else:
            self.currentPlayerIndex = self.use_predetermined_startingplayer
        self.players[self.currentPlayerIndex].setActive()

        # Once all setup is completed, start the show
        self.gameLoop()

    def selectRandomFirstPlayer(self):
        """Return an index representing the position which will take the first turn"""
        self.logger.debug("Enter Function")
        return random.randrange(0, len(self.players))

    def getCurrentPlayer(self) -> Player:
        self.logger.debug("Enter Function")
        if len(self.players) > 0:
            return self.players[self.currentPlayerIndex]
        else:
            return None

    def changeTurn(self):
        """Alter player state """
        numPlayers = len(self.players)
        prev_player = self.currentPlayerIndex
        self.players[self.currentPlayerIndex].setInactive()
        if self.currentPlayerIndex == numPlayers - 1:
            self.currentPlayerIndex = 0
        else:
            self.currentPlayerIndex += 1
        self.players[self.currentPlayerIndex].setActive()

        self.logger.debug("Changed player from %s (%s) to %s (%s)" %
                          (self.players[prev_player].getName(), prev_player,
                           self.players[self.currentPlayerIndex].getName(),
                           self.currentPlayerIndex))
        self.pushUpdateGameState()

    def enrollPlayers(self):
        """Determine number of users playing"""
        # TODO: find num_players
        self.logger.debug("got here")
        num_players = 0
        done = False
        while done is False:
            current_player_names = [x.getName() for x in self.players]
            while self.MSG_controller.clientqueue.empty():
                QtTest.QTest.qWait(100)
            response = json.loads(self.MSG_controller.clientqueue.get())
            if response['action'] == "responsePlayerRegistration":
                playerList = json.loads(response['arguments'])
                try:
                    self.checkSanityPlayerList(playerList)
                except Exception as e:
                    message = dict()
                    message['action'] = "responsePlayerRegistration"
                    #TODO: Perhaps a better structure for passing info back with Nack
                    message['arguments'] = ":".join(["NACK", str(e)])
                    self.MSG_controller.send_message(json.dumps(message))
                else:
                    for playerName in playerList:
                        playerIndex = len(self.players)
                        self.players.append(
                            Player(id=playerIndex, name=playerName))
                        num_players += 1
                        self.pushUpdateGameState()
                    message = dict()
                    message['action'] = "responsePlayerRegistration"
                    message['arguments'] = "ACK"
                    self.MSG_controller.send_message(json.dumps(message))
                    done = True

    def checkSanityPlayerList(self, playerList):
        if not isinstance(playerList, list):
            raise Exception("provided argument is not a list")
        elif len(set(playerList)) < len(playerList):
            raise Exception("provided list contains duplicate names")
        elif len(playerList) < self.minPlayers:
            raise Exception("not enough players")
        elif len(playerList) > self.maxPlayers:
            raise Exception("too many players")
        else:
            return

    def changeRound(self):
        """Progress GameState to the Next Round"""
        self.logger.info("Begin Round Change")
        for player in self.players:
            player.archivePoints()

        #document the categories utilized so they aren't reused later
        if type(self.current_trivia) != type([]):
            raise Exception("The type of self.current_trivia is not list")
        if len(self.current_trivia) <= 0 and self.round >= 1:
            raise Exception(
                "The length of the current trivia db is not sufficient")

        self.round += 1
        self.logger.info("Changing round from " + str(self.round - 1) +
                         " to " + str(self.round))
        self.spins = 0
        for each in [x for x in self.current_trivia]:
            self.logger.debug("new category:", each)
            if each['category'] not in self.utilized_categories:
                self.utilized_categories.append(each['category'])

        #record current board state
        self.current_trivia = self.triviadb.selectRandomCategories(
            self.geometry_width,
            n_questions_per_category=self.geometry_height,
            exclude=self.utilized_categories)

        self.wheel_map = self.build_map()
        if self.round == 1:
            self.current_triviaDB = TriviaDB(self.current_trivia,
                                             loglevel=self.loglevel,
                                             starting_price=100)
        else:
            self.current_triviaDB = TriviaDB(self.current_trivia,
                                             loglevel=self.loglevel,
                                             starting_price=200)

        self.logger.debug("self.current_trivia=" + str(self.current_trivia))
        self.logger.debug(str(self.wheel_map))

        self.pushUpdateGameState()
        self.logger.debug("Round Change Complete")

    def gameLoop(self):
        self.logger.info("Start Game Loop")
        #self.currentPlayerIndex = self.selectRandomFirstPlayer()
        spinMap = {

            # borrowed idea for switch from
            # https://jaxenter.com/implement-switch-case-statement-python-138315.html
            0: self.pickLoseTurn,
            1: self.pickAccumulateFreeTurnToken,
            2: self.pickBecomeBankrupt,
            3: self.pickPlayersChoice,
            4: self.pickOpponentsChoice,
            5: self.pickDoublePlayerRoundScore,
            6: self.pickRandomCategory,
            7: self.pickRandomCategory,
            8: self.pickRandomCategory,
            9: self.pickRandomCategory,
            10: self.pickRandomCategory,
            11: self.pickRandomCategory
        }

        for round in range(0, self.totalRounds):
            self.changeRound()
            # ready player 1
            self.logger.info("Begin Round" + str(self.round))
            while self.spins < self.maxSpins:
                self.logger.debug("stats: totalSpins=" + str(self.spins) +
                                  " round=" + str(self.round))
                spinResult = self.doSpin()

                self.logger.debug("Spin Result=" + str(spinResult))

                postSpinAction = spinMap.get(self.wheel_map.index(spinResult),
                                             lambda: "Out of Scope")
                if self.wheel_map.index(spinResult) < 6:
                    postSpinAction()
                else:
                    postSpinAction(self.wheel_map.index(spinResult))
                self.pushUpdateGameState()
                message = dict()
                message['action'] = "endSpin"
                message['arguments'] = None
                self.MSG_controller.send_message(json.dumps(message))
                self.receive_ack("endSpin")

        for play in self.players:
            play.archivePoints()
        message = dict()
        message['action'] = "displayWinner"
        message['arguments'] = self.calculateWinner()
        self.MSG_controller.send_message(json.dumps(message))

    def receive_ack(self, action, extra_test=True):
        while self.MSG_controller.clientqueue.empty() and extra_test is True:
            QtTest.QTest.qWait(100)
        if not self.MSG_controller.clientqueue.empty():
            response = self.MSG_controller.clientqueue.get()
            if json.loads(response)['action'] != action:
                raise Exception(
                    "Expecting action=%s, received action=%s arguments=%s" %
                    (action, json.loads(response)['action'],
                     json.loads(response)['arguments']))
            if json.loads(response)['arguments'] != "ACK":
                raise Exception(
                    "Expecting ACK to action=%s, received action=%s arguments=%s"
                    % (action, json.loads(response)['action'],
                       json.loads(response)['arguments']))
            return response
        else:
            raise Exception("Queue was emptied prior to being serviced")

    def calculateWinner(self):
        scores = [x.getGameScore() for x in self.players]
        score_set = list(set(scores))
        score_set.sort()
        high_score = score_set[-1]

        winners = []
        for each in self.players:
            if each.getGameScore() == high_score:
                winners.append(each)

        if len(winners) > 1:
            return " & ".join([x.getName() for x in self.players])
        else:
            return winners[0].getName()

    def doSpin(self):
        """Emulate 'Spin' and select a random number between 0-11"""

        while self.MSG_controller.clientqueue.empty():

            QtTest.QTest.qWait(100)
        response = self.MSG_controller.clientqueue.get()
        if json.loads(response)['action'] != 'userInitiatedSpin':
            raise Exception("Was expecting user initiated spin, received " +
                            str(json.loads(response)['action']))
        message = dict()
        message['action'] = "userInitiatedSpin"
        message['arguments'] = "ACK"
        self.MSG_controller.send_message(json.dumps(message))

        if self.predetermined_spins.empty():
            random_int = random.randrange(0, self.geometry_width + 6)
        else:
            function_to_index_map = {
                "pickLoseTurn": 0,
                "pickAccumulateFreeTurnToken": 1,
                "pickBecomeBankrupt": 2,
                "pickPlayersChoice": 3,
                "pickOpponentsChoice": 4,
                "pickDoublePlayerRoundScore": 5,
                "pickRandomCategory1": 6,
                "pickRandomCategory2": 7,
                "pickRandomCategory3": 8,
                "pickRandomCategory4": 9,
                "pickRandomCategory5": 10,
                "pickRandomCategory6": 11,
            }
            #roll 9
            #wheel_map = [5, 1, ** 9 **, 7, 0]
            #spinMap = {... 2: loseturnfunc, ...}
            desired_function = self.predetermined_spins.get()
            try:
                function_index = function_to_index_map[desired_function]
            except:
                raise Exception("Provided function call does not exist")
            random_int = self.wheel_map[function_index]

        message = dict()
        message['action'] = "spinWheel"
        message['arguments'] = random_int
        self.MSG_controller.send_message(json.dumps(message))
        self.spins += 1

        self.receive_ack("spinWheel")
        return random_int

    def build_map(self):
        random_list = list()
        while len(random_list) < (self.geometry_width + 6):
            randomint = random.randrange(0, (self.geometry_width + 6))
            if randomint not in random_list:
                random_list.append(randomint)
        return random_list

    def build_wheelboard(self):
        # 1 - 6 always represent static sectors, 7-n represent categorical columns
        # current_trivia = [a,b,c.. n]
        #           where a = {'category': 'blah', 'questions': [{q1: a1, q2: a2, .. qn, an}] }
        r = list()
        for each in range(0, 6):
            t = dict()
            t['index'] = self.wheel_map[each]
            t['type'] = "noncategory"
            if each == 0:
                t['name'] = "loseturn"
            elif each == 1:
                t['name'] = "accumulatefreeturn"
            elif each == 2:
                t['name'] = "bankrupt"
            elif each == 3:
                t['name'] = 'playerschoice'
            elif each == 4:
                t['name'] = "opponentschoice"
            else:
                t['name'] = "doublescore"
            r.append(t)
        for index, catobject in enumerate(self.current_trivia):
            t = dict()
            t['index'] = self.wheel_map[index + 6]
            t['name'] = catobject['category']
            t['type'] = "category"
            t['questions'] = self.current_triviaDB.listRemainingQuestions(
                catobject['category'])
            t['valid_prices'] = self.current_triviaDB.getListOfPrices()
            r.append(t)

        return sorted(r, key=lambda i: i['index'])

    def pickCategoryHelper(self, category):
        self.logger.debug("Start")
        ANSWER_TIMEOUT = 30

        message = dict()
        message['action'] = "displayQuestion"
        question_answer = self.current_triviaDB.getQuestion(category)
        question_answer['timeout'] = ANSWER_TIMEOUT
        question_answer['player'] = self.getCurrentPlayer().getName()
        question_only = dict(question_answer)
        question_only.pop("answer")
        message['arguments'] = question_only
        self.MSG_controller.send_message(json.dumps(message))
        # kick off 30s timer

        start = timer()
        self.receive_ack("displayQuestion",
                         extra_test=((timer() - start) < ANSWER_TIMEOUT))

        # wait for revealAnswer
        doChangeTurn = True
        while self.MSG_controller.clientqueue.empty() and (
            (timer() - start) < ANSWER_TIMEOUT):
            QtTest.QTest.qWait(100)
        if not self.MSG_controller.clientqueue.empty():
            response = self.MSG_controller.clientqueue.get()
            if json.loads(response)['action'] != "revealAnswer":
                raise Exception("Expecting action type 'revealAnswer'")

            message = dict()
            message['action'] = "revealAnswer"
            message['arguments'] = "ACK"
            self.MSG_controller.send_message(json.dumps(message))

            message = dict()
            message['action'] = "displayAnswer"
            message['arguments'] = question_answer
            self.MSG_controller.send_message(json.dumps(message))

            self.receive_ack("displayAnswer")

            while self.MSG_controller.clientqueue.empty():
                QtTest.QTest.qWait(100)
            response = self.MSG_controller.clientqueue.get()
            if json.loads(response)['action'] != "responseQuestion":
                raise Exception(
                    "Expecting action type 'responseQuestion' for ACK")
            if json.loads(response)['arguments'] is not False and json.loads(
                    response)['arguments'] is not True:
                raise Exception(
                    "Expecting responseQuestion to contain either True or False only"
                )

            if json.loads(response)['arguments'] is True:
                self.getCurrentPlayer().addToScore(
                    int(question_answer['score']))
            else:
                # User answered question incorrectly

                # Check to see if user has freeTurn tokens available
                if self.getCurrentPlayer().getFreeTurnTokens() > 0:
                    message = dict()
                    message['action'] = "promptSpendFreeTurnToken"
                    message['arguments'] = None
                    self.MSG_controller.send_message(json.dumps(message))

                    self.receive_ack("promptSpendFreeTurnToken")

                    correctResponseReceived = False
                    while not correctResponseReceived:
                        self.logger.debug(
                            "entered currectResponseReceived loop")
                        while self.MSG_controller.clientqueue.empty():
                            QtTest.QTest.qWait(100)
                        self.logger.debug(
                            "msg_controller queue is no longer empty")
                        response = self.MSG_controller.clientqueue.get()
                        if json.loads(response)[
                                'action'] == 'userInitiatedFreeTurnTokenSpend':
                            self.logger.debug(
                                "user indicated to spend ft token")
                            self.getCurrentPlayer().spendFreeTurnToken()
                            self.getCurrentPlayer().addToScore(
                                int(int(question_answer['score']) * -1))
                            # user indicated to spend free turn token
                            correctResponseReceived = True
                            doChangeTurn = False
                            message = dict()
                            message[
                                'action'] = "userInitiatedFreeTurnTokenSpend"
                            message['arguments'] = "ACK"
                            self.MSG_controller.send_message(
                                json.dumps(message))
                        elif json.loads(response)[
                                'action'] == 'userInitiatedFreeTurnTokenSkip':
                            self.logger.debug(
                                "user indicated to skip spending ft token")
                            # user declided to spend token, decrement score since they answered incorrectly
                            self.getCurrentPlayer().addToScore(
                                int(int(question_answer['score']) * -1))
                            correctResponseReceived = True
                            message = dict()
                            message[
                                'action'] = "userInitiatedFreeTurnTokenSkip"
                            message['arguments'] = "ACK"
                            self.MSG_controller.send_message(
                                json.dumps(message))
                        else:
                            raise Exception(
                                "Was expecting a decision on free token spending, received "
                                + str(json.loads(response)['action']))
                else:
                    self.getCurrentPlayer().addToScore(
                        int(int(question_answer['score']) * -1))

            message = dict()
            message['action'] = "responseQuestion"
            message['arguments'] = "ACK"
            self.MSG_controller.send_message(json.dumps(message))

        else:
            #timer ran out
            pass
        if doChangeTurn:
            self.changeTurn()

    def pickRandomCategory(self, index):
        self.logger.debug("Start")
        QtTest.QTest.qWait(self.delay_before_question)
        self.logger.debug("index=" + str(index))
        category = self.current_trivia[index - 6]['category']
        self.logger.debug("category=" + str(category))
        if len(self.current_triviaDB.listRemainingQuestions(category)) > 0:
            self.pickCategoryHelper(category)
        else:
            #do nothing, don't change turn - allow player to spin again
            pass

    def quit(self) -> None:
        self.logger.debug("quitting")
        self.MSG_controller.quit()
        super(Game, self).quit()

    def pickLoseTurn(self):
        self.logger.debug("Start")
        doChangeTurn = False
        if self.getCurrentPlayer().getFreeTurnTokens() > 0:
            message = dict()
            message['action'] = "promptSpendFreeTurnToken"
            message['arguments'] = None
            self.MSG_controller.send_message(json.dumps(message))

            self.receive_ack("promptSpendFreeTurnToken")

            correctResponseReceived = False
            while not correctResponseReceived:
                self.logger.debug("entered currectResponseReceived loop")
                while self.MSG_controller.clientqueue.empty():
                    QtTest.QTest.qWait(100)
                self.logger.debug("msg_controller queue is no longer empty")
                response = self.MSG_controller.clientqueue.get()
                if json.loads(response
                              )['action'] == 'userInitiatedFreeTurnTokenSpend':
                    self.logger.debug("user indicated to spend ft token")
                    self.getCurrentPlayer().spendFreeTurnToken()
                    # user indicated to spend free turn token
                    correctResponseReceived = True
                    doChangeTurn = False
                    message = dict()
                    message['action'] = "userInitiatedFreeTurnTokenSpend"
                    message['arguments'] = "ACK"
                    self.MSG_controller.send_message(json.dumps(message))
                elif json.loads(response)[
                        'action'] == 'userInitiatedFreeTurnTokenSkip':
                    self.logger.debug(
                        "user indicated to skip spending ft token")
                    # user declided to spend token, decrement score since they answered incorrectly
                    doChangeTurn = True
                    correctResponseReceived = True
                    message = dict()
                    message['action'] = "userInitiatedFreeTurnTokenSkip"
                    message['arguments'] = "ACK"
                    self.MSG_controller.send_message(json.dumps(message))
                else:
                    raise Exception(
                        "Was expecting a decision on free token spending, received "
                        + str(json.loads(response)['action']))
        else:
            doChangeTurn = True
        if doChangeTurn:
            self.changeTurn()

    def pickAccumulateFreeTurnToken(self):
        self.logger.debug("Start")
        self.getCurrentPlayer().addFreeTurnToken()
        self.changeTurn()

    def pickBecomeBankrupt(self):
        self.logger.debug("Start")
        self.getCurrentPlayer().setScore(0)
        message = dict()
        message['action'] = "playerBecomesBankrupt"
        message['arguments'] = None
        self.MSG_controller.send_message(json.dumps(message))
        self.receive_ack("playerBecomesBankrupt")
        self.changeTurn()

    def pickPlayersChoice(self):
        self.logger.debug("Start")
        QtTest.QTest.qWait(self.delay_before_question)
        categorylist = self.current_triviaDB.getPlayableCategories()

        message = dict()
        message['action'] = "promptCategorySelectByUser"
        message['arguments'] = categorylist
        self.MSG_controller.send_message(json.dumps(message))
        while self.MSG_controller.clientqueue.empty():
            QtTest.QTest.qWait(100)
        response = self.MSG_controller.clientqueue.get()
        if json.loads(response)['arguments'] in message['arguments']:
            self.pickCategoryHelper(json.loads(response)['arguments'])
        else:
            raise Exception("Response Category not from the allowed list")

    def pickOpponentsChoice(self):
        self.logger.debug("Start")
        QtTest.QTest.qWait(self.delay_before_question)
        categorylist = self.current_triviaDB.getPlayableCategories()

        message = dict()
        message['action'] = "promptCategorySelectByOpponent"
        message['arguments'] = categorylist
        self.MSG_controller.send_message(json.dumps(message))
        while self.MSG_controller.clientqueue.empty():
            QtTest.QTest.qWait(100)
        response = self.MSG_controller.clientqueue.get()
        if json.loads(response)['arguments'] in message['arguments']:
            self.pickCategoryHelper(json.loads(response)['arguments'])
        else:
            raise Exception("Response Category not from the allowed list")

    def buildGameState(self):
        gameState = dict()
        gameState['round'] = self.round
        gameState['totalRounds'] = self.totalRounds
        gameState['players'] = [dict(x.renderStatus()) for x in self.players]
        gameState['spinsExecuted'] = self.spins
        gameState['maxSpins'] = self.maxSpins
        if len(self.players) > 0 and self.currentPlayerIndex is not None:
            gameState['currentPlayer'] = self.getCurrentPlayer().getName()
        else:
            gameState['currentPlayer'] = ""
        if self.wheel_map is not None:
            gameState['wheelboard'] = self.build_wheelboard()
        return gameState

    def pickDoublePlayerRoundScore(self):
        self.logger.debug("Start")
        self.getCurrentPlayer().setScore(
            self.getCurrentPlayer().getRoundScore() * 2)
        self.changeTurn()

    def pushUpdateGameState(self):
        message = dict()
        message['action'] = "updateGameState"
        message['arguments'] = self.buildGameState()
        self.MSG_controller.send_message(json.dumps(message))
        response = self.receive_ack("updateGameState")
Exemplo n.º 16
0
#!/usr/bin/env python3
import discord
import sys
from usage import print_usage
from prime import check_for_prime
from eightball import ask8ball
from spoilme import spoilme
from kill import kill_bot
from wisecracker import crack_a_joke
from trivia import Trivia
from gitpull import gitpull

client = discord.Client()
trivia = Trivia()


@client.event
async def on_ready():
  print ('Logged in as')
  print (client.user.name)
  print (client.user.id)
  print ('------')


@client.event
async def on_message(message):
  if message.content.startswith('!8ball'):
    await ask8ball(client, message)
  elif message.content.startswith("!gitpull"):
    await gitpull(client, message)
  elif message.content.startswith('!help') or message.content.startswith('!usage'):
Exemplo n.º 17
0
from cleverbot import cleverbot
from chatbot import Chatbot
from polls import Poll
from reminder import Reminder
from timezone import Timezone
from trivia import Trivia

# Set up the logging module to output diagnostic to the console.
logging.basicConfig()

# Create new instances of bot objects
bot = Chatbot('settings.txt')
remind_module = Reminder()
timezone_module = Timezone()
trivia_module = Trivia()
poll_module = Poll()

#cleverbot object
clever_bot = cleverbot.Session()

# Initialize client object, begin connection
client = discord.Client()

serv = ''


# Event handler
@client.event
async def on_member_join(newmember):
    admin_users = []
Exemplo n.º 18
0
 def __init__(self):
     self.t = Trivia()
Exemplo n.º 19
0
from player import Player
from question import Question
from trivia import Trivia

player_one = Player(input("Player 1 Name: "))
player_two = Player(input("Player 2 Name: "))

question = Question()
trivia_game = Trivia(player_one, player_two, question)
trivia_game.ask_question()
trivia_game.display_winner()
Exemplo n.º 20
0
 def __init__(self):
     self.t = Trivia()