Beispiel #1
0
 def test_case_where_contestant_guesses_correctly(self):
     door_1, door_2, door_3 = Door(False), Door(True), Door(False)
     game = Game(door_1, door_2, door_3)
     game.contestant_guess = door_2
     game.host_open_door()
     self.assertEqual(False, door_2.is_open)
     self.assertEqual(True, door_1.is_open ^ door_3.is_open)
Beispiel #2
0
def main():
    game = Game(1, 1, debug=True)
    status = Game.GAME_CONTINUES
    while status == Game.GAME_CONTINUES:
        print game.board
        try:
            input = raw_input('cmd: ')
            args = input.split(' ')
            if args[0] == 'T':
                ticks = int(args[1])
                for i in xrange(ticks):
                    status = game.tick()
                    if status != Game.GAME_CONTINUES:
                        break
            elif args[0] == 'M':
                from_row, from_col, to_row, to_col = int(args[1]), int(
                    args[2]), int(args[3]), int(args[4])
                piece = game.board.get_piece_by_location(from_row, from_col)
                valid = game.move(piece.id, piece.player, to_row, to_col)
                if not valid:
                    print 'Invalid move!'
        except KeyboardInterrupt:
            break
        except Exception, e:
            print 'Error: ' + str(e)
Beispiel #3
0
def reset(data):
    data = json.loads(data)
    game_id = data['gameId']
    player_key = data['playerKey']
    print 'reset', data

    if game_id not in game_states:
        return

    game_state = game_states[game_id]
    auth_player = get_auth_player(game_state, player_key)

    # only authenticated players can reset game
    if auth_player is not None:
        old_game = game_state.game
        game = Game(old_game.speed, old_game.players)
        for player in game_state.bots:
            game.mark_ready(player)
        game_state.game = game

        emit('resetack', {
            'game': game.to_json_obj(),
        },
             room=game_id,
             json=True)
Beispiel #4
0
 def test_case_where_contestant_guesses_correctly(self):
     door_1, door_2, door_3 = Door(False), Door(True), Door(False)
     game = Game(door_1, door_2, door_3)
     game.contestant_guess = door_2
     game.host_open_door()
     self.assertEqual(False, door_2.is_open)
     self.assertEqual(True, door_1.is_open ^ door_3.is_open)
Beispiel #5
0
 def test_contestant_can_switch(self):
     door_1, door_2, door_3 = Door(False), Door(True), Door(False)
     game = Game(door_1, door_2, door_3)
     game.contestant_guess = door_1
     game.contestant_switch()
     self.assertNotEqual(door_1, game.contestant_guess)
     self.assertIsInstance(game.contestant_guess, Door)
Beispiel #6
0
def main():
    game = Game(
        config.game['switches'],
        config.game['columns'],
        config.game['rows'],
        config.game['shapes_next_count'],
        config.game['fps'],
        config.game['countdown'],
        config.game['interval'],
        config.game['score_increments'],
        config.game['level_increment'],
        config.game['interval_increment'],
        config.game['rgb_matrix_hardware'],
        config.game['rgb_matrix_rows'],
        config.game['rgb_matrix_chain_length'],
        config.game['rgb_matrix_parallel'],
        config.game['rgb_matrix_pwm_bits'],
        config.game['rgb_matrix_brightness'],
        config.game['rgb_matrix_lsb_nanoseconds'],
        config.game['rgb_matrix_gpio_slowdown'],
        config.game['rgb_matrix_disable_hardware_pulsing'],
        config.game['rgb_matrix_rgb_sequence'],
    )

    atexit.register(game.__exit__)

    game.start()
Beispiel #7
0
class Bot:

    def __init__(self, config):
        self.config = config
        self.irc = Irc(config)
        self.game = Game()

    def run(self):
        last_start = time.time()

        while True:
            new_messages = self.irc.recv_messages(1024)
            
            if new_messages:
                for message in new_messages:
                    button = message['message'].lower()
                    username = message['username']

                    if not self.game.is_valid_button(button):
                        continue

                    if self.config['start_throttle']['enabled'] and button == 'start':
                        if time.time() - last_start < self.config['start_throttle']['time']:
                            continue

                    pbutton(username, button)
                    self.game.push_button(button)

                    if button == 'start':
                        last_start = time.time()
Beispiel #8
0
 def test_contestant_can_switch(self):
     door_1, door_2, door_3 = Door(False), Door(True), Door(False)
     game = Game(door_1, door_2, door_3)
     game.contestant_guess = door_1
     game.contestant_switch()
     self.assertNotEqual(door_1, game.contestant_guess)
     self.assertIsInstance(game.contestant_guess, Door)
Beispiel #9
0
def replay_start():
    data = json.loads(request.data)
    history_id = data['historyId']
    print 'replay start', data

    game_history = db_service.get_game_history(history_id)
    if game_history is None:
        return json.dumps({
            'success': False,
            'message': 'Replay does not exist.',
        })

    # create game and add to game states
    replay = Replay.from_json_obj(game_history.replay)
    game = Game(Speed(replay.speed), replay.players)
    for player in replay.players:
        game.mark_ready(player)

    game_id = generate_game_id()
    game_states[game_id] = GameState(game_id, game, {}, {}, replay)

    return json.dumps({
        'success': True,
        'gameId': game_id,
    })
Beispiel #10
0
 def __init__(self):
     self.config = config
     self.irc = Irc(config)
     self.game = Game()
     self.stats = Stats()
     if self.config['features']['gui_stats']:
         self.GUI = GUI(self)
Beispiel #11
0
    def __init__(self):
        self.config = config
        self.irc = Irc(config)
        self.game = Game()
        self.extConfig = configparser.ConfigParser()
        self.message_buffer = deque(
            ' ', self.bufferLength
        )  #deque happens to be marginally more convenient for this
        self.curQueue = comQueue(
        )  #Based on Queue object, and therefore threadsafe
        self.daQueue = demAnQueue(
        )  #Based on deque object, and therefore threadsafe
        self.queueStatus = "Nominal"
        self.lastButton = ""
        self.voteCount = {}
        self.lastPushed = ""
        self.voteItems = self.voteCount.items(
        )  #Dynamically changing list in python 3 that keeps up with voteCount
        self.democracy = False  #Anarchy is default on.
        self.game.democracy = self.democracy  #Command processor needs this information due to slightly different processing in democracy vs. anarchy
        self.lastConfigTime = time.time()  #Timer on config file updates
        self.configUpdateFreq = 60  #config file updates every 60 seconds

        ###DEFAULT VALUES (should be overwritten by readConfigText() at the end###
        self.botConfig = {'votetime': 20, 'checktime': 0.1, 'votethresh': 75}
        ###END DEFAULT VALUES###

        self.readConfigText(
        )  #read in config file (after all possible object initializations)
        self.daQueue.updateQueue(
        )  #It's poor form that I have to do this, but it's cleanest
Beispiel #12
0
 def prepare_test(trump, player_card, ai_card):
     game = Game()
     game.trump = trump
     game.player.hand = [player_card]
     game.ai.hand = [ai_card]
     game.set_first_turn()
     return game
Beispiel #13
0
 def test_a_game_chooses_a_player_at_random_to_go_first(self):
     first_turns = []
     test_count = 10
     for i in range(test_count):
         self.game = Game('Helen')
         first_turns.append(self.game.whose_turn)
     self.assertLess(first_turns.count('Helen'), test_count)
def main():
    """
    Game function.
    """
    # Game creation
    maze_game = Game('ressources/map.txt')
    # Game loop
    maze_game.on_execute()
Beispiel #15
0
 def test_if_a_player_tries_to_choose_a_space_already_taken_game_gives_a_msg_to_choose_again(
         self):
     self.game = Game('Pete')
     self.game.whose_turn = 'Pete'
     self.game.take_turn('4')
     self.game.whose_turn = 'Pete'
     message = self.game.take_turn('4')
     self.assertEqual(message, 'Sorry that space is already taken')
Beispiel #16
0
    def test_when_a_game_is_won_game_announces_who_won(self):
        player = 'Mary'
        self.game = Game(player)
        for i in range(3):
            self.game.whose_turn = player
            message = self.game.take_turn(str(i + 1))

        self.assertEqual(message, player + ' won!!!')
Beispiel #17
0
 def test_drop_piece_returns_final_position(self):
     g = Game() # 6x7 by default
     self.assertEquals(g._drop_piece('X', 0), (0,5))
     self.assertEquals(g._drop_piece('X', 0), (0,4))
     self.assertEquals(g._drop_piece('X', 0), (0,3))
     self.assertEquals(g._drop_piece('O', 0), (0,2))
     self.assertEquals(g._drop_piece('X', 0), (0,1))
     self.assertEquals(g._drop_piece('X', 0), (0,0))
def test_play_states_when_the_player_wins(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.player_input.read_choice', return_value="p")
   mocker.patch('lib.computer_input.read_choice', return_value="r")

   Game.play()

   lib.console.display.assert_any_call("Player wins!")
Beispiel #19
0
def main():
    game = Game()
    game.start()

    while True:
        game.event()
        game.update()
        game.draw()
def test_play_states_when_a_tie_occurres(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.player_input.read_choice', return_value="r")
   mocker.patch('lib.computer_input.read_choice', return_value="r")

   Game.play()

   lib.console.display.assert_any_call("It's a tie!")
def test_play_states_when_the_player_wins(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.player_input.read_choice', return_value="p")
   mocker.patch('lib.computer_input.read_choice', return_value="r")

   Game.play()

   lib.console.display.assert_any_call("Player wins!")
Beispiel #22
0
 def test_once_a_player_has_taken_their_turn_the_other_player_goes_next(
         self):
     self.game = Game('Helen', 'X')
     self.game.whose_turn = 'Helen'
     previous_turn = self.game.whose_turn
     self.game.take_turn('4')
     current_turn = self.game.whose_turn
     self.assertNotEqual(previous_turn, current_turn)
Beispiel #23
0
def main():
    game = Game(config.game['leds'], config.game['switches'],
                config.game['countdown'], config.game['game_time'],
                config.game['score_increment'])

    game.start()

    atexit.register(game.__exit__)
Beispiel #24
0
 def __init__(self):
     self.config = config
     self.irc = Irc(config)
     self.game = Game()
     self.message_buffer = [{
         'username': '',
         'button': ''
     }] * self.config['misc']['chat_height']
def test_play_prompts_for_users_option(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.console.display_no_newline')
   mocker.patch('lib.player_input.read_choice')
   mocker.patch('lib.computer_input.read_choice')

   Game.play()

   lib.console.display.assert_any_call("Rock (r), Paper (p) or Scissors (s):")
def test_play_computers_choice_is_displayed(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.console.display_no_newline')
   mocker.patch('lib.player_input.read_choice')
   mocker.patch('lib.computer_input.read_choice', return_value="p")

   Game.play()

   lib.console.display.assert_any_call("Computer played Paper!")
def test_play_prompts_for_users_option(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.console.display_no_newline')
   mocker.patch('lib.player_input.read_choice')
   mocker.patch('lib.computer_input.read_choice')

   Game.play()

   lib.console.display.assert_any_call("Rock (r), Paper (p) or Scissors (s):")
def test_play_computers_choice_is_displayed_if_computer_picks_other_option(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.console.display_no_newline')
   mocker.patch('lib.player_input.read_choice')
   mocker.patch('lib.computer_input.read_choice', return_value="r")

   Game.play()

   lib.console.display.assert_any_call("Computer played Rock!")
def test_play_computers_choice_is_displayed(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.console.display_no_newline')
   mocker.patch('lib.player_input.read_choice')
   mocker.patch('lib.computer_input.read_choice', return_value="p")

   Game.play()

   lib.console.display.assert_any_call("Computer played Paper!")
def test_play_computers_choice_is_displayed_if_computer_picks_other_option(mocker):
   mocker.patch('lib.console.display')
   mocker.patch('lib.console.display_no_newline')
   mocker.patch('lib.player_input.read_choice')
   mocker.patch('lib.computer_input.read_choice', return_value="r")

   Game.play()

   lib.console.display.assert_any_call("Computer played Rock!")
Beispiel #31
0
    def test_fill_hand(self):
        game = Game()

        old_len = len(game.deck)
        game.player.hand = game.player.hand[:1]
        print(game.player.missing_cards)
        game.fill_hand(game.player)
        new_len = len(game.deck)
        assert old_len - 5 == new_len
        assert len(game.player.hand) == 6
Beispiel #32
0
def new():
    data = json.loads(request.data)
    speed = data['speed']
    bots = data.get('bots', {})
    bots = {int(player): ai.get_bot(difficulty) for player, difficulty in bots.iteritems()}
    username = data.get('username')
    print 'new game', data

    # generate game ID and player keys
    game_id = generate_game_id()
    player_keys = {i: str(uuid.uuid4()) for i in xrange(1, 3) if i not in bots}

    # if logged in, add current user to game
    players = {i: 'b:%s' % bot.difficulty for i, bot in bots.iteritems()}
    if current_user.is_authenticated:
        players[1] = 'u:%s' % current_user.user_id
        db_service.update_user_current_game(current_user.user_id, game_id, player_keys[1])

    # check opponent
    if username is not None:
        user = db_service.get_user_by_username(username)
        if user is None:
            return json.dumps({
                'success': False,
                'message': 'User to invite does not exist.',
            })

        if user.current_game is not None:
            return json.dumps({
                'success': False,
                'message': 'User to invite is already in a game.',
            })

        players[2] = 'u:%s' % user.user_id
        db_service.update_user_current_game(user.user_id, game_id, player_keys[2])

        socketio.emit('invite', '', room=str(user.user_id))

    for i in xrange(1, 3):
        if i not in players:
            players[i] = 'o'

    # create game and add to game states
    game = Game(Speed(speed), players)
    for player in bots:
        game.mark_ready(player)

    game_states[game_id] = GameState(game_id, game, player_keys, bots)

    return json.dumps({
        'success': True,
        'gameId': game_id,
        'playerKeys': player_keys,
    })
Beispiel #33
0
 def test_get_pieces(self):
     g = Game(rows=1)
     g.drop_cross(0)
     g.drop_round(1)
     self.assertTrue((0,0) in g._get_pieces('X'))
     self.assertFalse((1,0) in g._get_pieces('X'))
     self.assertTrue((1,0) in g._get_pieces('O'))
     self.assertFalse((0,0) in g._get_pieces('O'))
 def test_dealCardsDealsCorrectly(self):
     deck = Deck()
     game = Game('SomeGameName', self.m)
     game.addPlayer(self.j)  # This isn't really necessary.
     game.dealCards([self.m, self.j], deck)
     self.assertEqual(self.m.hand.size(), 3)
     self.assertEqual(self.m.up.size(), 3)
     self.assertEqual(self.m.down.size(), 3)
     self.assertEqual(self.j.hand.size(), 3)
     self.assertEqual(self.j.up.size(), 3)
     self.assertEqual(self.m.down.size(), 3)
     self.assertEqual(deck.size(), (52 - 18))
 def test_rotatesPlayersCorrectly(self):
     game = Game("SomeGameName", self.m)
     game.addPlayer(self.j)
     game.beginGame()
     self.assertRegex(game.currentPlayer.name, self.j.name)
     game.rotateCurrentPlayer()
     self.assertRegex(game.currentPlayer.name, self.m.name)
Beispiel #36
0
class Bot:
    def __init__(self):
        self.config = config
        self.irc = Irc(config)
        self.game = Game()
        self.stats = Stats()
        if self.config['features']['gui_stats']:
            self.GUI = GUI(self)

    def run(self):
        throttle_timers = {
            button: 0
            for button in config['throttled_buttons'].keys()
        }

        while True:
            new_messages = self.irc.recv_messages(1024)

            if not new_messages:
                continue

            for message in new_messages:
                button = message['message'].lower()
                username = message['username'].lower()

                if not self.game.is_valid_button(button):
                    continue

                if button in self.config['throttled_buttons']:
                    if (time.time() - throttle_timers[button] <
                            self.config['throttled_buttons'][button]):
                        continue
                    throttle_timers[button] = time.time()

                if not self.game.is_political(button):
                    if (self.config['features']['play_game'] and not button
                            in self.config['misc']['blocked_buttons']):
                        self.game.push_button(button)

                self.stats.tally_message(username, message['message'])

            if self.config['features']['stats_on']:
                if self.config['features']['gui_stats']:
                    self.GUI.run()
                if self.config['features']['console_stats']:
                    pframe(self.stats)

            elif self.config['features']['pbutton_on']:
                pbutton(self.stats.message_buffer)
Beispiel #37
0
def main():
    game = Game(
        config.game['columns'],
        config.game['rows'],
        config.game['fps'],
        config.game['countdown'],
        config.game['interval'],
        config.game['score_increment'],
        config.game['level_increment'],
        config.game['interval_increment'],
    )

    game.start()

    atexit.register(game.__exit__)
Beispiel #38
0
    def test_defense_when_cant_beat_attack(self):
        hand = [
            Card(Suit.CLUBS, Rank.SEVEN),
            Card(Suit.HEARTS, Rank.SEVEN),
            Card(Suit.SPADES, Rank.SEVEN),
            Card(Suit.HEARTS, Rank.JACK),
            Card(Suit.CLUBS, Rank.JACK),
            Card(Suit.SPADES, Rank.JACK)
        ]
        game = Game()
        game.trump = Card(Suit.DIAMONDS, Rank.SIX)
        game.attack_cards = [Card(Suit.CLUBS, Rank.ACE)]
        p = AIPlayer(hand=hand, game=game)

        assert p.defend() == None
Beispiel #39
0
def get_game() -> Game:
    return Game(
        bot=TestBot(),
        alpha=TestMember(),
        beta=TestMember(id=570243143958528010, mention='@daima3629#1235'),
        channel=TestChannel(),
    )
Beispiel #40
0
 def __init__(self):
     self.config = config
     self.irc = Irc(config)
     self.game = Game()
     self.stats = Stats()
     if self.config['features']['gui_stats']:
         self.GUI = GUI(self)
Beispiel #41
0
 def __init__(self):
     self.config = config
     self.irc = Irc(config)
     self.game = Game()
     self.extConfig=configparser.ConfigParser()
     self.message_buffer = deque(' ',self.bufferLength) #deque happens to be marginally more convenient for this
     self.curQueue=comQueue() #Based on Queue object, and therefore threadsafe
     self.daQueue=demAnQueue() #Based on deque object, and therefore threadsafe
     self.queueStatus="Nominal"
     self.lastButton=""
     self.voteCount={}
     self.lastPushed=""
     self.voteItems=self.voteCount.items() #Dynamically changing list in python 3 that keeps up with voteCount
     self.democracy=False #Anarchy is default on.
     self.game.democracy=self.democracy #Command processor needs this information due to slightly different processing in democracy vs. anarchy
     self.lastConfigTime=time.time() #Timer on config file updates
     self.configUpdateFreq=60 #config file updates every 60 seconds
     
     ###DEFAULT VALUES (should be overwritten by readConfigText() at the end###
     self.botConfig={'votetime':20,
         'checktime':0.1,
         'votethresh':75}
     ###END DEFAULT VALUES###
     
     self.readConfigText() #read in config file (after all possible object initializations)
     self.daQueue.updateQueue() #It's poor form that I have to do this, but it's cleanest
Beispiel #42
0
 def __init__(self):
     self.config = config
     self.irc = Irc(config)
     self.game = Game()
     self.message_buffer = []
     self.scrolling_chat = []
     self.chat_buffer = []
     self.game_tracker = [0,0,0,0,0,0,0,0,0]
     self.windowSurface = pygame.display.set_mode((1300,800), 0, 32)
     self.BLACK = (0,0,0)
     self.WHITE = (255,255,255)
     self.start = time.clock()
     self.game_timer = 0
     self.old_time = 0;
     self.xwins = 0
     self.owins = 0
     self.cats_games = 0
     self.games = 0
     self.who_starts = 0
     self.whos_move = 0
     self.suspend = 0
     self.winner = False
     self.is_cats = False
     self.music = pygame.mixer.Sound('music_loop.wav')
     self.basicFont = pygame.font.SysFont(None, 36)
Beispiel #43
0
class Bot:

    def __init__(self):
        self.config = config
        self.irc = Irc(config)
        self.game = Game()
        self.stats = Stats()
        if self.config['features']['gui_stats']:
            self.GUI = GUI(self)

    def run(self):
        throttle_timers = {button:0 for button in config['throttled_buttons'].keys()}

        while True:
            new_messages = self.irc.recv_messages(1024)
            
            if not new_messages:
                continue
            
            for message in new_messages: 
                button = message['message'].lower()
                username = message['username'].lower()
                
                if not self.game.is_valid_button(button):
                    continue
                
                if button in self.config['throttled_buttons']:
                    if (time.time() - throttle_timers[button] <
                            self.config['throttled_buttons'][button]):
                        continue
                    throttle_timers[button] = time.time()
                    
                if not self.game.is_political(button):
                    if (self.config['features']['play_game'] and
                            not button in self.config['misc']['blocked_buttons']):
                        self.game.push_button(button)
                
                self.stats.tally_message(username, message['message'])
            
            if self.config['features']['stats_on']:
                if self.config['features']['gui_stats']:
                    self.GUI.run()
                if self.config['features']['console_stats']:
                    pframe(self.stats)
                    
            elif self.config['features']['pbutton_on']:
                pbutton(self.stats.message_buffer)
Beispiel #44
0
class Bot:
    def __init__(self):
        self.config = config
        self.irc = Irc(config)
        self.game = Game()
        self.message_buffer = [{
            'username': '',
            'button': ''
        }] * self.config['misc']['chat_height']

    def set_message_buffer(self, message):
        self.message_buffer.insert(self.config['misc']['chat_height'] - 1,
                                   message)
        self.message_buffer.pop(0)

    def run(self):
        throttle_timers = {
            button: 0
            for button in config['throttled_buttons'].keys()
        }

        while True:
            new_messages = self.irc.recv_messages(1024)

            if not new_messages:
                continue

            for message in new_messages:
                button = message['message'].lower()
                username = message['username'].lower()

                if not self.game.is_valid_button(button):
                    continue

                if button in self.config['throttled_buttons']:
                    if time.time() - throttle_timers[button] < self.config[
                            'throttled_buttons'][button]:
                        continue

                    throttle_timers[button] = time.time()

                self.set_message_buffer({
                    'username': username,
                    'button': button
                })
                pbutton(self.message_buffer)
                self.game.push_button(button)
Beispiel #45
0
    def test_attack_with_all_cards_with_lowest_value(self):
        hand = [
            Card(Suit.CLUBS, Rank.SEVEN),
            Card(Suit.HEARTS, Rank.SEVEN),
            Card(Suit.SPADES, Rank.SEVEN),
            Card(Suit.HEARTS, Rank.JACK),
            Card(Suit.CLUBS, Rank.JACK),
            Card(Suit.SPADES, Rank.JACK)
        ]
        game = Game()
        game.trump = Card(Suit.SPADES, Rank.SIX)
        p = AIPlayer(hand=hand, game=game)

        attack = p.attack()
        assert len(attack) == 2
        assert attack[0].rank == attack[1].rank == Rank.SEVEN
        assert len(p.hand) == 4
 def test_rotatesPlayersCorrectly(self):
     game = Game("SomeGameName", self.m)
     game.addPlayer(self.j)
     game.beginGame()
     self.assertRegex(game.currentPlayer.name, self.j.name)
     game.rotateCurrentPlayer()
     self.assertRegex(game.currentPlayer.name, self.m.name)
Beispiel #47
0
class Bot:

    def __init__(self):
        self.config = config
        self.irc = Irc(config)
        self.game = Game()

        self.message_buffer = [{'username': '', 'button': ''}] * 10


    def set_message_buffer(self, message):
        chat_height = 10
        self.message_buffer.insert(chat_height - 1, message)
        self.message_buffer.pop(0)


    def run(self):
        last_start = time.time()

        while True:
            new_messages = self.irc.recv_messages(1024)
            
            if not new_messages:
                continue

            for message in new_messages: 
                button = message['message'].lower()
                username = message['username'].lower()

                if not self.game.is_valid_button(button):
                    continue

                print button

                if self.config['start_throttle']['enabled'] and button == 'start':
                    if time.time() - last_start < self.config['start_throttle']['time']:
                        continue

                if button == 'start':
                    last_start = time.time()

                self.set_message_buffer({'username': username, 'button': button})
                pbutton(self.message_buffer)
                self.game.push_button(button)
Beispiel #48
0
class Bot:

    def __init__(self):
        self.config = config
        self.irc = Irc(config)
        self.game = Game()

        self.message_buffer = [{'username': '', 'button': ''}] * self.config['misc']['chat_height']


    def set_message_buffer(self, message):
        self.message_buffer.insert(self.config['misc']['chat_height'] - 1, message)
        self.message_buffer.pop(0)


    def run(self):
        throttle_timers = {button:0 for button in config['throttled_buttons'].keys()}

        while True:
            new_messages = self.irc.recv_messages(1024)
            
            if not new_messages:
                continue

            for message in new_messages: 
                button = message['message'].lower()
                username = message['username'].lower()

                if not self.game.is_valid_button(button):
                    continue

                if button in self.config['throttled_buttons']:
                    if time.time() - throttle_timers[button] < self.config['throttled_buttons'][button]:
                        continue

                    throttle_timers[button] = time.time()
         

                self.set_message_buffer({'username': username, 'button': button})
                pbutton(self.message_buffer)
                self.game.push_button(button)
 def test_returnsRotationOfPlayers(self):
     game = Game("SomeGame", self.m)
     game.addPlayer(self.j)
     game.beginGame()
     self.assertEqual(len(game.currentTurn), 1)
     self.assertRegex(game.currentPlayer.name, self.j.name)
     nextPlayer = game.getNextPlayer()
     self.assertRegex(nextPlayer.name, self.m.name)
     nextPlayer = game.getNextPlayer()
     self.assertRegex(nextPlayer.name, self.j.name)
Beispiel #50
0
    def test_total_minimum_pieces(self):
        g = Game()
        [g.drop_cross(0) for i in range(3)]
        self.assertFalse(g._minimum_pieces(g._pieces))

        g = Game()
        [g.drop_cross(0) for i in range(4)]
        self.assertTrue(g._minimum_pieces(g._pieces))
Beispiel #51
0
class Bot:

	def __init__(self):
		self.config = config
		self.game = Game()
		self.message_buffer = [{'button': ''}] * self.config['misc']['chat_height']

	def set_message_buffer(self, message):
		self.message_buffer.insert(self.config['misc']['chat_height'] - 1, message)
		self.message_buffer.pop(0)

	def run(self):
		throttle_timers = {button:0 for button in config['throttled_buttons'].keys()}

		while True:
			button = choice(self.game.keymap)
			if button in self.config['throttled_buttons']:
				if time.time() - throttle_timers[button] < self.config['throttled_buttons'][button]:
					continue
				throttle_timers[button] = time.time()

			self.set_message_buffer({'username': username, 'button': button})
			pbutton(self.message_buffer)
			self.game.push_button(button)
#!/usr/bin/python2.5

######################
# DUNGEON-RPG ########
# By: John Gunderman #
######################

from lib.game import Game

game = Game()

game.run()
Beispiel #53
0
 def test_horizontal_win_by_round(self):
     # Horizontal win using round
     g = Game()
     [g.drop_round(i) for i in range(4)]
     self.assertTrue(g._horizontal_win('O'))
     self.assertFalse(g._horizontal_win('X'))
Beispiel #54
0
    def test_horizontal_win_by_cross(self):
        # No victory, insufficient total pieces
        g = Game()
        [g.drop_cross(i) for i in range(3)]
        self.assertFalse(g._horizontal_win('X'))

        # No victory insufficient row total pieces
        g = Game()
        [g.drop_cross(i) for i in range(3)]
        g.drop_cross(0)
        self.assertFalse(g._horizontal_win('X'))

        # Horizontal win using crosses
        g = Game()
        [g.drop_cross(i) for i in range(4)]
        self.assertTrue(g._horizontal_win('X'))
Beispiel #55
0
 def test_vertical_win_by_round(self):
     # Vertical win using round
     g = Game()
     [g.drop_round(0) for i in range(4)]
     self.assertTrue(g._vertical_win('O'))
     self.assertFalse(g._vertical_win('X'))
Beispiel #56
0
    def test_vertical_win_by_cross(self):
        # No victory, insufficient total pieces
        g = Game()
        [g.drop_cross(0) for i in range(3)]
        self.assertFalse(g._vertical_win('X'))

        # No victory, insufficient column total pieces
        g = Game()
        [g.drop_cross(0) for i in range(3)]
        g.drop_cross(1)
        self.assertFalse(g._vertical_win('X'))

        # Vertical win using crosses
        g = Game()
        [g.drop_cross(0) for i in range(4)]
        self.assertTrue(g._vertical_win('X'))
Beispiel #57
0
 def test_drop_round_on_full_column_raises(self):
     g = Game(rows=2)
     self.assertEquals(g.drop_round(0), (0,1))
     self.assertEquals(g.drop_round(0), (0,0))
     self.assertRaises(ColumnFullException, g.drop_round, 0)
Beispiel #58
0
 def test_drop_round(self):
     g = Game()
     self.assertEquals(g.drop_round(0), (0,5))
     self.assertTrue((0,5) in g._round_pieces)
Beispiel #59
0
 def test_drop_cross(self):
     g = Game()
     self.assertEquals(g.drop_cross(0), (0,5))
     self.assertTrue((0,5) in g._cross_pieces)
Beispiel #60
0
 def test_drop_piece_on_full_column_raises(self):
     g = Game(rows=2)
     self.assertEquals(g._drop_piece('X', 0), (0,1))
     self.assertEquals(g._drop_piece('X', 0), (0,0))
     self.assertRaises(ColumnFullException, g._drop_piece, 'X', 0)