Esempio n. 1
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)
    if replay.players[2].startswith('c'):
        level = int(replay.players[2][2:])
        campaign_level = campaign.get_level(level)
        game = Game(Speed(replay.speed),
                    replay.players,
                    board=Board.from_str(campaign_level.board),
                    is_campaign=True)
    else:
        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,
    })
Esempio n. 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)
Esempio n. 3
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
Esempio n. 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)
Esempio n. 5
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()
Esempio n. 6
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)
Esempio n. 7
0
def get_game() -> Game:
    return Game(
        bot=TestBot(),
        alpha=TestMember(),
        beta=TestMember(id=570243143958528010, mention='@daima3629#1235'),
        channel=TestChannel(),
    )
Esempio n. 8
0
 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)
Esempio n. 9
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)
Esempio n. 10
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)
Esempio n. 11
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,
    })
Esempio n. 12
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)
Esempio n. 13
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
Esempio n. 14
0
def main():
    """
    Game function.
    """
    # Game creation
    maze_game = Game('ressources/map.txt')
    # Game loop
    maze_game.on_execute()
Esempio n. 15
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)
Esempio n. 16
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__)
Esempio n. 17
0
def create_game(session):
    game = Game()
    session.add(game)
    session.flush()
    game_id = game.game_id
    _card_bootstrap(session, game_id)
    session.commit()
    return game_id
Esempio n. 18
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!!!')
Esempio n. 19
0
 def __init__(self):
     self.config = config
     self.irc = Irc(config)
     self.game = Game()
     self.message_buffer = [{
         'username': '',
         'button': ''
     }] * self.config['misc']['chat_height']
Esempio n. 20
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')
Esempio n. 21
0
def main():
    game = Game()
    game.start()

    while True:
        game.event()
        game.update()
        game.draw()
Esempio n. 22
0
    def test_failing_defense_pushes_attack_cards_into_defender_hand(self):
        game = Game()
        game.turn = 'player'

        game.attack_cards = [Card(Suit.CLUBS, Rank.JACK)]
        game.defender.hand = []

        game.defend()
        assert game.defender.hand[0] == Card(Suit.CLUBS, Rank.JACK)
Esempio n. 23
0
 def setUp(self):
     self.game = Game(constant.SMALL)
     rand_location = [randrange(10 - 1), -1]
     set_location = [2, 3]
     shape = 0
     t_id = 0
     self.tetrino1 = Tetrino(self.game, rand_location, shape, t_id)
     self.tetrino2 = Tetrino(self.game, rand_location, shape, t_id + 1)
     self.tetrino3 = Tetrino(self.game, set_location, shape, t_id + 2)
     self.tetrino4 = Tetrino(self.game, set_location, shape + 1, t_id + 3)
Esempio n. 24
0
 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)
Esempio n. 25
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
Esempio n. 26
0
def main(folder, ite, gtp):
    player, _ = load_player(folder, ite)
    if not isinstance(player, str):
        game = Game(player, 0)
        engine = Engine(game, board_size=game.goban_size)
        while True:
            print(engine.send(input()))
    elif not gtp:
        print(player)
    else:
        print("¯\_(ツ)_/¯")
Esempio n. 27
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,
    })
Esempio n. 28
0
 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))
Esempio n. 29
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__)
Esempio n. 30
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