<commit_before>gamestate = {
    "tournament_id":"550d1d68cd7bd10003000003",     # Id of the current tournament

    "game_id":"550da1cb2d909006e90004b1",           # Id of the current sit'n'go game. You can use this to link a
                                                    # sequence of game states together for logging purposes, or to
                                                    # make sure that the same strategy is played for an entire game

    "round":0,                                      # Index of the current round within a sit'n'go

    "bet_index":0,                                  # Index of the betting opportunity within a round

    "small_blind": 10,                              # The small blind in the current round. The big blind is twice the
                                                    #     small blind

    "current_buy_in": 80,                          # The amount of the largest current bet from any one player

    "pot": 400,                                     # The size of the pot (sum of the player bets)

    "minimum_raise": 240,                           # Minimum raise amount. To raise you have to return at least:
                                                    #     current_buy_in - players[in_action][bet] + minimum_raise

    "dealer": 1,                                    # The index of the player on the dealer button in this round
                                                    #     The first player is (dealer+1)%(players.length)

    "orbits": 7,                                    # Number of orbits completed. (The number of times the dealer
                                                    #     button returned to the same player.)

    "in_action": 1,                                 # The index of your player, in the players array

    "players": [                                    # An array of the players. The order stays the same during the
        {                                           #     entire tournament

            "id": 0,                                # Id of the player (same as the index)

            "name": "Albert",                       # Name specified in the tournament config

            "status": "active",                     # Status of the player:
                                                    #   - active: the player can make bets, and win the current pot
                                                    #   - folded: the player folded, and gave up interest in
                                                    #       the current pot. They can return in the next round.
                                                    #   - out: the player lost all chips, and is out of this sit'n'go

            "version": "Default random player",     # Version identifier returned by the player

            "stack": 1010,                          # Amount of chips still available for the player. (Not including
                                                    #     the chips the player bet in this round.)

            "bet": 0                              # The amount of chips the player put into the pot
        },
        {
            "id": 1,                                # Your own player looks similar, with one extension.
            "name": "Fishes",
            "status": "active",
            "version": "Default random player",
            "stack": 1590,
            "bet": 80,
            "hole_cards": [                         # The cards of the player. This is only visible for your own player
                                                    #     except after showdown, when cards revealed are also included.
                {
                    "rank": "A",                    # Rank of the card. Possible values are numbers 2-10 and J,Q,K,A
                    "suit": "hearts"                # Suit of the card. Possible values are: clubs,spades,hearts,diamonds
                },
                {
                    "rank": "A",
                    "suit": "spades"
                }
            ]
        },
        {
            "id": 2,
            "name": "Chuck",
            "status": "out",
            "version": "Default random player",
            "stack": 0,
            "bet": 0
        }
    ],
    "community_cards": [                            # Finally the array of community cards.
        {
            "rank": "10",
            "suit": "spades"
        },
        {
            "rank": "10",
            "suit": "hearts"
        },
        {
            "rank": "10",
            "suit": "clubs"
        }
    ]
}

class Board:

    def check_one_pair(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        ranks = set(ranks)
        if len(ranks) == 4:
            return True

        return False

    def check_two_pairs(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        ranks = set(ranks)
        if len(ranks) == 3:
            return True

        return False

    def check_set(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        for rank in ranks:
            if ranks.count(rank) == 3:
                return True

        return False

    def check_poker(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        for rank in ranks:
            if ranks.count(rank) == 4:
                return True

        return False

    def get_hand_rank(self):
        if self.check_poker():
            return "Poker"
        if self.check_set():
            return "Set"
        if self.check_two_pairs():
            return "Two pairs"
        if self.check_one_pair():
            return 'One pair'

    def update_cards(self, game_state, player_data):
        cards = []
        community_cards = [i['rank']  + i['suit'][0] if i['rank'] != "10" else "T" + i['suit'][0] for i in game_state['community_cards']]
        own_cards = [i['rank']  + i['suit'][0] if i['rank'] != "10" else "T" + i['suit'][0] for i in player_data['hole_cards']]
        for card in community_cards:
            cards.append(card)
        for card in own_cards:
            cards.append(card)
        self.cards = cards
        print(self.cards)

    def update_status(self, game_state):
        if(len(game_state['community_cards']) == 0):
            self.status = 'preflop'
        elif (len(game_state['community_cards']) == 3):
            self.status = 'flop'
        elif (len(game_state['community_cards']) == 4):
            self.status = 'turn'
        elif (len(game_state['community_cards']) == 5):
            self.status = 'river'

        self.current_buy_in = int(game_state['current_buy_in'])

        self.small_blind = int(game_state['small_blind'])

    def update_action(self, game_state):
        bets = []
        for player in game_state['players']:
            if player['bet'] > game_state['small_blind'] * 2:
                bets.append(int(player['bet']))
        bets = set(bets)
        if len(bets) == 0:
            self.action = 'no_bet'
        elif len(bets) == 1:
            self.action = 'bet'
        else:
            self.action = 'raise'

    def format_cards(self):
        suits = []
        suit = 'o'
        cards = []
        for card in self.player_data['hole_cards']:
            if card['rank'] == '10':
                rank = 'T'
            else:
                rank = card['rank']
            suits.append(card['suit'])
            cards.append(rank)

        if suits[0] == suits[1]:
            suit = 's'
        self.own_cards = "".join(cards)

class Player:
    VERSION = "bela"
    top_1 = ['AAo', 'KKo', 'AKo', 'AKs', 'QQo', 'JJo', 'TTo', 'AQs', 'AQo', 'KQs', 'ATs', '99o', '88o', '77o']
    top_2 = [
        'AAo', 'KKo', 'AKo', 'AKs', 'QQo', 'JJo', 'TTo', 'AQs', 'AQo', 'AJo', 'KQo', 'KQs', 'KJs', 'QJs',
        'ATs', '99o', '88o', '77o'
    ]
    top_3 = [
        'AAo', 'KKo', 'AKo', 'AKs', 'QQo', 'JJo', 'TTo', 'AQs', 'AQo', 'AJo', 'KQo', 'KQs', 'KJs', 'QJs', 'ATs',
        '99o', '88o', '77o', '66o', '55o', '44o', '33o', '22o', 'A9s', 'A8s', 'A7s', 'A6s', 'A5s', 'A4s', 'A3s',
        'A2s', 'KTs', 'K9s', 'K8s', 'K7s', 'K6s', 'QTs', 'Q9s', 'Q8s', 'JTs', 'J9s', 'T9s', 'ATo', 'A9o', 'A8o',
        'KJo', 'KTo', 'K9o', 'QJo', 'QTo', 'JTo'
    ]

    def __init__(self):
        self.board = Board()

    # Finds player data
    def find_player(self, game_state):
        for player in game_state["players"]:
            if player["name"] == "Fishes":
                self.player_data = player

    # Formats our cards into a desired format, example: 'AKs' - meaning ace, king, offsuite (not the same color)
    def format_own_cards(self):
        suits = []
        suit = 'o'
        cards = []
        for card in self.player_data['hole_cards']:
            if card['rank'] == '10':
                rank = 'T'
            else:
                rank = card['rank']
            suits.append(card['suit'])
            cards.append(rank)

        if suits[0] == suits[1]:
            suit = 's'
        self.own_cards = "".join(cards) + suit

    # Checks if our cards are in top5%
    def check_top1(self):
        altered_cards = self.own_cards[1] + self.own_cards[0] + self.own_cards[2]
        return self.own_cards in self.top_1 or altered_cards in self.top_1

    def check_top2(self):
        altered_cards = self.own_cards[1] + self.own_cards[0] + self.own_cards[2]
        return self.own_cards in self.top_2 or altered_cards in self.top_2

    def check_top3(self):
        altered_cards = self.own_cards[1] + self.own_cards[0] + self.own_cards[2]
        return self.own_cards in self.top_3 or altered_cards in self.top_3

    def reraise(self):
        return self.board.current_buy_in * 3

    def bet(self):
        return self.board.small_blind * 8

    def call(self):
        return self.board.current_buy_in

    def check(self):
        return 0

    def fold(self):
        return 0

    def all_in(self):
        return self.stack

    def betRequest(self, game_state):
        self.find_player(game_state)
        self.format_own_cards()

        self.stack = self.player_data['stack']
        self.board.update_status(game_state)
        self.board.update_action(game_state)
        self.board.update_cards(game_state, self.player_data)
        print("hand_rank")
        hand_rank = self.board.get_hand_rank()
        print(hand_rank)

        if self.board.status == 'preflop':
            if self.check_top1():
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.reraise()
                if self.board.action == 'raise':
                    return self.all_in()

            elif self.check_top2():
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.call()
                if self.board.action == 'raise':
                    return self.fold()

            elif self.check_top3():
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.call()
                if self.board.action == 'raise':
                    return self.fold()

            else:
                return 0

        else:
            if hand_rank == "Set":
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.reraise()
                if self.board.action == 'raise':
                    return self.all_in()
            elif hand_rank == "Two pairs":
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.reraise()
                if self.board.action == 'raise':
                    return self.all_in()
            elif hand_rank == "One pair":
                if self.check_top1():
                    if self.board.action == 'no_bet':
                        return self.bet()
                    if self.board.action == 'bet':
                        return self.call()
                    if self.board.action == 'raise':
                        return self.call()
                else:
                    if self.board.action == 'no_bet':
                        return self.bet()
                    if self.board.action == 'bet':
                        return self.fold()
                    if self.board.action == 'raise':
                        return self.fold()
            else:
                if self.board.action == 'no_bet':
                    return self.check()
                if self.board.action == 'bet':
                    return self.fold()
                if self.board.action == 'raise':
                    return self.fold()

    def showdown(self, game_state):
        pass

    def get_my_hand(self, game_state):
        all_data = game_state
        for player in all_data["players"]:
            if player["name"] == "Fishes":
                return player

    def check_hand_for_pairs(self, cards):
        return cards[0]["rank"] == cards[1]["rank"]

    def check_hand_for_figures(self, cards):
        first_good = False
        second_good = False
        try:
            first = int(cards[0]["rank"])
        except:
            first_good = True
        try:
            second = int(cards[1]["rank"])
        except:
            second_good = True
        return first_good and second_good

player = Player()
print(player.betRequest(gamestate))

<commit_msg>reraise top2<commit_after>gamestate = {
    "tournament_id":"550d1d68cd7bd10003000003",     # Id of the current tournament

    "game_id":"550da1cb2d909006e90004b1",           # Id of the current sit'n'go game. You can use this to link a
                                                    # sequence of game states together for logging purposes, or to
                                                    # make sure that the same strategy is played for an entire game

    "round":0,                                      # Index of the current round within a sit'n'go

    "bet_index":0,                                  # Index of the betting opportunity within a round

    "small_blind": 10,                              # The small blind in the current round. The big blind is twice the
                                                    #     small blind

    "current_buy_in": 80,                          # The amount of the largest current bet from any one player

    "pot": 400,                                     # The size of the pot (sum of the player bets)

    "minimum_raise": 240,                           # Minimum raise amount. To raise you have to return at least:
                                                    #     current_buy_in - players[in_action][bet] + minimum_raise

    "dealer": 1,                                    # The index of the player on the dealer button in this round
                                                    #     The first player is (dealer+1)%(players.length)

    "orbits": 7,                                    # Number of orbits completed. (The number of times the dealer
                                                    #     button returned to the same player.)

    "in_action": 1,                                 # The index of your player, in the players array

    "players": [                                    # An array of the players. The order stays the same during the
        {                                           #     entire tournament

            "id": 0,                                # Id of the player (same as the index)

            "name": "Albert",                       # Name specified in the tournament config

            "status": "active",                     # Status of the player:
                                                    #   - active: the player can make bets, and win the current pot
                                                    #   - folded: the player folded, and gave up interest in
                                                    #       the current pot. They can return in the next round.
                                                    #   - out: the player lost all chips, and is out of this sit'n'go

            "version": "Default random player",     # Version identifier returned by the player

            "stack": 1010,                          # Amount of chips still available for the player. (Not including
                                                    #     the chips the player bet in this round.)

            "bet": 0                              # The amount of chips the player put into the pot
        },
        {
            "id": 1,                                # Your own player looks similar, with one extension.
            "name": "Fishes",
            "status": "active",
            "version": "Default random player",
            "stack": 1590,
            "bet": 80,
            "hole_cards": [                         # The cards of the player. This is only visible for your own player
                                                    #     except after showdown, when cards revealed are also included.
                {
                    "rank": "A",                    # Rank of the card. Possible values are numbers 2-10 and J,Q,K,A
                    "suit": "hearts"                # Suit of the card. Possible values are: clubs,spades,hearts,diamonds
                },
                {
                    "rank": "A",
                    "suit": "spades"
                }
            ]
        },
        {
            "id": 2,
            "name": "Chuck",
            "status": "out",
            "version": "Default random player",
            "stack": 0,
            "bet": 0
        }
    ],
    "community_cards": [                            # Finally the array of community cards.
        {
            "rank": "10",
            "suit": "spades"
        },
        {
            "rank": "10",
            "suit": "hearts"
        },
        {
            "rank": "10",
            "suit": "clubs"
        }
    ]
}

class Board:

    def check_one_pair(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        ranks = set(ranks)
        if len(ranks) == 4:
            return True

        return False

    def check_two_pairs(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        ranks = set(ranks)
        if len(ranks) == 3:
            return True

        return False

    def check_set(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        for rank in ranks:
            if ranks.count(rank) == 3:
                return True

        return False

    def check_poker(self):
        ranks = []
        for card in self.cards:
            ranks.append(card[0])

        for rank in ranks:
            if ranks.count(rank) == 4:
                return True

        return False

    def get_hand_rank(self):
        if self.check_poker():
            return "Poker"
        if self.check_set():
            return "Set"
        if self.check_two_pairs():
            return "Two pairs"
        if self.check_one_pair():
            return 'One pair'

    def update_cards(self, game_state, player_data):
        cards = []
        community_cards = [i['rank']  + i['suit'][0] if i['rank'] != "10" else "T" + i['suit'][0] for i in game_state['community_cards']]
        own_cards = [i['rank']  + i['suit'][0] if i['rank'] != "10" else "T" + i['suit'][0] for i in player_data['hole_cards']]
        for card in community_cards:
            cards.append(card)
        for card in own_cards:
            cards.append(card)
        self.cards = cards
        print(self.cards)

    def update_status(self, game_state):
        if(len(game_state['community_cards']) == 0):
            self.status = 'preflop'
        elif (len(game_state['community_cards']) == 3):
            self.status = 'flop'
        elif (len(game_state['community_cards']) == 4):
            self.status = 'turn'
        elif (len(game_state['community_cards']) == 5):
            self.status = 'river'

        self.current_buy_in = int(game_state['current_buy_in'])

        self.small_blind = int(game_state['small_blind'])

    def update_action(self, game_state):
        bets = []
        for player in game_state['players']:
            if player['bet'] > game_state['small_blind'] * 2:
                bets.append(int(player['bet']))
        bets = set(bets)
        if len(bets) == 0:
            self.action = 'no_bet'
        elif len(bets) == 1:
            self.action = 'bet'
        else:
            self.action = 'raise'

    def format_cards(self):
        suits = []
        suit = 'o'
        cards = []
        for card in self.player_data['hole_cards']:
            if card['rank'] == '10':
                rank = 'T'
            else:
                rank = card['rank']
            suits.append(card['suit'])
            cards.append(rank)

        if suits[0] == suits[1]:
            suit = 's'
        self.own_cards = "".join(cards)

class Player:
    VERSION = "bela"
    top_1 = ['AAo', 'KKo', 'AKo', 'AKs', 'QQo', 'JJo', 'TTo', 'AQs', 'AQo', 'KQs', 'ATs', '99o', '88o', '77o']
    top_2 = [
        'AAo', 'KKo', 'AKo', 'AKs', 'QQo', 'JJo', 'TTo', 'AQs', 'AQo', 'AJo', 'KQo', 'KQs', 'KJs', 'QJs',
        'ATs', '99o', '88o', '77o'
    ]
    top_3 = [
        'AAo', 'KKo', 'AKo', 'AKs', 'QQo', 'JJo', 'TTo', 'AQs', 'AQo', 'AJo', 'KQo', 'KQs', 'KJs', 'QJs', 'ATs',
        '99o', '88o', '77o', '66o', '55o', '44o', '33o', '22o', 'A9s', 'A8s', 'A7s', 'A6s', 'A5s', 'A4s', 'A3s',
        'A2s', 'KTs', 'K9s', 'K8s', 'K7s', 'K6s', 'QTs', 'Q9s', 'Q8s', 'JTs', 'J9s', 'T9s', 'ATo', 'A9o', 'A8o',
        'KJo', 'KTo', 'K9o', 'QJo', 'QTo', 'JTo'
    ]

    def __init__(self):
        self.board = Board()

    # Finds player data
    def find_player(self, game_state):
        for player in game_state["players"]:
            if player["name"] == "Fishes":
                self.player_data = player

    # Formats our cards into a desired format, example: 'AKs' - meaning ace, king, offsuite (not the same color)
    def format_own_cards(self):
        suits = []
        suit = 'o'
        cards = []
        for card in self.player_data['hole_cards']:
            if card['rank'] == '10':
                rank = 'T'
            else:
                rank = card['rank']
            suits.append(card['suit'])
            cards.append(rank)

        if suits[0] == suits[1]:
            suit = 's'
        self.own_cards = "".join(cards) + suit

    # Checks if our cards are in top5%
    def check_top1(self):
        altered_cards = self.own_cards[1] + self.own_cards[0] + self.own_cards[2]
        return self.own_cards in self.top_1 or altered_cards in self.top_1

    def check_top2(self):
        altered_cards = self.own_cards[1] + self.own_cards[0] + self.own_cards[2]
        return self.own_cards in self.top_2 or altered_cards in self.top_2

    def check_top3(self):
        altered_cards = self.own_cards[1] + self.own_cards[0] + self.own_cards[2]
        return self.own_cards in self.top_3 or altered_cards in self.top_3

    def reraise(self):
        return self.board.current_buy_in * 3

    def bet(self):
        return self.board.small_blind * 8

    def call(self):
        return self.board.current_buy_in

    def check(self):
        return 0

    def fold(self):
        return 0

    def all_in(self):
        return self.stack

    def betRequest(self, game_state):
        self.find_player(game_state)
        self.format_own_cards()

        self.stack = self.player_data['stack']
        self.board.update_status(game_state)
        self.board.update_action(game_state)
        self.board.update_cards(game_state, self.player_data)
        print("hand_rank")
        hand_rank = self.board.get_hand_rank()
        print(hand_rank)

        if self.board.status == 'preflop':
            if self.check_top1():
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.reraise()
                if self.board.action == 'raise':
                    return self.all_in()

            elif self.check_top2():
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.reraise()
                if self.board.action == 'raise':
                    return self.fold()

            elif self.check_top3():
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.call()
                if self.board.action == 'raise':
                    return self.fold()

            else:
                return 0

        else:
            if hand_rank == "Set":
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.reraise()
                if self.board.action == 'raise':
                    return self.all_in()
            elif hand_rank == "Two pairs":
                if self.board.action == 'no_bet':
                    return self.bet()
                if self.board.action == 'bet':
                    return self.reraise()
                if self.board.action == 'raise':
                    return self.all_in()
            elif hand_rank == "One pair":
                if self.check_top1():
                    if self.board.action == 'no_bet':
                        return self.bet()
                    if self.board.action == 'bet':
                        return self.call()
                    if self.board.action == 'raise':
                        return self.call()
                else:
                    if self.board.action == 'no_bet':
                        return self.bet()
                    if self.board.action == 'bet':
                        return self.fold()
                    if self.board.action == 'raise':
                        return self.fold()
            else:
                if self.board.action == 'no_bet':
                    return self.check()
                if self.board.action == 'bet':
                    return self.fold()
                if self.board.action == 'raise':
                    return self.fold()

    def showdown(self, game_state):
        pass

    def get_my_hand(self, game_state):
        all_data = game_state
        for player in all_data["players"]:
            if player["name"] == "Fishes":
                return player

    def check_hand_for_pairs(self, cards):
        return cards[0]["rank"] == cards[1]["rank"]

    def check_hand_for_figures(self, cards):
        first_good = False
        second_good = False
        try:
            first = int(cards[0]["rank"])
        except:
            first_good = True
        try:
            second = int(cards[1]["rank"])
        except:
            second_good = True
        return first_good and second_good

player = Player()
print(player.betRequest(gamestate))

<|endoftext|>


<commit_before># gamestate = {
#     "tournament_id":"550d1d68cd7bd10003000003",     # Id of the current tournament
#
#     "game_id":"550da1cb2d909006e90004b1",           # Id of the current sit'n'go game. You can use this to link a
#                                                     # sequence of game states together for logging purposes, or to
#                                                     # make sure that the same strategy is played for an entire game
#
#     "round":0,                                      # Index of the current round within a sit'n'go
#
#     "bet_index":0,                                  # Index of the betting opportunity within a round
#
#     "small_blind": 10,                              # The small blind in the current round. The big blind is twice the
#                                                     #     small blind
#
#     "current_buy_in": 80,                          # The amount of the largest current bet from any one player
#
#     "pot": 400,                                     # The size of the pot (sum of the player bets)
#
#     "minimum_raise": 240,                           # Minimum raise amount. To raise you have to return at least:
#                                                     #     current_buy_in - players[in_action][bet] + minimum_raise
#
#     "dealer": 1,                                    # The index of the player on the dealer button in this round
#                                                     #     The first player is (dealer+1)%(players.length)
#
#     "orbits": 7,                                    # Number of orbits completed. (The number of times the dealer
#                                                     #     button returned to the same player.)
#
#     "in_action": 1,                                 # The index of your player, in the players array
#
#     "players": [                                    # An array of the players. The order stays the same during the
#         {                                           #     entire tournament
#
#             "id": 0,                                # Id of the player (same as the index)
#
#             "name": "Albert",                       # Name specified in the tournament config
#
#             "status": "active",                     # Status of the player:
#                                                     #   - active: the player can make bets, and win the current pot
#                                                     #   - folded: the player folded, and gave up interest in
#                                                     #       the current pot. They can return in the next round.
#                                                     #   - out: the player lost all chips, and is out of this sit'n'go
#
#             "version": "Default random player",     # Version identifier returned by the player
#
#             "stack": 1010,                          # Amount of chips still available for the player. (Not including
#                                                     #     the chips the player bet in this round.)
#
#             "bet": 0                              # The amount of chips the player put into the pot
#         },
#         {
#             "id": 1,                                # Your own player looks similar, with one extension.
#             "name": "Glorious Ape",
#             "status": "active",
#             "version": "Default random player",
#             "stack": 1590,
#             "bet": 80,
#             "hole_cards": [                         # The cards of the player. This is only visible for your own player
#                                                     #     except after showdown, when cards revealed are also included.
#                 {
#                     "rank": "A",                    # Rank of the card. Possible values are numbers 2-10 and J,Q,K,A
#                     "suit": "hearts"                # Suit of the card. Possible values are: clubs,spades,hearts,diamonds
#                 },
#                 {
#                     "rank": "A",
#                     "suit": "spades"
#                 }
#             ]
#         },
#         {
#             "id": 2,
#             "name": "Chuck",
#             "status": "out",
#             "version": "Default random player",
#             "stack": 0,
#             "bet": 0
#         }
#     ],
#     "community_cards": [                            # Finally the array of community cards.
#         {
#             "rank": "10",
#             "suit": "spades"
#         },
#         {
#             "rank": "10",
#             "suit": "hearts"
#         },
#         {
#             "rank": "10",
#             "suit": "clubs"
#         }
#     ]
# }

class Player:
    VERSION = "Tami joined the dark side!"

    def betRequest(self, game_state):
        for player in game_state['players']:
            if player['name'] == 'Glorious Ape':
                if player['hole_cards'][0]['rank'] == player['hole_cards'][1]['rank']:
                    return 1000
                else:
                    return 0

    def showdown(self, game_state):
        pass

    def player(self, game_state):
        for player in game_state['players']:
            if player['name'] == 'Glorious Ape':
                return player

    def hand(self, game_state):
        player = self.player(game_state)
        return player['hole_cards']

    def community_cards(self, game_state):
        print game_state['community_cards']
        return game_state['community_cards']

# x = Player()
# x.betRequest(gamestate)
<commit_msg>community cards method added<commit_after># gamestate = {
#     "tournament_id":"550d1d68cd7bd10003000003",     # Id of the current tournament
#
#     "game_id":"550da1cb2d909006e90004b1",           # Id of the current sit'n'go game. You can use this to link a
#                                                     # sequence of game states together for logging purposes, or to
#                                                     # make sure that the same strategy is played for an entire game
#
#     "round":0,                                      # Index of the current round within a sit'n'go
#
#     "bet_index":0,                                  # Index of the betting opportunity within a round
#
#     "small_blind": 10,                              # The small blind in the current round. The big blind is twice the
#                                                     #     small blind
#
#     "current_buy_in": 80,                          # The amount of the largest current bet from any one player
#
#     "pot": 400,                                     # The size of the pot (sum of the player bets)
#
#     "minimum_raise": 240,                           # Minimum raise amount. To raise you have to return at least:
#                                                     #     current_buy_in - players[in_action][bet] + minimum_raise
#
#     "dealer": 1,                                    # The index of the player on the dealer button in this round
#                                                     #     The first player is (dealer+1)%(players.length)
#
#     "orbits": 7,                                    # Number of orbits completed. (The number of times the dealer
#                                                     #     button returned to the same player.)
#
#     "in_action": 1,                                 # The index of your player, in the players array
#
#     "players": [                                    # An array of the players. The order stays the same during the
#         {                                           #     entire tournament
#
#             "id": 0,                                # Id of the player (same as the index)
#
#             "name": "Albert",                       # Name specified in the tournament config
#
#             "status": "active",                     # Status of the player:
#                                                     #   - active: the player can make bets, and win the current pot
#                                                     #   - folded: the player folded, and gave up interest in
#                                                     #       the current pot. They can return in the next round.
#                                                     #   - out: the player lost all chips, and is out of this sit'n'go
#
#             "version": "Default random player",     # Version identifier returned by the player
#
#             "stack": 1010,                          # Amount of chips still available for the player. (Not including
#                                                     #     the chips the player bet in this round.)
#
#             "bet": 0                              # The amount of chips the player put into the pot
#         },
#         {
#             "id": 1,                                # Your own player looks similar, with one extension.
#             "name": "Glorious Ape",
#             "status": "active",
#             "version": "Default random player",
#             "stack": 1590,
#             "bet": 80,
#             "hole_cards": [                         # The cards of the player. This is only visible for your own player
#                                                     #     except after showdown, when cards revealed are also included.
#                 {
#                     "rank": "A",                    # Rank of the card. Possible values are numbers 2-10 and J,Q,K,A
#                     "suit": "hearts"                # Suit of the card. Possible values are: clubs,spades,hearts,diamonds
#                 },
#                 {
#                     "rank": "A",
#                     "suit": "spades"
#                 }
#             ]
#         },
#         {
#             "id": 2,
#             "name": "Chuck",
#             "status": "out",
#             "version": "Default random player",
#             "stack": 0,
#             "bet": 0
#         }
#     ],
#     "community_cards": [                            # Finally the array of community cards.
#         {
#             "rank": "10",
#             "suit": "spades"
#         },
#         {
#             "rank": "10",
#             "suit": "hearts"
#         },
#         {
#             "rank": "10",
#             "suit": "clubs"
#         }
#     ]
# }

class Player:
    VERSION = "Tami joined the dark side!"

    def betRequest(self, game_state):
        for player in game_state['players']:
            if player['name'] == 'Glorious Ape':
                if player['hole_cards'][0]['rank'] == player['hole_cards'][1]['rank']:
                    return 1000
                else:
                    return 0

    def showdown(self, game_state):
        pass

    def player(self, game_state):
        for player in game_state['players']:
            if player['name'] == 'Glorious Ape':
                return player

    def hand(self, game_state):
        player = self.player(game_state)
        return player['hole_cards']

    def community_cards(self, game_state):
        return game_state['community_cards']

# x = Player()
# x.betRequest(gamestate)
<|endoftext|>


<commit_before>from mpd import MPDClient
from threading import Lock
from book import Book

class LockableMPDClient(MPDClient):
    def __init__(self, use_unicode=False):
        super(LockableMPDClient, self).__init__()
        self.use_unicode = use_unicode
        self._lock = Lock()
    def acquire(self):
        self._lock.acquire()
    def release(self):
        self._lock.release()
    def __enter__(self):
        self.acquire()
    def __exit__(self, type, value, traceback):
        self.release()

class Player(object):

    """The class responsible for playing the audio books"""

    def __init__(self, conn_details):
        """Setup a connection to MPD to be able to play audio.

        Also update the MPD database with any new MP3 files that may have been added
        and clear any existing playlists.
        """
        self.book = Book()

        self.mpd_client = LockableMPDClient()
        with self.mpd_client:
            self.mpd_client.connect(**conn_details)

            self.mpd_client.update()
            self.mpd_client.clear()
            self.mpd_client.setvol(100)

    def toggle_pause(self, channel):
        """Toggle playback status between play and pause"""

        with self.mpd_client:
            state = self.mpd_client.status()['state']
            if state == 'play':
                self.mpd_client.pause()
            elif state == 'pause':
                self.mpd_client.play()

    def rewind(self, channel):
        if self.is_playing():
            with self.mpd_client:
                seek = max(int(self.book.elapsed) - 20, 0)
                self.mpd_client.seek(int(self.book.part) - 1, seek)

    def volume_up(self, channel):

        volume = int(self.get_status()['volume'])
        self.set_volume(min(volume + 10, 100))

    def volume_down(self, channel):
        self.player.volume_down()

        volume = int(self.get_status()['volume'])
        self.set_volume(max(volume - 10, 0))

    def set_volume(self, volume):
        """Set the volume on the MPD client"""

        with self.mpd_client:
            self.mpd_client.setvol(volume)
            print "volume set to %d" % volume

    def stop(self):
        """On stopping, reset the current playback and stop and clear the playlist

        In contract to pausing, stopping is actually meant to completely stop playing
        the current book and start listening to another"""

        self.playing = False
        self.book.reset()

        with self.mpd_client:
            self.mpd_client.stop()
            self.mpd_client.clear()

    def play(self, book_id, progress=None):
        """Play the book as defined in self.book

        1. Get the parts from the current book and add them to the playlsit
        2. Start playing the playlist
        3. Immediately set the position the last know position to resume playback where
           we last left off"""

        with self.mpd_client:
            self.mpd_client.clear()

            parts = self.mpd_client.search('filename', book_id)

            if not parts:
                print "Unused book id: %d" % book_id
                return

            for part in parts:
                self.mpd_client.add(part['file'])

            self.mpd_client.play()

            if progress:
                # resume at last known position
                self.book.set_progress(progress)
                self.mpd_client.seek(int(self.book.part) - 1, int(self.book.elapsed))

    def is_playing(self):
        return self.get_status()['state'] == 'play'

    def get_status(self):
        with self.mpd_client:
            return self.mpd_client.status()

    def close(self):
        self.stop()
        self.mpd_client.close()
        self.mpd_client.disconnect()
<commit_msg>set book_id when starting a new book<commit_after>from mpd import MPDClient
from threading import Lock
from book import Book

class LockableMPDClient(MPDClient):
    def __init__(self, use_unicode=False):
        super(LockableMPDClient, self).__init__()
        self.use_unicode = use_unicode
        self._lock = Lock()
    def acquire(self):
        self._lock.acquire()
    def release(self):
        self._lock.release()
    def __enter__(self):
        self.acquire()
    def __exit__(self, type, value, traceback):
        self.release()

class Player(object):

    """The class responsible for playing the audio books"""

    def __init__(self, conn_details):
        """Setup a connection to MPD to be able to play audio.

        Also update the MPD database with any new MP3 files that may have been added
        and clear any existing playlists.
        """
        self.book = Book()

        self.mpd_client = LockableMPDClient()
        with self.mpd_client:
            self.mpd_client.connect(**conn_details)

            self.mpd_client.update()
            self.mpd_client.clear()
            self.mpd_client.setvol(100)

    def toggle_pause(self, channel):
        """Toggle playback status between play and pause"""

        with self.mpd_client:
            state = self.mpd_client.status()['state']
            if state == 'play':
                self.mpd_client.pause()
            elif state == 'pause':
                self.mpd_client.play()

    def rewind(self, channel):
        if self.is_playing():
            with self.mpd_client:
                seek = max(int(self.book.elapsed) - 20, 0)
                self.mpd_client.seek(int(self.book.part) - 1, seek)

    def volume_up(self, channel):

        volume = int(self.get_status()['volume'])
        self.set_volume(min(volume + 10, 100))

    def volume_down(self, channel):
        self.player.volume_down()

        volume = int(self.get_status()['volume'])
        self.set_volume(max(volume - 10, 0))

    def set_volume(self, volume):
        """Set the volume on the MPD client"""

        with self.mpd_client:
            self.mpd_client.setvol(volume)
            print "volume set to %d" % volume

    def stop(self):
        """On stopping, reset the current playback and stop and clear the playlist

        In contract to pausing, stopping is actually meant to completely stop playing
        the current book and start listening to another"""

        self.playing = False
        self.book.reset()

        with self.mpd_client:
            self.mpd_client.stop()
            self.mpd_client.clear()

    def play(self, book_id, progress=None):
        """Play the book as defined in self.book

        1. Get the parts from the current book and add them to the playlsit
        2. Start playing the playlist
        3. Immediately set the position the last know position to resume playback where
           we last left off"""

        with self.mpd_client:
            self.mpd_client.clear()

            parts = self.mpd_client.search('filename', book_id)

            if not parts:
                print "Unused book id: %d" % book_id
                return

            for part in parts:
                self.mpd_client.add(part['file'])

            self.mpd_client.play()

            self.book.book_id = book_id

            if progress:
                # resume at last known position
                self.book.set_progress(progress)
                self.mpd_client.seek(int(self.book.part) - 1, int(self.book.elapsed))

    def is_playing(self):
        return self.get_status()['state'] == 'play'

    def get_status(self):
        with self.mpd_client:
            return self.mpd_client.status()

    def close(self):
        self.stop()
        self.mpd_client.close()
        self.mpd_client.disconnect()
<|endoftext|>


<commit_before>
class Player:
    VERSION = "We're kicking your ass!"
    name = "weneverwonanything"
    stack = 0
    current_bid = 0
    player = True
    bet = 0
    hand = True
    good_cards = ["10", "J", "Q", "K", "A"]
    counter = 0
    common_cards = []
    suit = False

    def get_info(self, gs):
        self.current_bid = gs.get("current_buy_in")
        players = gs.get("players")
        self.player = players[gs.get("in_action")]
        self.stack = self.player.get("stack")
        self.bet = self.player.get("bet")
        self.hand = self.player.get("hole_cards")
        self.common_cards = gs.get("community_cards")
        self.suit = self.hand[0]["suit"] == self.hand[1]["suit"]
        pass

    def betRequest(self, gs):
        self.get_info(gs)
        while(self.counter == 0):
            if self.hand[0]["rank"] in self.good_cards:
                if self.hand[0]["rank"] == self.hand[1]["rank"]:
                    self.counter += 1
                    return 200
            if self.hand[1]["rank"] in self.good_cards:
                self.counter += 1
                return 10
            return 0
        if self.hand[0]["rank"] in self.good_cards and self.hand[1]["rank"] in self.good_cards:
            if len(self.common_cards) == 0:
                return 20
        if len(self.common_cards) >= 3:
            flush_checker = self.check_flush()
            if flush_checker is not False:
                return flush_checker
            if self.hand[0]["rank"] in self.common_cards.values() and self.hand[1]["rank"] in self.common_cards.values():
                return self.current_bid - self.bet
            if self.hand[0]["rank"] in self.common_cards.values() or self.hand[1]["rank"] in self.common_cards.values():
                if self.hand[0]["rank"] == self.hand[1]["rank"]:
                    return 1000
                for i in range(len(self.common_cards)):  # drill
                    for j in range(len(self.common_cards) - 1):
                        if i != j+1:
                            if self.common_cards[i].get("rank") == self.common_cards[j+1].get("rank"):
                                return 1000
                return 100
            return 0
        return 0

    def showdown(self, game_state):
        pass

    def check_flush(self):
        flush_counter = 2
        for i in range(len(self.common_cards)):
            if self.suit == self.common_cards[i].get("suit"):
                flush_counter += 1
        if len(self.common_cards) == 3:
            if flush_counter == 4:
                return 50
            if flush_counter == 5:
                return 1000
            if len(self.common_cards) == 4:
                if flush_counter == 4:
                    return 50
                if flush_counter == 5:
                    return 1000
            if len(self.common_cards) == 5:
                if flush_counter == 5:
                    return 1000
        return False
<commit_msg>add flush checker<commit_after>
class Player:
    VERSION = "We're kicking your ass!"
    name = "weneverwonanything"
    stack = 0
    current_bid = 0
    player = True
    bet = 0
    hand = True
    good_cards = ["10", "J", "Q", "K", "A"]
    counter = 0
    common_cards = []
    suit = False

    def get_info(self, gs):
        self.current_bid = gs.get("current_buy_in")
        players = gs.get("players")
        self.player = players[gs.get("in_action")]
        self.stack = self.player.get("stack")
        self.bet = self.player.get("bet")
        self.hand = self.player.get("hole_cards")
        self.common_cards = gs.get("community_cards")
        self.suit = self.hand[0]["suit"] == self.hand[1]["suit"]
        pass

    def betRequest(self, gs):
        self.get_info(gs)
        while(self.counter == 0):
            if self.hand[0]["rank"] in self.good_cards:
                if self.hand[0]["rank"] == self.hand[1]["rank"]:
                    self.counter += 1
                    return self.current_bid - self.bet
            if self.hand[1]["rank"] in self.good_cards:
                self.counter += 1
                return self.current_bid - self.bet
            return 0
        if self.hand[0]["rank"] in self.good_cards and self.hand[1]["rank"] in self.good_cards:
            if len(self.common_cards) == 0:
                return 20
        if len(self.common_cards) >= 3:
            flush_checker = self.check_flush()
            if flush_checker is not False:
                return flush_checker
            if self.hand[0]["rank"] in self.common_cards.values() and self.hand[1]["rank"] in self.common_cards.values():
                return self.current_bid - self.bet
            if self.hand[0]["rank"] in self.common_cards.values() or self.hand[1]["rank"] in self.common_cards.values():
                if self.hand[0]["rank"] == self.hand[1]["rank"]:
                    return 1000
                for i in range(len(self.common_cards)):  # drill
                    for j in range(len(self.common_cards) - 1):
                        if i != j+1:
                            if self.common_cards[i].get("rank") == self.common_cards[j+1].get("rank"):
                                return 1000
                return 100
            return 0
        return 0

    def showdown(self, game_state):
        pass

    def check_flush(self):
        flush_counter = 2
        for i in range(len(self.common_cards)):
            if self.suit == self.common_cards[i].get("suit"):
                flush_counter += 1
        if len(self.common_cards) == 3:
            if flush_counter == 4:
                return 50
            if flush_counter == 5:
                return 1000
            if len(self.common_cards) == 4:
                if flush_counter == 4:
                    return 50
                if flush_counter == 5:
                    return 1000
            if len(self.common_cards) == 5:
                if flush_counter == 5:
                    return 1000
        return False
<|endoftext|>


<commit_before>import pprint
from utils import getHandPower

class Player:
    VERSION = "Default Python folding player"

    def get_hand(self, game_state):
        player = [elem['hole_cards'] for elem in game_state['players'] if elem['version'] == self.VERSION]
        return player

    def bets_per_round(self, game_state):
        bets = [(elem['name'], elem['bet']) for elem in game_state['players']]
        return bets

    def get_community_card(self, game_state):
        return game_state["community_cards"]

    def get_active_players(self, game_state):
        active_players = [1 for elem in game_state['players'] if elem['status'] == 'active']
        return sum(active_players)

    def betRequest(self, game_state):
        print("#######################################")
        print("#######################################")
        print("                 GAME STATE                       ")
        pprint.pprint(game_state, width=1)
        print("#######################################")
        print("#######################################")
        print("                 PLAYER BETS                       ")
        bets = self.bets_per_round(game_state)
        pprint.pprint(bets, width=1)
        print("#######################################")
        print("#######################################")
        hand = self.get_hand(game_state)
        community_cards = self.get_community_card(game_state)
        hand_power = getHandPower(hand)

        if hand_power >= 35:
            bet = 9999
        elif hand_power >= 21:
            bet = 300
        elif hand_power >= 19:
            bet = 200
        elif hand_power > 10:
            bet = 0
        else:
            bet = 0

        bet = 0
        if hand_power >= 40:
            bet = 9999

        print("#######################################")
        print("                 OUR HAND                       ")
        print(hand)
        print("#######################################")
        print("#######################################")
        print("                 COMMUNITY CARDS                ")
        print(community_cards)
        print("#######################################")
        print("#######################################")
        print("                 HAND POWER                      ")
        print(hand_power)
        print("#######################################")
        print("#######################################")
        print("                 OUR BET               ")
        print(bet)
        return bet

    def get_winner_stats(self, game_state):
        winner = [{'winner': elem} for elem in game_state['players'] if elem['status'] == 'active']
        try:
            winner_hand = winner[0]['hole_cards']
            winner_hand_power = getHandPower(winner_hand)
        except:
            winner_hand = 'COULD NOT FOUND'
            winner_hand_power = 'COULD NOT FOUND'
        return {'winner': winner[0]['name'],
                'hand': winner_hand,
                'hand_power': winner_hand_power}

    def showdown(self, game_state):
        winner_stats = self.get_winner_stats(game_state)
        print("#######################################")
        print("#######################################")
        print("                 PLAYERS ON SHOWDOWN            ")
        pprint.pprint(game_state['players'])
        print("#######################################")
        print("#######################################")
        print("            COMMUNITY CARDS IN SHOWDOWN         ")
        print(self.get_community_card(game_state))
        print("#######################################")
        print("#######################################")
        print("                WINNER STATS                          ")
        pprint.pprint(winner_stats, width=1)
        print("#######################################")
        print("#######################################")

<commit_msg>revert stats<commit_after>import pprint
from utils import getHandPower

class Player:
    VERSION = "Default Python folding player"

    def get_hand(self, game_state):
        player = [elem['hole_cards'] for elem in game_state['players'] if elem['version'] == self.VERSION]
        return player

    def bets_per_round(self, game_state):
        bets = [(elem['name'], elem['bet']) for elem in game_state['players']]
        return bets

    def get_community_card(self, game_state):
        return game_state["community_cards"]

    def get_active_players(self, game_state):
        active_players = [1 for elem in game_state['players'] if elem['status'] == 'active']
        return sum(active_players)

    def betRequest(self, game_state):
        print("#######################################")
        print("#######################################")
        print("                 GAME STATE                       ")
        pprint.pprint(game_state, width=1)
        print("#######################################")
        print("#######################################")
        print("                 PLAYER BETS                       ")
        bets = self.bets_per_round(game_state)
        pprint.pprint(bets, width=1)
        print("#######################################")
        print("#######################################")
        hand = self.get_hand(game_state)
        community_cards = self.get_community_card(game_state)
        hand_power = getHandPower(hand)

        if hand_power >= 35:
            bet = 9999
        elif hand_power >= 21:
            bet = 300
        elif hand_power >= 19:
            bet = 200
        elif hand_power > 10:
            bet = 0
        else:
            bet = 0

        bet = 0
        if hand_power >= 40:
            bet = 9999

        print("#######################################")
        print("                 OUR HAND                       ")
        print(hand)
        print("#######################################")
        print("#######################################")
        print("                 COMMUNITY CARDS                ")
        print(community_cards)
        print("#######################################")
        print("#######################################")
        print("                 HAND POWER                      ")
        print(hand_power)
        print("#######################################")
        print("#######################################")
        print("                 OUR BET               ")
        print(bet)
        return bet

    def get_winner_stats(self, game_state):
        winner = [{'winner': elem} for elem in game_state['players'] if elem['status'] == 'active']
        try:
            winner_hand = winner[0]['hole_cards']
            winner_hand_power = getHandPower(winner_hand)
        except:
            winner_hand = 'COULD NOT FOUND'
            winner_hand_power = 'COULD NOT FOUND'
        return {'winner': winner[0]['name'],
                'hand': winner_hand,
                'hand_power': winner_hand_power}

    def showdown(self, game_state):
        # winner_stats = self.get_winner_stats(game_state)
        print("#######################################")
        print("#######################################")
        print("                 PLAYERS ON SHOWDOWN            ")
        pprint.pprint(game_state['players'])
        print("#######################################")
        print("#######################################")
        print("            COMMUNITY CARDS IN SHOWDOWN         ")
        print(self.get_community_card(game_state))
        print("#######################################")
        print("#######################################")
        print("                WINNER STATS                          ")
        # pprint.pprint(winner_stats, width=1)
        # print("#######################################")
        # print("#######################################")

<|endoftext|>


<commit_before>import json

game_state = {
    "tournament_id":"550d1d68cd7bd10003000003",     # Id of the current tournament

    "game_id":"550da1cb2d909006e90004b1",           # Id of the current sit'n'go game. You can use this to link a
                                                    # sequence of game states together for logging purposes, or to
                                                    # make sure that the same strategy is played for an entire game

    "round":0,                                      # Index of the current round within a sit'n'go

    "bet_index":0,                                  # Index of the betting opportunity within a round

    "small_blind": 10,                              # The small blind in the current round. The big blind is twice the
                                                    #     small blind

    "current_buy_in": 80,                          # The amount of the largest current bet from any one player

    "pot": 400,                                     # The size of the pot (sum of the player bets)

    "minimum_raise": 240,                           # Minimum raise amount. To raise you have to return at least:
                                                    #     current_buy_in - players[in_action][bet] + minimum_raise

    "dealer": 1,                                    # The index of the player on the dealer button in this round
                                                    #     The first player is (dealer+1)%(players.length)

    "orbits": 7,                                    # Number of orbits completed. (The number of times the dealer
                                                    #     button returned to the same player.)

    "in_action": 1,                                 # The index of your player, in the players array

    "players": [                                    # An array of the players. The order stays the same during the
        {                                           #     entire tournament

            "id": 0,                                # Id of the player (same as the index)

            "name": "Albert",                       # Name specified in the tournament config

            "status": "active",                     # Status of the player:
                                                    #   - active: the player can make bets, and win the current pot
                                                    #   - folded: the player folded, and gave up interest in
                                                    #       the current pot. They can return in the next round.
                                                    #   - out: the player lost all chips, and is out of this sit'n'go

            "version": "Default random player",     # Version identifier returned by the player

            "stack": 1010,                          # Amount of chips still available for the player. (Not including
                                                    #     the chips the player bet in this round.)

            "bet": 0                              # The amount of chips the player put into the pot
        },
        {
            "id": 1,                                # Your own player looks similar, with one extension.
            "name": "Fishes",
            "status": "active",
            "version": "Default random player",
            "stack": 1590,
            "bet": 80,
            "hole_cards": [                         # The cards of the player. This is only visible for your own player
                                                    #     except after showdown, when cards revealed are also included.
                {
                    "rank": "A",                    # Rank of the card. Possible values are numbers 2-10 and J,Q,K,A
                    "suit": "hearts"                # Suit of the card. Possible values are: clubs,spades,hearts,diamonds
                },
                {
                    "rank": "A",
                    "suit": "spades"
                }
            ]
        },
        {
            "id": 2,
            "name": "Chuck",
            "status": "out",
            "version": "Default random player",
            "stack": 0,
            "bet": 0
        }
    ],
    "community_cards": [                            # Finally the array of community cards.
        {
            "rank": "10",
            "suit": "spades"
        },
        {
            "rank": "10",
            "suit": "hearts"
        },
        {
            "rank": "10",
            "suit": "clubs"
        }
    ]
}

class Player:
    VERSION = "Leanear Snakes"

    def get_own_cards(self, game_state):
        for player in game_state['players']:
            try:
                return player['hole_cards']
                break;
            except KeyError:
                pass

    def betRequest(self, game_state):
        self.own_cards = self.get_own_cards(game_state)
        print(self.own_cards)
        return 10000

    def showdown(self, game_state):
        pass

player = Player()
print(player.betRequest(game_state))
<commit_msg>saving community cards<commit_after>import json

game_state = {
    "tournament_id":"550d1d68cd7bd10003000003",     # Id of the current tournament

    "game_id":"550da1cb2d909006e90004b1",           # Id of the current sit'n'go game. You can use this to link a
                                                    # sequence of game states together for logging purposes, or to
                                                    # make sure that the same strategy is played for an entire game

    "round":0,                                      # Index of the current round within a sit'n'go

    "bet_index":0,                                  # Index of the betting opportunity within a round

    "small_blind": 10,                              # The small blind in the current round. The big blind is twice the
                                                    #     small blind

    "current_buy_in": 80,                          # The amount of the largest current bet from any one player

    "pot": 400,                                     # The size of the pot (sum of the player bets)

    "minimum_raise": 240,                           # Minimum raise amount. To raise you have to return at least:
                                                    #     current_buy_in - players[in_action][bet] + minimum_raise

    "dealer": 1,                                    # The index of the player on the dealer button in this round
                                                    #     The first player is (dealer+1)%(players.length)

    "orbits": 7,                                    # Number of orbits completed. (The number of times the dealer
                                                    #     button returned to the same player.)

    "in_action": 1,                                 # The index of your player, in the players array

    "players": [                                    # An array of the players. The order stays the same during the
        {                                           #     entire tournament

            "id": 0,                                # Id of the player (same as the index)

            "name": "Albert",                       # Name specified in the tournament config

            "status": "active",                     # Status of the player:
                                                    #   - active: the player can make bets, and win the current pot
                                                    #   - folded: the player folded, and gave up interest in
                                                    #       the current pot. They can return in the next round.
                                                    #   - out: the player lost all chips, and is out of this sit'n'go

            "version": "Default random player",     # Version identifier returned by the player

            "stack": 1010,                          # Amount of chips still available for the player. (Not including
                                                    #     the chips the player bet in this round.)

            "bet": 0                              # The amount of chips the player put into the pot
        },
        {
            "id": 1,                                # Your own player looks similar, with one extension.
            "name": "Fishes",
            "status": "active",
            "version": "Default random player",
            "stack": 1590,
            "bet": 80,
            "hole_cards": [                         # The cards of the player. This is only visible for your own player
                                                    #     except after showdown, when cards revealed are also included.
                {
                    "rank": "A",                    # Rank of the card. Possible values are numbers 2-10 and J,Q,K,A
                    "suit": "hearts"                # Suit of the card. Possible values are: clubs,spades,hearts,diamonds
                },
                {
                    "rank": "A",
                    "suit": "spades"
                }
            ]
        },
        {
            "id": 2,
            "name": "Chuck",
            "status": "out",
            "version": "Default random player",
            "stack": 0,
            "bet": 0
        }
    ],
    "community_cards": [                            # Finally the array of community cards.
        {
            "rank": "10",
            "suit": "spades"
        },
        {
            "rank": "10",
            "suit": "hearts"
        },
        {
            "rank": "10",
            "suit": "clubs"
        }
    ]
}

class Player:
    VERSION = "Leanear Snakes"

    def get_own_cards(self, game_state):
        for player in game_state['players']:
            try:
                return player['hole_cards']
            except KeyError:
                pass

    def get_community_cards(self, game_state):
        return game_state['community_cards']

    def betRequest(self, game_state):
        self.own_cards = self.get_own_cards(game_state)
        self.community_cards = self.get_community_cards(game_state)
        print(self.own_cards)
        return 10000

    def showdown(self, game_state):
        pass

player = Player()
print(player.betRequest(game_state))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import logging
import threading
import time

import http_server
import netrpc_server
import web_services
import websrv_lib

import openerp.cron
import openerp.modules
import openerp.netsvc
import openerp.osv
import openerp.tools
import openerp.service.wsgi_server
import openerp.service.workers

#.apidoc title: RPC Services

""" Classes of this module implement the network protocols that the
    OpenERP server uses to communicate with remote clients.

    Some classes are mostly utilities, whose API need not be visible to
    the average user/developer. Study them only if you are about to
    implement an extension to the network protocols, or need to debug some
    low-level behavior of the wire.
"""

_logger = logging.getLogger(__name__)

def load_server_wide_modules():
    for m in openerp.conf.server_wide_modules:
        try:
            openerp.modules.module.load_openerp_module(m)
        except Exception:
            msg = ''
            if m == 'web':
                msg = """
The `web` module is provided by the addons found in the `openerp-web` project.
Maybe you forgot to add those addons in your addons_path configuration."""
            _logger.exception('Failed to load server-wide module `%s`.%s', m, msg)

start_internal_done = False

def start_internal():
    global start_internal_done
    if start_internal_done:
        return
    openerp.netsvc.init_logger()
    openerp.modules.loading.open_openerp_namespace()
    # Instantiate local services (this is a legacy design).
    openerp.osv.osv.start_object_proxy()
    # Export (for RPC) services.
    web_services.start_web_services()
    load_server_wide_modules()
    start_internal_done = True

def start_services():
    """ Start all services including http, netrpc and cron """
    start_internal()

    # Initialize the HTTP stack.
    netrpc_server.init_servers()

    # Start the main cron thread.
    openerp.cron.start_master_thread()

    # Start the top-level servers threads (normally HTTP, HTTPS, and NETRPC).
    openerp.netsvc.Server.startAll()

    # Start the WSGI server.
    openerp.service.wsgi_server.start_server()

def stop_services():
    """ Stop all services. """
    # stop scheduling new jobs; we will have to wait for the jobs to complete below
    openerp.cron.cancel_all()

    openerp.netsvc.Server.quitAll()
    openerp.service.wsgi_server.stop_server()
    config = openerp.tools.config
    _logger.info("Initiating shutdown")
    _logger.info("Hit CTRL-C again or send a second signal to force the shutdown.")
    logging.shutdown()

    # Manually join() all threads before calling sys.exit() to allow a second signal
    # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
    # threading.Thread.join() should not mask signals (at least in python 2.5).
    for thread in threading.enumerate():
        if thread != threading.currentThread() and not thread.isDaemon():
            while thread.isAlive():
                # Need a busyloop here as thread.join() masks signals
                # and would prevent the forced shutdown.
                thread.join(0.05)
                time.sleep(0.05)

    openerp.modules.registry.RegistryManager.delete_all()

def start_services_workers():
    openerp.multi_process = True # Nah!

    openerp.service.workers.Multicorn(openerp.service.wsgi_server.application).run()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

<commit_msg>[IMP] Do not start cron master thread if max_cron_threads == 0<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import logging
import threading
import time

import http_server
import netrpc_server
import web_services
import websrv_lib

import openerp.cron
import openerp.modules
import openerp.netsvc
import openerp.osv
import openerp.tools
import openerp.service.wsgi_server
import openerp.service.workers

#.apidoc title: RPC Services

""" Classes of this module implement the network protocols that the
    OpenERP server uses to communicate with remote clients.

    Some classes are mostly utilities, whose API need not be visible to
    the average user/developer. Study them only if you are about to
    implement an extension to the network protocols, or need to debug some
    low-level behavior of the wire.
"""

_logger = logging.getLogger(__name__)

def load_server_wide_modules():
    for m in openerp.conf.server_wide_modules:
        try:
            openerp.modules.module.load_openerp_module(m)
        except Exception:
            msg = ''
            if m == 'web':
                msg = """
The `web` module is provided by the addons found in the `openerp-web` project.
Maybe you forgot to add those addons in your addons_path configuration."""
            _logger.exception('Failed to load server-wide module `%s`.%s', m, msg)

start_internal_done = False

def start_internal():
    global start_internal_done
    if start_internal_done:
        return
    openerp.netsvc.init_logger()
    openerp.modules.loading.open_openerp_namespace()
    # Instantiate local services (this is a legacy design).
    openerp.osv.osv.start_object_proxy()
    # Export (for RPC) services.
    web_services.start_web_services()
    load_server_wide_modules()
    start_internal_done = True

def start_services():
    """ Start all services including http, netrpc and cron """
    start_internal()

    # Initialize the HTTP stack.
    netrpc_server.init_servers()

    # Start the main cron thread.
    if openerp.conf.max_cron_threads:
        openerp.cron.start_master_thread()

    # Start the top-level servers threads (normally HTTP, HTTPS, and NETRPC).
    openerp.netsvc.Server.startAll()

    # Start the WSGI server.
    openerp.service.wsgi_server.start_server()

def stop_services():
    """ Stop all services. """
    # stop scheduling new jobs; we will have to wait for the jobs to complete below
    openerp.cron.cancel_all()

    openerp.netsvc.Server.quitAll()
    openerp.service.wsgi_server.stop_server()
    config = openerp.tools.config
    _logger.info("Initiating shutdown")
    _logger.info("Hit CTRL-C again or send a second signal to force the shutdown.")
    logging.shutdown()

    # Manually join() all threads before calling sys.exit() to allow a second signal
    # to trigger _force_quit() in case some non-daemon threads won't exit cleanly.
    # threading.Thread.join() should not mask signals (at least in python 2.5).
    for thread in threading.enumerate():
        if thread != threading.currentThread() and not thread.isDaemon():
            while thread.isAlive():
                # Need a busyloop here as thread.join() masks signals
                # and would prevent the forced shutdown.
                thread.join(0.05)
                time.sleep(0.05)

    openerp.modules.registry.RegistryManager.delete_all()

def start_services_workers():
    openerp.multi_process = True # Nah!

    openerp.service.workers.Multicorn(openerp.service.wsgi_server.application).run()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

<|endoftext|>


<commit_before>"""
Force10 Backend.

This backend will only work with SSH version 2 capable Force10 switches.

This excludes most, if not all, of the etherscale series.

The backend has been developed for the E series.
The backend has been developed and tested on a Terascale E300 switch.

The switch (or router, depending on your level off pedanticness) is configured
by the backend logging via ssh, requesting a cli, and firing the necessary
command for configuring a VLAN. This approach was choosen over netconf / XML,
as a fairly reliable source said that not all the necessary functionality
needed was available via the previously mentioned interfaces.

Currently the backend does support VLAN rewriting, and I am not sure if/how it
is supported.

Configuration:

To setup a VLAN connection:

configure
interface vlan $vlan_id
name $name
description $description
no shut
tagged $source_port
tagged $dest_port
end

Teardown:

configure
no interface vlan $vlan_id
end

Ensure that the interfaces are configure to be layer 2.

Ralph developed a backend for etherscale, where a lot of the input from this
backend comes from.

Authors: Henrik Thostrup Jensen <htj@nordu.net>
         Ralph Koning <R.Koning@uva.nl>

Copyright: NORDUnet (2011-2012)
"""

from twisted.python import log
from twisted.internet import defer

from opennsa import error, config
from opennsa.backends.common import calendar as reservationcalendar, simplebackend, ssh

LOG_SYSTEM = 'opennsa.force10'

COMMAND_CONFIGURE       = 'configure'
COMMAND_END             = 'end'
COMMAND_EXIT            = 'exit'
COMMAND_WRITE           = 'write'       # writes config

COMMAND_INTERFACE_VLAN  = 'interface vlan %(vlan)i'
COMMAND_NAME            = 'name %(name)s'
COMMAND_NO_SHUTDOWN     = 'no shutdown'
COMMAND_TAGGED          = 'tagged %(interface)s'

COMMAND_NO_INTERFACE    = 'no interface vlan %(vlan)i'

def _portToInterfaceVLAN(nrm_port):

    interface, vlan = nrm_port.rsplit('.')
    vlan = int(vlan)
    return interface, vlan

def _createSetupCommands(source_nrm_port, dest_nrm_port):

    s_interface, s_vlan = _portToInterfaceVLAN(source_nrm_port)
    d_interface, d_vlan = _portToInterfaceVLAN(dest_nrm_port)

    assert s_vlan == d_vlan, 'Source and destination VLANs differ, unpossible!'

    name = 'opennsa-%i' % s_vlan

    cmd_vlan    = COMMAND_INTERFACE_VLAN    % { 'vlan' : s_vlan }
    cmd_name    = COMMAND_NAME              % { 'name' : name   }
    cmd_s_intf  = COMMAND_TAGGED            % { 'interface' : s_interface }
    cmd_d_intf  = COMMAND_TAGGED            % { 'interface' : d_interface }

    commands = [ cmd_vlan, cmd_name, cmd_s_intf, cmd_d_intf, COMMAND_NO_SHUTDOWN, COMMAND_END ]
    return commands

def _createTeardownCommands(source_nrm_port, dest_nrm_port):

    _, s_vlan = _portToInterfaceVLAN(source_nrm_port)
    _, d_vlan = _portToInterfaceVLAN(dest_nrm_port)

    assert s_vlan == d_vlan, 'Source and destination VLANs differ, unpossible!'

    cmd_no_intf = COMMAND_NO_INTERFACE % { 'vlan' : s_vlan }

    commands = [ cmd_no_intf, COMMAND_END ]
    return commands

class SSHChannel(ssh.SSHChannel):

    name = 'session'

    def __init__(self, conn):
        ssh.SSHChannel.__init__(self, conn=conn)

        self.data = ''

        self.wait_defer = None
        self.wait_data  = None

    @defer.inlineCallbacks
    def sendCommands(self, commands):
        LT = '\r' # line termination

        try:
            log.msg('Requesting shell for sending commands', debug=True, system=LOG_SYSTEM)
            yield self.conn.sendRequest(self, 'shell', '', wantReply=1)

            d = self.waitForData('#')
            self.write(COMMAND_CONFIGURE + LT)
            yield d
            log.msg('Entered configure mode', debug=True, system=LOG_SYSTEM)

            for cmd in commands:
                log.msg('CMD> %s' % cmd, debug=True, system=LOG_SYSTEM)
                d = self.waitForData('#')
                self.write(cmd + LT)
                yield d

            # not quite sure how to handle failure here
            log.msg('Commands send, sending end command.', debug=True, system=LOG_SYSTEM)
            d = self.waitForData('#')
            self.write(COMMAND_END + LT)
            yield d

            log.msg('Configuration done, writing configuration.', debug=True, system=LOG_SYSTEM)
            d = self.waitForData('#')
            self.write(COMMAND_WRITE + LT)
            yield d

        log.msg('Configuration written. Exiting.', debug=True, system=LOG_SYSTEM)
            d = self.waitForData('#')
            self.write(COMMAND_EXIT + LT)
            yield d

        except Exception, e:
            log.msg('Error sending commands: %s' % str(e))
            raise e

        log.msg('Commands successfully send', system=LOG_SYSTEM)
        self.sendEOF()
        self.closeIt()

    def waitForData(self, data):
        self.wait_data  = data
        self.wait_defer = defer.Deferred()
        return self.wait_defer

    def dataReceived(self, data):
        if len(data) == 0:
            pass
        else:
            self.data += data
            if self.wait_data and self.wait_data in self.data:
                d = self.wait_defer
                self.data       = ''
                self.wait_data  = None
                self.wait_defer = None
                d.callback(self)

class Force10CommandSender:

    def __init__(self, host, port, ssh_host_fingerprint, user, ssh_public_key_path, ssh_private_key_path):

        self.ssh_connection_creator = \
             ssh.SSHConnectionCreator(host, port, [ ssh_host_fingerprint ], user, ssh_public_key_path, ssh_private_key_path)

    @defer.inlineCallbacks
    def _sendCommands(self, commands):

        # Note: FTOS does not allow multiple channels in an SSH connection,
        # so we open a connection for each request. Party like it is 1988.

        # The "correct" solution for this would be to create a connection pool,
        # but that won't happen just now.

        log.msg('Creating new SSH connection', debug=True, system=LOG_SYSTEM)
        ssh_connection = yield self.ssh_connection_creator.getSSHConnection()

        try:
            channel = SSHChannel(conn=ssh_connection)
            ssh_connection.openChannel(channel)

            yield channel.channel_open
            yield channel.sendCommands(commands)

        finally:
            ssh_connection.transport.loseConnection()

    def setupLink(self, source_nrm_port, dest_nrm_port):

        log.msg('Setting up link: %s-%s' % (source_nrm_port, dest_nrm_port), debug=True, system=LOG_SYSTEM)
        commands = _createSetupCommands(source_nrm_port, dest_nrm_port)
        return self._sendCommands(commands)

    def teardownLink(self, source_nrm_port, dest_nrm_port):

        log.msg('Tearing down link: %s-%s' % (source_nrm_port, dest_nrm_port), debug=True, system=LOG_SYSTEM)
        commands = _createTeardownCommands(source_nrm_port, dest_nrm_port)
        return self._sendCommands(commands)

class Force10Backend:

    def __init__(self, network_name, configuration):
        self.network_name = network_name
        self.calendar = reservationcalendar.ReservationCalendar()

        # extract config items
        cfg_dict = dict(configuration)

        host             = cfg_dict[config.FORCE10_HOST]
        port             = cfg_dict.get(config.FORCE10_PORT, 22)
        host_fingerprint = cfg_dict[config.FORCE10_HOST_FINGERPRINT]
        user             = cfg_dict[config.FORCE10_USER]
        ssh_public_key   = cfg_dict[config.FORCE10_SSH_PUBLIC_KEY]
        ssh_private_key  = cfg_dict[config.FORCE10_SSH_PRIVATE_KEY]

        self.command_sender = Force10CommandSender(host, port, host_fingerprint, user, ssh_public_key, ssh_private_key)

    def createConnection(self, source_nrm_port, dest_nrm_port, service_parameters):

        self._checkVLANMatch(source_nrm_port, dest_nrm_port)

        # probably need a short hand for this
        self.calendar.checkReservation(source_nrm_port, service_parameters.start_time, service_parameters.end_time)
        self.calendar.checkReservation(dest_nrm_port  , service_parameters.start_time, service_parameters.end_time)

        self.calendar.addConnection(source_nrm_port, service_parameters.start_time, service_parameters.end_time)
        self.calendar.addConnection(dest_nrm_port  , service_parameters.start_time, service_parameters.end_time)

        c = simplebackend.GenericConnection(source_nrm_port, dest_nrm_port, service_parameters, self.network_name, self.calendar,
                                            'Force10 NRM', LOG_SYSTEM, self.command_sender)
        return c

    def _checkVLANMatch(self, source_nrm_port, dest_nrm_port):
        source_vlan = source_nrm_port.split('.')[-1]
        dest_vlan = dest_nrm_port.split('.')[-1]
        if source_vlan != dest_vlan:
            raise error.InvalidRequestError('Cannot create connection between different VLANs (%s/%s).' % (source_vlan, dest_vlan) )

<commit_msg>fix indention error in force10 backend<commit_after>"""
Force10 Backend.

This backend will only work with SSH version 2 capable Force10 switches.

This excludes most, if not all, of the etherscale series.

The backend has been developed for the E series.
The backend has been developed and tested on a Terascale E300 switch.

The switch (or router, depending on your level off pedanticness) is configured
by the backend logging via ssh, requesting a cli, and firing the necessary
command for configuring a VLAN. This approach was choosen over netconf / XML,
as a fairly reliable source said that not all the necessary functionality
needed was available via the previously mentioned interfaces.

Currently the backend does support VLAN rewriting, and I am not sure if/how it
is supported.

Configuration:

To setup a VLAN connection:

configure
interface vlan $vlan_id
name $name
description $description
no shut
tagged $source_port
tagged $dest_port
end

Teardown:

configure
no interface vlan $vlan_id
end

Ensure that the interfaces are configure to be layer 2.

Ralph developed a backend for etherscale, where a lot of the input from this
backend comes from.

Authors: Henrik Thostrup Jensen <htj@nordu.net>
         Ralph Koning <R.Koning@uva.nl>

Copyright: NORDUnet (2011-2012)
"""

from twisted.python import log
from twisted.internet import defer

from opennsa import error, config
from opennsa.backends.common import calendar as reservationcalendar, simplebackend, ssh

LOG_SYSTEM = 'opennsa.force10'

COMMAND_CONFIGURE       = 'configure'
COMMAND_END             = 'end'
COMMAND_EXIT            = 'exit'
COMMAND_WRITE           = 'write'       # writes config

COMMAND_INTERFACE_VLAN  = 'interface vlan %(vlan)i'
COMMAND_NAME            = 'name %(name)s'
COMMAND_NO_SHUTDOWN     = 'no shutdown'
COMMAND_TAGGED          = 'tagged %(interface)s'

COMMAND_NO_INTERFACE    = 'no interface vlan %(vlan)i'

def _portToInterfaceVLAN(nrm_port):

    interface, vlan = nrm_port.rsplit('.')
    vlan = int(vlan)
    return interface, vlan

def _createSetupCommands(source_nrm_port, dest_nrm_port):

    s_interface, s_vlan = _portToInterfaceVLAN(source_nrm_port)
    d_interface, d_vlan = _portToInterfaceVLAN(dest_nrm_port)

    assert s_vlan == d_vlan, 'Source and destination VLANs differ, unpossible!'

    name = 'opennsa-%i' % s_vlan

    cmd_vlan    = COMMAND_INTERFACE_VLAN    % { 'vlan' : s_vlan }
    cmd_name    = COMMAND_NAME              % { 'name' : name   }
    cmd_s_intf  = COMMAND_TAGGED            % { 'interface' : s_interface }
    cmd_d_intf  = COMMAND_TAGGED            % { 'interface' : d_interface }

    commands = [ cmd_vlan, cmd_name, cmd_s_intf, cmd_d_intf, COMMAND_NO_SHUTDOWN, COMMAND_END ]
    return commands

def _createTeardownCommands(source_nrm_port, dest_nrm_port):

    _, s_vlan = _portToInterfaceVLAN(source_nrm_port)
    _, d_vlan = _portToInterfaceVLAN(dest_nrm_port)

    assert s_vlan == d_vlan, 'Source and destination VLANs differ, unpossible!'

    cmd_no_intf = COMMAND_NO_INTERFACE % { 'vlan' : s_vlan }

    commands = [ cmd_no_intf, COMMAND_END ]
    return commands

class SSHChannel(ssh.SSHChannel):

    name = 'session'

    def __init__(self, conn):
        ssh.SSHChannel.__init__(self, conn=conn)

        self.data = ''

        self.wait_defer = None
        self.wait_data  = None

    @defer.inlineCallbacks
    def sendCommands(self, commands):
        LT = '\r' # line termination

        try:
            log.msg('Requesting shell for sending commands', debug=True, system=LOG_SYSTEM)
            yield self.conn.sendRequest(self, 'shell', '', wantReply=1)

            d = self.waitForData('#')
            self.write(COMMAND_CONFIGURE + LT)
            yield d
            log.msg('Entered configure mode', debug=True, system=LOG_SYSTEM)

            for cmd in commands:
                log.msg('CMD> %s' % cmd, debug=True, system=LOG_SYSTEM)
                d = self.waitForData('#')
                self.write(cmd + LT)
                yield d

            # not quite sure how to handle failure here
            log.msg('Commands send, sending end command.', debug=True, system=LOG_SYSTEM)
            d = self.waitForData('#')
            self.write(COMMAND_END + LT)
            yield d

            log.msg('Configuration done, writing configuration.', debug=True, system=LOG_SYSTEM)
            d = self.waitForData('#')
            self.write(COMMAND_WRITE + LT)
            yield d

            log.msg('Configuration written. Exiting.', debug=True, system=LOG_SYSTEM)
            d = self.waitForData('#')
            self.write(COMMAND_EXIT + LT)
            yield d

        except Exception, e:
            log.msg('Error sending commands: %s' % str(e))
            raise e

        log.msg('Commands successfully send', system=LOG_SYSTEM)
        self.sendEOF()
        self.closeIt()

    def waitForData(self, data):
        self.wait_data  = data
        self.wait_defer = defer.Deferred()
        return self.wait_defer

    def dataReceived(self, data):
        if len(data) == 0:
            pass
        else:
            self.data += data
            if self.wait_data and self.wait_data in self.data:
                d = self.wait_defer
                self.data       = ''
                self.wait_data  = None
                self.wait_defer = None
                d.callback(self)

class Force10CommandSender:

    def __init__(self, host, port, ssh_host_fingerprint, user, ssh_public_key_path, ssh_private_key_path):

        self.ssh_connection_creator = \
             ssh.SSHConnectionCreator(host, port, [ ssh_host_fingerprint ], user, ssh_public_key_path, ssh_private_key_path)

    @defer.inlineCallbacks
    def _sendCommands(self, commands):

        # Note: FTOS does not allow multiple channels in an SSH connection,
        # so we open a connection for each request. Party like it is 1988.

        # The "correct" solution for this would be to create a connection pool,
        # but that won't happen just now.

        log.msg('Creating new SSH connection', debug=True, system=LOG_SYSTEM)
        ssh_connection = yield self.ssh_connection_creator.getSSHConnection()

        try:
            channel = SSHChannel(conn=ssh_connection)
            ssh_connection.openChannel(channel)

            yield channel.channel_open
            yield channel.sendCommands(commands)

        finally:
            ssh_connection.transport.loseConnection()

    def setupLink(self, source_nrm_port, dest_nrm_port):

        log.msg('Setting up link: %s-%s' % (source_nrm_port, dest_nrm_port), debug=True, system=LOG_SYSTEM)
        commands = _createSetupCommands(source_nrm_port, dest_nrm_port)
        return self._sendCommands(commands)

    def teardownLink(self, source_nrm_port, dest_nrm_port):

        log.msg('Tearing down link: %s-%s' % (source_nrm_port, dest_nrm_port), debug=True, system=LOG_SYSTEM)
        commands = _createTeardownCommands(source_nrm_port, dest_nrm_port)
        return self._sendCommands(commands)

class Force10Backend:

    def __init__(self, network_name, configuration):
        self.network_name = network_name
        self.calendar = reservationcalendar.ReservationCalendar()

        # extract config items
        cfg_dict = dict(configuration)

        host             = cfg_dict[config.FORCE10_HOST]
        port             = cfg_dict.get(config.FORCE10_PORT, 22)
        host_fingerprint = cfg_dict[config.FORCE10_HOST_FINGERPRINT]
        user             = cfg_dict[config.FORCE10_USER]
        ssh_public_key   = cfg_dict[config.FORCE10_SSH_PUBLIC_KEY]
        ssh_private_key  = cfg_dict[config.FORCE10_SSH_PRIVATE_KEY]

        self.command_sender = Force10CommandSender(host, port, host_fingerprint, user, ssh_public_key, ssh_private_key)

    def createConnection(self, source_nrm_port, dest_nrm_port, service_parameters):

        self._checkVLANMatch(source_nrm_port, dest_nrm_port)

        # probably need a short hand for this
        self.calendar.checkReservation(source_nrm_port, service_parameters.start_time, service_parameters.end_time)
        self.calendar.checkReservation(dest_nrm_port  , service_parameters.start_time, service_parameters.end_time)

        self.calendar.addConnection(source_nrm_port, service_parameters.start_time, service_parameters.end_time)
        self.calendar.addConnection(dest_nrm_port  , service_parameters.start_time, service_parameters.end_time)

        c = simplebackend.GenericConnection(source_nrm_port, dest_nrm_port, service_parameters, self.network_name, self.calendar,
                                            'Force10 NRM', LOG_SYSTEM, self.command_sender)
        return c

    def _checkVLANMatch(self, source_nrm_port, dest_nrm_port):
        source_vlan = source_nrm_port.split('.')[-1]
        dest_vlan = dest_nrm_port.split('.')[-1]
        if source_vlan != dest_vlan:
            raise error.InvalidRequestError('Cannot create connection between different VLANs (%s/%s).' % (source_vlan, dest_vlan) )

<|endoftext|>