{"class_name": "blackjack", "id": "./MultiFileTest/Python/blackjack.py", "original_code": "# ./blackjack/__init__.py\nfrom blackjack.base import Card as Card\nfrom blackjack.dealer import BlackjackDealer as Dealer\nfrom blackjack.judger import BlackjackJudger as Judger\nfrom blackjack.player import BlackjackPlayer as Player\nfrom blackjack.game import BlackjackGame as Game\n\n\n\n# ./blackjack/base.py\n''' Game-related base classes\n'''\nclass Card:\n '''\n Card stores the suit and rank of a single card\n\n Note:\n The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]\n Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]\n '''\n suit = None\n rank = None\n valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']\n valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n\n def __init__(self, suit, rank):\n ''' Initialize the suit and rank of a card\n\n Args:\n suit: string, suit of the card, should be one of valid_suit\n rank: string, rank of the card, should be one of valid_rank\n '''\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if isinstance(other, Card):\n return self.rank == other.rank and self.suit == other.suit\n else:\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n def __hash__(self):\n suit_index = Card.valid_suit.index(self.suit)\n rank_index = Card.valid_rank.index(self.rank)\n return rank_index + 100 * suit_index\n\n def __str__(self):\n ''' Get string representation of a card.\n\n Returns:\n string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...\n '''\n return self.rank + self.suit\n\n def get_index(self):\n ''' Get index of a card.\n\n Returns:\n string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...\n '''\n return self.suit+self.rank\n\n\n# ./blackjack/dealer.py\nimport numpy as np\nfrom blackjack import Card\n\ndef init_standard_deck():\n ''' Initialize a standard deck of 52 cards\n\n Returns:\n (list): A list of Card object\n '''\n suit_list = ['S', 'H', 'D', 'C']\n rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n res = [Card(suit, rank) for suit in suit_list for rank in rank_list]\n return res\n\nclass BlackjackDealer:\n\n def __init__(self, np_random, num_decks=1):\n ''' Initialize a Blackjack dealer class\n '''\n self.np_random = np_random\n self.num_decks = num_decks\n self.deck = init_standard_deck()\n if self.num_decks not in [0, 1]: # 0 indicates infinite decks of cards\n self.deck = self.deck * self.num_decks # copy m standard decks of cards\n self.shuffle()\n self.hand = []\n self.status = 'alive'\n self.score = 0\n\n def shuffle(self):\n ''' Shuffle the deck\n '''\n shuffle_deck = np.array(self.deck)\n self.np_random.shuffle(shuffle_deck)\n self.deck = list(shuffle_deck)\n\n def deal_card(self, player):\n ''' Distribute one card to the player\n\n Args:\n player_id (int): the target player's id\n '''\n idx = self.np_random.choice(len(self.deck))\n card = self.deck[idx]\n if self.num_decks != 0: # If infinite decks, do not pop card from deck\n self.deck.pop(idx)\n # card = self.deck.pop()\n player.hand.append(card)\n\n\n# ./blackjack/game.py\nfrom copy import deepcopy\nimport numpy as np\n\nfrom blackjack import Dealer\nfrom blackjack import Player\nfrom blackjack import Judger\n\nclass BlackjackGame:\n\n def __init__(self, allow_step_back=False):\n ''' Initialize the class Blackjack Game\n '''\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n\n def configure(self, game_config):\n ''' Specifiy some game specific parameters, such as number of players\n '''\n self.num_players = game_config['game_num_players']\n self.num_decks = game_config['game_num_decks']\n\n def init_game(self):\n ''' Initialilze the game\n\n Returns:\n state (dict): the first state of the game\n player_id (int): current player's id\n '''\n self.dealer = Dealer(self.np_random, self.num_decks)\n\n self.players = []\n for i in range(self.num_players):\n self.players.append(Player(i, self.np_random))\n\n self.judger = Judger(self.np_random)\n\n for i in range(2):\n for j in range(self.num_players):\n self.dealer.deal_card(self.players[j])\n self.dealer.deal_card(self.dealer)\n\n for i in range(self.num_players):\n self.players[i].status, self.players[i].score = self.judger.judge_round(self.players[i])\n\n self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer)\n\n self.winner = {'dealer': 0}\n for i in range(self.num_players):\n self.winner['player' + str(i)] = 0\n\n self.history = []\n self.game_pointer = 0\n\n return self.get_state(self.game_pointer), self.game_pointer\n\n def step(self, action):\n ''' Get the next state\n\n Args:\n action (str): a specific action of blackjack. (Hit or Stand)\n\n Returns:/\n dict: next player's state\n int: next plater's id\n '''\n if self.allow_step_back:\n p = deepcopy(self.players[self.game_pointer])\n d = deepcopy(self.dealer)\n w = deepcopy(self.winner)\n self.history.append((d, p, w))\n\n next_state = {}\n # Play hit\n if action != \"stand\":\n self.dealer.deal_card(self.players[self.game_pointer])\n self.players[self.game_pointer].status, self.players[self.game_pointer].score = self.judger.judge_round(\n self.players[self.game_pointer])\n if self.players[self.game_pointer].status == 'bust':\n # game over, set up the winner, print out dealer's hand # If bust, pass the game pointer\n if self.game_pointer >= self.num_players - 1:\n while self.judger.judge_score(self.dealer.hand) < 17:\n self.dealer.deal_card(self.dealer)\n self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer)\n for i in range(self.num_players):\n self.judger.judge_game(self, i) \n self.game_pointer = 0\n else:\n self.game_pointer += 1\n\n \n elif action == \"stand\": # If stand, first try to pass the pointer, if it's the last player, dealer deal for himself, then judge game for everyone using a loop\n self.players[self.game_pointer].status, self.players[self.game_pointer].score = self.judger.judge_round(\n self.players[self.game_pointer])\n if self.game_pointer >= self.num_players - 1:\n while self.judger.judge_score(self.dealer.hand) < 17:\n self.dealer.deal_card(self.dealer)\n self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer)\n for i in range(self.num_players):\n self.judger.judge_game(self, i) \n self.game_pointer = 0\n else:\n self.game_pointer += 1\n\n\n \n \n\n hand = [card.get_index() for card in self.players[self.game_pointer].hand]\n\n if self.is_over():\n dealer_hand = [card.get_index() for card in self.dealer.hand]\n else:\n dealer_hand = [card.get_index() for card in self.dealer.hand[1:]]\n\n for i in range(self.num_players):\n next_state['player' + str(i) + ' hand'] = [card.get_index() for card in self.players[i].hand]\n next_state['dealer hand'] = dealer_hand\n next_state['actions'] = ('hit', 'stand')\n next_state['state'] = (hand, dealer_hand)\n\n \n\n return next_state, self.game_pointer\n\n def step_back(self):\n ''' Return to the previous state of the game\n\n Returns:\n Status (bool): check if the step back is success or not\n '''\n #while len(self.history) > 0:\n if len(self.history) > 0:\n self.dealer, self.players[self.game_pointer], self.winner = self.history.pop()\n return True\n return False\n\n def get_num_players(self):\n ''' Return the number of players in blackjack\n\n Returns:\n number_of_player (int): blackjack only have 1 player\n '''\n return self.num_players\n\n @staticmethod\n def get_num_actions():\n ''' Return the number of applicable actions\n\n Returns:\n number_of_actions (int): there are only two actions (hit and stand)\n '''\n return 2\n\n def get_player_id(self):\n ''' Return the current player's id\n\n Returns:\n player_id (int): current player's id\n '''\n return self.game_pointer\n\n def get_state(self, player_id):\n ''' Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n state (dict): corresponding player's state\n '''\n '''\n before change state only have two keys (action, state)\n but now have more than 4 keys (action, state, player0 hand, player1 hand, ... , dealer hand)\n Although key 'state' have duplicated information with key 'player hand' and 'dealer hand', I couldn't remove it because of other codes\n To remove it, we need to change dqn agent too in my opinion\n '''\n state = {}\n state['actions'] = ('hit', 'stand')\n hand = [card.get_index() for card in self.players[player_id].hand]\n if self.is_over():\n dealer_hand = [card.get_index() for card in self.dealer.hand]\n else:\n dealer_hand = [card.get_index() for card in self.dealer.hand[1:]]\n\n for i in range(self.num_players):\n state['player' + str(i) + ' hand'] = [card.get_index() for card in self.players[i].hand]\n state['dealer hand'] = dealer_hand\n state['state'] = (hand, dealer_hand)\n\n return state\n\n def is_over(self):\n ''' Check if the game is over\n\n Returns:\n status (bool): True/False\n '''\n '''\n I should change here because judger and self.winner is changed too\n '''\n for i in range(self.num_players):\n if self.winner['player' + str(i)] == 0:\n return False\n\n return True\n\n\n# ./blackjack/judger.py\nclass BlackjackJudger:\n def __init__(self, np_random):\n ''' Initialize a BlackJack judger class\n '''\n self.np_random = np_random\n self.rank2score = {\"A\":11, \"2\":2, \"3\":3, \"4\":4, \"5\":5, \"6\":6, \"7\":7, \"8\":8, \"9\":9, \"T\":10, \"J\":10, \"Q\":10, \"K\":10}\n\n def judge_round(self, player):\n ''' Judge the target player's status\n\n Args:\n player (int): target player's id\n\n Returns:\n status (str): the status of the target player\n score (int): the current score of the player\n '''\n score = self.judge_score(player.hand)\n if score <= 21:\n return \"alive\", score\n else:\n return \"bust\", score\n\n def judge_game(self, game, game_pointer):\n ''' Judge the winner of the game\n\n Args:\n game (class): target game class\n '''\n '''\n game.winner['dealer'] doesn't need anymore if we change code like this\n\n player bust (whether dealer bust or not) => game.winner[playerX] = -1\n player and dealer tie => game.winner[playerX] = 1\n dealer bust and player not bust => game.winner[playerX] = 2\n player get higher score than dealer => game.winner[playerX] = 2\n dealer get higher score than player => game.winner[playerX] = -1\n game.winner[playerX] = 0 => the game is still ongoing\n '''\n\n if game.players[game_pointer].status == 'bust':\n game.winner['player' + str(game_pointer)] = -1\n elif game.dealer.status == 'bust':\n game.winner['player' + str(game_pointer)] = 2\n else:\n if game.players[game_pointer].score > game.dealer.score:\n game.winner['player' + str(game_pointer)] = 2\n elif game.players[game_pointer].score < game.dealer.score:\n game.winner['player' + str(game_pointer)] = -1\n else:\n game.winner['player' + str(game_pointer)] = 1\n\n def judge_score(self, cards):\n ''' Judge the score of a given cards set\n\n Args:\n cards (list): a list of cards\n\n Returns:\n score (int): the score of the given cards set\n '''\n score = 0\n count_a = 0\n for card in cards:\n card_score = self.rank2score[card.rank]\n score += card_score\n if card.rank == 'A':\n count_a += 1\n while score > 21 and count_a > 0:\n count_a -= 1\n score -= 10\n return score\n\n\n# ./blackjack/player.py\nclass BlackjackPlayer:\n\n def __init__(self, player_id, np_random):\n ''' Initialize a Blackjack player class\n\n Args:\n player_id (int): id for the player\n '''\n self.np_random = np_random\n self.player_id = player_id\n self.hand = []\n self.status = 'alive'\n self.score = 0\n\n def get_player_id(self):\n ''' Return player's id\n '''\n return self.player_id\n", "num_file": 6, "num_lines": 401, "programming_language": "Python"} {"class_name": "bridge", "id": "./MultiFileTest/Python/bridge.py", "original_code": "# ./bridge/__init__.py\nfrom bridge.base import Card as Card\nfrom bridge.player import BridgePlayer as Player\nfrom bridge.dealer import BridgeDealer as Dealer\nfrom bridge.judger import BridgeJudger as Judger\nfrom bridge.game import BridgeGame as Game\n\n\n\n# ./bridge/action_event.py\nfrom bridge_card import BridgeCard\n\n# ====================================\n# Action_ids:\n# 0 -> no_bid_action_id\n# 1 to 35 -> bid_action_id (bid amount by suit or NT)\n# 36 -> pass_action_id\n# 37 -> dbl_action_id\n# 38 -> rdbl_action_id\n# 39 to 90 -> play_card_action_id\n# ====================================\n\n\nclass ActionEvent(object): # Interface\n\n no_bid_action_id = 0\n first_bid_action_id = 1\n pass_action_id = 36\n dbl_action_id = 37\n rdbl_action_id = 38\n first_play_card_action_id = 39\n\n def __init__(self, action_id: int):\n self.action_id = action_id\n\n def __eq__(self, other):\n result = False\n if isinstance(other, ActionEvent):\n result = self.action_id == other.action_id\n return result\n\n @staticmethod\n def from_action_id(action_id: int):\n if action_id == ActionEvent.pass_action_id:\n return PassAction()\n elif ActionEvent.first_bid_action_id <= action_id <= 35:\n bid_amount = 1 + (action_id - ActionEvent.first_bid_action_id) // 5\n bid_suit_id = (action_id - ActionEvent.first_bid_action_id) % 5\n bid_suit = BridgeCard.suits[bid_suit_id] if bid_suit_id < 4 else None\n return BidAction(bid_amount, bid_suit)\n elif action_id == ActionEvent.dbl_action_id:\n return DblAction()\n elif action_id == ActionEvent.rdbl_action_id:\n return RdblAction()\n elif ActionEvent.first_play_card_action_id <= action_id < ActionEvent.first_play_card_action_id + 52:\n card_id = action_id - ActionEvent.first_play_card_action_id\n card = BridgeCard.card(card_id=card_id)\n return PlayCardAction(card=card)\n else:\n raise Exception(f'ActionEvent from_action_id: invalid action_id={action_id}')\n\n @staticmethod\n def get_num_actions():\n ''' Return the number of possible actions in the game\n '''\n return 1 + 35 + 3 + 52 # no_bid, 35 bids, pass, dbl, rdl, 52 play_card\n\n\nclass CallActionEvent(ActionEvent): # Interface\n pass\n\n\nclass PassAction(CallActionEvent):\n\n def __init__(self):\n super().__init__(action_id=ActionEvent.pass_action_id)\n\n def __str__(self):\n return \"pass\"\n\n def __repr__(self):\n return \"pass\"\n\n\nclass BidAction(CallActionEvent):\n\n def __init__(self, bid_amount: int, bid_suit: str or None):\n suits = BridgeCard.suits\n if bid_suit and bid_suit not in suits:\n raise Exception(f'BidAction has invalid suit: {bid_suit}')\n if bid_suit in suits:\n bid_suit_id = suits.index(bid_suit)\n else:\n bid_suit_id = 4\n bid_action_id = bid_suit_id + 5 * (bid_amount - 1) + ActionEvent.first_bid_action_id\n super().__init__(action_id=bid_action_id)\n self.bid_amount = bid_amount\n self.bid_suit = bid_suit\n\n def __str__(self):\n bid_suit = self.bid_suit\n if not bid_suit:\n bid_suit = 'NT'\n return f'{self.bid_amount}{bid_suit}'\n\n def __repr__(self):\n return self.__str__()\n\n\nclass DblAction(CallActionEvent):\n\n def __init__(self):\n super().__init__(action_id=ActionEvent.dbl_action_id)\n\n def __str__(self):\n return \"dbl\"\n\n def __repr__(self):\n return \"dbl\"\n\n\nclass RdblAction(CallActionEvent):\n\n def __init__(self):\n super().__init__(action_id=ActionEvent.rdbl_action_id)\n\n def __str__(self):\n return \"rdbl\"\n\n def __repr__(self):\n return \"rdbl\"\n\n\nclass PlayCardAction(ActionEvent):\n\n def __init__(self, card: BridgeCard):\n play_card_action_id = ActionEvent.first_play_card_action_id + card.card_id\n super().__init__(action_id=play_card_action_id)\n self.card: BridgeCard = card\n\n def __str__(self):\n return f\"{self.card}\"\n\n def __repr__(self):\n return f\"{self.card}\"\n\n\n# ./bridge/base.py\n''' Game-related base classes\n'''\nclass Card:\n '''\n Card stores the suit and rank of a single card\n\n Note:\n The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]\n Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]\n '''\n suit = None\n rank = None\n valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']\n valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n\n def __init__(self, suit, rank):\n ''' Initialize the suit and rank of a card\n\n Args:\n suit: string, suit of the card, should be one of valid_suit\n rank: string, rank of the card, should be one of valid_rank\n '''\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if isinstance(other, Card):\n return self.rank == other.rank and self.suit == other.suit\n else:\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n def __hash__(self):\n suit_index = Card.valid_suit.index(self.suit)\n rank_index = Card.valid_rank.index(self.rank)\n return rank_index + 100 * suit_index\n\n def __str__(self):\n ''' Get string representation of a card.\n\n Returns:\n string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...\n '''\n return self.rank + self.suit\n\n def get_index(self):\n ''' Get index of a card.\n\n Returns:\n string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...\n '''\n return self.suit+self.rank\n\n\n# ./bridge/bridge_card.py\nfrom bridge import Card\n\n\nclass BridgeCard(Card):\n\n suits = ['C', 'D', 'H', 'S']\n ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']\n\n @staticmethod\n def card(card_id: int):\n return _deck[card_id]\n\n @staticmethod\n def get_deck() -> [Card]:\n return _deck.copy()\n\n def __init__(self, suit: str, rank: str):\n super().__init__(suit=suit, rank=rank)\n suit_index = BridgeCard.suits.index(self.suit)\n rank_index = BridgeCard.ranks.index(self.rank)\n self.card_id = 13 * suit_index + rank_index\n\n def __str__(self):\n return f'{self.rank}{self.suit}'\n\n def __repr__(self):\n return f'{self.rank}{self.suit}'\n\n\n# deck is always in order from 2C, ... KC, AC, 2D, ... KD, AD, 2H, ... KH, AH, 2S, ... KS, AS\n_deck = [BridgeCard(suit=suit, rank=rank) for suit in BridgeCard.suits for rank in BridgeCard.ranks] # want this to be read-only\n\n\n# ./bridge/dealer.py\nfrom typing import List\n\nfrom bridge import Player\nfrom bridge_card import BridgeCard\n\n\nclass BridgeDealer:\n ''' Initialize a BridgeDealer dealer class\n '''\n def __init__(self, np_random):\n ''' set shuffled_deck, set stock_pile\n '''\n self.np_random = np_random\n self.shuffled_deck: List[BridgeCard] = BridgeCard.get_deck() # keep a copy of the shuffled cards at start of new hand\n self.np_random.shuffle(self.shuffled_deck)\n self.stock_pile: List[BridgeCard] = self.shuffled_deck.copy()\n\n def deal_cards(self, player: Player, num: int):\n ''' Deal some cards from stock_pile to one player\n\n Args:\n player (BridgePlayer): The BridgePlayer object\n num (int): The number of cards to be dealt\n '''\n for _ in range(num):\n player.hand.append(self.stock_pile.pop())\n\n\n# ./bridge/game.py\nfrom typing import List\n\nimport numpy as np\n\nfrom bridge import Judger\nfrom round import BridgeRound\nfrom action_event import ActionEvent, CallActionEvent, PlayCardAction\n\n\nclass BridgeGame:\n ''' Game class. This class will interact with outer environment.\n '''\n\n def __init__(self, allow_step_back=False):\n '''Initialize the class BridgeGame\n '''\n self.allow_step_back: bool = allow_step_back\n self.np_random = np.random.RandomState()\n self.judger: Judger = Judger(game=self)\n self.actions: [ActionEvent] = [] # must reset in init_game\n self.round: BridgeRound or None = None # must reset in init_game\n self.num_players: int = 4\n\n def init_game(self):\n ''' Initialize all characters in the game and start round 1\n '''\n board_id = self.np_random.choice([1, 2, 3, 4])\n self.actions: List[ActionEvent] = []\n self.round = BridgeRound(num_players=self.num_players, board_id=board_id, np_random=self.np_random)\n for player_id in range(4):\n player = self.round.players[player_id]\n self.round.dealer.deal_cards(player=player, num=13)\n current_player_id = self.round.current_player_id\n state = self.get_state(player_id=current_player_id)\n return state, current_player_id\n\n def step(self, action: ActionEvent):\n ''' Perform game action and return next player number, and the state for next player\n '''\n if isinstance(action, CallActionEvent):\n self.round.make_call(action=action)\n elif isinstance(action, PlayCardAction):\n self.round.play_card(action=action)\n else:\n raise Exception(f'Unknown step action={action}')\n self.actions.append(action)\n next_player_id = self.round.current_player_id\n next_state = self.get_state(player_id=next_player_id)\n return next_state, next_player_id\n\n def get_num_players(self) -> int:\n ''' Return the number of players in the game\n '''\n return self.num_players\n\n @staticmethod\n def get_num_actions() -> int:\n ''' Return the number of possible actions in the game\n '''\n return ActionEvent.get_num_actions()\n\n def get_player_id(self):\n ''' Return the current player that will take actions soon\n '''\n return self.round.current_player_id\n\n def is_over(self) -> bool:\n ''' Return whether the current game is over\n '''\n return self.round.is_over()\n\n def get_state(self, player_id: int): # wch: not really used\n ''' Get player's state\n\n Return:\n state (dict): The information of the state\n '''\n state = {}\n if not self.is_over():\n state['player_id'] = player_id\n state['current_player_id'] = self.round.current_player_id\n state['hand'] = self.round.players[player_id].hand\n else:\n state['player_id'] = player_id\n state['current_player_id'] = self.round.current_player_id\n state['hand'] = self.round.players[player_id].hand\n return state\n\n\n# ./bridge/judger.py\nfrom typing import List\n\nfrom typing import TYPE_CHECKING\n\nfrom action_event import PlayCardAction\nfrom action_event import ActionEvent, BidAction, PassAction, DblAction, RdblAction\nfrom move import MakeBidMove, MakeDblMove, MakeRdblMove\nfrom bridge_card import BridgeCard\n\n\nclass BridgeJudger:\n\n '''\n Judger decides legal actions for current player\n '''\n\n def __init__(self, game: 'BridgeGame'):\n ''' Initialize the class BridgeJudger\n :param game: BridgeGame\n '''\n self.game: BridgeGame = game\n\n def get_legal_actions(self) -> List[ActionEvent]:\n \"\"\"\n :return: List[ActionEvent] of legal actions\n \"\"\"\n legal_actions: List[ActionEvent] = []\n if not self.game.is_over():\n current_player = self.game.round.get_current_player()\n if not self.game.round.is_bidding_over():\n legal_actions.append(PassAction())\n last_make_bid_move: MakeBidMove or None = None\n last_dbl_move: MakeDblMove or None = None\n last_rdbl_move: MakeRdblMove or None = None\n for move in reversed(self.game.round.move_sheet):\n if isinstance(move, MakeBidMove):\n last_make_bid_move = move\n break\n elif isinstance(move, MakeRdblMove):\n last_rdbl_move = move\n elif isinstance(move, MakeDblMove) and not last_rdbl_move:\n last_dbl_move = move\n first_bid_action_id = ActionEvent.first_bid_action_id\n next_bid_action_id = last_make_bid_move.action.action_id + 1 if last_make_bid_move else first_bid_action_id\n for bid_action_id in range(next_bid_action_id, first_bid_action_id + 35):\n action = BidAction.from_action_id(action_id=bid_action_id)\n legal_actions.append(action)\n if last_make_bid_move and last_make_bid_move.player.player_id % 2 != current_player.player_id % 2 and not last_dbl_move and not last_rdbl_move:\n legal_actions.append(DblAction())\n if last_dbl_move and last_dbl_move.player.player_id % 2 != current_player.player_id % 2:\n legal_actions.append(RdblAction())\n else:\n trick_moves = self.game.round.get_trick_moves()\n hand = self.game.round.players[current_player.player_id].hand\n legal_cards = hand\n if trick_moves and len(trick_moves) < 4:\n led_card: BridgeCard = trick_moves[0].card\n cards_of_led_suit = [card for card in hand if card.suit == led_card.suit]\n if cards_of_led_suit:\n legal_cards = cards_of_led_suit\n for card in legal_cards:\n action = PlayCardAction(card=card)\n legal_actions.append(action)\n return legal_actions\n\n\n# ./bridge/move.py\n#\n# These classes are used to keep a move_sheet history of the moves in a round.\n#\n\nfrom action_event import ActionEvent, BidAction, PassAction, DblAction, RdblAction, PlayCardAction\nfrom bridge_card import BridgeCard\n\nfrom bridge import Player\n\n\nclass BridgeMove(object): # Interface\n pass\n\n\nclass PlayerMove(BridgeMove): # Interface\n\n def __init__(self, player: Player, action: ActionEvent):\n super().__init__()\n self.player = player\n self.action = action\n\n\nclass CallMove(PlayerMove): # Interface\n\n def __init__(self, player: Player, action: ActionEvent):\n super().__init__(player=player, action=action)\n\n\nclass DealHandMove(BridgeMove):\n\n def __init__(self, dealer: Player, shuffled_deck: [BridgeCard]):\n super().__init__()\n self.dealer = dealer\n self.shuffled_deck = shuffled_deck\n\n def __str__(self):\n shuffled_deck_text = \" \".join([str(card) for card in self.shuffled_deck])\n return f'{self.dealer} deal shuffled_deck=[{shuffled_deck_text}]'\n\n\nclass MakePassMove(CallMove):\n\n def __init__(self, player: Player):\n super().__init__(player=player, action=PassAction())\n\n def __str__(self):\n return f'{self.player} {self.action}'\n\n\nclass MakeDblMove(CallMove):\n\n def __init__(self, player: Player):\n super().__init__(player=player, action=DblAction())\n\n def __str__(self):\n return f'{self.player} {self.action}'\n\n\nclass MakeRdblMove(CallMove):\n\n def __init__(self, player: Player):\n super().__init__(player=player, action=RdblAction())\n\n def __str__(self):\n return f'{self.player} {self.action}'\n\n\nclass MakeBidMove(CallMove):\n\n def __init__(self, player: Player, bid_action: BidAction):\n super().__init__(player=player, action=bid_action)\n self.action = bid_action # Note: keep type as BidAction rather than ActionEvent\n\n def __str__(self):\n return f'{self.player} bids {self.action}'\n\n\nclass PlayCardMove(PlayerMove):\n\n def __init__(self, player: Player, action: PlayCardAction):\n super().__init__(player=player, action=action)\n self.action = action # Note: keep type as PlayCardAction rather than ActionEvent\n\n @property\n def card(self):\n return self.action.card\n\n def __str__(self):\n return f'{self.player} plays {self.action}'\n\n\n# ./bridge/player.py\nfrom typing import List\n\nfrom bridge_card import BridgeCard\n\n\nclass BridgePlayer:\n\n def __init__(self, player_id: int, np_random):\n ''' Initialize a BridgePlayer player class\n\n Args:\n player_id (int): id for the player\n '''\n if player_id < 0 or player_id > 3:\n raise Exception(f'BridgePlayer has invalid player_id: {player_id}')\n self.np_random = np_random\n self.player_id: int = player_id\n self.hand: List[BridgeCard] = []\n\n def remove_card_from_hand(self, card: BridgeCard):\n self.hand.remove(card)\n\n def __str__(self):\n return ['N', 'E', 'S', 'W'][self.player_id]\n\n\n# ./bridge/round.py\nfrom typing import List\n\nfrom bridge import Dealer\nfrom bridge import Player\n\nfrom action_event import CallActionEvent, PassAction, DblAction, RdblAction, BidAction, PlayCardAction\nfrom move import BridgeMove, DealHandMove, PlayCardMove, MakeBidMove, MakePassMove, MakeDblMove, MakeRdblMove, CallMove\nfrom tray import Tray\n\n\nclass BridgeRound:\n\n @property\n def dealer_id(self) -> int:\n return self.tray.dealer_id\n\n @property\n def vul(self):\n return self.tray.vul\n\n @property\n def board_id(self) -> int:\n return self.tray.board_id\n\n @property\n def round_phase(self):\n if self.is_over():\n result = 'game over'\n elif self.is_bidding_over():\n result = 'play card'\n else:\n result = 'make bid'\n return result\n\n def __init__(self, num_players: int, board_id: int, np_random):\n ''' Initialize the round class\n\n The round class maintains the following instances:\n 1) dealer: the dealer of the round; dealer has trick_pile\n 2) players: the players in the round; each player has his own hand_pile\n 3) current_player_id: the id of the current player who has the move\n 4) doubling_cube: 2 if contract is doubled; 4 if contract is redoubled; else 1\n 5) play_card_count: count of PlayCardMoves\n 5) move_sheet: history of the moves of the players (including the deal_hand_move)\n\n The round class maintains a list of moves made by the players in self.move_sheet.\n move_sheet is similar to a chess score sheet.\n I didn't want to call it a score_sheet since it is not keeping score.\n I could have called move_sheet just moves, but that might conflict with the name moves used elsewhere.\n I settled on the longer name \"move_sheet\" to indicate that it is the official list of moves being made.\n\n Args:\n num_players: int\n board_id: int\n np_random\n '''\n tray = Tray(board_id=board_id)\n dealer_id = tray.dealer_id\n self.tray = tray\n self.np_random = np_random\n self.dealer: Dealer = Dealer(self.np_random)\n self.players: List[Player] = []\n for player_id in range(num_players):\n self.players.append(Player(player_id=player_id, np_random=self.np_random))\n self.current_player_id: int = dealer_id\n self.doubling_cube: int = 1\n self.play_card_count: int = 0\n self.contract_bid_move: MakeBidMove or None = None\n self.won_trick_counts = [0, 0] # count of won tricks by side\n self.move_sheet: List[BridgeMove] = []\n self.move_sheet.append(DealHandMove(dealer=self.players[dealer_id], shuffled_deck=self.dealer.shuffled_deck))\n\n def is_bidding_over(self) -> bool:\n ''' Return whether the current bidding is over\n '''\n is_bidding_over = True\n if len(self.move_sheet) < 5:\n is_bidding_over = False\n else:\n last_make_pass_moves: List[MakePassMove] = []\n for move in reversed(self.move_sheet):\n if isinstance(move, MakePassMove):\n last_make_pass_moves.append(move)\n if len(last_make_pass_moves) == 3:\n break\n elif isinstance(move, CallMove):\n is_bidding_over = False\n break\n else:\n break\n return is_bidding_over\n\n def is_over(self) -> bool:\n ''' Return whether the current game is over\n '''\n is_over = True\n if not self.is_bidding_over():\n is_over = False\n elif self.contract_bid_move:\n for player in self.players:\n if player.hand:\n is_over = False\n break\n return is_over\n\n def get_current_player(self) -> Player or None:\n current_player_id = self.current_player_id\n return None if current_player_id is None else self.players[current_player_id]\n\n def get_trick_moves(self) -> List[PlayCardMove]:\n trick_moves: List[PlayCardMove] = []\n if self.is_bidding_over():\n if self.play_card_count > 0:\n trick_pile_count = self.play_card_count % 4\n if trick_pile_count == 0:\n trick_pile_count = 4 # wch: note this\n for move in self.move_sheet[-trick_pile_count:]:\n if isinstance(move, PlayCardMove):\n trick_moves.append(move)\n if len(trick_moves) != trick_pile_count:\n raise Exception(f'get_trick_moves: count of trick_moves={[str(move.card) for move in trick_moves]} does not equal {trick_pile_count}')\n return trick_moves\n\n def get_trump_suit(self) -> str or None:\n trump_suit = None\n if self.contract_bid_move:\n trump_suit = self.contract_bid_move.action.bid_suit\n return trump_suit\n\n def make_call(self, action: CallActionEvent):\n # when current_player takes CallActionEvent step, the move is recorded and executed\n current_player = self.players[self.current_player_id]\n if isinstance(action, PassAction):\n self.move_sheet.append(MakePassMove(current_player))\n elif isinstance(action, BidAction):\n self.doubling_cube = 1\n make_bid_move = MakeBidMove(current_player, action)\n self.contract_bid_move = make_bid_move\n self.move_sheet.append(make_bid_move)\n elif isinstance(action, DblAction):\n self.doubling_cube = 2\n self.move_sheet.append(MakeDblMove(current_player))\n elif isinstance(action, RdblAction):\n self.doubling_cube = 4\n self.move_sheet.append(MakeRdblMove(current_player))\n if self.is_bidding_over():\n if not self.is_over():\n self.current_player_id = self.get_left_defender().player_id\n else:\n self.current_player_id = (self.current_player_id + 1) % 4\n\n def play_card(self, action: PlayCardAction):\n # when current_player takes PlayCardAction step, the move is recorded and executed\n current_player = self.players[self.current_player_id]\n self.move_sheet.append(PlayCardMove(current_player, action))\n card = action.card\n current_player.remove_card_from_hand(card=card)\n self.play_card_count += 1\n # update current_player_id\n trick_moves = self.get_trick_moves()\n if len(trick_moves) == 4:\n trump_suit = self.get_trump_suit()\n winning_card = trick_moves[0].card\n trick_winner = trick_moves[0].player\n for move in trick_moves[1:]:\n trick_card = move.card\n trick_player = move.player\n if trick_card.suit == winning_card.suit:\n if trick_card.card_id > winning_card.card_id:\n winning_card = trick_card\n trick_winner = trick_player\n elif trick_card.suit == trump_suit:\n winning_card = trick_card\n trick_winner = trick_player\n self.current_player_id = trick_winner.player_id\n self.won_trick_counts[trick_winner.player_id % 2] += 1\n else:\n self.current_player_id = (self.current_player_id + 1) % 4\n\n def get_declarer(self) -> Player or None:\n declarer = None\n if self.contract_bid_move:\n trump_suit = self.contract_bid_move.action.bid_suit\n side = self.contract_bid_move.player.player_id % 2\n for move in self.move_sheet:\n if isinstance(move, MakeBidMove) and move.action.bid_suit == trump_suit and move.player.player_id % 2 == side:\n declarer = move.player\n break\n return declarer\n\n def get_dummy(self) -> Player or None:\n dummy = None\n declarer = self.get_declarer()\n if declarer:\n dummy = self.players[(declarer.player_id + 2) % 4]\n return dummy\n\n def get_left_defender(self) -> Player or None:\n left_defender = None\n declarer = self.get_declarer()\n if declarer:\n left_defender = self.players[(declarer.player_id + 1) % 4]\n return left_defender\n\n def get_right_defender(self) -> Player or None:\n right_defender = None\n declarer = self.get_declarer()\n if declarer:\n right_defender = self.players[(declarer.player_id + 3) % 4]\n return right_defender\n\n def get_perfect_information(self):\n state = {}\n last_call_move = None\n if not self.is_bidding_over() or self.play_card_count == 0:\n last_move = self.move_sheet[-1]\n if isinstance(last_move, CallMove):\n last_call_move = last_move\n trick_moves = [None, None, None, None]\n if self.is_bidding_over():\n for trick_move in self.get_trick_moves():\n trick_moves[trick_move.player.player_id] = trick_move.card\n state['move_count'] = len(self.move_sheet)\n state['tray'] = self.tray\n state['current_player_id'] = self.current_player_id\n state['round_phase'] = self.round_phase\n state['last_call_move'] = last_call_move\n state['doubling_cube'] = self.doubling_cube\n state['contact'] = self.contract_bid_move if self.is_bidding_over() and self.contract_bid_move else None\n state['hands'] = [player.hand for player in self.players]\n state['trick_moves'] = trick_moves\n return state\n\n def print_scene(self):\n print(f'===== Board: {self.tray.board_id} move: {len(self.move_sheet)} player: {self.players[self.current_player_id]} phase: {self.round_phase} =====')\n print(f'dealer={self.players[self.tray.dealer_id]}')\n print(f'vul={self.vul}')\n if not self.is_bidding_over() or self.play_card_count == 0:\n last_move = self.move_sheet[-1]\n last_call_text = f'{last_move}' if isinstance(last_move, CallMove) else 'None'\n print(f'last call: {last_call_text}')\n if self.is_bidding_over() and self.contract_bid_move:\n bid_suit = self.contract_bid_move.action.bid_suit\n doubling_cube = self.doubling_cube\n if not bid_suit:\n bid_suit = 'NT'\n doubling_cube_text = \"\" if doubling_cube == 1 else \"dbl\" if doubling_cube == 2 else \"rdbl\"\n print(f'contract: {self.contract_bid_move.player} {self.contract_bid_move.action.bid_amount}{bid_suit} {doubling_cube_text}')\n for player in self.players:\n print(f'{player}: {[str(card) for card in player.hand]}')\n if self.is_bidding_over():\n trick_pile = ['None', 'None', 'None', 'None']\n for trick_move in self.get_trick_moves():\n trick_pile[trick_move.player.player_id] = trick_move.card\n print(f'trick_pile: {[str(card) for card in trick_pile]}')\n\n\n# ./bridge/tray.py\nclass Tray(object):\n\n def __init__(self, board_id: int):\n if board_id <= 0:\n raise Exception(f'Tray: invalid board_id={board_id}')\n self.board_id = board_id\n\n @property\n def dealer_id(self):\n return (self.board_id - 1) % 4\n\n @property\n def vul(self):\n vul_none = [0, 0, 0, 0]\n vul_n_s = [1, 0, 1, 0]\n vul_e_w = [0, 1, 0, 1]\n vul_all = [1, 1, 1, 1]\n basic_vuls = [vul_none, vul_n_s, vul_e_w, vul_all]\n offset = (self.board_id - 1) // 4\n return basic_vuls[(self.board_id - 1 + offset) % 4]\n\n def __str__(self):\n return f'{self.board_id}: dealer_id={self.dealer_id} vul={self.vul}'\n", "num_file": 11, "num_lines": 792, "programming_language": "Python"} {"class_name": "doudizhu", "id": "./MultiFileTest/Python/doudizhu.py", "original_code": "# ./doudizhu/__init__.py\nfrom doudizhu.base import Card as Card\nfrom doudizhu.dealer import DoudizhuDealer as Dealer\nfrom doudizhu.judger import DoudizhuJudger as Judger\nfrom doudizhu.player import DoudizhuPlayer as Player\nfrom doudizhu.round import DoudizhuRound as Round\nfrom doudizhu.game import DoudizhuGame as Game\n\n# ./doudizhu/base.py\n''' Game-related base classes\n'''\nclass Card:\n '''\n Card stores the suit and rank of a single card\n\n Note:\n The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]\n Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]\n '''\n suit = None\n rank = None\n valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']\n valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n\n def __init__(self, suit, rank):\n ''' Initialize the suit and rank of a card\n\n Args:\n suit: string, suit of the card, should be one of valid_suit\n rank: string, rank of the card, should be one of valid_rank\n '''\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if isinstance(other, Card):\n return self.rank == other.rank and self.suit == other.suit\n else:\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n def __hash__(self):\n suit_index = Card.valid_suit.index(self.suit)\n rank_index = Card.valid_rank.index(self.rank)\n return rank_index + 100 * suit_index\n\n def __str__(self):\n ''' Get string representation of a card.\n\n Returns:\n string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...\n '''\n return self.rank + self.suit\n\n def get_index(self):\n ''' Get index of a card.\n\n Returns:\n string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...\n '''\n return self.suit+self.rank\n\n\n# ./doudizhu/dealer.py\n# -*- coding: utf-8 -*-\n''' Implement Doudizhu Dealer class\n'''\nimport functools\n\nfrom doudizhu import Card\nfrom doudizhu.utils import cards2str, doudizhu_sort_card\n\ndef init_54_deck():\n ''' Initialize a standard deck of 52 cards, BJ and RJ\n\n Returns:\n (list): Alist of Card object\n '''\n suit_list = ['S', 'H', 'D', 'C']\n rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n res = [Card(suit, rank) for suit in suit_list for rank in rank_list]\n res.append(Card('BJ', ''))\n res.append(Card('RJ', ''))\n return res\n \nclass DoudizhuDealer:\n ''' Dealer will shuffle, deal cards, and determine players' roles\n '''\n def __init__(self, np_random):\n '''Give dealer the deck\n\n Notes:\n 1. deck with 54 cards including black joker and red joker\n '''\n self.np_random = np_random\n self.deck = init_54_deck()\n self.deck.sort(key=functools.cmp_to_key(doudizhu_sort_card))\n self.landlord = None\n\n def shuffle(self):\n ''' Randomly shuffle the deck\n '''\n self.np_random.shuffle(self.deck)\n\n def deal_cards(self, players):\n ''' Deal cards to players\n\n Args:\n players (list): list of DoudizhuPlayer objects\n '''\n hand_num = (len(self.deck) - 3) // len(players)\n for index, player in enumerate(players):\n current_hand = self.deck[index*hand_num:(index+1)*hand_num]\n current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card))\n player.set_current_hand(current_hand)\n player.initial_hand = cards2str(player.current_hand)\n\n def determine_role(self, players):\n ''' Determine landlord and peasants according to players' hand\n\n Args:\n players (list): list of DoudizhuPlayer objects\n\n Returns:\n int: landlord's player_id\n '''\n # deal cards\n self.shuffle()\n self.deal_cards(players)\n players[0].role = 'landlord'\n self.landlord = players[0]\n players[1].role = 'peasant'\n players[2].role = 'peasant'\n #players[0].role = 'peasant'\n #self.landlord = players[0]\n\n ## determine 'landlord'\n #max_score = get_landlord_score(\n # cards2str(self.landlord.current_hand))\n #for player in players[1:]:\n # player.role = 'peasant'\n # score = get_landlord_score(\n # cards2str(player.current_hand))\n # if score > max_score:\n # max_score = score\n # self.landlord = player\n #self.landlord.role = 'landlord'\n\n # give the 'landlord' the three cards\n self.landlord.current_hand.extend(self.deck[-3:])\n self.landlord.current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card))\n self.landlord.initial_hand = cards2str(self.landlord.current_hand)\n return self.landlord.player_id\n\n\n# ./doudizhu/game.py\n# -*- coding: utf-8 -*-\n''' Implement Doudizhu Game class\n'''\nimport functools\nfrom heapq import merge\nimport numpy as np\n\nfrom doudizhu.utils import cards2str, doudizhu_sort_card, CARD_RANK_STR\nfrom doudizhu import Player\nfrom doudizhu import Round\nfrom doudizhu import Judger\n\n\nclass DoudizhuGame:\n ''' Provide game APIs for env to run doudizhu and get corresponding state\n information.\n '''\n def __init__(self, allow_step_back=False):\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n self.num_players = 3\n\n def init_game(self):\n ''' Initialize players and state.\n\n Returns:\n dict: first state in one game\n int: current player's id\n '''\n # initialize public variables\n self.winner_id = None\n self.history = []\n\n # initialize players\n self.players = [Player(num, self.np_random)\n for num in range(self.num_players)]\n\n # initialize round to deal cards and determine landlord\n self.played_cards = [np.zeros((len(CARD_RANK_STR), ), dtype=np.int32)\n for _ in range(self.num_players)]\n self.round = Round(self.np_random, self.played_cards)\n self.round.initiate(self.players)\n\n # initialize judger\n self.judger = Judger(self.players, self.np_random)\n\n # get state of first player\n player_id = self.round.current_player\n self.state = self.get_state(player_id)\n\n return self.state, player_id\n\n def step(self, action):\n ''' Perform one draw of the game\n\n Args:\n action (str): specific action of doudizhu. Eg: '33344'\n\n Returns:\n dict: next player's state\n int: next player's id\n '''\n if self.allow_step_back:\n # TODO: don't record game.round, game.players, game.judger if allow_step_back not set\n pass\n\n # perfrom action\n player = self.players[self.round.current_player]\n self.round.proceed_round(player, action)\n if (action != 'pass'):\n self.judger.calc_playable_cards(player)\n if self.judger.judge_game(self.players, self.round.current_player):\n self.winner_id = self.round.current_player\n next_id = (player.player_id+1) % len(self.players)\n self.round.current_player = next_id\n\n # get next state\n state = self.get_state(next_id)\n self.state = state\n\n return state, next_id\n\n def step_back(self):\n ''' Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n '''\n if not self.round.trace:\n return False\n\n #winner_id will be always None no matter step_back from any case\n self.winner_id = None\n\n #reverse round\n player_id, cards = self.round.step_back(self.players)\n\n #reverse player\n if (cards != 'pass'):\n self.players[player_id].played_cards = self.round.find_last_played_cards_in_trace(player_id)\n self.players[player_id].play_back()\n\n #reverse judger.played_cards if needed\n if (cards != 'pass'):\n self.judger.restore_playable_cards(player_id)\n\n self.state = self.get_state(self.round.current_player)\n return True\n\n def get_state(self, player_id):\n ''' Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n (dict): The state of the player\n '''\n player = self.players[player_id]\n others_hands = self._get_others_current_hand(player)\n num_cards_left = [len(self.players[i].current_hand) for i in range(self.num_players)]\n if self.is_over():\n actions = []\n else:\n actions = list(player.available_actions(self.round.greater_player, self.judger))\n state = player.get_state(self.round.public, others_hands, num_cards_left, actions)\n\n return state\n\n @staticmethod\n def get_num_actions():\n ''' Return the total number of abstract acitons\n\n Returns:\n int: the total number of abstract actions of doudizhu\n '''\n return 27472\n\n def get_player_id(self):\n ''' Return current player's id\n\n Returns:\n int: current player's id\n '''\n return self.round.current_player\n\n def get_num_players(self):\n ''' Return the number of players in doudizhu\n\n Returns:\n int: the number of players in doudizhu\n '''\n return self.num_players\n\n def is_over(self):\n ''' Judge whether a game is over\n\n Returns:\n Bool: True(over) / False(not over)\n '''\n if self.winner_id is None:\n return False\n return True\n\n def _get_others_current_hand(self, player):\n player_up = self.players[(player.player_id+1) % len(self.players)]\n player_down = self.players[(player.player_id-1) % len(self.players)]\n others_hand = merge(player_up.current_hand, player_down.current_hand, key=functools.cmp_to_key(doudizhu_sort_card))\n return cards2str(others_hand)\n\n\n# ./doudizhu/judger.py\n# -*- coding: utf-8 -*-\n''' Implement Doudizhu Judger class\n'''\nimport numpy as np\nimport collections\nfrom itertools import combinations\nfrom bisect import bisect_left\n\nfrom doudizhu.utils import CARD_RANK_STR, CARD_RANK_STR_INDEX\nfrom doudizhu.utils import cards2str, contains_cards\n\n\n\nclass DoudizhuJudger:\n ''' Determine what cards a player can play\n '''\n @staticmethod\n def chain_indexes(indexes_list):\n ''' Find chains for solos, pairs and trios by using indexes_list\n\n Args:\n indexes_list: the indexes of cards those have the same count, the count could be 1, 2, or 3.\n\n Returns:\n list of tuples: [(start_index1, length1), (start_index1, length1), ...]\n\n '''\n chains = []\n prev_index = -100\n count = 0\n start = None\n for i in indexes_list:\n if (i[0] >= 12): #no chains for '2BR'\n break\n if (i[0] == prev_index + 1):\n count += 1\n else:\n if (count > 1):\n chains.append((start, count))\n count = 1\n start = i[0]\n prev_index = i[0]\n if (count > 1):\n chains.append((start, count))\n return chains\n\n @classmethod\n def solo_attachments(cls, hands, chain_start, chain_length, size):\n ''' Find solo attachments for trio_chain_solo_x and four_two_solo\n\n Args:\n hands:\n chain_start: the index of start card of the trio_chain or trio or four\n chain_length: the size of the sequence of the chain, 1 for trio_solo or four_two_solo\n size: count of solos for the attachments\n\n Returns:\n list of tuples: [attachment1, attachment2, ...]\n Each attachment has two elemnts,\n the first one contains indexes of attached cards smaller than the index of chain_start,\n the first one contains indexes of attached cards larger than the index of chain_start\n '''\n attachments = set()\n candidates = []\n prev_card = None\n same_card_count = 0\n for card in hands:\n #dont count those cards in the chain\n if (CARD_RANK_STR_INDEX[card] >= chain_start and CARD_RANK_STR_INDEX[card] < chain_start + chain_length):\n continue\n if (card == prev_card):\n #attachments can not have bomb\n if (same_card_count == 3):\n continue\n #attachments can not have 3 same cards consecutive with the trio (except 3 cards of '222')\n elif (same_card_count == 2 and (CARD_RANK_STR_INDEX[card] == chain_start - 1 or CARD_RANK_STR_INDEX[card] == chain_start + chain_length) and card != '2'):\n continue\n else:\n same_card_count += 1\n else:\n prev_card = card\n same_card_count = 1\n candidates.append(CARD_RANK_STR_INDEX[card])\n for attachment in combinations(candidates, size):\n if (attachment[-1] == 14 and attachment[-2] == 13):\n continue\n i = bisect_left(attachment, chain_start)\n attachments.add((attachment[:i], attachment[i:]))\n return list(attachments)\n\n @classmethod\n def pair_attachments(cls, cards_count, chain_start, chain_length, size):\n ''' Find pair attachments for trio_chain_pair_x and four_two_pair\n\n Args:\n cards_count:\n chain_start: the index of start card of the trio_chain or trio or four\n chain_length: the size of the sequence of the chain, 1 for trio_pair or four_two_pair\n size: count of pairs for the attachments\n\n Returns:\n list of tuples: [attachment1, attachment2, ...]\n Each attachment has two elemnts,\n the first one contains indexes of attached cards smaller than the index of chain_start,\n the first one contains indexes of attached cards larger than the index of chain_start\n '''\n attachments = set()\n candidates = []\n for i, _ in enumerate(cards_count):\n if (i >= chain_start and i < chain_start + chain_length):\n continue\n if (cards_count[i] == 2 or cards_count[i] == 3):\n candidates.append(i)\n elif (cards_count[i] == 4):\n candidates.append(i)\n for attachment in combinations(candidates, size):\n if (attachment[-1] == 14 and attachment[-2] == 13):\n continue\n i = bisect_left(attachment, chain_start)\n attachments.add((attachment[:i], attachment[i:]))\n return list(attachments)\n \n @staticmethod\n def playable_cards_from_hand(current_hand):\n ''' Get playable cards from hand\n\n Returns:\n set: set of string of playable cards\n '''\n cards_dict = collections.defaultdict(int)\n for card in current_hand:\n cards_dict[card] += 1\n cards_count = np.array([cards_dict[k] for k in CARD_RANK_STR])\n playable_cards = set()\n\n non_zero_indexes = np.argwhere(cards_count > 0)\n more_than_1_indexes = np.argwhere(cards_count > 1)\n more_than_2_indexes = np.argwhere(cards_count > 2)\n more_than_3_indexes = np.argwhere(cards_count > 3)\n #solo\n for i in non_zero_indexes:\n playable_cards.add(CARD_RANK_STR[i[0]])\n #pair\n for i in more_than_1_indexes:\n playable_cards.add(CARD_RANK_STR[i[0]] * 2)\n #bomb, four_two_solo, four_two_pair\n for i in more_than_3_indexes:\n cards = CARD_RANK_STR[i[0]] * 4\n playable_cards.add(cards)\n for left, right in DoudizhuJudger.solo_attachments(current_hand, i[0], 1, 2):\n pre_attached = ''\n for j in left:\n pre_attached += CARD_RANK_STR[j]\n post_attached = ''\n for j in right:\n post_attached += CARD_RANK_STR[j]\n playable_cards.add(pre_attached + cards + post_attached)\n for left, right in DoudizhuJudger.pair_attachments(cards_count, i[0], 1, 2):\n pre_attached = ''\n for j in left:\n pre_attached += CARD_RANK_STR[j] * 2\n post_attached = ''\n for j in right:\n post_attached += CARD_RANK_STR[j] * 2\n playable_cards.add(pre_attached + cards + post_attached)\n\n #solo_chain_5 -- #solo_chain_12\n solo_chain_indexes = DoudizhuJudger.chain_indexes(non_zero_indexes)\n for (start_index, length) in solo_chain_indexes:\n s, l = start_index, length\n while(l >= 5):\n cards = ''\n curr_index = s - 1\n curr_length = 0\n while (curr_length < l and curr_length < 12):\n curr_index += 1\n curr_length += 1\n cards += CARD_RANK_STR[curr_index]\n if (curr_length >= 5):\n playable_cards.add(cards)\n l -= 1\n s += 1\n\n #pair_chain_3 -- #pair_chain_10\n pair_chain_indexes = DoudizhuJudger.chain_indexes(more_than_1_indexes)\n for (start_index, length) in pair_chain_indexes:\n s, l = start_index, length\n while(l >= 3):\n cards = ''\n curr_index = s - 1\n curr_length = 0\n while (curr_length < l and curr_length < 10):\n curr_index += 1\n curr_length += 1\n cards += CARD_RANK_STR[curr_index] * 2\n if (curr_length >= 3):\n playable_cards.add(cards)\n l -= 1\n s += 1\n\n #trio, trio_solo and trio_pair\n for i in more_than_2_indexes:\n playable_cards.add(CARD_RANK_STR[i[0]] * 3)\n for j in non_zero_indexes:\n if (j < i):\n playable_cards.add(CARD_RANK_STR[j[0]] + CARD_RANK_STR[i[0]] * 3)\n elif (j > i):\n playable_cards.add(CARD_RANK_STR[i[0]] * 3 + CARD_RANK_STR[j[0]])\n for j in more_than_1_indexes:\n if (j < i):\n playable_cards.add(CARD_RANK_STR[j[0]] * 2 + CARD_RANK_STR[i[0]] * 3)\n elif (j > i):\n playable_cards.add(CARD_RANK_STR[i[0]] * 3 + CARD_RANK_STR[j[0]] * 2)\n\n #trio_solo, trio_pair, #trio -- trio_chain_2 -- trio_chain_6; trio_solo_chain_2 -- trio_solo_chain_5; trio_pair_chain_2 -- trio_pair_chain_4\n trio_chain_indexes = DoudizhuJudger.chain_indexes(more_than_2_indexes)\n for (start_index, length) in trio_chain_indexes:\n s, l = start_index, length\n while(l >= 2):\n cards = ''\n curr_index = s - 1\n curr_length = 0\n while (curr_length < l and curr_length < 6):\n curr_index += 1\n curr_length += 1\n cards += CARD_RANK_STR[curr_index] * 3\n\n #trio_chain_2 to trio_chain_6\n if (curr_length >= 2 and curr_length <= 6):\n playable_cards.add(cards)\n\n #trio_solo_chain_2 to trio_solo_chain_5\n if (curr_length >= 2 and curr_length <= 5):\n for left, right in DoudizhuJudger.solo_attachments(current_hand, s, curr_length, curr_length):\n pre_attached = ''\n for j in left:\n pre_attached += CARD_RANK_STR[j]\n post_attached = ''\n for j in right:\n post_attached += CARD_RANK_STR[j]\n playable_cards.add(pre_attached + cards + post_attached)\n\n #trio_pair_chain2 -- trio_pair_chain_4\n if (curr_length >= 2 and curr_length <= 4):\n for left, right in DoudizhuJudger.pair_attachments(cards_count, s, curr_length, curr_length):\n pre_attached = ''\n for j in left:\n pre_attached += CARD_RANK_STR[j] * 2\n post_attached = ''\n for j in right:\n post_attached += CARD_RANK_STR[j] * 2\n playable_cards.add(pre_attached + cards + post_attached)\n l -= 1\n s += 1\n #rocket\n if (cards_count[13] and cards_count[14]):\n playable_cards.add(CARD_RANK_STR[13] + CARD_RANK_STR[14])\n return playable_cards\n\n def __init__(self, players, np_random):\n ''' Initilize the Judger class for Dou Dizhu\n '''\n self.playable_cards = [set() for _ in range(3)]\n self._recorded_removed_playable_cards = [[] for _ in range(3)]\n for player in players:\n player_id = player.player_id\n current_hand = cards2str(player.current_hand)\n self.playable_cards[player_id] = self.playable_cards_from_hand(current_hand)\n\n def calc_playable_cards(self, player):\n ''' Recalculate all legal cards the player can play according to his\n current hand.\n\n Args:\n player (DoudizhuPlayer object): object of DoudizhuPlayer\n init_flag (boolean): For the first time, set it True to accelerate\n the preocess.\n\n Returns:\n list: list of string of playable cards\n '''\n removed_playable_cards = []\n\n player_id = player.player_id\n current_hand = cards2str(player.current_hand)\n missed = None\n for single in player.singles:\n if single not in current_hand:\n missed = single\n break\n\n playable_cards = self.playable_cards[player_id].copy()\n\n if missed is not None:\n position = player.singles.find(missed)\n player.singles = player.singles[position+1:]\n for cards in playable_cards:\n if missed in cards or (not contains_cards(current_hand, cards)):\n removed_playable_cards.append(cards)\n self.playable_cards[player_id].remove(cards)\n else:\n for cards in playable_cards:\n if not contains_cards(current_hand, cards):\n #del self.playable_cards[player_id][cards]\n removed_playable_cards.append(cards)\n self.playable_cards[player_id].remove(cards)\n self._recorded_removed_playable_cards[player_id].append(removed_playable_cards)\n return self.playable_cards[player_id]\n\n def restore_playable_cards(self, player_id):\n ''' restore playable_cards for judger for game.step_back().\n\n Args:\n player_id: The id of the player whose playable_cards need to be restored\n '''\n removed_playable_cards = self._recorded_removed_playable_cards[player_id].pop()\n self.playable_cards[player_id].update(removed_playable_cards)\n\n def get_playable_cards(self, player):\n ''' Provide all legal cards the player can play according to his\n current hand.\n\n Args:\n player (DoudizhuPlayer object): object of DoudizhuPlayer\n init_flag (boolean): For the first time, set it True to accelerate\n the preocess.\n\n Returns:\n list: list of string of playable cards\n '''\n return self.playable_cards[player.player_id]\n\n\n @staticmethod\n def judge_game(players, player_id):\n ''' Judge whether the game is over\n\n Args:\n players (list): list of DoudizhuPlayer objects\n player_id (int): integer of player's id\n\n Returns:\n (bool): True if the game is over\n '''\n player = players[player_id]\n if not player.current_hand:\n return True\n return False\n\n @staticmethod\n def judge_payoffs(landlord_id, winner_id):\n payoffs = np.array([0, 0, 0])\n if winner_id == landlord_id:\n payoffs[landlord_id] = 1\n else:\n for index, _ in enumerate(payoffs):\n if index != landlord_id:\n payoffs[index] = 1\n return payoffs\n\n\n# ./doudizhu/player.py\n# -*- coding: utf-8 -*-\n''' Implement Doudizhu Player class\n'''\nimport functools\n\nfrom doudizhu.utils import get_gt_cards\nfrom doudizhu.utils import cards2str, doudizhu_sort_card\n\n\nclass DoudizhuPlayer:\n ''' Player can store cards in the player's hand and the role,\n determine the actions can be made according to the rules,\n and can perfrom corresponding action\n '''\n def __init__(self, player_id, np_random):\n ''' Give the player an id in one game\n\n Args:\n player_id (int): the player_id of a player\n\n Notes:\n 1. role: A player's temporary role in one game(landlord or peasant)\n 2. played_cards: The cards played in one round\n 3. hand: Initial cards\n 4. _current_hand: The rest of the cards after playing some of them\n '''\n self.np_random = np_random\n self.player_id = player_id\n self.initial_hand = None\n self._current_hand = []\n self.role = ''\n self.played_cards = None\n self.singles = '3456789TJQKA2BR'\n\n #record cards removed from self._current_hand for each play()\n # and restore cards back to self._current_hand when play_back()\n self._recorded_played_cards = []\n\n @property\n def current_hand(self):\n return self._current_hand\n\n def set_current_hand(self, value):\n self._current_hand = value\n\n def get_state(self, public, others_hands, num_cards_left, actions):\n state = {}\n state['seen_cards'] = public['seen_cards']\n state['landlord'] = public['landlord']\n state['trace'] = public['trace'].copy()\n state['played_cards'] = public['played_cards']\n state['self'] = self.player_id\n state['current_hand'] = cards2str(self._current_hand)\n state['others_hand'] = others_hands\n state['num_cards_left'] = num_cards_left\n state['actions'] = actions\n\n return state\n\n def available_actions(self, greater_player=None, judger=None):\n ''' Get the actions can be made based on the rules\n\n Args:\n greater_player (DoudizhuPlayer object): player who played\n current biggest cards.\n judger (DoudizhuJudger object): object of DoudizhuJudger\n\n Returns:\n list: list of string of actions. Eg: ['pass', '8', '9', 'T', 'J']\n '''\n actions = []\n if greater_player is None or greater_player.player_id == self.player_id:\n actions = judger.get_playable_cards(self)\n else:\n actions = get_gt_cards(self, greater_player)\n return actions\n\n def play(self, action, greater_player=None):\n ''' Perfrom action\n\n Args:\n action (string): specific action\n greater_player (DoudizhuPlayer object): The player who played current biggest cards.\n\n Returns:\n object of DoudizhuPlayer: If there is a new greater_player, return it, if not, return None\n '''\n trans = {'B': 'BJ', 'R': 'RJ'}\n if action == 'pass':\n self._recorded_played_cards.append([])\n return greater_player\n else:\n removed_cards = []\n self.played_cards = action\n for play_card in action:\n if play_card in trans:\n play_card = trans[play_card]\n for _, remain_card in enumerate(self._current_hand):\n if remain_card.rank != '':\n remain_card = remain_card.rank\n else:\n remain_card = remain_card.suit\n if play_card == remain_card:\n removed_cards.append(self.current_hand[_])\n self._current_hand.remove(self._current_hand[_])\n break\n self._recorded_played_cards.append(removed_cards)\n return self\n\n def play_back(self):\n ''' Restore recorded cards back to self._current_hand\n '''\n removed_cards = self._recorded_played_cards.pop()\n self._current_hand.extend(removed_cards)\n self._current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card))\n\n\n# ./doudizhu/round.py\n# -*- coding: utf-8 -*-\n''' Implement Doudizhu Round class\n'''\n\nimport functools\nimport numpy as np\n\nfrom doudizhu import Dealer\nfrom doudizhu.utils import cards2str, doudizhu_sort_card\nfrom doudizhu.utils import CARD_RANK_STR, CARD_RANK_STR_INDEX\n\n\nclass DoudizhuRound:\n ''' Round can call other Classes' functions to keep the game running\n '''\n def __init__(self, np_random, played_cards):\n self.np_random = np_random\n self.played_cards = played_cards\n self.trace = []\n\n self.greater_player = None\n self.dealer = Dealer(self.np_random)\n self.deck_str = cards2str(self.dealer.deck)\n\n def initiate(self, players):\n ''' Call dealer to deal cards and bid landlord.\n\n Args:\n players (list): list of DoudizhuPlayer objects\n '''\n landlord_id = self.dealer.determine_role(players)\n seen_cards = self.dealer.deck[-3:]\n seen_cards.sort(key=functools.cmp_to_key(doudizhu_sort_card))\n self.seen_cards = cards2str(seen_cards)\n self.landlord_id = landlord_id\n self.current_player = landlord_id\n self.public = {'deck': self.deck_str, 'seen_cards': self.seen_cards,\n 'landlord': self.landlord_id, 'trace': self.trace,\n 'played_cards': ['' for _ in range(len(players))]}\n\n @staticmethod\n def cards_ndarray_to_str(ndarray_cards):\n result = []\n for cards in ndarray_cards:\n _result = []\n for i, _ in enumerate(cards):\n if cards[i] != 0:\n _result.extend([CARD_RANK_STR[i]] * cards[i])\n result.append(''.join(_result))\n return result\n\n def update_public(self, action):\n ''' Update public trace and played cards\n\n Args:\n action(str): string of legal specific action\n '''\n self.trace.append((self.current_player, action))\n if action != 'pass':\n for c in action:\n self.played_cards[self.current_player][CARD_RANK_STR_INDEX[c]] += 1\n if self.current_player == 0 and c in self.seen_cards:\n self.seen_cards = self.seen_cards.replace(c, '') \n self.public['seen_cards'] = self.seen_cards\n self.public['played_cards'] = self.cards_ndarray_to_str(self.played_cards)\n\n def proceed_round(self, player, action):\n ''' Call other Classes's functions to keep one round running\n\n Args:\n player (object): object of DoudizhuPlayer\n action (str): string of legal specific action\n\n Returns:\n object of DoudizhuPlayer: player who played current biggest cards.\n '''\n self.update_public(action)\n self.greater_player = player.play(action, self.greater_player)\n return self.greater_player\n\n def step_back(self, players):\n ''' Reverse the last action\n\n Args:\n players (list): list of DoudizhuPlayer objects\n Returns:\n The last player id and the cards played\n '''\n player_id, cards = self.trace.pop()\n self.current_player = player_id\n if (cards != 'pass'):\n for card in cards:\n # self.played_cards.remove(card)\n self.played_cards[player_id][CARD_RANK_STR_INDEX[card]] -= 1\n self.public['played_cards'] = self.cards_ndarray_to_str(self.played_cards)\n greater_player_id = self.find_last_greater_player_id_in_trace()\n if (greater_player_id is not None):\n self.greater_player = players[greater_player_id]\n else:\n self.greater_player = None\n return player_id, cards\n\n def find_last_greater_player_id_in_trace(self):\n ''' Find the last greater_player's id in trace\n\n Returns:\n The last greater_player's id in trace\n '''\n for i in range(len(self.trace) - 1, -1, -1):\n _id, action = self.trace[i]\n if (action != 'pass'):\n return _id\n return None\n\n def find_last_played_cards_in_trace(self, player_id):\n ''' Find the player_id's last played_cards in trace\n\n Returns:\n The player_id's last played_cards in trace\n '''\n for i in range(len(self.trace) - 1, -1, -1):\n _id, action = self.trace[i]\n if (_id == player_id and action != 'pass'):\n return action\n return None\n\n\n# ./doudizhu/utils.py\n''' Doudizhu utils\n'''\nimport os\nimport json\nfrom collections import OrderedDict\nimport threading\nimport collections\n\n# import rlcard\n\n# Read required docs\nROOT_PATH = '.'\n\n# if not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/action_space.txt')) \\\n# or not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/card_type.json')) \\\n# or not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/type_card.json')):\n# import zipfile\n# with zipfile.ZipFile(os.path.join(ROOT_PATH, 'jsondata.zip'),\"r\") as zip_ref:\n# zip_ref.extractall(os.path.join(ROOT_PATH, '/'))\n\n# Action space\naction_space_path = os.path.join(ROOT_PATH, './jsondata/action_space.txt')\n\nwith open(action_space_path, 'r') as f:\n ID_2_ACTION = f.readline().strip().split()\n ACTION_2_ID = {}\n for i, action in enumerate(ID_2_ACTION):\n ACTION_2_ID[action] = i\n\n# a map of card to its type. Also return both dict and list to accelerate\ncard_type_path = os.path.join(ROOT_PATH, './jsondata/card_type.json')\nwith open(card_type_path, 'r') as f:\n data = json.load(f, object_pairs_hook=OrderedDict)\n CARD_TYPE = (data, list(data), set(data))\n\n# a map of type to its cards\ntype_card_path = os.path.join(ROOT_PATH, './jsondata/type_card.json')\nwith open(type_card_path, 'r') as f:\n TYPE_CARD = json.load(f, object_pairs_hook=OrderedDict)\n\n# rank list of solo character of cards\nCARD_RANK_STR = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K',\n 'A', '2', 'B', 'R']\nCARD_RANK_STR_INDEX = {'3': 0, '4': 1, '5': 2, '6': 3, '7': 4,\n '8': 5, '9': 6, 'T': 7, 'J': 8, 'Q': 9,\n 'K': 10, 'A': 11, '2': 12, 'B': 13, 'R': 14}\n# rank list\nCARD_RANK = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K',\n 'A', '2', 'BJ', 'RJ']\n\nINDEX = {'3': 0, '4': 1, '5': 2, '6': 3, '7': 4,\n '8': 5, '9': 6, 'T': 7, 'J': 8, 'Q': 9,\n 'K': 10, 'A': 11, '2': 12, 'B': 13, 'R': 14}\nINDEX = OrderedDict(sorted(INDEX.items(), key=lambda t: t[1]))\n\n\ndef doudizhu_sort_str(card_1, card_2):\n ''' Compare the rank of two cards of str representation\n\n Args:\n card_1 (str): str representation of solo card\n card_2 (str): str representation of solo card\n\n Returns:\n int: 1(card_1 > card_2) / 0(card_1 = card2) / -1(card_1 < card_2)\n '''\n key_1 = CARD_RANK_STR.index(card_1)\n key_2 = CARD_RANK_STR.index(card_2)\n if key_1 > key_2:\n return 1\n if key_1 < key_2:\n return -1\n return 0\n\n\ndef doudizhu_sort_card(card_1, card_2):\n ''' Compare the rank of two cards of Card object\n\n Args:\n card_1 (object): object of Card\n card_2 (object): object of card\n '''\n key = []\n for card in [card_1, card_2]:\n if card.rank == '':\n key.append(CARD_RANK.index(card.suit))\n else:\n key.append(CARD_RANK.index(card.rank))\n if key[0] > key[1]:\n return 1\n if key[0] < key[1]:\n return -1\n return 0\n\n\ndef get_landlord_score(current_hand):\n ''' Roughly judge the quality of the hand, and provide a score as basis to\n bid landlord.\n\n Args:\n current_hand (str): string of cards. Eg: '56888TTQKKKAA222R'\n\n Returns:\n int: score\n '''\n score_map = {'A': 1, '2': 2, 'B': 3, 'R': 4}\n score = 0\n # rocket\n if current_hand[-2:] == 'BR':\n score += 8\n current_hand = current_hand[:-2]\n length = len(current_hand)\n i = 0\n while i < length:\n # bomb\n if i <= (length - 4) and current_hand[i] == current_hand[i+3]:\n score += 6\n i += 4\n continue\n # 2, Black Joker, Red Joker\n if current_hand[i] in score_map:\n score += score_map[current_hand[i]]\n i += 1\n return score\n\ndef cards2str_with_suit(cards):\n ''' Get the corresponding string representation of cards with suit\n\n Args:\n cards (list): list of Card objects\n\n Returns:\n string: string representation of cards\n '''\n return ' '.join([card.suit+card.rank for card in cards])\n\ndef cards2str(cards):\n ''' Get the corresponding string representation of cards\n\n Args:\n cards (list): list of Card objects\n\n Returns:\n string: string representation of cards\n '''\n response = ''\n for card in cards:\n if card.rank == '':\n response += card.suit[0]\n else:\n response += card.rank\n return response\n\nclass LocalObjs(threading.local):\n def __init__(self):\n self.cached_candidate_cards = None\n_local_objs = LocalObjs()\n\ndef contains_cards(candidate, target):\n ''' Check if cards of candidate contains cards of target.\n\n Args:\n candidate (string): A string representing the cards of candidate\n target (string): A string representing the number of cards of target\n\n Returns:\n boolean\n '''\n # In normal cases, most continuous calls of this function\n # will test different targets against the same candidate.\n # So the cached counts of each card in candidate can speed up\n # the comparison for following tests if candidate keeps the same.\n if not _local_objs.cached_candidate_cards or _local_objs.cached_candidate_cards != candidate:\n _local_objs.cached_candidate_cards = candidate\n cards_dict = collections.defaultdict(int)\n for card in candidate:\n cards_dict[card] += 1\n _local_objs.cached_candidate_cards_dict = cards_dict\n cards_dict = _local_objs.cached_candidate_cards_dict\n if (target == ''):\n return True\n curr_card = target[0]\n curr_count = 1\n for card in target[1:]:\n if (card != curr_card):\n if (cards_dict[curr_card] < curr_count):\n return False\n curr_card = card\n curr_count = 1\n else:\n curr_count += 1\n if (cards_dict[curr_card] < curr_count):\n return False\n return True\n\ndef encode_cards(plane, cards):\n ''' Encode cards and represerve it into plane.\n\n Args:\n cards (list or str): list or str of cards, every entry is a\n character of solo representation of card\n '''\n if not cards:\n return None\n layer = 1\n if len(cards) == 1:\n rank = CARD_RANK_STR.index(cards[0])\n plane[layer][rank] = 1\n plane[0][rank] = 0\n else:\n for index, card in enumerate(cards):\n if index == 0:\n continue\n if card == cards[index-1]:\n layer += 1\n else:\n rank = CARD_RANK_STR.index(cards[index-1])\n plane[layer][rank] = 1\n layer = 1\n plane[0][rank] = 0\n rank = CARD_RANK_STR.index(cards[-1])\n plane[layer][rank] = 1\n plane[0][rank] = 0\n\n\ndef get_gt_cards(player, greater_player):\n ''' Provide player's cards which are greater than the ones played by\n previous player in one round\n\n Args:\n player (DoudizhuPlayer object): the player waiting to play cards\n greater_player (DoudizhuPlayer object): the player who played current biggest cards.\n\n Returns:\n list: list of string of greater cards\n\n Note:\n 1. return value contains 'pass'\n '''\n # add 'pass' to legal actions\n gt_cards = ['pass']\n current_hand = cards2str(player.current_hand)\n target_cards = greater_player.played_cards\n target_types = CARD_TYPE[0][target_cards]\n type_dict = {}\n for card_type, weight in target_types:\n if card_type not in type_dict:\n type_dict[card_type] = weight\n if 'rocket' in type_dict:\n return gt_cards\n type_dict['rocket'] = -1\n if 'bomb' not in type_dict:\n type_dict['bomb'] = -1\n for card_type, weight in type_dict.items():\n candidate = TYPE_CARD[card_type]\n for can_weight, cards_list in candidate.items():\n if int(can_weight) > int(weight):\n for cards in cards_list:\n # TODO: improve efficiency\n if cards not in gt_cards and contains_cards(current_hand, cards):\n # if self.contains_cards(current_hand, cards):\n gt_cards.append(cards)\n return gt_cards\n", "num_file": 8, "num_lines": 1178, "programming_language": "Python"} {"class_name": "fuzzywuzzy", "id": "./MultiFileTest/Python/fuzzywuzzy.py", "original_code": "# ./fuzzywuzzy/StringMatcher.py\n#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nStringMatcher.py\n\nported from python-Levenshtein\n[https://github.com/miohtama/python-Levenshtein]\nLicense available here: https://github.com/miohtama/python-Levenshtein/blob/master/COPYING\n\"\"\"\n\nfrom Levenshtein import *\nfrom warnings import warn\n\n\nclass StringMatcher:\n \"\"\"A SequenceMatcher-like class built on the top of Levenshtein\"\"\"\n\n def _reset_cache(self):\n self._ratio = self._distance = None\n self._opcodes = self._editops = self._matching_blocks = None\n\n def __init__(self, isjunk=None, seq1='', seq2=''):\n if isjunk:\n warn(\"isjunk not NOT implemented, it will be ignored\")\n self._str1, self._str2 = seq1, seq2\n self._reset_cache()\n\n def set_seqs(self, seq1, seq2):\n self._str1, self._str2 = seq1, seq2\n self._reset_cache()\n\n def set_seq1(self, seq1):\n self._str1 = seq1\n self._reset_cache()\n\n def set_seq2(self, seq2):\n self._str2 = seq2\n self._reset_cache()\n\n def get_opcodes(self):\n if not self._opcodes:\n if self._editops:\n self._opcodes = opcodes(self._editops, self._str1, self._str2)\n else:\n self._opcodes = opcodes(self._str1, self._str2)\n return self._opcodes\n\n def get_editops(self):\n if not self._editops:\n if self._opcodes:\n self._editops = editops(self._opcodes, self._str1, self._str2)\n else:\n self._editops = editops(self._str1, self._str2)\n return self._editops\n\n def get_matching_blocks(self):\n if not self._matching_blocks:\n self._matching_blocks = matching_blocks(self.get_opcodes(),\n self._str1, self._str2)\n return self._matching_blocks\n\n def ratio(self):\n if not self._ratio:\n self._ratio = ratio(self._str1, self._str2)\n return self._ratio\n\n def quick_ratio(self):\n # This is usually quick enough :o)\n if not self._ratio:\n self._ratio = ratio(self._str1, self._str2)\n return self._ratio\n\n def real_quick_ratio(self):\n len1, len2 = len(self._str1), len(self._str2)\n return 2.0 * min(len1, len2) / (len1 + len2)\n\n def distance(self):\n if not self._distance:\n self._distance = distance(self._str1, self._str2)\n return self._distance\n\n\n# ./fuzzywuzzy/__init__.py\n# -*- coding: utf-8 -*-\n__version__ = '0.18.0'\n\n\n# ./fuzzywuzzy/fuzz.py\n#!/usr/bin/env python\n# encoding: utf-8\nfrom __future__ import unicode_literals\nimport platform\nimport warnings\n\ntry:\n from .StringMatcher import StringMatcher as SequenceMatcher\nexcept ImportError:\n if platform.python_implementation() != \"PyPy\":\n warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning')\n from difflib import SequenceMatcher\n\nimport utils\n\n\n###########################\n# Basic Scoring Functions #\n###########################\n\n@utils.check_for_none\n@utils.check_for_equivalence\n@utils.check_empty_string\ndef ratio(s1, s2):\n s1, s2 = utils.make_type_consistent(s1, s2)\n\n m = SequenceMatcher(None, s1, s2)\n return utils.intr(100 * m.ratio())\n\n\n@utils.check_for_none\n@utils.check_for_equivalence\n@utils.check_empty_string\ndef partial_ratio(s1, s2):\n \"\"\"\"Return the ratio of the most similar substring\n as a number between 0 and 100.\"\"\"\n s1, s2 = utils.make_type_consistent(s1, s2)\n\n if len(s1) <= len(s2):\n shorter = s1\n longer = s2\n else:\n shorter = s2\n longer = s1\n\n m = SequenceMatcher(None, shorter, longer)\n blocks = m.get_matching_blocks()\n\n # each block represents a sequence of matching characters in a string\n # of the form (idx_1, idx_2, len)\n # the best partial match will block align with at least one of those blocks\n # e.g. shorter = \"abcd\", longer = XXXbcdeEEE\n # block = (1,3,3)\n # best score === ratio(\"abcd\", \"Xbcd\")\n scores = []\n for block in blocks:\n long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0\n long_end = long_start + len(shorter)\n long_substr = longer[long_start:long_end]\n\n m2 = SequenceMatcher(None, shorter, long_substr)\n r = m2.ratio()\n if r > .995:\n return 100\n else:\n scores.append(r)\n\n return utils.intr(100 * max(scores))\n\n\n##############################\n# Advanced Scoring Functions #\n##############################\n\ndef _process_and_sort(s, force_ascii, full_process=True):\n \"\"\"Return a cleaned string with token sorted.\"\"\"\n # pull tokens\n ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s\n tokens = ts.split()\n\n # sort tokens and join\n sorted_string = u\" \".join(sorted(tokens))\n return sorted_string.strip()\n\n\n# Sorted Token\n# find all alphanumeric tokens in the string\n# sort those tokens and take ratio of resulting joined strings\n# controls for unordered string elements\n@utils.check_for_none\ndef _token_sort(s1, s2, partial=True, force_ascii=True, full_process=True):\n sorted1 = _process_and_sort(s1, force_ascii, full_process=full_process)\n sorted2 = _process_and_sort(s2, force_ascii, full_process=full_process)\n\n if partial:\n return partial_ratio(sorted1, sorted2)\n else:\n return ratio(sorted1, sorted2)\n\n\ndef token_sort_ratio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"Return a measure of the sequences' similarity between 0 and 100\n but sorting the token before comparing.\n \"\"\"\n return _token_sort(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process)\n\n\ndef partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"Return the ratio of the most similar substring as a number between\n 0 and 100 but sorting the token before comparing.\n \"\"\"\n return _token_sort(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process)\n\n\n@utils.check_for_none\ndef _token_set(s1, s2, partial=True, force_ascii=True, full_process=True):\n \"\"\"Find all alphanumeric tokens in each string...\n - treat them as a set\n - construct two strings of the form:\n \n - take ratios of those two strings\n - controls for unordered partial matches\"\"\"\n\n if not full_process and s1 == s2:\n return 100\n\n p1 = utils.full_process(s1, force_ascii=force_ascii) if full_process else s1\n p2 = utils.full_process(s2, force_ascii=force_ascii) if full_process else s2\n\n if not utils.validate_string(p1):\n return 0\n if not utils.validate_string(p2):\n return 0\n\n # pull tokens\n tokens1 = set(p1.split())\n tokens2 = set(p2.split())\n\n intersection = tokens1.intersection(tokens2)\n diff1to2 = tokens1.difference(tokens2)\n diff2to1 = tokens2.difference(tokens1)\n\n sorted_sect = \" \".join(sorted(intersection))\n sorted_1to2 = \" \".join(sorted(diff1to2))\n sorted_2to1 = \" \".join(sorted(diff2to1))\n\n combined_1to2 = sorted_sect + \" \" + sorted_1to2\n combined_2to1 = sorted_sect + \" \" + sorted_2to1\n\n # strip\n sorted_sect = sorted_sect.strip()\n combined_1to2 = combined_1to2.strip()\n combined_2to1 = combined_2to1.strip()\n\n if partial:\n ratio_func = partial_ratio\n else:\n ratio_func = ratio\n\n pairwise = [\n ratio_func(sorted_sect, combined_1to2),\n ratio_func(sorted_sect, combined_2to1),\n ratio_func(combined_1to2, combined_2to1)\n ]\n return max(pairwise)\n\n\ndef token_set_ratio(s1, s2, force_ascii=True, full_process=True):\n return _token_set(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process)\n\n\ndef partial_token_set_ratio(s1, s2, force_ascii=True, full_process=True):\n return _token_set(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process)\n\n\n###################\n# Combination API #\n###################\n\n# q is for quick\ndef QRatio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Quick ratio comparison between two strings.\n\n Runs full_process from utils on both strings\n Short circuits if either of the strings is empty after processing.\n\n :param s1:\n :param s2:\n :param force_ascii: Allow only ASCII characters (Default: True)\n :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)\n :return: similarity ratio\n \"\"\"\n\n if full_process:\n p1 = utils.full_process(s1, force_ascii=force_ascii)\n p2 = utils.full_process(s2, force_ascii=force_ascii)\n else:\n p1 = s1\n p2 = s2\n\n if not utils.validate_string(p1):\n return 0\n if not utils.validate_string(p2):\n return 0\n\n return ratio(p1, p2)\n\n\ndef UQRatio(s1, s2, full_process=True):\n \"\"\"\n Unicode quick ratio\n\n Calls QRatio with force_ascii set to False\n\n :param s1:\n :param s2:\n :return: similarity ratio\n \"\"\"\n return QRatio(s1, s2, force_ascii=False, full_process=full_process)\n\n\n# w is for weighted\ndef WRatio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Return a measure of the sequences' similarity between 0 and 100, using different algorithms.\n\n **Steps in the order they occur**\n\n #. Run full_process from utils on both strings\n #. Short circuit if this makes either string empty\n #. Take the ratio of the two processed strings (fuzz.ratio)\n #. Run checks to compare the length of the strings\n * If one of the strings is more than 1.5 times as long as the other\n use partial_ratio comparisons - scale partial results by 0.9\n (this makes sure only full results can return 100)\n * If one of the strings is over 8 times as long as the other\n instead scale by 0.6\n\n #. Run the other ratio functions\n * if using partial ratio functions call partial_ratio,\n partial_token_sort_ratio and partial_token_set_ratio\n scale all of these by the ratio based on length\n * otherwise call token_sort_ratio and token_set_ratio\n * all token based comparisons are scaled by 0.95\n (on top of any partial scalars)\n\n #. Take the highest value from these results\n round it and return it as an integer.\n\n :param s1:\n :param s2:\n :param force_ascii: Allow only ascii characters\n :type force_ascii: bool\n :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)\n :return:\n \"\"\"\n\n if full_process:\n p1 = utils.full_process(s1, force_ascii=force_ascii)\n p2 = utils.full_process(s2, force_ascii=force_ascii)\n else:\n p1 = s1\n p2 = s2\n\n if not utils.validate_string(p1):\n return 0\n if not utils.validate_string(p2):\n return 0\n\n # should we look at partials?\n try_partial = True\n unbase_scale = .95\n partial_scale = .90\n\n base = ratio(p1, p2)\n len_ratio = float(max(len(p1), len(p2))) / min(len(p1), len(p2))\n\n # if strings are similar length, don't use partials\n if len_ratio < 1.5:\n try_partial = False\n\n # if one string is much much shorter than the other\n if len_ratio > 8:\n partial_scale = .6\n\n if try_partial:\n partial = partial_ratio(p1, p2) * partial_scale\n ptsor = partial_token_sort_ratio(p1, p2, full_process=False) \\\n * unbase_scale * partial_scale\n ptser = partial_token_set_ratio(p1, p2, full_process=False) \\\n * unbase_scale * partial_scale\n\n return utils.intr(max(base, partial, ptsor, ptser))\n else:\n tsor = token_sort_ratio(p1, p2, full_process=False) * unbase_scale\n tser = token_set_ratio(p1, p2, full_process=False) * unbase_scale\n\n return utils.intr(max(base, tsor, tser))\n\n\ndef UWRatio(s1, s2, full_process=True):\n \"\"\"Return a measure of the sequences' similarity between 0 and 100,\n using different algorithms. Same as WRatio but preserving unicode.\n \"\"\"\n return WRatio(s1, s2, force_ascii=False, full_process=full_process)\n\n\n# ./fuzzywuzzy/process.py\n#!/usr/bin/env python\n# encoding: utf-8\nimport fuzz\nimport utils\nimport heapq\nimport logging\nfrom functools import partial\n\n\ndefault_scorer = fuzz.WRatio\n\n\ndefault_processor = utils.full_process\n\n\ndef extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):\n \"\"\"Select the best match in a list or dictionary of choices.\n\n Find best matches in a list or dictionary of choices, return a\n generator of tuples containing the match and its score. If a dictionary\n is used, also returns the key for each match.\n\n Arguments:\n query: An object representing the thing we want to find.\n choices: An iterable or dictionary-like object containing choices\n to be matched against the query. Dictionary arguments of\n {key: value} pairs will attempt to match the query against\n each value.\n processor: Optional function of the form f(a) -> b, where a is the query or\n individual choice and b is the choice to be used in matching.\n\n This can be used to match against, say, the first element of\n a list:\n\n lambda x: x[0]\n\n Defaults to fuzzywuzzy.utils.full_process().\n scorer: Optional function for scoring matches between the query and\n an individual processed choice. This should be a function\n of the form f(query, choice) -> int.\n\n By default, fuzz.WRatio() is used and expects both query and\n choice to be strings.\n score_cutoff: Optional argument for score threshold. No matches with\n a score less than this number will be returned. Defaults to 0.\n\n Returns:\n Generator of tuples containing the match and its score.\n\n If a list is used for choices, then the result will be 2-tuples.\n If a dictionary is used, then the result will be 3-tuples containing\n the key for each match.\n\n For example, searching for 'bird' in the dictionary\n\n {'bard': 'train', 'dog': 'man'}\n\n may return\n\n ('train', 22, 'bard'), ('man', 0, 'dog')\n \"\"\"\n # Catch generators without lengths\n def no_process(x):\n return x\n\n try:\n if choices is None or len(choices) == 0:\n return\n except TypeError:\n pass\n\n # If the processor was removed by setting it to None\n # perfom a noop as it still needs to be a function\n if processor is None:\n processor = no_process\n\n # Run the processor on the input query.\n processed_query = processor(query)\n\n if len(processed_query) == 0:\n logging.warning(u\"Applied processor reduces input query to empty string, \"\n \"all comparisons will have score 0. \"\n \"[Query: \\'{0}\\']\".format(query))\n\n # Don't run full_process twice\n if scorer in [fuzz.WRatio, fuzz.QRatio,\n fuzz.token_set_ratio, fuzz.token_sort_ratio,\n fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio,\n fuzz.UWRatio, fuzz.UQRatio] \\\n and processor == utils.full_process:\n processor = no_process\n\n # Only process the query once instead of for every choice\n if scorer in [fuzz.UWRatio, fuzz.UQRatio]:\n pre_processor = partial(utils.full_process, force_ascii=False)\n scorer = partial(scorer, full_process=False)\n elif scorer in [fuzz.WRatio, fuzz.QRatio,\n fuzz.token_set_ratio, fuzz.token_sort_ratio,\n fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio]:\n pre_processor = partial(utils.full_process, force_ascii=True)\n scorer = partial(scorer, full_process=False)\n else:\n pre_processor = no_process\n processed_query = pre_processor(processed_query)\n\n try:\n # See if choices is a dictionary-like object.\n for key, choice in choices.items():\n processed = pre_processor(processor(choice))\n score = scorer(processed_query, processed)\n if score >= score_cutoff:\n yield (choice, score, key)\n except AttributeError:\n # It's a list; just iterate over it.\n for choice in choices:\n processed = pre_processor(processor(choice))\n score = scorer(processed_query, processed)\n if score >= score_cutoff:\n yield (choice, score)\n\n\ndef extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5):\n \"\"\"Select the best match in a list or dictionary of choices.\n\n Find best matches in a list or dictionary of choices, return a\n list of tuples containing the match and its score. If a dictionary\n is used, also returns the key for each match.\n\n Arguments:\n query: An object representing the thing we want to find.\n choices: An iterable or dictionary-like object containing choices\n to be matched against the query. Dictionary arguments of\n {key: value} pairs will attempt to match the query against\n each value.\n processor: Optional function of the form f(a) -> b, where a is the query or\n individual choice and b is the choice to be used in matching.\n\n This can be used to match against, say, the first element of\n a list:\n\n lambda x: x[0]\n\n Defaults to fuzzywuzzy.utils.full_process().\n scorer: Optional function for scoring matches between the query and\n an individual processed choice. This should be a function\n of the form f(query, choice) -> int.\n By default, fuzz.WRatio() is used and expects both query and\n choice to be strings.\n limit: Optional maximum for the number of elements returned. Defaults\n to 5.\n\n Returns:\n List of tuples containing the match and its score.\n\n If a list is used for choices, then the result will be 2-tuples.\n If a dictionary is used, then the result will be 3-tuples containing\n the key for each match.\n\n For example, searching for 'bird' in the dictionary\n\n {'bard': 'train', 'dog': 'man'}\n\n may return\n\n [('train', 22, 'bard'), ('man', 0, 'dog')]\n \"\"\"\n sl = extractWithoutOrder(query, choices, processor, scorer)\n return heapq.nlargest(limit, sl, key=lambda i: i[1]) if limit is not None else \\\n sorted(sl, key=lambda i: i[1], reverse=True)\n\n\ndef extractBests(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0, limit=5):\n \"\"\"Get a list of the best matches to a collection of choices.\n\n Convenience function for getting the choices with best scores.\n\n Args:\n query: A string to match against\n choices: A list or dictionary of choices, suitable for use with\n extract().\n processor: Optional function for transforming choices before matching.\n See extract().\n scorer: Scoring function for extract().\n score_cutoff: Optional argument for score threshold. No matches with\n a score less than this number will be returned. Defaults to 0.\n limit: Optional maximum for the number of elements returned. Defaults\n to 5.\n\n Returns: A a list of (match, score) tuples.\n \"\"\"\n\n best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff)\n return heapq.nlargest(limit, best_list, key=lambda i: i[1]) if limit is not None else \\\n sorted(best_list, key=lambda i: i[1], reverse=True)\n\n\ndef extractOne(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):\n \"\"\"Find the single best match above a score in a list of choices.\n\n This is a convenience method which returns the single best choice.\n See extract() for the full arguments list.\n\n Args:\n query: A string to match against\n choices: A list or dictionary of choices, suitable for use with\n extract().\n processor: Optional function for transforming choices before matching.\n See extract().\n scorer: Scoring function for extract().\n score_cutoff: Optional argument for score threshold. If the best\n match is found, but it is not greater than this number, then\n return None anyway (\"not a good enough match\"). Defaults to 0.\n\n Returns:\n A tuple containing a single match and its score, if a match\n was found that was above score_cutoff. Otherwise, returns None.\n \"\"\"\n best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff)\n try:\n return max(best_list, key=lambda i: i[1])\n except ValueError:\n return None\n\n\ndef dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio):\n \"\"\"This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify\n and remove duplicates. Specifically, it uses the process.extract to identify duplicates that\n score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list\n since we assume this item contains the most entity information and returns that. It breaks string\n length ties on an alphabetical sort.\n\n Note: as the threshold DECREASES the number of duplicates that are found INCREASES. This means that the\n returned deduplicated list will likely be shorter. Raise the threshold for fuzzy_dedupe to be less\n sensitive.\n\n Args:\n contains_dupes: A list of strings that we would like to dedupe.\n threshold: the numerical value (0,100) point at which we expect to find duplicates.\n Defaults to 70 out of 100\n scorer: Optional function for scoring matches between the query and\n an individual processed choice. This should be a function\n of the form f(query, choice) -> int.\n By default, fuzz.token_set_ratio() is used and expects both query and\n choice to be strings.\n\n Returns:\n A deduplicated list. For example:\n\n In: contains_dupes = ['Frodo Baggin', 'Frodo Baggins', 'F. Baggins', 'Samwise G.', 'Gandalf', 'Bilbo Baggins']\n In: fuzzy_dedupe(contains_dupes)\n Out: ['Frodo Baggins', 'Samwise G.', 'Bilbo Baggins', 'Gandalf']\n \"\"\"\n\n extractor = []\n\n # iterate over items in *contains_dupes*\n for item in contains_dupes:\n # return all duplicate matches found\n matches = extract(item, contains_dupes, limit=None, scorer=scorer)\n # filter matches based on the threshold\n filtered = [x for x in matches if x[1] > threshold]\n # if there is only 1 item in *filtered*, no duplicates were found so append to *extracted*\n if len(filtered) == 1:\n extractor.append(filtered[0][0])\n\n else:\n # alpha sort\n filtered = sorted(filtered, key=lambda x: x[0])\n # length sort\n filter_sort = sorted(filtered, key=lambda x: len(x[0]), reverse=True)\n # take first item as our 'canonical example'\n extractor.append(filter_sort[0][0])\n\n # uniquify *extractor* list\n keys = {}\n for e in extractor:\n keys[e] = 1\n extractor = keys.keys()\n\n # check that extractor differs from contain_dupes (e.g. duplicates were found)\n # if not, then return the original list\n if len(extractor) == len(contains_dupes):\n return contains_dupes\n else:\n return extractor\n\n\n# ./fuzzywuzzy/string_processing.py\nfrom __future__ import unicode_literals\nimport re\nimport string\nimport sys\n\nPY3 = sys.version_info[0] == 3\nif PY3:\n string = str\n\n\nclass StringProcessor(object):\n \"\"\"\n This class defines method to process strings in the most\n efficient way. Ideally all the methods below use unicode strings\n for both input and output.\n \"\"\"\n\n regex = re.compile(r\"(?ui)\\W\")\n\n @classmethod\n def replace_non_letters_non_numbers_with_whitespace(cls, a_string):\n \"\"\"\n This function replaces any sequence of non letters and non\n numbers with a single white space.\n \"\"\"\n return cls.regex.sub(\" \", a_string)\n\n strip = staticmethod(string.strip)\n to_lower_case = staticmethod(string.lower)\n to_upper_case = staticmethod(string.upper)\n\n\n# ./fuzzywuzzy/utils.py\nfrom __future__ import unicode_literals\nimport sys\nimport functools\n\nfrom string_processing import StringProcessor\n\n\nPY3 = sys.version_info[0] == 3\n\n\ndef validate_string(s):\n \"\"\"\n Check input has length and that length > 0\n\n :param s:\n :return: True if len(s) > 0 else False\n \"\"\"\n try:\n return len(s) > 0\n except TypeError:\n return False\n\n\ndef check_for_equivalence(func):\n @functools.wraps(func)\n def decorator(*args, **kwargs):\n if args[0] == args[1]:\n return 100\n return func(*args, **kwargs)\n return decorator\n\n\ndef check_for_none(func):\n @functools.wraps(func)\n def decorator(*args, **kwargs):\n if args[0] is None or args[1] is None:\n return 0\n return func(*args, **kwargs)\n return decorator\n\n\ndef check_empty_string(func):\n @functools.wraps(func)\n def decorator(*args, **kwargs):\n if len(args[0]) == 0 or len(args[1]) == 0:\n return 0\n return func(*args, **kwargs)\n return decorator\n\n\nbad_chars = str(\"\").join([chr(i) for i in range(128, 256)]) # ascii dammit!\nif PY3:\n translation_table = dict((ord(c), None) for c in bad_chars)\n unicode = str\n\n\ndef asciionly(s):\n if PY3:\n return s.translate(translation_table)\n else:\n return s.translate(None, bad_chars)\n\n\ndef asciidammit(s):\n if type(s) is str:\n return asciionly(s)\n elif type(s) is unicode:\n return asciionly(s.encode('ascii', 'ignore'))\n else:\n return asciidammit(unicode(s))\n\n\ndef make_type_consistent(s1, s2):\n \"\"\"If both objects aren't either both string or unicode instances force them to unicode\"\"\"\n if isinstance(s1, str) and isinstance(s2, str):\n return s1, s2\n\n elif isinstance(s1, unicode) and isinstance(s2, unicode):\n return s1, s2\n\n else:\n return unicode(s1), unicode(s2)\n\n\ndef full_process(s, force_ascii=False):\n \"\"\"Process string by\n -- removing all but letters and numbers\n -- trim whitespace\n -- force to lower case\n if force_ascii == True, force convert to ascii\"\"\"\n\n if force_ascii:\n s = asciidammit(s)\n # Keep only Letters and Numbers (see Unicode docs).\n string_out = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s)\n # Force into lowercase.\n string_out = StringProcessor.to_lower_case(string_out)\n # Remove leading and trailing whitespaces.\n string_out = StringProcessor.strip(string_out)\n return string_out\n\n\ndef intr(n):\n '''Returns a correctly rounded integer'''\n return int(round(n))\n", "num_file": 6, "num_lines": 808, "programming_language": "Python"} {"class_name": "gin_rummy", "id": "./MultiFileTest/Python/gin_rummy.py", "original_code": "# ./gin_rummy/__init__.py\n\nfrom gin_rummy.base import Card as Card\nfrom gin_rummy.player import GinRummyPlayer as Player\nfrom gin_rummy.dealer import GinRummyDealer as Dealer\nfrom gin_rummy.judge import GinRummyJudge as Judger\n\n\nfrom gin_rummy.game import GinRummyGame as Game\n\n# ./gin_rummy/action_event.py\nfrom gin_rummy import Card\n\nimport utils as utils\n\n# ====================================\n# Action_ids:\n# 0 -> score_player_0_id\n# 1 -> score_player_1_id\n# 2 -> draw_card_id\n# 3 -> pick_up_discard_id\n# 4 -> declare_dead_hand_id\n# 5 -> gin_id\n# 6 to 57 -> discard_id card_id\n# 58 to 109 -> knock_id card_id\n# ====================================\n\nscore_player_0_action_id = 0\nscore_player_1_action_id = 1\ndraw_card_action_id = 2\npick_up_discard_action_id = 3\ndeclare_dead_hand_action_id = 4\ngin_action_id = 5\ndiscard_action_id = 6\nknock_action_id = discard_action_id + 52\n\n\nclass ActionEvent(object):\n\n def __init__(self, action_id: int):\n self.action_id = action_id\n\n def __eq__(self, other):\n result = False\n if isinstance(other, ActionEvent):\n result = self.action_id == other.action_id\n return result\n\n @staticmethod\n def get_num_actions():\n ''' Return the number of possible actions in the game\n '''\n return knock_action_id + 52 # FIXME: sensitive to code changes 200213\n\n @staticmethod\n def decode_action(action_id) -> 'ActionEvent':\n ''' Action id -> the action_event in the game.\n\n Args:\n action_id (int): the id of the action\n\n Returns:\n action (ActionEvent): the action that will be passed to the game engine.\n '''\n if action_id == score_player_0_action_id:\n action_event = ScoreNorthPlayerAction()\n elif action_id == score_player_1_action_id:\n action_event = ScoreSouthPlayerAction()\n elif action_id == draw_card_action_id:\n action_event = DrawCardAction()\n elif action_id == pick_up_discard_action_id:\n action_event = PickUpDiscardAction()\n elif action_id == declare_dead_hand_action_id:\n action_event = DeclareDeadHandAction()\n elif action_id == gin_action_id:\n action_event = GinAction()\n elif action_id in range(discard_action_id, discard_action_id + 52):\n card_id = action_id - discard_action_id\n card = utils.get_card(card_id=card_id)\n action_event = DiscardAction(card=card)\n elif action_id in range(knock_action_id, knock_action_id + 52):\n card_id = action_id - knock_action_id\n card = utils.get_card(card_id=card_id)\n action_event = KnockAction(card=card)\n else:\n raise Exception(\"decode_action: unknown action_id={}\".format(action_id))\n return action_event\n\n\nclass ScoreNorthPlayerAction(ActionEvent):\n\n def __init__(self):\n super().__init__(action_id=score_player_0_action_id)\n\n def __str__(self):\n return \"score N\"\n\n\nclass ScoreSouthPlayerAction(ActionEvent):\n\n def __init__(self):\n super().__init__(action_id=score_player_1_action_id)\n\n def __str__(self):\n return \"score S\"\n\n\nclass DrawCardAction(ActionEvent):\n\n def __init__(self):\n super().__init__(action_id=draw_card_action_id)\n\n def __str__(self):\n return \"draw_card\"\n\n\nclass PickUpDiscardAction(ActionEvent):\n\n def __init__(self):\n super().__init__(action_id=pick_up_discard_action_id)\n\n def __str__(self):\n return \"pick_up_discard\"\n\n\nclass DeclareDeadHandAction(ActionEvent):\n\n def __init__(self):\n super().__init__(action_id=declare_dead_hand_action_id)\n\n def __str__(self):\n return \"declare_dead_hand\"\n\n\nclass GinAction(ActionEvent):\n\n def __init__(self):\n super().__init__(action_id=gin_action_id)\n\n def __str__(self):\n return \"gin\"\n\n\nclass DiscardAction(ActionEvent):\n\n def __init__(self, card: Card):\n card_id = utils.get_card_id(card)\n super().__init__(action_id=discard_action_id + card_id)\n self.card = card\n\n def __str__(self):\n return \"discard {}\".format(str(self.card))\n\n\nclass KnockAction(ActionEvent):\n\n def __init__(self, card: Card):\n card_id = utils.get_card_id(card)\n super().__init__(action_id=knock_action_id + card_id)\n self.card = card\n\n def __str__(self):\n return \"knock {}\".format(str(self.card))\n\n\n# ./gin_rummy/base.py\n''' Game-related base classes\n'''\nclass Card:\n '''\n Card stores the suit and rank of a single card\n\n Note:\n The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]\n Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]\n '''\n suit = None\n rank = None\n valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']\n valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n\n def __init__(self, suit, rank):\n ''' Initialize the suit and rank of a card\n\n Args:\n suit: string, suit of the card, should be one of valid_suit\n rank: string, rank of the card, should be one of valid_rank\n '''\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if isinstance(other, Card):\n return self.rank == other.rank and self.suit == other.suit\n else:\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n def __hash__(self):\n suit_index = Card.valid_suit.index(self.suit)\n rank_index = Card.valid_rank.index(self.rank)\n return rank_index + 100 * suit_index\n\n def __str__(self):\n ''' Get string representation of a card.\n\n Returns:\n string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...\n '''\n return self.rank + self.suit\n\n def get_index(self):\n ''' Get index of a card.\n\n Returns:\n string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...\n '''\n return self.suit+self.rank\n\n\n# ./gin_rummy/dealer.py\nfrom gin_rummy import Player\nimport utils as utils\n\n\nclass GinRummyDealer:\n ''' Initialize a GinRummy dealer class\n '''\n def __init__(self, np_random):\n ''' Empty discard_pile, set shuffled_deck, set stock_pile\n '''\n self.np_random = np_random\n self.discard_pile = [] # type: List[Card]\n self.shuffled_deck = utils.get_deck() # keep a copy of the shuffled cards at start of new hand\n self.np_random.shuffle(self.shuffled_deck)\n self.stock_pile = self.shuffled_deck.copy() # type: List[Card]\n\n def deal_cards(self, player: Player, num: int):\n ''' Deal some cards from stock_pile to one player\n\n Args:\n player (Player): The Player object\n num (int): The number of cards to be dealt\n '''\n for _ in range(num):\n player.hand.append(self.stock_pile.pop())\n player.did_populate_hand()\n\n\n# ./gin_rummy/game.py\nimport numpy as np\n\nfrom gin_rummy import Player\nfrom round import GinRummyRound\nfrom gin_rummy import Judger\nfrom settings import Settings, DealerForRound\n\nfrom action_event import *\n\n\nclass GinRummyGame:\n ''' Game class. This class will interact with outer environment.\n '''\n\n def __init__(self, allow_step_back=False):\n '''Initialize the class GinRummyGame\n '''\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n self.judge = Judger(game=self)\n self.settings = Settings()\n self.actions = None # type: List[ActionEvent] or None # must reset in init_game\n self.round = None # round: GinRummyRound or None, must reset in init_game\n self.num_players = 2\n\n def init_game(self):\n ''' Initialize all characters in the game and start round 1\n '''\n dealer_id = self.np_random.choice([0, 1])\n if self.settings.dealer_for_round == DealerForRound.North:\n dealer_id = 0\n elif self.settings.dealer_for_round == DealerForRound.South:\n dealer_id = 1\n self.actions = []\n self.round = GinRummyRound(dealer_id=dealer_id, np_random=self.np_random)\n for i in range(2):\n num = 11 if i == 0 else 10\n player = self.round.players[(dealer_id + 1 + i) % 2]\n self.round.dealer.deal_cards(player=player, num=num)\n current_player_id = self.round.current_player_id\n state = self.get_state(player_id=current_player_id)\n return state, current_player_id\n\n def step(self, action: ActionEvent):\n ''' Perform game action and return next player number, and the state for next player\n '''\n if isinstance(action, ScoreNorthPlayerAction):\n self.round.score_player_0(action)\n elif isinstance(action, ScoreSouthPlayerAction):\n self.round.score_player_1(action)\n elif isinstance(action, DrawCardAction):\n self.round.draw_card(action)\n elif isinstance(action, PickUpDiscardAction):\n self.round.pick_up_discard(action)\n elif isinstance(action, DeclareDeadHandAction):\n self.round.declare_dead_hand(action)\n elif isinstance(action, GinAction):\n self.round.gin(action, going_out_deadwood_count=self.settings.going_out_deadwood_count)\n elif isinstance(action, DiscardAction):\n self.round.discard(action)\n elif isinstance(action, KnockAction):\n self.round.knock(action)\n else:\n raise Exception('Unknown step action={}'.format(action))\n self.actions.append(action)\n next_player_id = self.round.current_player_id\n next_state = self.get_state(player_id=next_player_id)\n return next_state, next_player_id\n\n def step_back(self):\n ''' Takes one step backward and restore to the last state\n '''\n raise NotImplementedError\n\n def get_num_players(self):\n ''' Return the number of players in the game\n '''\n return 2\n\n def get_num_actions(self):\n ''' Return the number of possible actions in the game\n '''\n return ActionEvent.get_num_actions()\n\n def get_player_id(self):\n ''' Return the current player that will take actions soon\n '''\n return self.round.current_player_id\n\n def is_over(self):\n ''' Return whether the current game is over\n '''\n return self.round.is_over\n\n def get_current_player(self) -> Player or None:\n return self.round.get_current_player()\n\n def get_last_action(self) -> ActionEvent or None:\n return self.actions[-1] if self.actions and len(self.actions) > 0 else None\n\n def get_state(self, player_id: int):\n ''' Get player's state\n\n Return:\n state (dict): The information of the state\n '''\n state = {}\n if not self.is_over():\n discard_pile = self.round.dealer.discard_pile\n top_discard = [] if not discard_pile else [discard_pile[-1]]\n dead_cards = discard_pile[:-1]\n last_action = self.get_last_action()\n opponent_id = (player_id + 1) % 2\n opponent = self.round.players[opponent_id]\n known_cards = opponent.known_cards\n if isinstance(last_action, ScoreNorthPlayerAction) or isinstance(last_action, ScoreSouthPlayerAction):\n known_cards = opponent.hand\n unknown_cards = self.round.dealer.stock_pile + [card for card in opponent.hand if card not in known_cards]\n state['player_id'] = self.round.current_player_id\n state['hand'] = [x.get_index() for x in self.round.players[self.round.current_player_id].hand]\n state['top_discard'] = [x.get_index() for x in top_discard]\n state['dead_cards'] = [x.get_index() for x in dead_cards]\n state['opponent_known_cards'] = [x.get_index() for x in known_cards]\n state['unknown_cards'] = [x.get_index() for x in unknown_cards]\n return state\n\n @staticmethod\n def decode_action(action_id) -> ActionEvent: # FIXME 200213 should return str\n ''' Action id -> the action_event in the game.\n\n Args:\n action_id (int): the id of the action\n\n Returns:\n action (ActionEvent): the action that will be passed to the game engine.\n '''\n return ActionEvent.decode_action(action_id=action_id)\n\n\n# ./gin_rummy/gin_rummy_error.py\nclass GinRummyError(Exception):\n pass\n\n\nclass GinRummyProgramError(GinRummyError):\n pass\n\n\n# ./gin_rummy/judge.py\nfrom typing import TYPE_CHECKING\n\nfrom typing import List, Tuple\n\nfrom action_event import *\nfrom scorers import GinRummyScorer\nimport melding\nfrom gin_rummy_error import GinRummyProgramError\n\nimport utils\n\n\nclass GinRummyJudge:\n\n '''\n Judge decides legal actions for current player\n '''\n\n def __init__(self, game: 'GinRummyGame'):\n ''' Initialize the class GinRummyJudge\n :param game: GinRummyGame\n '''\n self.game = game\n self.scorer = GinRummyScorer()\n\n def get_legal_actions(self) -> List[ActionEvent]:\n \"\"\"\n :return: List[ActionEvent] of legal actions\n \"\"\"\n legal_actions = [] # type: List[ActionEvent]\n last_action = self.game.get_last_action()\n if last_action is None or \\\n isinstance(last_action, DrawCardAction) or \\\n isinstance(last_action, PickUpDiscardAction):\n current_player = self.game.get_current_player()\n going_out_deadwood_count = self.game.settings.going_out_deadwood_count\n hand = current_player.hand\n meld_clusters = current_player.get_meld_clusters() # improve speed 2020-Apr\n knock_cards, gin_cards = _get_going_out_cards(meld_clusters=meld_clusters,\n hand=hand,\n going_out_deadwood_count=going_out_deadwood_count)\n if self.game.settings.is_allowed_gin and gin_cards:\n legal_actions = [GinAction()]\n else:\n cards_to_discard = [card for card in hand]\n if isinstance(last_action, PickUpDiscardAction):\n if not self.game.settings.is_allowed_to_discard_picked_up_card:\n picked_up_card = self.game.round.move_sheet[-1].card\n cards_to_discard.remove(picked_up_card)\n discard_actions = [DiscardAction(card=card) for card in cards_to_discard]\n legal_actions = discard_actions\n if self.game.settings.is_allowed_knock:\n if current_player.player_id == 0 or not self.game.settings.is_south_never_knocks:\n if knock_cards:\n knock_actions = [KnockAction(card=card) for card in knock_cards]\n if not self.game.settings.is_always_knock:\n legal_actions.extend(knock_actions)\n else:\n legal_actions = knock_actions\n elif isinstance(last_action, DeclareDeadHandAction):\n legal_actions = [ScoreNorthPlayerAction()]\n elif isinstance(last_action, GinAction):\n legal_actions = [ScoreNorthPlayerAction()]\n elif isinstance(last_action, DiscardAction):\n can_draw_card = len(self.game.round.dealer.stock_pile) > self.game.settings.stockpile_dead_card_count\n if self.game.settings.max_drawn_card_count < 52: # NOTE: this\n drawn_card_actions = [action for action in self.game.actions if isinstance(action, DrawCardAction)]\n if len(drawn_card_actions) >= self.game.settings.max_drawn_card_count:\n can_draw_card = False\n move_count = len(self.game.round.move_sheet)\n if move_count >= self.game.settings.max_move_count:\n legal_actions = [DeclareDeadHandAction()] # prevent unlimited number of moves in a game\n elif can_draw_card:\n legal_actions = [DrawCardAction()]\n if self.game.settings.is_allowed_pick_up_discard:\n legal_actions.append(PickUpDiscardAction())\n else:\n legal_actions = [DeclareDeadHandAction()]\n if self.game.settings.is_allowed_pick_up_discard:\n legal_actions.append(PickUpDiscardAction())\n elif isinstance(last_action, KnockAction):\n legal_actions = [ScoreNorthPlayerAction()]\n elif isinstance(last_action, ScoreNorthPlayerAction):\n legal_actions = [ScoreSouthPlayerAction()]\n elif isinstance(last_action, ScoreSouthPlayerAction):\n pass\n else:\n raise Exception('get_legal_actions: unknown last_action={}'.format(last_action))\n return legal_actions\n\n\ndef get_going_out_cards(hand: List[Card], going_out_deadwood_count: int) -> Tuple[List[Card], List[Card]]:\n '''\n :param hand: List[Card] -- must have 11 cards\n :param going_out_deadwood_count: int\n :return List[Card], List[Card: cards in hand that be knocked, cards in hand that can be ginned\n '''\n if not len(hand) == 11:\n raise GinRummyProgramError(\"len(hand) is {}: should be 11.\".format(len(hand)))\n meld_clusters = melding.get_meld_clusters(hand=hand)\n knock_cards, gin_cards = _get_going_out_cards(meld_clusters=meld_clusters,\n hand=hand,\n going_out_deadwood_count=going_out_deadwood_count)\n return list(knock_cards), list(gin_cards)\n\n\n#\n# private methods\n#\n\ndef _get_going_out_cards(meld_clusters: List[List[List[Card]]],\n hand: List[Card],\n going_out_deadwood_count: int) -> Tuple[List[Card], List[Card]]:\n '''\n :param meld_clusters\n :param hand: List[Card] -- must have 11 cards\n :param going_out_deadwood_count: int\n :return List[Card], List[Card: cards in hand that be knocked, cards in hand that can be ginned\n '''\n if not len(hand) == 11:\n raise GinRummyProgramError(\"len(hand) is {}: should be 11.\".format(len(hand)))\n knock_cards = set()\n gin_cards = set()\n for meld_cluster in meld_clusters:\n meld_cards = [card for meld_pile in meld_cluster for card in meld_pile]\n hand_deadwood = [card for card in hand if card not in meld_cards] # hand has 11 cards\n if len(hand_deadwood) == 0:\n # all 11 cards are melded;\n # take gin_card as first card of first 4+ meld;\n # could also take gin_card as last card of 4+ meld, but won't do this.\n for meld_pile in meld_cluster:\n if len(meld_pile) >= 4:\n gin_cards.add(meld_pile[0])\n break\n elif len(hand_deadwood) == 1:\n card = hand_deadwood[0]\n gin_cards.add(card)\n else:\n hand_deadwood_values = [utils.get_deadwood_value(card) for card in hand_deadwood]\n hand_deadwood_count = sum(hand_deadwood_values)\n max_hand_deadwood_value = max(hand_deadwood_values, default=0)\n if hand_deadwood_count <= 10 + max_hand_deadwood_value:\n for card in hand_deadwood:\n next_deadwood_count = hand_deadwood_count - utils.get_deadwood_value(card)\n if next_deadwood_count <= going_out_deadwood_count:\n knock_cards.add(card)\n return list(knock_cards), list(gin_cards)\n\n\n# ./gin_rummy/melding.py\nfrom typing import List\n\nfrom gin_rummy import Card\n\nimport utils\nfrom gin_rummy_error import GinRummyProgramError\n\n# ===============================================================\n# Terminology:\n# run_meld - three or more cards of same suit in sequence\n# set_meld - three or more cards of same rank\n# meld_pile - a run_meld or a set_meld\n# meld_piles - a list of meld_pile\n# meld_cluster - same as meld_piles, but usually with the piles being mutually disjoint\n# meld_clusters - a list of meld_cluster\n# ===============================================================\n\n\ndef get_meld_clusters(hand: List[Card]) -> List[List[List[Card]]]:\n result = [] # type: List[List[List[Card]]]\n all_run_melds = [frozenset(x) for x in get_all_run_melds(hand)]\n all_set_melds = [frozenset(x) for x in get_all_set_melds(hand)]\n all_melds = all_run_melds + all_set_melds\n all_melds_count = len(all_melds)\n for i in range(0, all_melds_count):\n first_meld = all_melds[i]\n first_meld_list = list(first_meld)\n meld_cluster_1 = [first_meld_list]\n result.append(meld_cluster_1)\n for j in range(i + 1, all_melds_count):\n second_meld = all_melds[j]\n second_meld_list = list(second_meld)\n if not second_meld.isdisjoint(first_meld):\n continue\n meld_cluster_2 = [first_meld_list, second_meld_list]\n result.append(meld_cluster_2)\n for k in range(j + 1, all_melds_count):\n third_meld = all_melds[k]\n third_meld_list = list(third_meld)\n if not third_meld.isdisjoint(first_meld) or not third_meld.isdisjoint(second_meld):\n continue\n meld_cluster_3 = [first_meld_list, second_meld_list, third_meld_list]\n result.append(meld_cluster_3)\n return result\n\n\ndef get_best_meld_clusters(hand: List[Card]) -> List[List[List[Card]]]:\n if len(hand) != 10:\n raise GinRummyProgramError(\"Hand contain {} cards: should be 10 cards.\".format(len(hand)))\n result = [] # type: List[List[List[Card]]]\n meld_clusters = get_meld_clusters(hand=hand) # type: List[List[List[Card]]]\n meld_clusters_count = len(meld_clusters)\n if meld_clusters_count > 0:\n deadwood_counts = [utils.get_deadwood_count(hand=hand, meld_cluster=meld_cluster)\n for meld_cluster in meld_clusters]\n best_deadwood_count = min(deadwood_counts)\n for i in range(meld_clusters_count):\n if deadwood_counts[i] == best_deadwood_count:\n result.append(meld_clusters[i])\n return result\n\n\ndef get_all_run_melds(hand: List[Card]) -> List[List[Card]]:\n card_count = len(hand)\n hand_by_suit = sorted(hand, key=utils.get_card_id)\n max_run_melds = []\n\n i = 0\n while i < card_count - 2:\n card_i = hand_by_suit[i]\n j = i + 1\n card_j = hand_by_suit[j]\n while utils.get_rank_id(card_j) == utils.get_rank_id(card_i) + j - i and card_j.suit == card_i.suit:\n j += 1\n if j < card_count:\n card_j = hand_by_suit[j]\n else:\n break\n max_run_meld = hand_by_suit[i:j]\n if len(max_run_meld) >= 3:\n max_run_melds.append(max_run_meld)\n i = j\n\n result = []\n for max_run_meld in max_run_melds:\n max_run_meld_count = len(max_run_meld)\n for i in range(max_run_meld_count - 2):\n for j in range(i + 3, max_run_meld_count + 1):\n result.append(max_run_meld[i:j])\n return result\n\n\ndef get_all_set_melds(hand: List[Card]) -> List[List[Card]]:\n max_set_melds = []\n hand_by_rank = sorted(hand, key=lambda x: x.rank)\n set_meld = []\n current_rank = None\n for card in hand_by_rank:\n if current_rank is None or current_rank == card.rank:\n set_meld.append(card)\n else:\n if len(set_meld) >= 3:\n max_set_melds.append(set_meld)\n set_meld = [card]\n current_rank = card.rank\n if len(set_meld) >= 3:\n max_set_melds.append(set_meld)\n result = []\n for max_set_meld in max_set_melds:\n result.append(max_set_meld)\n if len(max_set_meld) == 4:\n for meld_card in max_set_meld:\n result.append([card for card in max_set_meld if card != meld_card])\n return result\n\n\ndef get_all_run_melds_for_suit(cards: List[Card], suit: str) -> List[List[Card]]:\n cards_for_suit = [card for card in cards if card.suit == suit]\n cards_for_suit_count = len(cards_for_suit)\n cards_for_suit = sorted(cards_for_suit, key=utils.get_card_id)\n max_run_melds = []\n\n i = 0\n while i < cards_for_suit_count - 2:\n card_i = cards_for_suit[i]\n j = i + 1\n card_j = cards_for_suit[j]\n while utils.get_rank_id(card_j) == utils.get_rank_id(card_i) + j - i:\n j += 1\n if j < cards_for_suit_count:\n card_j = cards_for_suit[j]\n else:\n break\n max_run_meld = cards_for_suit[i:j]\n if len(max_run_meld) >= 3:\n max_run_melds.append(max_run_meld)\n i = j\n\n result = []\n for max_run_meld in max_run_melds:\n max_run_meld_count = len(max_run_meld)\n for i in range(max_run_meld_count - 2):\n for j in range(i + 3, max_run_meld_count + 1):\n result.append(max_run_meld[i:j])\n return result\n\n\n# ./gin_rummy/move.py\nfrom typing import List\n\nfrom gin_rummy import Player\n\nfrom action_event import *\n\nfrom gin_rummy_error import GinRummyProgramError\n\n\n#\n# These classes are used to keep a move_sheet history of the moves in a round.\n#\n\nclass GinRummyMove(object):\n pass\n\n\nclass PlayerMove(GinRummyMove):\n\n def __init__(self, player: Player, action: ActionEvent):\n super().__init__()\n self.player = player\n self.action = action\n\n\nclass DealHandMove(GinRummyMove):\n\n def __init__(self, player_dealing: Player, shuffled_deck: List[Card]):\n super().__init__()\n self.player_dealing = player_dealing\n self.shuffled_deck = shuffled_deck\n\n def __str__(self):\n shuffled_deck_text = \" \".join([str(card) for card in self.shuffled_deck])\n return \"{} deal shuffled_deck=[{}]\".format(self.player_dealing, shuffled_deck_text)\n\n\nclass DrawCardMove(PlayerMove):\n\n def __init__(self, player: Player, action: DrawCardAction, card: Card):\n super().__init__(player, action)\n if not isinstance(action, DrawCardAction):\n raise GinRummyProgramError(\"action must be DrawCardAction.\")\n self.card = card\n\n def __str__(self):\n return \"{} {} {}\".format(self.player, self.action, str(self.card))\n\n\nclass PickupDiscardMove(PlayerMove):\n\n def __init__(self, player: Player, action: PickUpDiscardAction, card: Card):\n super().__init__(player, action)\n if not isinstance(action, PickUpDiscardAction):\n raise GinRummyProgramError(\"action must be PickUpDiscardAction.\")\n self.card = card\n\n def __str__(self):\n return \"{} {} {}\".format(self.player, self.action, str(self.card))\n\n\nclass DeclareDeadHandMove(PlayerMove):\n\n def __init__(self, player: Player, action: DeclareDeadHandAction):\n super().__init__(player, action)\n if not isinstance(action, DeclareDeadHandAction):\n raise GinRummyProgramError(\"action must be DeclareDeadHandAction.\")\n\n def __str__(self):\n return \"{} {}\".format(self.player, self.action)\n\n\nclass DiscardMove(PlayerMove):\n\n def __init__(self, player: Player, action: DiscardAction):\n super().__init__(player, action)\n if not isinstance(action, DiscardAction):\n raise GinRummyProgramError(\"action must be DiscardAction.\")\n\n def __str__(self):\n return \"{} {}\".format(self.player, self.action)\n\n\nclass KnockMove(PlayerMove):\n\n def __init__(self, player: Player, action: KnockAction):\n super().__init__(player, action)\n if not isinstance(action, KnockAction):\n raise GinRummyProgramError(\"action must be KnockAction.\")\n\n def __str__(self):\n return \"{} {}\".format(self.player, self.action)\n\n\nclass GinMove(PlayerMove):\n\n def __init__(self, player: Player, action: GinAction):\n super().__init__(player, action)\n if not isinstance(action, GinAction):\n raise GinRummyProgramError(\"action must be GinAction.\")\n\n def __str__(self):\n return \"{} {}\".format(self.player, self.action)\n\n\nclass ScoreNorthMove(PlayerMove):\n\n def __init__(self, player: Player,\n action: ScoreNorthPlayerAction,\n best_meld_cluster: List[List[Card]],\n deadwood_count: int):\n super().__init__(player, action)\n if not isinstance(action, ScoreNorthPlayerAction):\n raise GinRummyProgramError(\"action must be ScoreNorthPlayerAction.\")\n self.best_meld_cluster = best_meld_cluster # for information use only\n self.deadwood_count = deadwood_count # for information use only\n\n def __str__(self):\n best_meld_cluster_str = [[str(card) for card in meld_pile] for meld_pile in self.best_meld_cluster]\n best_meld_cluster_text = \"{}\".format(best_meld_cluster_str)\n return \"{} {} {} {}\".format(self.player, self.action, self.deadwood_count, best_meld_cluster_text)\n\n\nclass ScoreSouthMove(PlayerMove):\n\n def __init__(self, player: Player,\n action: ScoreSouthPlayerAction,\n best_meld_cluster: List[List[Card]],\n deadwood_count: int):\n super().__init__(player, action)\n if not isinstance(action, ScoreSouthPlayerAction):\n raise GinRummyProgramError(\"action must be ScoreSouthPlayerAction.\")\n self.best_meld_cluster = best_meld_cluster # for information use only\n self.deadwood_count = deadwood_count # for information use only\n\n def __str__(self):\n best_meld_cluster_str = [[str(card) for card in meld_pile] for meld_pile in self.best_meld_cluster]\n best_meld_cluster_text = \"{}\".format(best_meld_cluster_str)\n return \"{} {} {} {}\".format(self.player, self.action, self.deadwood_count, best_meld_cluster_text)\n\n\n# ./gin_rummy/player.py\nfrom typing import List\n\nfrom gin_rummy import Card\n\nimport utils\n\nimport melding\n\n\nclass GinRummyPlayer:\n\n def __init__(self, player_id: int, np_random):\n ''' Initialize a GinRummy player class\n\n Args:\n player_id (int): id for the player\n '''\n self.np_random = np_random\n self.player_id = player_id\n self.hand = [] # type: List[Card]\n self.known_cards = [] # type: List[Card] # opponent knows cards picked up by player and not yet discarded\n # memoization for speed\n self.meld_kinds_by_rank_id = [[] for _ in range(13)] # type: List[List[List[Card]]]\n self.meld_run_by_suit_id = [[] for _ in range(4)] # type: List[List[List[Card]]]\n\n def get_player_id(self) -> int:\n ''' Return player's id\n '''\n return self.player_id\n\n def get_meld_clusters(self) -> List[List[List[Card]]]:\n result = [] # type: List[List[List[Card]]]\n all_run_melds = [frozenset(meld_kind) for meld_kinds in self.meld_kinds_by_rank_id for meld_kind in meld_kinds]\n all_set_melds = [frozenset(meld_run) for meld_runs in self.meld_run_by_suit_id for meld_run in meld_runs]\n all_melds = all_run_melds + all_set_melds\n all_melds_count = len(all_melds)\n for i in range(0, all_melds_count):\n first_meld = all_melds[i]\n first_meld_list = list(first_meld)\n meld_cluster_1 = [first_meld_list]\n result.append(meld_cluster_1)\n for j in range(i + 1, all_melds_count):\n second_meld = all_melds[j]\n second_meld_list = list(second_meld)\n if not second_meld.isdisjoint(first_meld):\n continue\n meld_cluster_2 = [first_meld_list, second_meld_list]\n result.append(meld_cluster_2)\n for k in range(j + 1, all_melds_count):\n third_meld = all_melds[k]\n third_meld_list = list(third_meld)\n if not third_meld.isdisjoint(first_meld) or not third_meld.isdisjoint(second_meld):\n continue\n meld_cluster_3 = [first_meld_list, second_meld_list, third_meld_list]\n result.append(meld_cluster_3)\n return result\n\n def did_populate_hand(self):\n self.meld_kinds_by_rank_id = [[] for _ in range(13)]\n self.meld_run_by_suit_id = [[] for _ in range(4)]\n all_set_melds = melding.get_all_set_melds(hand=self.hand)\n for set_meld in all_set_melds:\n rank_id = utils.get_rank_id(set_meld[0])\n self.meld_kinds_by_rank_id[rank_id].append(set_meld)\n all_run_melds = melding.get_all_run_melds(hand=self.hand)\n for run_meld in all_run_melds:\n suit_id = utils.get_suit_id(run_meld[0])\n self.meld_run_by_suit_id[suit_id].append(run_meld)\n\n def add_card_to_hand(self, card: Card):\n self.hand.append(card)\n self._increase_meld_kinds_by_rank_id(card=card)\n self._increase_run_kinds_by_suit_id(card=card)\n\n def remove_card_from_hand(self, card: Card):\n self.hand.remove(card)\n self._reduce_meld_kinds_by_rank_id(card=card)\n self._reduce_run_kinds_by_suit_id(card=card)\n\n def __str__(self):\n return \"N\" if self.player_id == 0 else \"S\"\n\n @staticmethod\n def short_name_of(player_id: int) -> str:\n return \"N\" if player_id == 0 else \"S\"\n\n @staticmethod\n def opponent_id_of(player_id: int) -> int:\n return (player_id + 1) % 2\n\n # private methods\n\n def _increase_meld_kinds_by_rank_id(self, card: Card):\n rank_id = utils.get_rank_id(card)\n meld_kinds = self.meld_kinds_by_rank_id[rank_id]\n if len(meld_kinds) == 0:\n card_rank = card.rank\n meld_kind = [card for card in self.hand if card.rank == card_rank]\n if len(meld_kind) >= 3:\n self.meld_kinds_by_rank_id[rank_id].append(meld_kind)\n else: # must have all cards of given rank\n suits = ['S', 'H', 'D', 'C']\n max_kind_meld = [Card(suit, card.rank) for suit in suits]\n self.meld_kinds_by_rank_id[rank_id] = [max_kind_meld]\n for meld_card in max_kind_meld:\n self.meld_kinds_by_rank_id[rank_id].append([card for card in max_kind_meld if card != meld_card])\n\n def _reduce_meld_kinds_by_rank_id(self, card: Card):\n rank_id = utils.get_rank_id(card)\n meld_kinds = self.meld_kinds_by_rank_id[rank_id]\n if len(meld_kinds) > 1:\n suits = ['S', 'H', 'D', 'C']\n self.meld_kinds_by_rank_id[rank_id] = [[Card(suit, card.rank) for suit in suits if suit != card.suit]]\n else:\n self.meld_kinds_by_rank_id[rank_id] = []\n\n def _increase_run_kinds_by_suit_id(self, card: Card):\n suit_id = utils.get_suit_id(card=card)\n self.meld_run_by_suit_id[suit_id] = melding.get_all_run_melds_for_suit(cards=self.hand, suit=card.suit)\n\n def _reduce_run_kinds_by_suit_id(self, card: Card):\n suit_id = utils.get_suit_id(card=card)\n meld_runs = self.meld_run_by_suit_id[suit_id]\n self.meld_run_by_suit_id[suit_id] = [meld_run for meld_run in meld_runs if card not in meld_run]\n\n\n# ./gin_rummy/round.py\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from move import GinRummyMove\n\nfrom typing import List\n\nfrom gin_rummy import Dealer\n\nfrom action_event import DrawCardAction, PickUpDiscardAction, DeclareDeadHandAction\nfrom action_event import DiscardAction, KnockAction, GinAction\nfrom action_event import ScoreNorthPlayerAction, ScoreSouthPlayerAction\n\nfrom move import DealHandMove\nfrom move import DrawCardMove, PickupDiscardMove, DeclareDeadHandMove\nfrom move import DiscardMove, KnockMove, GinMove\nfrom move import ScoreNorthMove, ScoreSouthMove\n\nfrom gin_rummy_error import GinRummyProgramError\n\nfrom gin_rummy import Player\nimport judge\n\nimport melding\nimport utils\n\n\nclass GinRummyRound:\n\n def __init__(self, dealer_id: int, np_random):\n ''' Initialize the round class\n\n The round class maintains the following instances:\n 1) dealer: the dealer of the round; dealer has stock_pile and discard_pile\n 2) players: the players in the round; each player has his own hand_pile\n 3) current_player_id: the id of the current player who has the move\n 4) is_over: true if the round is over\n 5) going_out_action: knock or gin or None\n 6) going_out_player_id: id of player who went out or None\n 7) move_sheet: history of the moves of the player (including the deal_hand_move)\n\n The round class maintains a list of moves made by the players in self.move_sheet.\n move_sheet is similar to a chess score sheet.\n I didn't want to call it a score_sheet since it is not keeping score.\n I could have called move_sheet just moves, but that might conflict with the name moves used elsewhere.\n I settled on the longer name \"move_sheet\" to indicate that it is the official list of moves being made.\n\n Args:\n dealer_id: int\n '''\n self.np_random = np_random\n self.dealer_id = dealer_id\n self.dealer = Dealer(self.np_random)\n self.players = [Player(player_id=0, np_random=self.np_random), Player(player_id=1, np_random=self.np_random)]\n self.current_player_id = (dealer_id + 1) % 2\n self.is_over = False\n self.going_out_action = None # going_out_action: int or None\n self.going_out_player_id = None # going_out_player_id: int or None\n self.move_sheet = [] # type: List[GinRummyMove]\n player_dealing = Player(player_id=dealer_id, np_random=self.np_random)\n shuffled_deck = self.dealer.shuffled_deck\n self.move_sheet.append(DealHandMove(player_dealing=player_dealing, shuffled_deck=shuffled_deck))\n\n def get_current_player(self) -> Player or None:\n current_player_id = self.current_player_id\n return None if current_player_id is None else self.players[current_player_id]\n\n def draw_card(self, action: DrawCardAction):\n # when current_player takes DrawCardAction step, the move is recorded and executed\n # current_player keeps turn\n current_player = self.players[self.current_player_id]\n if not len(current_player.hand) == 10:\n raise GinRummyProgramError(\"len(current_player.hand) is {}: should be 10.\".format(len(current_player.hand)))\n card = self.dealer.stock_pile.pop()\n self.move_sheet.append(DrawCardMove(current_player, action=action, card=card))\n current_player.add_card_to_hand(card=card)\n\n def pick_up_discard(self, action: PickUpDiscardAction):\n # when current_player takes PickUpDiscardAction step, the move is recorded and executed\n # opponent knows that the card is in current_player hand\n # current_player keeps turn\n current_player = self.players[self.current_player_id]\n if not len(current_player.hand) == 10:\n raise GinRummyProgramError(\"len(current_player.hand) is {}: should be 10.\".format(len(current_player.hand)))\n card = self.dealer.discard_pile.pop()\n self.move_sheet.append(PickupDiscardMove(current_player, action, card=card))\n current_player.add_card_to_hand(card=card)\n current_player.known_cards.append(card)\n\n def declare_dead_hand(self, action: DeclareDeadHandAction):\n # when current_player takes DeclareDeadHandAction step, the move is recorded and executed\n # north becomes current_player to score his hand\n current_player = self.players[self.current_player_id]\n self.move_sheet.append(DeclareDeadHandMove(current_player, action))\n self.going_out_action = action\n self.going_out_player_id = self.current_player_id\n if not len(current_player.hand) == 10:\n raise GinRummyProgramError(\"len(current_player.hand) is {}: should be 10.\".format(len(current_player.hand)))\n self.current_player_id = 0\n\n def discard(self, action: DiscardAction):\n # when current_player takes DiscardAction step, the move is recorded and executed\n # opponent knows that the card is no longer in current_player hand\n # current_player loses his turn and the opponent becomes the current player\n current_player = self.players[self.current_player_id]\n if not len(current_player.hand) == 11:\n raise GinRummyProgramError(\"len(current_player.hand) is {}: should be 11.\".format(len(current_player.hand)))\n self.move_sheet.append(DiscardMove(current_player, action))\n card = action.card\n current_player.remove_card_from_hand(card=card)\n if card in current_player.known_cards:\n current_player.known_cards.remove(card)\n self.dealer.discard_pile.append(card)\n self.current_player_id = (self.current_player_id + 1) % 2\n\n def knock(self, action: KnockAction):\n # when current_player takes KnockAction step, the move is recorded and executed\n # opponent knows that the card is no longer in current_player hand\n # north becomes current_player to score his hand\n current_player = self.players[self.current_player_id]\n self.move_sheet.append(KnockMove(current_player, action))\n self.going_out_action = action\n self.going_out_player_id = self.current_player_id\n if not len(current_player.hand) == 11:\n raise GinRummyProgramError(\"len(current_player.hand) is {}: should be 11.\".format(len(current_player.hand)))\n card = action.card\n current_player.remove_card_from_hand(card=card)\n if card in current_player.known_cards:\n current_player.known_cards.remove(card)\n self.current_player_id = 0\n\n def gin(self, action: GinAction, going_out_deadwood_count: int):\n # when current_player takes GinAction step, the move is recorded and executed\n # opponent knows that the card is no longer in current_player hand\n # north becomes current_player to score his hand\n current_player = self.players[self.current_player_id]\n self.move_sheet.append(GinMove(current_player, action))\n self.going_out_action = action\n self.going_out_player_id = self.current_player_id\n if not len(current_player.hand) == 11:\n raise GinRummyProgramError(\"len(current_player.hand) is {}: should be 11.\".format(len(current_player.hand)))\n _, gin_cards = judge.get_going_out_cards(current_player.hand, going_out_deadwood_count)\n card = gin_cards[0]\n current_player.remove_card_from_hand(card=card)\n if card in current_player.known_cards:\n current_player.known_cards.remove(card)\n self.current_player_id = 0\n\n def score_player_0(self, action: ScoreNorthPlayerAction):\n # when current_player takes ScoreNorthPlayerAction step, the move is recorded and executed\n # south becomes current player\n if not self.current_player_id == 0:\n raise GinRummyProgramError(\"current_player_id is {}: should be 0.\".format(self.current_player_id))\n current_player = self.get_current_player()\n best_meld_clusters = melding.get_best_meld_clusters(hand=current_player.hand)\n best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0]\n deadwood_count = utils.get_deadwood_count(hand=current_player.hand, meld_cluster=best_meld_cluster)\n self.move_sheet.append(ScoreNorthMove(player=current_player,\n action=action,\n best_meld_cluster=best_meld_cluster,\n deadwood_count=deadwood_count))\n self.current_player_id = 1\n\n def score_player_1(self, action: ScoreSouthPlayerAction):\n # when current_player takes ScoreSouthPlayerAction step, the move is recorded and executed\n # south remains current player\n # the round is over\n if not self.current_player_id == 1:\n raise GinRummyProgramError(\"current_player_id is {}: should be 1.\".format(self.current_player_id))\n current_player = self.get_current_player()\n best_meld_clusters = melding.get_best_meld_clusters(hand=current_player.hand)\n best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0]\n deadwood_count = utils.get_deadwood_count(hand=current_player.hand, meld_cluster=best_meld_cluster)\n self.move_sheet.append(ScoreSouthMove(player=current_player,\n action=action,\n best_meld_cluster=best_meld_cluster,\n deadwood_count=deadwood_count))\n self.is_over = True\n\n\n# ./gin_rummy/scorers.py\nfrom typing import TYPE_CHECKING\n\nfrom typing import Callable\n\nfrom action_event import *\nfrom gin_rummy import Player\nfrom move import ScoreNorthMove, ScoreSouthMove\nfrom gin_rummy_error import GinRummyProgramError\n\nimport melding\nimport utils\n\n\nclass GinRummyScorer:\n\n def __init__(self, name: str = None, get_payoff: Callable[[Player, 'GinRummyGame'], int or float] = None):\n self.name = name if name is not None else \"GinRummyScorer\"\n self.get_payoff = get_payoff if get_payoff else get_payoff_gin_rummy_v1\n\n def get_payoffs(self, game: 'GinRummyGame'):\n payoffs = [0, 0]\n for i in range(2):\n player = game.round.players[i]\n payoff = self.get_payoff(player=player, game=game)\n payoffs[i] = payoff\n return payoffs\n\n\ndef get_payoff_gin_rummy_v0(player: Player, game: 'GinRummyGame') -> int:\n ''' Get the payoff of player: deadwood_count of player\n\n Returns:\n payoff (int or float): payoff for player (lower is better)\n '''\n moves = game.round.move_sheet\n if player.player_id == 0:\n score_player_move = moves[-2]\n if not isinstance(score_player_move, ScoreNorthMove):\n raise GinRummyProgramError(\"score_player_move must be ScoreNorthMove.\")\n else:\n score_player_move = moves[-1]\n if not isinstance(score_player_move, ScoreSouthMove):\n raise GinRummyProgramError(\"score_player_move must be ScoreSouthMove.\")\n deadwood_count = score_player_move.deadwood_count\n return deadwood_count\n\n\ndef get_payoff_gin_rummy_v1(player: Player, game: 'GinRummyGame') -> float:\n ''' Get the payoff of player:\n a) 1.0 if player gins\n b) 0.2 if player knocks\n c) -deadwood_count / 100 otherwise\n\n Returns:\n payoff (int or float): payoff for player (higher is better)\n '''\n # payoff is 1.0 if player gins\n # payoff is 0.2 if player knocks\n # payoff is -deadwood_count / 100 if otherwise\n # The goal is to have the agent learn how to knock and gin.\n # The negative payoff when the agent fails to knock or gin should encourage the agent to form melds.\n # The payoff is scaled to lie between -1 and 1.\n going_out_action = game.round.going_out_action\n going_out_player_id = game.round.going_out_player_id\n if going_out_player_id == player.player_id and isinstance(going_out_action, KnockAction):\n payoff = 0.2\n elif going_out_player_id == player.player_id and isinstance(going_out_action, GinAction):\n payoff = 1\n else:\n hand = player.hand\n best_meld_clusters = melding.get_best_meld_clusters(hand=hand)\n best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0]\n deadwood_count = utils.get_deadwood_count(hand, best_meld_cluster)\n payoff = -deadwood_count / 100\n return payoff\n\n\n# ./gin_rummy/settings.py\nfrom typing import Dict, Any\n\nfrom enum import Enum\n\n\nclass DealerForRound(int, Enum):\n North = 0\n South = 1\n Random = 2\n\n\nclass Setting(str, Enum):\n dealer_for_round = \"dealer_for_round\"\n stockpile_dead_card_count = \"stockpile_dead_card_count\"\n going_out_deadwood_count = \"going_out_deadwood_count\"\n max_drawn_card_count = \"max_drawn_card_count\"\n max_move_count = \"max_move_count\"\n is_allowed_knock = \"is_allowed_knock\"\n is_allowed_gin = \"is_allowed_gin\"\n is_allowed_pick_up_discard = \"is_allowed_pick_up_discard\"\n is_allowed_to_discard_picked_up_card = \"is_allowed_to_discard_picked_up_card\"\n is_always_knock = \"is_always_knock\"\n is_south_never_knocks = \"is_south_never_knocks\"\n\n @staticmethod\n def default_setting() -> Dict['Setting', Any]:\n return {Setting.dealer_for_round: DealerForRound.Random,\n Setting.stockpile_dead_card_count: 2,\n Setting.going_out_deadwood_count: 10, # Can specify going_out_deadwood_count before running game.\n Setting.max_drawn_card_count: 52,\n Setting.max_move_count: 200, # prevent unlimited number of moves in a game\n Setting.is_allowed_knock: True,\n Setting.is_allowed_gin: True,\n Setting.is_allowed_pick_up_discard: True,\n Setting.is_allowed_to_discard_picked_up_card: False,\n Setting.is_always_knock: False,\n Setting.is_south_never_knocks: False\n }\n\n @staticmethod\n def simple_gin_rummy_setting(): # speeding up training 200213\n # North should be agent being trained.\n # North always deals.\n # South never knocks.\n # North always knocks when can.\n return {Setting.dealer_for_round: DealerForRound.North,\n Setting.stockpile_dead_card_count: 2,\n Setting.going_out_deadwood_count: 10, # Can specify going_out_deadwood_count before running game.\n Setting.max_drawn_card_count: 52,\n Setting.max_move_count: 200, # prevent unlimited number of moves in a game\n Setting.is_allowed_knock: True,\n Setting.is_allowed_gin: True,\n Setting.is_allowed_pick_up_discard: True,\n Setting.is_allowed_to_discard_picked_up_card: False,\n Setting.is_always_knock: True,\n Setting.is_south_never_knocks: True\n }\n\n\ndealer_for_round = Setting.dealer_for_round\nstockpile_dead_card_count = Setting.stockpile_dead_card_count\ngoing_out_deadwood_count = Setting.going_out_deadwood_count\nmax_drawn_card_count = Setting.max_drawn_card_count\nmax_move_count = Setting.max_move_count\nis_allowed_knock = Setting.is_allowed_knock\nis_allowed_gin = Setting.is_allowed_gin\nis_allowed_pick_up_discard = Setting.is_allowed_pick_up_discard\nis_allowed_to_discard_picked_up_card = Setting.is_allowed_to_discard_picked_up_card\nis_always_knock = Setting.is_always_knock\nis_south_never_knocks = Setting.is_south_never_knocks\n\n\nclass Settings(object):\n\n def __init__(self):\n self.scorer_name = \"GinRummyScorer\"\n default_setting = Setting.default_setting()\n self.dealer_for_round = default_setting[Setting.dealer_for_round]\n self.stockpile_dead_card_count = default_setting[Setting.stockpile_dead_card_count]\n self.going_out_deadwood_count = default_setting[Setting.going_out_deadwood_count]\n self.max_drawn_card_count = default_setting[Setting.max_drawn_card_count]\n self.max_move_count = default_setting[Setting.max_move_count]\n self.is_allowed_knock = default_setting[Setting.is_allowed_knock]\n self.is_allowed_gin = default_setting[Setting.is_allowed_gin]\n self.is_allowed_pick_up_discard = default_setting[Setting.is_allowed_pick_up_discard]\n self.is_allowed_to_discard_picked_up_card = default_setting[Setting.is_allowed_to_discard_picked_up_card]\n self.is_always_knock = default_setting[Setting.is_always_knock]\n self.is_south_never_knocks = default_setting[Setting.is_south_never_knocks]\n\n def change_settings(self, config: Dict[Setting, Any]):\n corrected_config = Settings.get_config_with_invalid_settings_set_to_default_value(config=config)\n for key, value in corrected_config.items():\n if key == Setting.dealer_for_round:\n self.dealer_for_round = value\n elif key == Setting.stockpile_dead_card_count:\n self.stockpile_dead_card_count = value\n elif key == Setting.going_out_deadwood_count:\n self.going_out_deadwood_count = value\n elif key == Setting.max_drawn_card_count:\n self.max_drawn_card_count = value\n elif key == Setting.max_move_count:\n self.max_move_count = value\n elif key == Setting.is_allowed_knock:\n self.is_allowed_knock = value\n elif key == Setting.is_allowed_gin:\n self.is_allowed_gin = value\n elif key == Setting.is_allowed_pick_up_discard:\n self.is_allowed_pick_up_discard = value\n elif key == Setting.is_allowed_to_discard_picked_up_card:\n self.is_allowed_to_discard_picked_up_card = value\n elif key == Setting.is_always_knock:\n self.is_always_knock = value\n elif key == Setting.is_south_never_knocks:\n self.is_south_never_knocks = value\n\n def print_settings(self):\n print(\"========== Settings ==========\")\n print(\"scorer_name={}\".format(self.scorer_name))\n print(\"dealer_for_round={}\".format(self.dealer_for_round))\n print(\"stockpile_dead_card_count={}\".format(self.stockpile_dead_card_count))\n print(\"going_out_deadwood_count={}\".format(self.going_out_deadwood_count))\n print(\"max_drawn_card_count={}\".format(self.max_drawn_card_count))\n print(\"max_move_count={}\".format(self.max_move_count))\n\n print(\"is_allowed_knock={}\".format(self.is_allowed_knock))\n print(\"is_allowed_gin={}\".format(self.is_allowed_gin))\n print(\"is_allowed_pick_up_discard={}\".format(self.is_allowed_pick_up_discard))\n\n print(\"is_allowed_to_discard_picked_up_card={}\".format(self.is_allowed_to_discard_picked_up_card))\n\n print(\"is_always_knock={}\".format(self.is_always_knock))\n print(\"is_south_never_knocks={}\".format(self.is_south_never_knocks))\n print(\"==============================\")\n\n @staticmethod\n def get_config_with_invalid_settings_set_to_default_value(config: Dict[Setting, Any]) -> Dict[Setting, Any]:\n # Set each invalid setting to its default_value.\n result = config.copy()\n default_setting = Setting.default_setting()\n for key, value in config.items():\n if key == dealer_for_round and not isinstance(value, DealerForRound):\n result[dealer_for_round] = default_setting[dealer_for_round]\n elif key == stockpile_dead_card_count and not isinstance(value, int):\n result[stockpile_dead_card_count] = default_setting[stockpile_dead_card_count]\n elif key == going_out_deadwood_count and not isinstance(value, int):\n result[going_out_deadwood_count] = default_setting[going_out_deadwood_count]\n elif key == max_drawn_card_count and not isinstance(value, int):\n result[max_drawn_card_count] = default_setting[max_drawn_card_count]\n elif key == max_move_count and not isinstance(value, int):\n result[max_move_count] = default_setting[max_move_count]\n elif key == is_allowed_knock and not isinstance(value, bool):\n result[is_allowed_knock] = default_setting[is_allowed_knock]\n elif key == is_allowed_gin and not isinstance(value, bool):\n result[is_allowed_gin] = default_setting[is_allowed_gin]\n elif key == is_allowed_pick_up_discard and not isinstance(value, bool):\n result[is_allowed_pick_up_discard] = default_setting[is_allowed_pick_up_discard]\n elif key == is_allowed_to_discard_picked_up_card and not isinstance(value, bool):\n result[is_allowed_to_discard_picked_up_card] = default_setting[is_allowed_to_discard_picked_up_card]\n elif key == is_always_knock and not isinstance(value, bool):\n result[is_always_knock] = default_setting[is_always_knock]\n elif key == is_south_never_knocks and not isinstance(value, bool):\n result[is_south_never_knocks] = default_setting[is_south_never_knocks]\n return result\n\n\n\n# ./gin_rummy/utils.py\nfrom typing import List, Iterable\n\nimport numpy as np\n\nfrom gin_rummy import Card\n\nfrom gin_rummy_error import GinRummyProgramError\n\nvalid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\nvalid_suit = ['S', 'H', 'D', 'C']\n\nrank_to_deadwood_value = {\"A\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9,\n \"T\": 10, \"J\": 10, \"Q\": 10, \"K\": 10}\n\n\ndef card_from_card_id(card_id: int) -> Card:\n ''' Make card from its card_id\n\n Args:\n card_id: int in range(0, 52)\n '''\n if not (0 <= card_id < 52):\n raise GinRummyProgramError(\"card_id is {}: should be 0 <= card_id < 52.\".format(card_id))\n rank_id = card_id % 13\n suit_id = card_id // 13\n rank = Card.valid_rank[rank_id]\n suit = Card.valid_suit[suit_id]\n return Card(rank=rank, suit=suit)\n\n\n# deck is always in order from AS, 2S, ..., AH, 2H, ..., AD, 2D, ..., AC, 2C, ... QC, KC\n_deck = [card_from_card_id(card_id) for card_id in range(52)] # want this to be read-only\n\n\ndef card_from_text(text: str) -> Card:\n if len(text) != 2:\n raise GinRummyProgramError(\"len(text) is {}: should be 2.\".format(len(text)))\n return Card(rank=text[0], suit=text[1])\n\n\ndef get_deck() -> List[Card]:\n return _deck.copy()\n\n\ndef get_card(card_id: int):\n return _deck[card_id]\n\n\ndef get_card_id(card: Card) -> int:\n rank_id = get_rank_id(card)\n suit_id = get_suit_id(card)\n return rank_id + 13 * suit_id\n\n\ndef get_rank_id(card: Card) -> int:\n return Card.valid_rank.index(card.rank)\n\n\ndef get_suit_id(card: Card) -> int:\n return Card.valid_suit.index(card.suit)\n\n\ndef get_deadwood_value(card: Card) -> int:\n rank = card.rank\n deadwood_value = rank_to_deadwood_value.get(rank, 10) # default to 10 is key does not exist\n return deadwood_value\n\n\ndef get_deadwood(hand: Iterable[Card], meld_cluster: List[Iterable[Card]]) -> List[Card]:\n if len(list(hand)) != 10:\n raise GinRummyProgramError(\"Hand contain {} cards: should be 10 cards.\".format(len(list(hand))))\n meld_cards = [card for meld_pile in meld_cluster for card in meld_pile]\n deadwood = [card for card in hand if card not in meld_cards]\n return deadwood\n\n\ndef get_deadwood_count(hand: List[Card], meld_cluster: List[Iterable[Card]]) -> int:\n if len(hand) != 10:\n raise GinRummyProgramError(\"Hand contain {} cards: should be 10 cards.\".format(len(hand)))\n deadwood = get_deadwood(hand=hand, meld_cluster=meld_cluster)\n deadwood_values = [get_deadwood_value(card) for card in deadwood]\n return sum(deadwood_values)\n\n\ndef decode_cards(env_cards: np.ndarray) -> List[Card]:\n result = [] # type: List[Card]\n if len(env_cards) != 52:\n raise GinRummyProgramError(\"len(env_cards) is {}: should be 52.\".format(len(env_cards)))\n for i in range(52):\n if env_cards[i] == 1:\n card = _deck[i]\n result.append(card)\n return result\n\n\ndef encode_cards(cards: List[Card]) -> np.ndarray:\n plane = np.zeros(52, dtype=int)\n for card in cards:\n card_id = get_card_id(card)\n plane[card_id] = 1\n return plane\n", "num_file": 14, "num_lines": 1453, "programming_language": "Python"} {"class_name": "keras_preprocessing", "id": "./MultiFileTest/Python/keras_preprocessing.py", "original_code": "# ./keras_preprocessing/__init__.py\n\"\"\"Enables dynamic setting of underlying Keras module.\n\"\"\"\n\n_KERAS_BACKEND = None\n_KERAS_UTILS = None\n\n\ndef set_keras_submodules(backend, utils):\n # Deprecated, will be removed in the future.\n global _KERAS_BACKEND\n global _KERAS_UTILS\n _KERAS_BACKEND = backend\n _KERAS_UTILS = utils\n\n\ndef get_keras_submodule(name):\n # Deprecated, will be removed in the future.\n if name not in {'backend', 'utils'}:\n raise ImportError(\n 'Can only retrieve \"backend\" and \"utils\". '\n 'Requested: %s' % name)\n if _KERAS_BACKEND is None:\n raise ImportError('You need to first `import keras` '\n 'in order to use `keras_preprocessing`. '\n 'For instance, you can do:\\n\\n'\n '```\\n'\n 'import keras\\n'\n 'from keras_preprocessing import image\\n'\n '```\\n\\n'\n 'Or, preferably, this equivalent formulation:\\n\\n'\n '```\\n'\n 'from keras import preprocessing\\n'\n '```\\n')\n if name == 'backend':\n return _KERAS_BACKEND\n elif name == 'utils':\n return _KERAS_UTILS\n\n\n__version__ = '1.1.2'\n\n\n# ./keras_preprocessing/sequence.py\n# -*- coding: utf-8 -*-\n\"\"\"Utilities for preprocessing sequence data.\n\"\"\"\nimport json\nimport random\n\nimport numpy as np\n\n\ndef pad_sequences(sequences, maxlen=None, dtype='int32',\n padding='pre', truncating='pre', value=0.):\n \"\"\"Pads sequences to the same length.\n\n This function transforms a list of\n `num_samples` sequences (lists of integers)\n into a 2D Numpy array of shape `(num_samples, num_timesteps)`.\n `num_timesteps` is either the `maxlen` argument if provided,\n or the length of the longest sequence otherwise.\n\n Sequences that are shorter than `num_timesteps`\n are padded with `value` at the beginning or the end\n if padding='post.\n\n Sequences longer than `num_timesteps` are truncated\n so that they fit the desired length.\n The position where padding or truncation happens is determined by\n the arguments `padding` and `truncating`, respectively.\n\n Pre-padding is the default.\n\n # Arguments\n sequences: List of lists, where each element is a sequence.\n maxlen: Int, maximum length of all sequences.\n dtype: Type of the output sequences.\n To pad sequences with variable length strings, you can use `object`.\n padding: String, 'pre' or 'post':\n pad either before or after each sequence.\n truncating: String, 'pre' or 'post':\n remove values from sequences larger than\n `maxlen`, either at the beginning or at the end of the sequences.\n value: Float or String, padding value.\n\n # Returns\n x: Numpy array with shape `(len(sequences), maxlen)`\n\n # Raises\n ValueError: In case of invalid values for `truncating` or `padding`,\n or in case of invalid shape for a `sequences` entry.\n \"\"\"\n if not hasattr(sequences, '__len__'):\n raise ValueError('`sequences` must be iterable.')\n num_samples = len(sequences)\n\n lengths = []\n sample_shape = ()\n flag = True\n\n # take the sample shape from the first non empty sequence\n # checking for consistency in the main loop below.\n\n for x in sequences:\n try:\n lengths.append(len(x))\n if flag and len(x):\n sample_shape = np.asarray(x).shape[1:]\n flag = False\n except TypeError:\n raise ValueError('`sequences` must be a list of iterables. '\n 'Found non-iterable: ' + str(x))\n\n if maxlen is None:\n maxlen = np.max(lengths)\n\n is_dtype_str = np.issubdtype(dtype, np.str_) or np.issubdtype(dtype, np.unicode_)\n if isinstance(value, str) and dtype != object and not is_dtype_str:\n raise ValueError(\"`dtype` {} is not compatible with `value`'s type: {}\\n\"\n \"You should set `dtype=object` for variable length strings.\"\n .format(dtype, type(value)))\n\n x = np.full((num_samples, maxlen) + sample_shape, value, dtype=dtype)\n for idx, s in enumerate(sequences):\n if not len(s):\n continue # empty list/array was found\n if truncating == 'pre':\n trunc = s[-maxlen:]\n elif truncating == 'post':\n trunc = s[:maxlen]\n else:\n raise ValueError('Truncating type \"%s\" '\n 'not understood' % truncating)\n\n # check `trunc` has expected shape\n trunc = np.asarray(trunc, dtype=dtype)\n if trunc.shape[1:] != sample_shape:\n raise ValueError('Shape of sample %s of sequence at position %s '\n 'is different from expected shape %s' %\n (trunc.shape[1:], idx, sample_shape))\n\n if padding == 'post':\n x[idx, :len(trunc)] = trunc\n elif padding == 'pre':\n x[idx, -len(trunc):] = trunc\n else:\n raise ValueError('Padding type \"%s\" not understood' % padding)\n return x\n\n\ndef make_sampling_table(size, sampling_factor=1e-5):\n \"\"\"Generates a word rank-based probabilistic sampling table.\n\n Used for generating the `sampling_table` argument for `skipgrams`.\n `sampling_table[i]` is the probability of sampling\n the word i-th most common word in a dataset\n (more common words should be sampled less frequently, for balance).\n\n The sampling probabilities are generated according\n to the sampling distribution used in word2vec:\n\n ```\n p(word) = (min(1, sqrt(word_frequency / sampling_factor) /\n (word_frequency / sampling_factor)))\n ```\n\n We assume that the word frequencies follow Zipf's law (s=1) to derive\n a numerical approximation of frequency(rank):\n\n `frequency(rank) ~ 1/(rank * (log(rank) + gamma) + 1/2 - 1/(12*rank))`\n where `gamma` is the Euler-Mascheroni constant.\n\n # Arguments\n size: Int, number of possible words to sample.\n sampling_factor: The sampling factor in the word2vec formula.\n\n # Returns\n A 1D Numpy array of length `size` where the ith entry\n is the probability that a word of rank i should be sampled.\n \"\"\"\n gamma = 0.577\n rank = np.arange(size)\n rank[0] = 1\n inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1. / (12. * rank)\n f = sampling_factor * inv_fq\n\n return np.minimum(1., f / np.sqrt(f))\n\n\ndef skipgrams(sequence, vocabulary_size,\n window_size=4, negative_samples=1., shuffle=True,\n categorical=False, sampling_table=None, seed=None):\n \"\"\"Generates skipgram word pairs.\n\n This function transforms a sequence of word indexes (list of integers)\n into tuples of words of the form:\n\n - (word, word in the same window), with label 1 (positive samples).\n - (word, random word from the vocabulary), with label 0 (negative samples).\n\n Read more about Skipgram in this gnomic paper by Mikolov et al.:\n [Efficient Estimation of Word Representations in\n Vector Space](http://arxiv.org/pdf/1301.3781v3.pdf)\n\n # Arguments\n sequence: A word sequence (sentence), encoded as a list\n of word indices (integers). If using a `sampling_table`,\n word indices are expected to match the rank\n of the words in a reference dataset (e.g. 10 would encode\n the 10-th most frequently occurring token).\n Note that index 0 is expected to be a non-word and will be skipped.\n vocabulary_size: Int, maximum possible word index + 1\n window_size: Int, size of sampling windows (technically half-window).\n The window of a word `w_i` will be\n `[i - window_size, i + window_size+1]`.\n negative_samples: Float >= 0. 0 for no negative (i.e. random) samples.\n 1 for same number as positive samples.\n shuffle: Whether to shuffle the word couples before returning them.\n categorical: bool. if False, labels will be\n integers (eg. `[0, 1, 1 .. ]`),\n if `True`, labels will be categorical, e.g.\n `[[1,0],[0,1],[0,1] .. ]`.\n sampling_table: 1D array of size `vocabulary_size` where the entry i\n encodes the probability to sample a word of rank i.\n seed: Random seed.\n\n # Returns\n couples, labels: where `couples` are int pairs and\n `labels` are either 0 or 1.\n\n # Note\n By convention, index 0 in the vocabulary is\n a non-word and will be skipped.\n \"\"\"\n couples = []\n labels = []\n for i, wi in enumerate(sequence):\n if not wi:\n continue\n if sampling_table is not None:\n if sampling_table[wi] < random.random():\n continue\n\n window_start = max(0, i - window_size)\n window_end = min(len(sequence), i + window_size + 1)\n for j in range(window_start, window_end):\n if j != i:\n wj = sequence[j]\n if not wj:\n continue\n couples.append([wi, wj])\n if categorical:\n labels.append([0, 1])\n else:\n labels.append(1)\n\n if negative_samples > 0:\n num_negative_samples = int(len(labels) * negative_samples)\n words = [c[0] for c in couples]\n random.shuffle(words)\n\n couples += [[words[i % len(words)],\n random.randint(1, vocabulary_size - 1)]\n for i in range(num_negative_samples)]\n if categorical:\n labels += [[1, 0]] * num_negative_samples\n else:\n labels += [0] * num_negative_samples\n\n if shuffle:\n if seed is None:\n seed = random.randint(0, 10e6)\n random.seed(seed)\n random.shuffle(couples)\n random.seed(seed)\n random.shuffle(labels)\n\n return couples, labels\n\n\ndef _remove_long_seq(maxlen, seq, label):\n \"\"\"Removes sequences that exceed the maximum length.\n\n # Arguments\n maxlen: Int, maximum length of the output sequences.\n seq: List of lists, where each sublist is a sequence.\n label: List where each element is an integer.\n\n # Returns\n new_seq, new_label: shortened lists for `seq` and `label`.\n \"\"\"\n new_seq, new_label = [], []\n for x, y in zip(seq, label):\n if len(x) < maxlen:\n new_seq.append(x)\n new_label.append(y)\n return new_seq, new_label\n\n\nclass TimeseriesGenerator(object):\n \"\"\"Utility class for generating batches of temporal data.\n\n This class takes in a sequence of data-points gathered at\n equal intervals, along with time series parameters such as\n stride, length of history, etc., to produce batches for\n training/validation.\n\n # Arguments\n data: Indexable generator (such as list or Numpy array)\n containing consecutive data points (timesteps).\n The data should be at 2D, and axis 0 is expected\n to be the time dimension.\n targets: Targets corresponding to timesteps in `data`.\n It should have same length as `data`.\n length: Length of the output sequences (in number of timesteps).\n sampling_rate: Period between successive individual timesteps\n within sequences. For rate `r`, timesteps\n `data[i]`, `data[i-r]`, ... `data[i - length]`\n are used for create a sample sequence.\n stride: Period between successive output sequences.\n For stride `s`, consecutive output samples would\n be centered around `data[i]`, `data[i+s]`, `data[i+2*s]`, etc.\n start_index: Data points earlier than `start_index` will not be used\n in the output sequences. This is useful to reserve part of the\n data for test or validation.\n end_index: Data points later than `end_index` will not be used\n in the output sequences. This is useful to reserve part of the\n data for test or validation.\n shuffle: Whether to shuffle output samples,\n or instead draw them in chronological order.\n reverse: Boolean: if `true`, timesteps in each output sample will be\n in reverse chronological order.\n batch_size: Number of timeseries samples in each batch\n (except maybe the last one).\n\n # Returns\n A [Sequence](/utils/#sequence) instance.\n\n # Examples\n\n ```python\n from keras.preprocessing.sequence import TimeseriesGenerator\n import numpy as np\n\n data = np.array([[i] for i in range(50)])\n targets = np.array([[i] for i in range(50)])\n\n data_gen = TimeseriesGenerator(data, targets,\n length=10, sampling_rate=2,\n batch_size=2)\n assert len(data_gen) == 20\n\n batch_0 = data_gen[0]\n x, y = batch_0\n assert np.array_equal(x,\n np.array([[[0], [2], [4], [6], [8]],\n [[1], [3], [5], [7], [9]]]))\n assert np.array_equal(y,\n np.array([[10], [11]]))\n ```\n \"\"\"\n\n def __init__(self, data, targets, length,\n sampling_rate=1,\n stride=1,\n start_index=0,\n end_index=None,\n shuffle=False,\n reverse=False,\n batch_size=128):\n\n if len(data) != len(targets):\n raise ValueError('Data and targets have to be' +\n ' of same length. '\n 'Data length is {}'.format(len(data)) +\n ' while target length is {}'.format(len(targets)))\n\n self.data = data\n self.targets = targets\n self.length = length\n self.sampling_rate = sampling_rate\n self.stride = stride\n self.start_index = start_index + length\n if end_index is None:\n end_index = len(data) - 1\n self.end_index = end_index\n self.shuffle = shuffle\n self.reverse = reverse\n self.batch_size = batch_size\n\n if self.start_index > self.end_index:\n raise ValueError('`start_index+length=%i > end_index=%i` '\n 'is disallowed, as no part of the sequence '\n 'would be left to be used as current step.'\n % (self.start_index, self.end_index))\n\n def __len__(self):\n return (self.end_index - self.start_index +\n self.batch_size * self.stride) // (self.batch_size * self.stride)\n\n def __getitem__(self, index):\n if self.shuffle:\n rows = np.random.randint(\n self.start_index, self.end_index + 1, size=self.batch_size)\n else:\n i = self.start_index + self.batch_size * self.stride * index\n rows = np.arange(i, min(i + self.batch_size *\n self.stride, self.end_index + 1), self.stride)\n\n samples = np.array([self.data[row - self.length:row:self.sampling_rate]\n for row in rows])\n targets = np.array([self.targets[row] for row in rows])\n\n if self.reverse:\n return samples[:, ::-1, ...], targets\n return samples, targets\n\n def get_config(self):\n '''Returns the TimeseriesGenerator configuration as Python dictionary.\n\n # Returns\n A Python dictionary with the TimeseriesGenerator configuration.\n '''\n data = self.data\n if type(self.data).__module__ == np.__name__:\n data = self.data.tolist()\n try:\n json_data = json.dumps(data)\n except TypeError:\n raise TypeError('Data not JSON Serializable:', data)\n\n targets = self.targets\n if type(self.targets).__module__ == np.__name__:\n targets = self.targets.tolist()\n try:\n json_targets = json.dumps(targets)\n except TypeError:\n raise TypeError('Targets not JSON Serializable:', targets)\n\n return {\n 'data': json_data,\n 'targets': json_targets,\n 'length': self.length,\n 'sampling_rate': self.sampling_rate,\n 'stride': self.stride,\n 'start_index': self.start_index,\n 'end_index': self.end_index,\n 'shuffle': self.shuffle,\n 'reverse': self.reverse,\n 'batch_size': self.batch_size\n }\n\n def to_json(self, **kwargs):\n \"\"\"Returns a JSON string containing the timeseries generator\n configuration. To load a generator from a JSON string, use\n `keras.preprocessing.sequence.timeseries_generator_from_json(json_string)`.\n\n # Arguments\n **kwargs: Additional keyword arguments\n to be passed to `json.dumps()`.\n\n # Returns\n A JSON string containing the tokenizer configuration.\n \"\"\"\n config = self.get_config()\n timeseries_generator_config = {\n 'class_name': self.__class__.__name__,\n 'config': config\n }\n return json.dumps(timeseries_generator_config, **kwargs)\n\n\ndef timeseries_generator_from_json(json_string):\n \"\"\"Parses a JSON timeseries generator configuration file and\n returns a timeseries generator instance.\n\n # Arguments\n json_string: JSON string encoding a timeseries\n generator configuration.\n\n # Returns\n A Keras TimeseriesGenerator instance\n \"\"\"\n full_config = json.loads(json_string)\n config = full_config.get('config')\n\n data = json.loads(config.pop('data'))\n config['data'] = data\n targets = json.loads(config.pop('targets'))\n config['targets'] = targets\n\n return TimeseriesGenerator(**config)\n\n\n# ./keras_preprocessing/text.py\n# -*- coding: utf-8 -*-\n\"\"\"Utilities for text input preprocessing.\n\"\"\"\nimport json\nimport warnings\nfrom collections import OrderedDict, defaultdict\nfrom hashlib import md5\n\nimport numpy as np\n\nmaketrans = str.maketrans\n\n\ndef text_to_word_sequence(text,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True, split=\" \"):\n \"\"\"Converts a text to a sequence of words (or tokens).\n\n # Arguments\n text: Input text (string).\n filters: list (or concatenation) of characters to filter out, such as\n punctuation. Default: ``!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\\\t\\\\n``,\n includes basic punctuation, tabs, and newlines.\n lower: boolean. Whether to convert the input to lowercase.\n split: str. Separator for word splitting.\n\n # Returns\n A list of words (or tokens).\n \"\"\"\n if lower:\n text = text.lower()\n\n translate_dict = {c: split for c in filters}\n translate_map = maketrans(translate_dict)\n text = text.translate(translate_map)\n\n seq = text.split(split)\n return [i for i in seq if i]\n\n\ndef one_hot(text, n,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True,\n split=' ',\n analyzer=None):\n \"\"\"One-hot encodes a text into a list of word indexes of size n.\n\n This is a wrapper to the `hashing_trick` function using `hash` as the\n hashing function; unicity of word to index mapping non-guaranteed.\n\n # Arguments\n text: Input text (string).\n n: int. Size of vocabulary.\n filters: list (or concatenation) of characters to filter out, such as\n punctuation. Default: ``!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\\\t\\\\n``,\n includes basic punctuation, tabs, and newlines.\n lower: boolean. Whether to set the text to lowercase.\n split: str. Separator for word splitting.\n analyzer: function. Custom analyzer to split the text\n\n # Returns\n List of integers in [1, n]. Each integer encodes a word\n (unicity non-guaranteed).\n \"\"\"\n return hashing_trick(text, n,\n hash_function=hash,\n filters=filters,\n lower=lower,\n split=split,\n analyzer=analyzer)\n\n\ndef hashing_trick(text, n,\n hash_function=None,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True,\n split=' ',\n analyzer=None):\n \"\"\"Converts a text to a sequence of indexes in a fixed-size hashing space.\n\n # Arguments\n text: Input text (string).\n n: Dimension of the hashing space.\n hash_function: defaults to python `hash` function, can be 'md5' or\n any function that takes in input a string and returns a int.\n Note that 'hash' is not a stable hashing function, so\n it is not consistent across different runs, while 'md5'\n is a stable hashing function.\n filters: list (or concatenation) of characters to filter out, such as\n punctuation. Default: ``!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\\\t\\\\n``,\n includes basic punctuation, tabs, and newlines.\n lower: boolean. Whether to set the text to lowercase.\n split: str. Separator for word splitting.\n analyzer: function. Custom analyzer to split the text\n\n # Returns\n A list of integer word indices (unicity non-guaranteed).\n\n `0` is a reserved index that won't be assigned to any word.\n\n Two or more words may be assigned to the same index, due to possible\n collisions by the hashing function.\n The [probability](\n https://en.wikipedia.org/wiki/Birthday_problem#Probability_table)\n of a collision is in relation to the dimension of the hashing space and\n the number of distinct objects.\n \"\"\"\n if hash_function is None:\n hash_function = hash\n elif hash_function == 'md5':\n def hash_function(w):\n return int(md5(w.encode()).hexdigest(), 16)\n\n if analyzer is None:\n seq = text_to_word_sequence(text,\n filters=filters,\n lower=lower,\n split=split)\n else:\n seq = analyzer(text)\n\n return [(hash_function(w) % (n - 1) + 1) for w in seq]\n\n\nclass Tokenizer(object):\n \"\"\"Text tokenization utility class.\n\n This class allows to vectorize a text corpus, by turning each\n text into either a sequence of integers (each integer being the index\n of a token in a dictionary) or into a vector where the coefficient\n for each token could be binary, based on word count, based on tf-idf...\n\n # Arguments\n num_words: the maximum number of words to keep, based\n on word frequency. Only the most common `num_words-1` words will\n be kept.\n filters: a string where each element is a character that will be\n filtered from the texts. The default is all punctuation, plus\n tabs and line breaks, minus the `'` character.\n lower: boolean. Whether to convert the texts to lowercase.\n split: str. Separator for word splitting.\n char_level: if True, every character will be treated as a token.\n oov_token: if given, it will be added to word_index and used to\n replace out-of-vocabulary words during text_to_sequence calls\n analyzer: function. Custom analyzer to split the text.\n The default analyzer is text_to_word_sequence\n\n By default, all punctuation is removed, turning the texts into\n space-separated sequences of words\n (words maybe include the `'` character). These sequences are then\n split into lists of tokens. They will then be indexed or vectorized.\n\n `0` is a reserved index that won't be assigned to any word.\n \"\"\"\n\n def __init__(self, num_words=None,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True,\n split=' ',\n char_level=False,\n oov_token=None,\n analyzer=None,\n **kwargs):\n # Legacy support\n if 'nb_words' in kwargs:\n warnings.warn('The `nb_words` argument in `Tokenizer` '\n 'has been renamed `num_words`.')\n num_words = kwargs.pop('nb_words')\n document_count = kwargs.pop('document_count', 0)\n if kwargs:\n raise TypeError('Unrecognized keyword arguments: ' + str(kwargs))\n\n self.word_counts = OrderedDict()\n self.word_docs = defaultdict(int)\n self.filters = filters\n self.split = split\n self.lower = lower\n self.num_words = num_words\n self.document_count = document_count\n self.char_level = char_level\n self.oov_token = oov_token\n self.index_docs = defaultdict(int)\n self.word_index = {}\n self.index_word = {}\n self.analyzer = analyzer\n\n def fit_on_texts(self, texts):\n \"\"\"Updates internal vocabulary based on a list of texts.\n\n In the case where texts contains lists,\n we assume each entry of the lists to be a token.\n\n Required before using `texts_to_sequences` or `texts_to_matrix`.\n\n # Arguments\n texts: can be a list of strings,\n a generator of strings (for memory-efficiency),\n or a list of list of strings.\n \"\"\"\n for text in texts:\n self.document_count += 1\n if self.char_level or isinstance(text, list):\n if self.lower:\n if isinstance(text, list):\n text = [text_elem.lower() for text_elem in text]\n else:\n text = text.lower()\n seq = text\n else:\n if self.analyzer is None:\n seq = text_to_word_sequence(text,\n filters=self.filters,\n lower=self.lower,\n split=self.split)\n else:\n seq = self.analyzer(text)\n for w in seq:\n if w in self.word_counts:\n self.word_counts[w] += 1\n else:\n self.word_counts[w] = 1\n for w in set(seq):\n # In how many documents each word occurs\n self.word_docs[w] += 1\n\n wcounts = list(self.word_counts.items())\n wcounts.sort(key=lambda x: x[1], reverse=True)\n # forcing the oov_token to index 1 if it exists\n if self.oov_token is None:\n sorted_voc = []\n else:\n sorted_voc = [self.oov_token]\n sorted_voc.extend(wc[0] for wc in wcounts)\n\n # note that index 0 is reserved, never assigned to an existing word\n self.word_index = dict(\n zip(sorted_voc, list(range(1, len(sorted_voc) + 1))))\n\n self.index_word = {c: w for w, c in self.word_index.items()}\n\n for w, c in list(self.word_docs.items()):\n self.index_docs[self.word_index[w]] = c\n\n def fit_on_sequences(self, sequences):\n \"\"\"Updates internal vocabulary based on a list of sequences.\n\n Required before using `sequences_to_matrix`\n (if `fit_on_texts` was never called).\n\n # Arguments\n sequences: A list of sequence.\n A \"sequence\" is a list of integer word indices.\n \"\"\"\n self.document_count += len(sequences)\n for seq in sequences:\n seq = set(seq)\n for i in seq:\n self.index_docs[i] += 1\n\n def texts_to_sequences(self, texts):\n \"\"\"Transforms each text in texts to a sequence of integers.\n\n Only top `num_words-1` most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n\n # Arguments\n texts: A list of texts (strings).\n\n # Returns\n A list of sequences.\n \"\"\"\n return list(self.texts_to_sequences_generator(texts))\n\n def texts_to_sequences_generator(self, texts):\n \"\"\"Transforms each text in `texts` to a sequence of integers.\n\n Each item in texts can also be a list,\n in which case we assume each item of that list to be a token.\n\n Only top `num_words-1` most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n\n # Arguments\n texts: A list of texts (strings).\n\n # Yields\n Yields individual sequences.\n \"\"\"\n num_words = self.num_words\n oov_token_index = self.word_index.get(self.oov_token)\n for text in texts:\n if self.char_level or isinstance(text, list):\n if self.lower:\n if isinstance(text, list):\n text = [text_elem.lower() for text_elem in text]\n else:\n text = text.lower()\n seq = text\n else:\n if self.analyzer is None:\n seq = text_to_word_sequence(text,\n filters=self.filters,\n lower=self.lower,\n split=self.split)\n else:\n seq = self.analyzer(text)\n vect = []\n for w in seq:\n i = self.word_index.get(w)\n if i is not None:\n if num_words and i >= num_words:\n if oov_token_index is not None:\n vect.append(oov_token_index)\n else:\n vect.append(i)\n elif self.oov_token is not None:\n vect.append(oov_token_index)\n yield vect\n\n def sequences_to_texts(self, sequences):\n \"\"\"Transforms each sequence into a list of text.\n\n Only top `num_words-1` most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n\n # Arguments\n sequences: A list of sequences (list of integers).\n\n # Returns\n A list of texts (strings)\n \"\"\"\n return list(self.sequences_to_texts_generator(sequences))\n\n def sequences_to_texts_generator(self, sequences):\n \"\"\"Transforms each sequence in `sequences` to a list of texts(strings).\n\n Each sequence has to a list of integers.\n In other words, sequences should be a list of sequences\n\n Only top `num_words-1` most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n\n # Arguments\n sequences: A list of sequences.\n\n # Yields\n Yields individual texts.\n \"\"\"\n num_words = self.num_words\n oov_token_index = self.word_index.get(self.oov_token)\n for seq in sequences:\n vect = []\n for num in seq:\n word = self.index_word.get(num)\n if word is not None:\n if num_words and num >= num_words:\n if oov_token_index is not None:\n vect.append(self.index_word[oov_token_index])\n else:\n vect.append(word)\n elif self.oov_token is not None:\n vect.append(self.index_word[oov_token_index])\n vect = ' '.join(vect)\n yield vect\n\n def texts_to_matrix(self, texts, mode='binary'):\n \"\"\"Convert a list of texts to a Numpy matrix.\n\n # Arguments\n texts: list of strings.\n mode: one of \"binary\", \"count\", \"tfidf\", \"freq\".\n\n # Returns\n A Numpy matrix.\n \"\"\"\n sequences = self.texts_to_sequences(texts)\n return self.sequences_to_matrix(sequences, mode=mode)\n\n def sequences_to_matrix(self, sequences, mode='binary'):\n \"\"\"Converts a list of sequences into a Numpy matrix.\n\n # Arguments\n sequences: list of sequences\n (a sequence is a list of integer word indices).\n mode: one of \"binary\", \"count\", \"tfidf\", \"freq\"\n\n # Returns\n A Numpy matrix.\n\n # Raises\n ValueError: In case of invalid `mode` argument,\n or if the Tokenizer requires to be fit to sample data.\n \"\"\"\n if not self.num_words:\n if self.word_index:\n num_words = len(self.word_index) + 1\n else:\n raise ValueError('Specify a dimension (`num_words` argument), '\n 'or fit on some text data first.')\n else:\n num_words = self.num_words\n\n if mode == 'tfidf' and not self.document_count:\n raise ValueError('Fit the Tokenizer on some data '\n 'before using tfidf mode.')\n\n x = np.zeros((len(sequences), num_words))\n for i, seq in enumerate(sequences):\n if not seq:\n continue\n counts = defaultdict(int)\n for j in seq:\n if j >= num_words:\n continue\n counts[j] += 1\n for j, c in list(counts.items()):\n if mode == 'count':\n x[i][j] = c\n elif mode == 'freq':\n x[i][j] = c / len(seq)\n elif mode == 'binary':\n x[i][j] = 1\n elif mode == 'tfidf':\n # Use weighting scheme 2 in\n # https://en.wikipedia.org/wiki/Tf%E2%80%93idf\n tf = 1 + np.log(c)\n idf = np.log(1 + self.document_count /\n (1 + self.index_docs.get(j, 0)))\n x[i][j] = tf * idf\n else:\n raise ValueError('Unknown vectorization mode:', mode)\n return x\n\n def get_config(self):\n '''Returns the tokenizer configuration as Python dictionary.\n The word count dictionaries used by the tokenizer get serialized\n into plain JSON, so that the configuration can be read by other\n projects.\n\n # Returns\n A Python dictionary with the tokenizer configuration.\n '''\n json_word_counts = json.dumps(self.word_counts)\n json_word_docs = json.dumps(self.word_docs)\n json_index_docs = json.dumps(self.index_docs)\n json_word_index = json.dumps(self.word_index)\n json_index_word = json.dumps(self.index_word)\n\n return {\n 'num_words': self.num_words,\n 'filters': self.filters,\n 'lower': self.lower,\n 'split': self.split,\n 'char_level': self.char_level,\n 'oov_token': self.oov_token,\n 'document_count': self.document_count,\n 'word_counts': json_word_counts,\n 'word_docs': json_word_docs,\n 'index_docs': json_index_docs,\n 'index_word': json_index_word,\n 'word_index': json_word_index\n }\n\n def to_json(self, **kwargs):\n \"\"\"Returns a JSON string containing the tokenizer configuration.\n To load a tokenizer from a JSON string, use\n `keras.preprocessing.text.tokenizer_from_json(json_string)`.\n\n # Arguments\n **kwargs: Additional keyword arguments\n to be passed to `json.dumps()`.\n\n # Returns\n A JSON string containing the tokenizer configuration.\n \"\"\"\n config = self.get_config()\n tokenizer_config = {\n 'class_name': self.__class__.__name__,\n 'config': config\n }\n return json.dumps(tokenizer_config, **kwargs)\n\n\ndef tokenizer_from_json(json_string):\n \"\"\"Parses a JSON tokenizer configuration file and returns a\n tokenizer instance.\n\n # Arguments\n json_string: JSON string encoding a tokenizer configuration.\n\n # Returns\n A Keras Tokenizer instance\n \"\"\"\n tokenizer_config = json.loads(json_string)\n config = tokenizer_config.get('config')\n\n word_counts = json.loads(config.pop('word_counts'))\n word_docs = json.loads(config.pop('word_docs'))\n index_docs = json.loads(config.pop('index_docs'))\n # Integer indexing gets converted to strings with json.dumps()\n index_docs = {int(k): v for k, v in index_docs.items()}\n index_word = json.loads(config.pop('index_word'))\n index_word = {int(k): v for k, v in index_word.items()}\n word_index = json.loads(config.pop('word_index'))\n\n tokenizer = Tokenizer(**config)\n tokenizer.word_counts = word_counts\n tokenizer.word_docs = word_docs\n tokenizer.index_docs = index_docs\n tokenizer.word_index = word_index\n tokenizer.index_word = index_word\n\n return tokenizer\n", "num_file": 3, "num_lines": 1002, "programming_language": "Python"} {"class_name": "leducholdem", "id": "./MultiFileTest/Python/leducholdem.py", "original_code": "# ./leducholdem/__init__.py\nfrom leducholdem.base import Card as Card\nfrom leducholdem.dealer import LeducholdemDealer as Dealer\nfrom leducholdem.judger import LeducholdemJudger as Judger\nfrom leducholdem.player import LeducholdemPlayer as Player\nfrom leducholdem.player import PlayerStatus\n\nfrom leducholdem.round import LeducholdemRound as Round\nfrom leducholdem.game import LeducholdemGame as Game\n\n\n\n# ./leducholdem/base.py\n''' Game-related base classes\n'''\nclass Card:\n '''\n Card stores the suit and rank of a single card\n\n Note:\n The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]\n Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]\n '''\n suit = None\n rank = None\n valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']\n valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n\n def __init__(self, suit, rank):\n ''' Initialize the suit and rank of a card\n\n Args:\n suit: string, suit of the card, should be one of valid_suit\n rank: string, rank of the card, should be one of valid_rank\n '''\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if isinstance(other, Card):\n return self.rank == other.rank and self.suit == other.suit\n else:\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n def __hash__(self):\n suit_index = Card.valid_suit.index(self.suit)\n rank_index = Card.valid_rank.index(self.rank)\n return rank_index + 100 * suit_index\n\n def __str__(self):\n ''' Get string representation of a card.\n\n Returns:\n string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...\n '''\n return self.rank + self.suit\n\n def get_index(self):\n ''' Get index of a card.\n\n Returns:\n string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...\n '''\n return self.suit+self.rank\n\n\n# ./leducholdem/dealer.py\nfrom leducholdem.utils import init_standard_deck\nfrom leducholdem import Card\n\nclass LimitHoldemDealer:\n def __init__(self, np_random):\n self.np_random = np_random\n self.deck = init_standard_deck()\n self.shuffle()\n self.pot = 0\n\n def shuffle(self):\n self.np_random.shuffle(self.deck)\n\n def deal_card(self):\n \"\"\"\n Deal one card from the deck\n\n Returns:\n (Card): The drawn card from the deck\n \"\"\"\n return self.deck.pop()\n\n\nclass LeducholdemDealer(LimitHoldemDealer):\n\n def __init__(self, np_random):\n ''' Initialize a leducholdem dealer class\n '''\n self.np_random = np_random\n self.deck = [Card('S', 'J'), Card('H', 'J'), Card('S', 'Q'), Card('H', 'Q'), Card('S', 'K'), Card('H', 'K')]\n self.shuffle()\n self.pot = 0\n\n\n\n# ./leducholdem/game.py\nimport numpy as np\nfrom copy import copy, deepcopy\n\nfrom leducholdem import Dealer\nfrom leducholdem import Player, PlayerStatus\nfrom leducholdem import Judger\nfrom leducholdem import Round\n\n\n\nclass LimitHoldemGame:\n def __init__(self, allow_step_back=False, num_players=2):\n \"\"\"Initialize the class limit holdem game\"\"\"\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n\n # Some configurations of the game\n # These arguments can be specified for creating new games\n\n # Small blind and big blind\n self.small_blind = 1\n self.big_blind = 2 * self.small_blind\n\n # Raise amount and allowed times\n self.raise_amount = self.big_blind\n self.allowed_raise_num = 4\n\n self.num_players = num_players\n\n # Save betting history\n self.history_raise_nums = [0 for _ in range(4)]\n\n self.dealer = None\n self.players = None\n self.judger = None\n self.public_cards = None\n self.game_pointer = None\n self.round = None\n self.round_counter = None\n self.history = None\n self.history_raises_nums = None\n\n def configure(self, game_config):\n \"\"\"Specify some game specific parameters, such as number of players\"\"\"\n self.num_players = game_config['game_num_players']\n\n def init_game(self):\n \"\"\"\n Initialize the game of limit texas holdem\n\n This version supports two-player limit texas holdem\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state of the game\n (int): Current player's id\n \"\"\"\n # Initialize a dealer that can deal cards\n self.dealer = Dealer(self.np_random)\n\n # Initialize two players to play the game\n self.players = [Player(i, self.np_random) for i in range(self.num_players)]\n\n # Initialize a judger class which will decide who wins in the end\n self.judger = Judger(self.np_random)\n\n # Deal cards to each player to prepare for the first round\n for i in range(2 * self.num_players):\n self.players[i % self.num_players].hand.append(self.dealer.deal_card())\n\n # Initialize public cards\n self.public_cards = []\n\n # Randomly choose a small blind and a big blind\n s = self.np_random.randint(0, self.num_players)\n b = (s + 1) % self.num_players\n self.players[b].in_chips = self.big_blind\n self.players[s].in_chips = self.small_blind\n\n # The player next to the big blind plays the first\n self.game_pointer = (b + 1) % self.num_players\n\n # Initialize a bidding round, in the first round, the big blind and the small blind needs to\n # be passed to the round for processing.\n self.round = Round(raise_amount=self.raise_amount,\n allowed_raise_num=self.allowed_raise_num,\n num_players=self.num_players,\n np_random=self.np_random)\n\n self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])\n\n # Count the round. There are 4 rounds in each game.\n self.round_counter = 0\n\n # Save the history for stepping back to the last state.\n self.history = []\n\n state = self.get_state(self.game_pointer)\n\n # Save betting history\n self.history_raise_nums = [0 for _ in range(4)]\n\n return state, self.game_pointer\n\n def step(self, action):\n \"\"\"\n Get the next state\n\n Args:\n action (str): a specific action. (call, raise, fold, or check)\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next player id\n \"\"\"\n if self.allow_step_back:\n # First snapshot the current state\n r = deepcopy(self.round)\n b = self.game_pointer\n r_c = self.round_counter\n d = deepcopy(self.dealer)\n p = deepcopy(self.public_cards)\n ps = deepcopy(self.players)\n rn = copy(self.history_raise_nums)\n self.history.append((r, b, r_c, d, p, ps, rn))\n\n # Then we proceed to the next round\n self.game_pointer = self.round.proceed_round(self.players, action)\n\n # Save the current raise num to history\n self.history_raise_nums[self.round_counter] = self.round.have_raised\n\n # If a round is over, we deal more public cards\n if self.round.is_over():\n # For the first round, we deal 3 cards\n if self.round_counter == 0:\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n\n # For the following rounds, we deal only 1 card\n elif self.round_counter <= 2:\n self.public_cards.append(self.dealer.deal_card())\n\n # Double the raise amount for the last two rounds\n if self.round_counter == 1:\n self.round.raise_amount = 2 * self.raise_amount\n\n self.round_counter += 1\n self.round.start_new_round(self.game_pointer)\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def step_back(self):\n \"\"\"\n Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n \"\"\"\n if len(self.history) > 0:\n self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \\\n self.players, self.history_raises_nums = self.history.pop()\n return True\n return False\n\n def get_num_players(self):\n \"\"\"\n Return the number of players in limit texas holdem\n\n Returns:\n (int): The number of players in the game\n \"\"\"\n return self.num_players\n\n @staticmethod\n def get_num_actions():\n \"\"\"\n Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 4 actions (call, raise, check and fold)\n \"\"\"\n return 4\n\n def get_player_id(self):\n \"\"\"\n Return the current player's id\n\n Returns:\n (int): current player's id\n \"\"\"\n return self.game_pointer\n\n def get_state(self, player):\n \"\"\"\n Return player's state\n\n Args:\n player (int): player id\n\n Returns:\n (dict): The state of the player\n \"\"\"\n chips = [self.players[i].in_chips for i in range(self.num_players)]\n legal_actions = self.get_legal_actions()\n state = self.players[player].get_state(self.public_cards, chips, legal_actions)\n state['raise_nums'] = self.history_raise_nums\n\n return state\n\n def is_over(self):\n \"\"\"\n Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n \"\"\"\n alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players]\n # If only one player is alive, the game is over.\n if sum(alive_players) == 1:\n return True\n\n # If all rounds are finished\n if self.round_counter >= 4:\n return True\n return False\n\n def get_payoffs(self):\n \"\"\"\n Return the payoffs of the game\n\n Returns:\n (list): Each entry corresponds to the payoff of one player\n \"\"\"\n hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players]\n chips_payoffs = self.judger.judge_game(self.players, hands)\n payoffs = np.array(chips_payoffs) / self.big_blind\n return payoffs\n\n def get_legal_actions(self):\n \"\"\"\n Return the legal actions for current player\n\n Returns:\n (list): A list of legal actions\n \"\"\"\n return self.round.get_legal_actions()\n\n\n\nclass LeducholdemGame(LimitHoldemGame):\n\n def __init__(self, allow_step_back=False, num_players=2):\n ''' Initialize the class leducholdem Game\n '''\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n ''' No big/small blind\n # Some configarations of the game\n # These arguments are fixed in Leduc Hold'em Game\n\n # Raise amount and allowed times\n self.raise_amount = 2\n self.allowed_raise_num = 2\n\n self.num_players = 2\n '''\n # Some configarations of the game\n # These arguments can be specified for creating new games\n\n # Small blind and big blind\n self.small_blind = 1\n self.big_blind = 2 * self.small_blind\n\n # Raise amount and allowed times\n self.raise_amount = self.big_blind\n self.allowed_raise_num = 2\n\n self.num_players = num_players\n\n def configure(self, game_config):\n ''' Specifiy some game specific parameters, such as number of players\n '''\n self.num_players = game_config['game_num_players']\n\n def init_game(self):\n ''' Initialilze the game of Limit Texas Hold'em\n\n This version supports two-player limit texas hold'em\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state of the game\n (int): Current player's id\n '''\n # Initilize a dealer that can deal cards\n self.dealer = Dealer(self.np_random)\n\n # Initilize two players to play the game\n self.players = [Player(i, self.np_random) for i in range(self.num_players)]\n\n # Initialize a judger class which will decide who wins in the end\n self.judger = Judger(self.np_random)\n\n # Prepare for the first round\n for i in range(self.num_players):\n self.players[i].hand = self.dealer.deal_card()\n # Randomly choose a small blind and a big blind\n s = self.np_random.randint(0, self.num_players)\n b = (s + 1) % self.num_players\n self.players[b].in_chips = self.big_blind\n self.players[s].in_chips = self.small_blind\n self.public_card = None\n # The player with small blind plays the first\n self.game_pointer = s\n\n # Initilize a bidding round, in the first round, the big blind and the small blind needs to\n # be passed to the round for processing.\n self.round = Round(raise_amount=self.raise_amount,\n allowed_raise_num=self.allowed_raise_num,\n num_players=self.num_players,\n np_random=self.np_random)\n\n self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])\n\n # Count the round. There are 2 rounds in each game.\n self.round_counter = 0\n\n # Save the hisory for stepping back to the last state.\n self.history = []\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def step(self, action):\n ''' Get the next state\n\n Args:\n action (str): a specific action. (call, raise, fold, or check)\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next plater's id\n '''\n if self.allow_step_back:\n # First snapshot the current state\n r = copy(self.round)\n r_raised = copy(self.round.raised)\n gp = self.game_pointer\n r_c = self.round_counter\n d_deck = copy(self.dealer.deck)\n p = copy(self.public_card)\n ps = [copy(self.players[i]) for i in range(self.num_players)]\n ps_hand = [copy(self.players[i].hand) for i in range(self.num_players)]\n self.history.append((r, r_raised, gp, r_c, d_deck, p, ps, ps_hand))\n\n # Then we proceed to the next round\n self.game_pointer = self.round.proceed_round(self.players, action)\n\n # If a round is over, we deal more public cards\n if self.round.is_over():\n # For the first round, we deal 1 card as public card. Double the raise amount for the second round\n if self.round_counter == 0:\n self.public_card = self.dealer.deal_card()\n self.round.raise_amount = 2 * self.raise_amount\n\n self.round_counter += 1\n self.round.start_new_round(self.game_pointer)\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def get_state(self, player):\n ''' Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n (dict): The state of the player\n '''\n chips = [self.players[i].in_chips for i in range(self.num_players)]\n legal_actions = self.get_legal_actions()\n state = self.players[player].get_state(self.public_card, chips, legal_actions)\n state['current_player'] = self.game_pointer\n\n return state\n\n def is_over(self):\n ''' Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n '''\n alive_players = [1 if p.status=='alive' else 0 for p in self.players]\n # If only one player is alive, the game is over.\n if sum(alive_players) == 1:\n return True\n\n # If all rounds are finshed\n if self.round_counter >= 2:\n return True\n return False\n\n def get_payoffs(self):\n ''' Return the payoffs of the game\n\n Returns:\n (list): Each entry corresponds to the payoff of one player\n '''\n chips_payoffs = self.judger.judge_game(self.players, self.public_card)\n payoffs = np.array(chips_payoffs) / (self.big_blind)\n return payoffs\n\n def step_back(self):\n ''' Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n '''\n if len(self.history) > 0:\n self.round, r_raised, self.game_pointer, self.round_counter, d_deck, self.public_card, self.players, ps_hand = self.history.pop()\n self.round.raised = r_raised\n self.dealer.deck = d_deck\n for i, hand in enumerate(ps_hand):\n self.players[i].hand = hand\n return True\n return False\n\n\n# ./leducholdem/judger.py\nfrom leducholdem.utils import rank2int\n\nclass LeducholdemJudger:\n ''' The Judger class for Leduc Hold'em\n '''\n def __init__(self, np_random):\n ''' Initialize a judger class\n '''\n self.np_random = np_random\n\n @staticmethod\n def judge_game(players, public_card):\n ''' Judge the winner of the game.\n\n Args:\n players (list): The list of players who play the game\n public_card (object): The public card that seen by all the players\n\n Returns:\n (list): Each entry of the list corresponds to one entry of the\n '''\n # Judge who are the winners\n winners = [0] * len(players)\n fold_count = 0\n ranks = []\n # If every player folds except one, the alive player is the winner\n for idx, player in enumerate(players):\n ranks.append(rank2int(player.hand.rank))\n if player.status == 'folded':\n fold_count += 1\n elif player.status == 'alive':\n alive_idx = idx\n if fold_count == (len(players) - 1):\n winners[alive_idx] = 1\n \n # If any of the players matches the public card wins\n if sum(winners) < 1:\n for idx, player in enumerate(players):\n if player.hand.rank == public_card.rank:\n winners[idx] = 1\n break\n \n # If non of the above conditions, the winner player is the one with the highest card rank\n if sum(winners) < 1:\n max_rank = max(ranks)\n max_index = [i for i, j in enumerate(ranks) if j == max_rank]\n for idx in max_index:\n winners[idx] = 1\n\n # Compute the total chips\n total = 0\n for p in players:\n total += p.in_chips\n\n each_win = float(total) / sum(winners)\n\n payoffs = []\n for i, _ in enumerate(players):\n if winners[i] == 1:\n payoffs.append(each_win - players[i].in_chips)\n else:\n payoffs.append(float(-players[i].in_chips))\n\n return payoffs\n\n\n# ./leducholdem/player.py\nfrom enum import Enum\n\n\nclass PlayerStatus(Enum):\n ALIVE = 0\n FOLDED = 1\n ALLIN = 2\n \n\nclass LeducholdemPlayer:\n\n def __init__(self, player_id, np_random):\n ''' Initilize a player.\n\n Args:\n player_id (int): The id of the player\n '''\n self.np_random = np_random\n self.player_id = player_id\n self.status = 'alive'\n self.hand = None\n\n # The chips that this player has put in until now\n self.in_chips = 0\n\n def get_state(self, public_card, all_chips, legal_actions):\n ''' Encode the state for the player\n\n Args:\n public_card (object): The public card that seen by all the players\n all_chips (int): The chips that all players have put in\n\n Returns:\n (dict): The state of the player\n '''\n state = {}\n state['hand'] = self.hand.get_index()\n state['public_card'] = public_card.get_index() if public_card else None\n state['all_chips'] = all_chips\n state['my_chips'] = self.in_chips\n state['legal_actions'] = legal_actions\n return state\n\n def get_player_id(self):\n ''' Return the id of the player\n '''\n return self.player_id\n\n\n# ./leducholdem/round.py\n# -*- coding: utf-8 -*-\n''' Implement Leduc Hold'em Round class\n'''\n\nclass LimitHoldemRound:\n \"\"\"Round can call other Classes' functions to keep the game running\"\"\"\n\n def __init__(self, raise_amount, allowed_raise_num, num_players, np_random):\n \"\"\"\n Initialize the round class\n\n Args:\n raise_amount (int): the raise amount for each raise\n allowed_raise_num (int): The number of allowed raise num\n num_players (int): The number of players\n \"\"\"\n self.np_random = np_random\n self.game_pointer = None\n self.raise_amount = raise_amount\n self.allowed_raise_num = allowed_raise_num\n\n self.num_players = num_players\n\n # Count the number of raise\n self.have_raised = 0\n\n # Count the number without raise\n # If every player agree to not raise, the round is over\n self.not_raise_num = 0\n\n # Raised amount for each player\n self.raised = [0 for _ in range(self.num_players)]\n self.player_folded = None\n\n def start_new_round(self, game_pointer, raised=None):\n \"\"\"\n Start a new bidding round\n\n Args:\n game_pointer (int): The game_pointer that indicates the next player\n raised (list): Initialize the chips for each player\n\n Note: For the first round of the game, we need to setup the big/small blind\n \"\"\"\n self.game_pointer = game_pointer\n self.have_raised = 0\n self.not_raise_num = 0\n if raised:\n self.raised = raised\n else:\n self.raised = [0 for _ in range(self.num_players)]\n\n def proceed_round(self, players, action):\n \"\"\"\n Call other classes functions to keep one round running\n\n Args:\n players (list): The list of players that play the game\n action (str): An legal action taken by the player\n\n Returns:\n (int): The game_pointer that indicates the next player\n \"\"\"\n if action not in self.get_legal_actions():\n raise Exception('{} is not legal action. Legal actions: {}'.format(action, self.get_legal_actions()))\n\n if action == 'call':\n diff = max(self.raised) - self.raised[self.game_pointer]\n self.raised[self.game_pointer] = max(self.raised)\n players[self.game_pointer].in_chips += diff\n self.not_raise_num += 1\n\n elif action == 'raise':\n diff = max(self.raised) - self.raised[self.game_pointer] + self.raise_amount\n self.raised[self.game_pointer] = max(self.raised) + self.raise_amount\n players[self.game_pointer].in_chips += diff\n self.have_raised += 1\n self.not_raise_num = 1\n\n elif action == 'fold':\n players[self.game_pointer].status = 'folded'\n self.player_folded = True\n\n elif action == 'check':\n self.not_raise_num += 1\n\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n # Skip the folded players\n while players[self.game_pointer].status == 'folded':\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n return self.game_pointer\n\n def get_legal_actions(self):\n \"\"\"\n Obtain the legal actions for the current player\n\n Returns:\n (list): A list of legal actions\n \"\"\"\n full_actions = ['call', 'raise', 'fold', 'check']\n\n # If the the number of raises already reaches the maximum number raises, we can not raise any more\n if self.have_raised >= self.allowed_raise_num:\n full_actions.remove('raise')\n\n # If the current chips are less than that of the highest one in the round, we can not check\n if self.raised[self.game_pointer] < max(self.raised):\n full_actions.remove('check')\n\n # If the current player has put in the chips that are more than others, we can not call\n if self.raised[self.game_pointer] == max(self.raised):\n full_actions.remove('call')\n\n return full_actions\n\n def is_over(self):\n \"\"\"\n Check whether the round is over\n\n Returns:\n (boolean): True if the current round is over\n \"\"\"\n if self.not_raise_num >= self.num_players:\n return True\n return False\n\n\n\nclass LeducholdemRound(LimitHoldemRound):\n ''' Round can call other Classes' functions to keep the game running\n '''\n\n def __init__(self, raise_amount, allowed_raise_num, num_players, np_random):\n ''' Initilize the round class\n\n Args:\n raise_amount (int): the raise amount for each raise\n allowed_raise_num (int): The number of allowed raise num\n num_players (int): The number of players\n '''\n super(LeducholdemRound, self).__init__(raise_amount, allowed_raise_num, num_players, np_random=np_random)\n\n\n# ./leducholdem/utils.py\nfrom leducholdem import Card\n\ndef init_standard_deck():\n ''' Initialize a standard deck of 52 cards\n\n Returns:\n (list): A list of Card object\n '''\n suit_list = ['S', 'H', 'D', 'C']\n rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n res = [Card(suit, rank) for suit in suit_list for rank in rank_list]\n return res\n\ndef rank2int(rank):\n ''' Get the coresponding number of a rank.\n\n Args:\n rank(str): rank stored in Card object\n\n Returns:\n (int): the number corresponding to the rank\n\n Note:\n 1. If the input rank is an empty string, the function will return -1.\n 2. If the input rank is not valid, the function will return None.\n '''\n if rank == '':\n return -1\n elif rank.isdigit():\n if int(rank) >= 2 and int(rank) <= 10:\n return int(rank)\n else:\n return None\n elif rank == 'A':\n return 14\n elif rank == 'T':\n return 10\n elif rank == 'J':\n return 11\n elif rank == 'Q':\n return 12\n elif rank == 'K':\n return 13\n return None\n\n\n", "num_file": 8, "num_lines": 833, "programming_language": "Python"} {"class_name": "limitholdem", "id": "./MultiFileTest/Python/limitholdem.py", "original_code": "# ./limitholdem/__init__.py\nfrom limitholdem.base import Card as Card\n\nfrom limitholdem.dealer import LimitHoldemDealer as Dealer\nfrom limitholdem.judger import LimitHoldemJudger as Judger\nfrom limitholdem.player import LimitHoldemPlayer as Player\nfrom limitholdem.player import PlayerStatus\nfrom limitholdem.round import LimitHoldemRound as Round\nfrom limitholdem.game import LimitHoldemGame as Game\n\n\n\n# ./limitholdem/base.py\n''' Game-related base classes\n'''\nclass Card:\n '''\n Card stores the suit and rank of a single card\n\n Note:\n The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]\n Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]\n '''\n suit = None\n rank = None\n valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']\n valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n\n def __init__(self, suit, rank):\n ''' Initialize the suit and rank of a card\n\n Args:\n suit: string, suit of the card, should be one of valid_suit\n rank: string, rank of the card, should be one of valid_rank\n '''\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if isinstance(other, Card):\n return self.rank == other.rank and self.suit == other.suit\n else:\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n def __hash__(self):\n suit_index = Card.valid_suit.index(self.suit)\n rank_index = Card.valid_rank.index(self.rank)\n return rank_index + 100 * suit_index\n\n def __str__(self):\n ''' Get string representation of a card.\n\n Returns:\n string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...\n '''\n return self.rank + self.suit\n\n def get_index(self):\n ''' Get index of a card.\n\n Returns:\n string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...\n '''\n return self.suit+self.rank\n\n\n# ./limitholdem/dealer.py\nfrom limitholdem.utils import init_standard_deck\n\nclass LimitHoldemDealer:\n def __init__(self, np_random):\n self.np_random = np_random\n self.deck = init_standard_deck()\n self.shuffle()\n self.pot = 0\n\n def shuffle(self):\n self.np_random.shuffle(self.deck)\n\n def deal_card(self):\n \"\"\"\n Deal one card from the deck\n\n Returns:\n (Card): The drawn card from the deck\n \"\"\"\n return self.deck.pop()\n\n\n# ./limitholdem/game.py\nfrom copy import deepcopy, copy\nimport numpy as np\n\nfrom limitholdem import Dealer\nfrom limitholdem import Player, PlayerStatus\nfrom limitholdem import Judger\nfrom limitholdem import Round\n\n\nclass LimitHoldemGame:\n def __init__(self, allow_step_back=False, num_players=2):\n \"\"\"Initialize the class limit holdem game\"\"\"\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n\n # Some configurations of the game\n # These arguments can be specified for creating new games\n\n # Small blind and big blind\n self.small_blind = 1\n self.big_blind = 2 * self.small_blind\n\n # Raise amount and allowed times\n self.raise_amount = self.big_blind\n self.allowed_raise_num = 4\n\n self.num_players = num_players\n\n # Save betting history\n self.history_raise_nums = [0 for _ in range(4)]\n\n self.dealer = None\n self.players = None\n self.judger = None\n self.public_cards = None\n self.game_pointer = None\n self.round = None\n self.round_counter = None\n self.history = None\n self.history_raises_nums = None\n\n def configure(self, game_config):\n \"\"\"Specify some game specific parameters, such as number of players\"\"\"\n self.num_players = game_config['game_num_players']\n\n def init_game(self):\n \"\"\"\n Initialize the game of limit texas holdem\n\n This version supports two-player limit texas holdem\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state of the game\n (int): Current player's id\n \"\"\"\n # Initialize a dealer that can deal cards\n self.dealer = Dealer(self.np_random)\n\n # Initialize two players to play the game\n self.players = [Player(i, self.np_random) for i in range(self.num_players)]\n\n # Initialize a judger class which will decide who wins in the end\n self.judger = Judger(self.np_random)\n\n # Deal cards to each player to prepare for the first round\n for i in range(2 * self.num_players):\n self.players[i % self.num_players].hand.append(self.dealer.deal_card())\n\n # Initialize public cards\n self.public_cards = []\n\n # Randomly choose a small blind and a big blind\n s = self.np_random.randint(0, self.num_players)\n b = (s + 1) % self.num_players\n self.players[b].in_chips = self.big_blind\n self.players[s].in_chips = self.small_blind\n\n # The player next to the big blind plays the first\n self.game_pointer = (b + 1) % self.num_players\n\n # Initialize a bidding round, in the first round, the big blind and the small blind needs to\n # be passed to the round for processing.\n self.round = Round(raise_amount=self.raise_amount,\n allowed_raise_num=self.allowed_raise_num,\n num_players=self.num_players,\n np_random=self.np_random)\n\n self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])\n\n # Count the round. There are 4 rounds in each game.\n self.round_counter = 0\n\n # Save the history for stepping back to the last state.\n self.history = []\n\n state = self.get_state(self.game_pointer)\n\n # Save betting history\n self.history_raise_nums = [0 for _ in range(4)]\n\n return state, self.game_pointer\n\n def step(self, action):\n \"\"\"\n Get the next state\n\n Args:\n action (str): a specific action. (call, raise, fold, or check)\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next player id\n \"\"\"\n if self.allow_step_back:\n # First snapshot the current state\n r = deepcopy(self.round)\n b = self.game_pointer\n r_c = self.round_counter\n d = deepcopy(self.dealer)\n p = deepcopy(self.public_cards)\n ps = deepcopy(self.players)\n rn = copy(self.history_raise_nums)\n self.history.append((r, b, r_c, d, p, ps, rn))\n\n # Then we proceed to the next round\n self.game_pointer = self.round.proceed_round(self.players, action)\n\n # Save the current raise num to history\n self.history_raise_nums[self.round_counter] = self.round.have_raised\n\n # If a round is over, we deal more public cards\n if self.round.is_over():\n # For the first round, we deal 3 cards\n if self.round_counter == 0:\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n\n # For the following rounds, we deal only 1 card\n elif self.round_counter <= 2:\n self.public_cards.append(self.dealer.deal_card())\n\n # Double the raise amount for the last two rounds\n if self.round_counter == 1:\n self.round.raise_amount = 2 * self.raise_amount\n\n self.round_counter += 1\n self.round.start_new_round(self.game_pointer)\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def step_back(self):\n \"\"\"\n Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n \"\"\"\n if len(self.history) > 0:\n self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \\\n self.players, self.history_raises_nums = self.history.pop()\n return True\n return False\n\n def get_num_players(self):\n \"\"\"\n Return the number of players in limit texas holdem\n\n Returns:\n (int): The number of players in the game\n \"\"\"\n return self.num_players\n\n @staticmethod\n def get_num_actions():\n \"\"\"\n Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 4 actions (call, raise, check and fold)\n \"\"\"\n return 4\n\n def get_player_id(self):\n \"\"\"\n Return the current player's id\n\n Returns:\n (int): current player's id\n \"\"\"\n return self.game_pointer\n\n def get_state(self, player):\n \"\"\"\n Return player's state\n\n Args:\n player (int): player id\n\n Returns:\n (dict): The state of the player\n \"\"\"\n chips = [self.players[i].in_chips for i in range(self.num_players)]\n legal_actions = self.get_legal_actions()\n state = self.players[player].get_state(self.public_cards, chips, legal_actions)\n state['raise_nums'] = self.history_raise_nums\n\n return state\n\n def is_over(self):\n \"\"\"\n Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n \"\"\"\n alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players]\n # If only one player is alive, the game is over.\n if sum(alive_players) == 1:\n return True\n\n # If all rounds are finished\n if self.round_counter >= 4:\n return True\n return False\n\n def get_payoffs(self):\n \"\"\"\n Return the payoffs of the game\n\n Returns:\n (list): Each entry corresponds to the payoff of one player\n \"\"\"\n hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players]\n chips_payoffs = self.judger.judge_game(self.players, hands)\n payoffs = np.array(chips_payoffs) / self.big_blind\n return payoffs\n\n def get_legal_actions(self):\n \"\"\"\n Return the legal actions for current player\n\n Returns:\n (list): A list of legal actions\n \"\"\"\n return self.round.get_legal_actions()\n\n\n# ./limitholdem/judger.py\nfrom limitholdem.utils import compare_hands\nimport numpy as np\n\n\nclass LimitHoldemJudger:\n \"\"\"The Judger class for limit texas holdem\"\"\"\n\n def __init__(self, np_random):\n self.np_random = np_random\n\n def judge_game(self, players, hands):\n \"\"\"\n Judge the winner of the game.\n\n Args:\n players (list): The list of players who play the game\n hands (list): The list of hands that from the players\n\n Returns:\n (list): Each entry of the list corresponds to one entry of the\n \"\"\"\n # Convert the hands into card indexes\n hands = [[card.get_index() for card in hand] if hand is not None else None for hand in hands]\n \n in_chips = [p.in_chips for p in players]\n remaining = sum(in_chips)\n payoffs = [0] * len(hands)\n while remaining > 0:\n winners = compare_hands(hands)\n each_win = self.split_pots_among_players(in_chips, winners)\n \n for i in range(len(players)):\n if winners[i]:\n remaining -= each_win[i]\n payoffs[i] += each_win[i] - in_chips[i]\n hands[i] = None\n in_chips[i] = 0\n elif in_chips[i] > 0:\n payoffs[i] += each_win[i] - in_chips[i]\n in_chips[i] = each_win[i]\n \n assert sum(payoffs) == 0\n return payoffs\n\n def split_pot_among_players(self, in_chips, winners):\n \"\"\"\n Splits the next (side) pot among players.\n Function is called in loop by distribute_pots_among_players until all chips are allocated.\n\n Args:\n in_chips (list): List with number of chips bet not yet distributed for each player\n winners (list): List with 1 if the player is among winners else 0\n\n Returns:\n (list): Of how much chips each player get after this pot has been split and list of chips left to distribute\n \"\"\"\n nb_winners_in_pot = sum((winners[i] and in_chips[i] > 0) for i in range(len(in_chips)))\n nb_players_in_pot = sum(in_chips[i] > 0 for i in range(len(in_chips)))\n if nb_winners_in_pot == 0 or nb_winners_in_pot == nb_players_in_pot:\n # no winner or all winners for this pot\n allocated = list(in_chips) # we give back their chips to each players in this pot\n in_chips_after = len(in_chips) * [0] # no more chips to distribute\n else:\n amount_in_pot_by_player = min(v for v in in_chips if v > 0)\n how_much_one_win, remaining = divmod(amount_in_pot_by_player * nb_players_in_pot, nb_winners_in_pot)\n '''\n In the event of a split pot that cannot be divided equally for every winner, the winner who is sitting \n closest to the left of the dealer receives the remaining differential in chips cf \n https://www.betclic.fr/poker/house-rules--play-safely--betclic-poker-cpok_rules to simplify and as this \n case is very rare, we will give the remaining differential in chips to a random winner\n '''\n allocated = len(in_chips) * [0]\n in_chips_after = list(in_chips)\n for i in range(len(in_chips)): # iterate on all players\n if in_chips[i] == 0: # player not in pot\n continue\n if winners[i]:\n allocated[i] += how_much_one_win\n in_chips_after[i] -= amount_in_pot_by_player\n if remaining > 0:\n random_winning_player = self.np_random.choice(\n [i for i in range(len(winners)) if winners[i] and in_chips[i] > 0])\n allocated[random_winning_player] += remaining\n assert sum(in_chips[i] - in_chips_after[i] for i in range(len(in_chips))) == sum(allocated)\n return allocated, in_chips_after\n\n def split_pots_among_players(self, in_chips_initial, winners):\n \"\"\"\n Splits main pot and side pots among players (to handle special case of all-in players).\n\n Args:\n in_chips_initial (list): List with number of chips bet for each player\n winners (list): List with 1 if the player is among winners else 0\n\n Returns:\n (list): List of how much chips each player get back after all pots have been split\n \"\"\"\n in_chips = list(in_chips_initial)\n assert len(in_chips) == len(winners)\n assert all(v == 0 or v == 1 for v in winners)\n assert sum(winners) >= 1 # there must be at least one winner\n allocated = np.zeros(len(in_chips), dtype=int)\n while any(v > 0 for v in in_chips): # while there are still chips to allocate\n allocated_current_pot, in_chips = self.split_pot_among_players(in_chips, winners)\n allocated += allocated_current_pot # element-wise addition\n assert all(chips >= 0 for chips in allocated) # check that all players got a non negative amount of chips\n assert sum(in_chips_initial) == sum(allocated) # check that all chips bet have been allocated\n return list(allocated)\n\n\n# ./limitholdem/player.py\nfrom enum import Enum\n\n\nclass PlayerStatus(Enum):\n ALIVE = 0\n FOLDED = 1\n ALLIN = 2\n\n\nclass LimitHoldemPlayer:\n\n def __init__(self, player_id, np_random):\n \"\"\"\n Initialize a player.\n\n Args:\n player_id (int): The id of the player\n \"\"\"\n self.np_random = np_random\n self.player_id = player_id\n self.hand = []\n self.status = PlayerStatus.ALIVE\n\n # The chips that this player has put in until now\n self.in_chips = 0\n\n def get_state(self, public_cards, all_chips, legal_actions):\n \"\"\"\n Encode the state for the player\n\n Args:\n public_cards (list): A list of public cards that seen by all the players\n all_chips (int): The chips that all players have put in\n\n Returns:\n (dict): The state of the player\n \"\"\"\n return {\n 'hand': [c.get_index() for c in self.hand],\n 'public_cards': [c.get_index() for c in public_cards],\n 'all_chips': all_chips,\n 'my_chips': self.in_chips,\n 'legal_actions': legal_actions\n }\n\n def get_player_id(self):\n return self.player_id\n\n\n# ./limitholdem/round.py\n# -*- coding: utf-8 -*-\n\"\"\"Limit texas holdem round class implementation\"\"\"\n\n\nclass LimitHoldemRound:\n \"\"\"Round can call other Classes' functions to keep the game running\"\"\"\n\n def __init__(self, raise_amount, allowed_raise_num, num_players, np_random):\n \"\"\"\n Initialize the round class\n\n Args:\n raise_amount (int): the raise amount for each raise\n allowed_raise_num (int): The number of allowed raise num\n num_players (int): The number of players\n \"\"\"\n self.np_random = np_random\n self.game_pointer = None\n self.raise_amount = raise_amount\n self.allowed_raise_num = allowed_raise_num\n\n self.num_players = num_players\n\n # Count the number of raise\n self.have_raised = 0\n\n # Count the number without raise\n # If every player agree to not raise, the round is over\n self.not_raise_num = 0\n\n # Raised amount for each player\n self.raised = [0 for _ in range(self.num_players)]\n self.player_folded = None\n\n def start_new_round(self, game_pointer, raised=None):\n \"\"\"\n Start a new bidding round\n\n Args:\n game_pointer (int): The game_pointer that indicates the next player\n raised (list): Initialize the chips for each player\n\n Note: For the first round of the game, we need to setup the big/small blind\n \"\"\"\n self.game_pointer = game_pointer\n self.have_raised = 0\n self.not_raise_num = 0\n if raised:\n self.raised = raised\n else:\n self.raised = [0 for _ in range(self.num_players)]\n\n def proceed_round(self, players, action):\n \"\"\"\n Call other classes functions to keep one round running\n\n Args:\n players (list): The list of players that play the game\n action (str): An legal action taken by the player\n\n Returns:\n (int): The game_pointer that indicates the next player\n \"\"\"\n if action not in self.get_legal_actions():\n raise Exception('{} is not legal action. Legal actions: {}'.format(action, self.get_legal_actions()))\n\n if action == 'call':\n diff = max(self.raised) - self.raised[self.game_pointer]\n self.raised[self.game_pointer] = max(self.raised)\n players[self.game_pointer].in_chips += diff\n self.not_raise_num += 1\n\n elif action == 'raise':\n diff = max(self.raised) - self.raised[self.game_pointer] + self.raise_amount\n self.raised[self.game_pointer] = max(self.raised) + self.raise_amount\n players[self.game_pointer].in_chips += diff\n self.have_raised += 1\n self.not_raise_num = 1\n\n elif action == 'fold':\n players[self.game_pointer].status = 'folded'\n self.player_folded = True\n\n elif action == 'check':\n self.not_raise_num += 1\n\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n # Skip the folded players\n while players[self.game_pointer].status == 'folded':\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n return self.game_pointer\n\n def get_legal_actions(self):\n \"\"\"\n Obtain the legal actions for the current player\n\n Returns:\n (list): A list of legal actions\n \"\"\"\n full_actions = ['call', 'raise', 'fold', 'check']\n\n # If the the number of raises already reaches the maximum number raises, we can not raise any more\n if self.have_raised >= self.allowed_raise_num:\n full_actions.remove('raise')\n\n # If the current chips are less than that of the highest one in the round, we can not check\n if self.raised[self.game_pointer] < max(self.raised):\n full_actions.remove('check')\n\n # If the current player has put in the chips that are more than others, we can not call\n if self.raised[self.game_pointer] == max(self.raised):\n full_actions.remove('call')\n\n return full_actions\n\n def is_over(self):\n \"\"\"\n Check whether the round is over\n\n Returns:\n (boolean): True if the current round is over\n \"\"\"\n if self.not_raise_num >= self.num_players:\n return True\n return False\n\n\n# ./limitholdem/utils.py\nimport numpy as np\nfrom limitholdem import Card\n\n\ndef init_standard_deck():\n ''' Initialize a standard deck of 52 cards\n\n Returns:\n (list): A list of Card object\n '''\n suit_list = ['S', 'H', 'D', 'C']\n rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n res = [Card(suit, rank) for suit in suit_list for rank in rank_list]\n return res\n\n\nclass Hand:\n def __init__(self, all_cards):\n self.all_cards = all_cards # two hand cards + five public cards\n self.category = 0\n #type of a players' best five cards, greater combination has higher number eg: 0:\"Not_Yet_Evaluated\" 1: \"High_Card\" , 9:\"Straight_Flush\"\n self.best_five = []\n #the largest combination of five cards in all the seven cards\n self.flush_cards = []\n #cards with same suit\n self.cards_by_rank = []\n #cards after sort\n self.product = 1\n #cards’ type indicator\n self.RANK_TO_STRING = {2: \"2\", 3: \"3\", 4: \"4\", 5: \"5\", 6: \"6\",\n 7: \"7\", 8: \"8\", 9: \"9\", 10: \"T\", 11: \"J\", 12: \"Q\", 13: \"K\", 14: \"A\"}\n self.STRING_TO_RANK = {v:k for k, v in self.RANK_TO_STRING.items()}\n self.RANK_LOOKUP = \"23456789TJQKA\"\n self.SUIT_LOOKUP = \"SCDH\"\n\n def get_hand_five_cards(self):\n '''\n Get the best five cards of a player\n Returns:\n (list): the best five cards among the seven cards of a player\n '''\n return self.best_five\n\n def _sort_cards(self):\n '''\n Sort all the seven cards ascendingly according to RANK_LOOKUP\n '''\n self.all_cards = sorted(\n self.all_cards, key=lambda card: self.RANK_LOOKUP.index(card[1]))\n\n def evaluateHand(self):\n \"\"\"\n Evaluate all the seven cards, get the best combination catagory\n And pick the best five cards (for comparing in case 2 hands have the same Category) .\n \"\"\"\n if len(self.all_cards) != 7:\n raise Exception(\n \"There are not enough 7 cards in this hand, quit evaluation now ! \")\n\n self._sort_cards()\n self.cards_by_rank, self.product = self._getcards_by_rank(\n self.all_cards)\n\n if self._has_straight_flush():\n self.category = 9\n #Straight Flush\n elif self._has_four():\n self.category = 8\n #Four of a Kind\n self.best_five = self._get_Four_of_a_kind_cards()\n elif self._has_fullhouse():\n self.category = 7\n #Full house\n self.best_five = self._get_Fullhouse_cards()\n elif self._has_flush():\n self.category = 6\n #Flush\n i = len(self.flush_cards)\n self.best_five = [card for card in self.flush_cards[i-5:i]]\n elif self._has_straight(self.all_cards):\n self.category = 5\n #Straight\n elif self._has_three():\n self.category = 4\n #Three of a Kind\n self.best_five = self._get_Three_of_a_kind_cards()\n elif self._has_two_pairs():\n self.category = 3\n #Two Pairs\n self.best_five = self._get_Two_Pair_cards()\n elif self._has_pair():\n self.category = 2\n #One Pair\n self.best_five = self._get_One_Pair_cards()\n elif self._has_high_card():\n self.category = 1\n #High Card\n self.best_five = self._get_High_cards()\n\n def _has_straight_flush(self):\n '''\n Check the existence of straight_flush cards\n Returns:\n True: exist\n False: not exist\n '''\n self.flush_cards = self._getflush_cards()\n if len(self.flush_cards) > 0:\n straightflush_cards = self._get_straightflush_cards()\n if len(straightflush_cards) > 0:\n self.best_five = straightflush_cards\n return True\n return False\n\n def _get_straightflush_cards(self):\n '''\n Pick straight_flush cards\n Returns:\n (list): the straightflush cards\n '''\n straightflush_cards = self._get_straight_cards(self.flush_cards)\n return straightflush_cards\n\n def _getflush_cards(self):\n '''\n Pick flush cards\n Returns:\n (list): the flush cards\n '''\n card_string = ''.join(self.all_cards)\n for suit in self.SUIT_LOOKUP:\n suit_count = card_string.count(suit)\n if suit_count >= 5:\n flush_cards = [\n card for card in self.all_cards if card[0] == suit]\n return flush_cards\n return []\n\n def _has_flush(self):\n '''\n Check the existence of flush cards\n Returns:\n True: exist\n False: not exist\n '''\n if len(self.flush_cards) > 0:\n return True\n else:\n return False\n\n def _has_straight(self, all_cards):\n '''\n Check the existence of straight cards\n Returns:\n True: exist\n False: not exist\n '''\n diff_rank_cards = self._get_different_rank_list(all_cards)\n self.best_five = self._get_straight_cards(diff_rank_cards)\n if len(self.best_five) != 0:\n return True\n else:\n return False\n @classmethod\n def _get_different_rank_list(self, all_cards):\n '''\n Get cards with different ranks, that is to say, remove duplicate-ranking cards, for picking straight cards' use\n Args:\n (list): two hand cards + five public cards\n Returns:\n (list): a list of cards with duplicate-ranking cards removed\n '''\n different_rank_list = []\n different_rank_list.append(all_cards[0])\n for card in all_cards:\n if(card[1] != different_rank_list[-1][1]):\n different_rank_list.append(card)\n return different_rank_list\n\n def _get_straight_cards(self, Cards):\n '''\n Pick straight cards\n Returns:\n (list): the straight cards\n '''\n ranks = [self.STRING_TO_RANK[c[1]] for c in Cards]\n\n highest_card = Cards[-1]\n if highest_card[1] == 'A':\n Cards.insert(0, highest_card)\n ranks.insert(0, 1)\n\n for i_last in range(len(ranks) - 1, 3, -1):\n if ranks[i_last-4] + 4 == ranks[i_last]: # works because ranks are unique and sorted in ascending order\n return Cards[i_last-4:i_last+1]\n return []\n\n def _getcards_by_rank(self, all_cards):\n '''\n Get cards by rank\n Args:\n (list): # two hand cards + five public cards\n Return:\n card_group(list): cards after sort\n product(int):cards‘ type indicator\n '''\n card_group = []\n card_group_element = []\n product = 1\n prime_lookup = {0: 1, 1: 1, 2: 2, 3: 3, 4: 5}\n count = 0\n current_rank = 0\n\n for card in all_cards:\n rank = self.RANK_LOOKUP.index(card[1])\n if rank == current_rank:\n count += 1\n card_group_element.append(card)\n elif rank != current_rank:\n product *= prime_lookup[count]\n # Explanation :\n # if count == 2, then product *= 2\n # if count == 3, then product *= 3\n # if count == 4, then product *= 5\n # if there is a Quad, then product = 5 ( 4, 1, 1, 1) or product = 10 ( 4, 2, 1) or product= 15 (4,3)\n # if there is a Fullhouse, then product = 12 ( 3, 2, 2) or product = 9 (3, 3, 1) or product = 6 ( 3, 2, 1, 1)\n # if there is a Trip, then product = 3 ( 3, 1, 1, 1, 1)\n # if there is two Pair, then product = 4 ( 2, 1, 2, 1, 1) or product = 8 ( 2, 2, 2, 1)\n # if there is one Pair, then product = 2 (2, 1, 1, 1, 1, 1)\n # if there is HighCard, then product = 1 (1, 1, 1, 1, 1, 1, 1)\n card_group_element.insert(0, count)\n card_group.append(card_group_element)\n # reset counting\n count = 1\n card_group_element = []\n card_group_element.append(card)\n current_rank = rank\n # the For Loop misses operation for the last card\n # These 3 lines below to compensate that\n product *= prime_lookup[count]\n # insert the number of same rank card to the beginning of the\n card_group_element.insert(0, count)\n # after the loop, there is still one last card to add\n card_group.append(card_group_element)\n return card_group, product\n\n def _has_four(self):\n '''\n Check the existence of four cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 5 or self.product == 10 or self.product == 15:\n return True\n else:\n return False\n\n def _has_fullhouse(self):\n '''\n Check the existence of fullhouse cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 6 or self.product == 9 or self.product == 12:\n return True\n else:\n return False\n\n def _has_three(self):\n '''\n Check the existence of three cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 3:\n return True\n else:\n return False\n\n def _has_two_pairs(self):\n '''\n Check the existence of 2 pair cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 4 or self.product == 8:\n return True\n else:\n return False\n\n def _has_pair(self):\n '''\n Check the existence of 1 pair cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 2:\n return True\n else:\n return False\n\n def _has_high_card(self):\n '''\n Check the existence of high cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 1:\n return True\n else:\n return False\n\n def _get_Four_of_a_kind_cards(self):\n '''\n Get the four of a kind cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Four_of_a_Kind = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 4:\n Four_of_a_Kind = cards_by_rank.pop(i)\n break\n # The Last cards_by_rank[The Second element]\n kicker = cards_by_rank[-1][1]\n Four_of_a_Kind[0] = kicker\n\n return Four_of_a_Kind\n\n def _get_Fullhouse_cards(self):\n '''\n Get the fullhouse cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Fullhouse = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 3:\n Trips = cards_by_rank.pop(i)[1:4]\n break\n for i in reversed(range(cards_len - 1)):\n if cards_by_rank[i][0] >= 2:\n TwoPair = cards_by_rank.pop(i)[1:3]\n break\n Fullhouse = TwoPair + Trips\n return Fullhouse\n\n def _get_Three_of_a_kind_cards(self):\n '''\n Get the three of a kind cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Trip_cards = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 3:\n Trip_cards += cards_by_rank.pop(i)[1:4]\n break\n\n Trip_cards += cards_by_rank.pop(-1)[1:2]\n Trip_cards += cards_by_rank.pop(-1)[1:2]\n Trip_cards.reverse()\n return Trip_cards\n\n def _get_Two_Pair_cards(self):\n '''\n Get the two pair cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Two_Pair_cards = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 2 and len(Two_Pair_cards) < 3:\n Two_Pair_cards += cards_by_rank.pop(i)[1:3]\n\n Two_Pair_cards += cards_by_rank.pop(-1)[1:2]\n Two_Pair_cards.reverse()\n return Two_Pair_cards\n\n def _get_One_Pair_cards(self):\n '''\n Get the one pair cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n One_Pair_cards = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 2:\n One_Pair_cards += cards_by_rank.pop(i)[1:3]\n break\n\n One_Pair_cards += cards_by_rank.pop(-1)[1:2]\n One_Pair_cards += cards_by_rank.pop(-1)[1:2]\n One_Pair_cards += cards_by_rank.pop(-1)[1:2]\n One_Pair_cards.reverse()\n return One_Pair_cards\n\n def _get_High_cards(self):\n '''\n Get the high cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n High_cards = self.all_cards[2:7]\n return High_cards\n\ndef compare_ranks(position, hands, winner):\n '''\n Compare cards in same position of plays' five handcards\n Args:\n position(int): the position of a card in a sorted handcard\n hands(list): cards of those players.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n winner: array of same length than hands with 1 if the hand is among winners and 0 among losers\n Returns:\n new updated winner array\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n '''\n assert len(hands) == len(winner)\n RANKS = '23456789TJQKA'\n cards_figure_all_players = [None]*len(hands) #cards without suit\n for i, hand in enumerate(hands):\n if winner[i]:\n cards = hands[i].get_hand_five_cards()\n if len(cards[0]) != 1:# remove suit\n for p in range(5):\n cards[p] = cards[p][1:]\n cards_figure_all_players[i] = cards\n\n rival_ranks = [] # ranks of rival_figures\n for i, cards_figure in enumerate(cards_figure_all_players):\n if winner[i]:\n rank = cards_figure_all_players[i][position]\n rival_ranks.append(RANKS.index(rank))\n else:\n rival_ranks.append(-1) # player has already lost\n new_winner = list(winner)\n for i, rival_rank in enumerate(rival_ranks):\n if rival_rank != max(rival_ranks):\n new_winner[i] = 0\n return new_winner\n\ndef determine_winner(key_index, hands, all_players, potential_winner_index):\n '''\n Find out who wins in the situation of having players with same highest hand_catagory\n Args:\n key_index(int): the position of a card in a sorted handcard\n hands(list): cards of those players with same highest hand_catagory.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n all_players(list): all the players in this round, 0 for losing and 1 for winning or draw\n potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n '''\n winner = [1]*len(hands)\n i_index = 0\n while i_index < len(key_index) and sum(winner) > 1:\n index_break_tie = key_index[i_index]\n winner = compare_ranks(index_break_tie, hands, winner)\n i_index += 1\n for i in range(len(potential_winner_index)):\n if winner[i]:\n all_players[potential_winner_index[i]] = 1\n return all_players\n\ndef determine_winner_straight(hands, all_players, potential_winner_index):\n '''\n Find out who wins in the situation of having players all having a straight or straight flush\n Args:\n key_index(int): the position of a card in a sorted handcard\n hands(list): cards of those players which all have a straight or straight flush\n all_players(list): all the players in this round, 0 for losing and 1 for winning or draw\n potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n '''\n highest_ranks = []\n for hand in hands:\n highest_rank = hand.STRING_TO_RANK[hand.best_five[-1][1]] # cards are sorted in ascending order\n highest_ranks.append(highest_rank)\n max_highest_rank = max(highest_ranks)\n for i_player in range(len(highest_ranks)):\n if highest_ranks[i_player] == max_highest_rank:\n all_players[potential_winner_index[i_player]] = 1\n return all_players\n\ndef determine_winner_four_of_a_kind(hands, all_players, potential_winner_index):\n '''\n Find out who wins in the situation of having players which all have a four of a kind\n Args:\n key_index(int): the position of a card in a sorted handcard\n hands(list): cards of those players with a four of a kind\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n all_players(list): all the players in this round, 0 for losing and 1 for winning or draw\n potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n '''\n ranks = []\n for hand in hands:\n rank_1 = hand.STRING_TO_RANK[hand.best_five[-1][1]] # rank of the four of a kind\n rank_2 = hand.STRING_TO_RANK[hand.best_five[0][1]] # rank of the kicker\n ranks.append((rank_1, rank_2))\n max_rank = max(ranks)\n for i, rank in enumerate(ranks):\n if rank == max_rank:\n all_players[potential_winner_index[i]] = 1\n return all_players\n\ndef compare_hands(hands):\n '''\n Compare all palyer's all seven cards\n Args:\n hands(list): cards of those players with same highest hand_catagory.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n if hands[0] == None:\n return [0, 1]\n elif hands[1] == None:\n return [1, 0]\n '''\n hand_category = [] #such as high_card, straight_flush, etc\n all_players = [0]*len(hands) #all the players in this round, 0 for losing and 1 for winning or draw\n if None in hands:\n fold_players = [i for i, j in enumerate(hands) if j is None]\n if len(fold_players) == len(all_players) - 1:\n for _ in enumerate(hands):\n if _[0] in fold_players:\n all_players[_[0]] = 0\n else:\n all_players[_[0]] = 1\n return all_players\n else:\n for _ in enumerate(hands):\n if hands[_[0]] is not None:\n hand = Hand(hands[_[0]])\n hand.evaluateHand()\n hand_category.append(hand.category)\n elif hands[_[0]] is None:\n hand_category.append(0)\n else:\n for i in enumerate(hands):\n hand = Hand(hands[i[0]])\n hand.evaluateHand()\n hand_category.append(hand.category)\n potential_winner_index = [i for i, j in enumerate(hand_category) if j == max(hand_category)]# potential winner are those with same max card_catagory\n\n return final_compare(hands, potential_winner_index, all_players)\n\ndef final_compare(hands, potential_winner_index, all_players):\n '''\n Find out the winners from those who didn't fold\n Args:\n hands(list): cards of those players with same highest hand_catagory.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n potential_winner_index(list): index of those with same max card_catagory in all_players\n all_players(list): a list of all the player's win/lose situation, 0 for lose and 1 for win\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n if hands[0] == None:\n return [0, 1]\n elif hands[1] == None:\n return [1, 0]\n '''\n if len(potential_winner_index) == 1:\n all_players[potential_winner_index[0]] = 1\n return all_players\n elif len(potential_winner_index) > 1:\n # compare when having equal max categories\n equal_hands = []\n for _ in potential_winner_index:\n hand = Hand(hands[_])\n hand.evaluateHand()\n equal_hands.append(hand)\n hand = equal_hands[0]\n if hand.category == 8:\n return determine_winner_four_of_a_kind(equal_hands, all_players, potential_winner_index)\n if hand.category == 7:\n return determine_winner([2, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 4:\n return determine_winner([2, 1, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 3:\n return determine_winner([4, 2, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 2:\n return determine_winner([4, 2, 1, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 1 or hand.category == 6:\n return determine_winner([4, 3, 2, 1, 0], equal_hands, all_players, potential_winner_index)\n if hand.category in [5, 9]:\n return determine_winner_straight(equal_hands, all_players, potential_winner_index)\n", "num_file": 8, "num_lines": 1243, "programming_language": "Python"} {"class_name": "mahjong", "id": "./MultiFileTest/Python/mahjong.py", "original_code": "# ./mahjong/__init__.py\nfrom mahjong.dealer import MahjongDealer as Dealer\nfrom mahjong.card import MahjongCard as Card\nfrom mahjong.player import MahjongPlayer as Player\nfrom mahjong.judger import MahjongJudger as Judger\nfrom mahjong.round import MahjongRound as Round\nfrom mahjong.game import MahjongGame as Game\n\n\n\n# ./mahjong/card.py\n\nclass MahjongCard:\n\n info = {'type': ['dots', 'bamboo', 'characters', 'dragons', 'winds'],\n 'trait': ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'green', 'red', 'white', 'east', 'west', 'north', 'south']\n }\n\n def __init__(self, card_type, trait):\n ''' Initialize the class of MahjongCard\n\n Args:\n card_type (str): The type of card\n trait (str): The trait of card\n '''\n self.type = card_type\n self.trait = trait\n self.index_num = 0\n\n def get_str(self):\n ''' Get the string representation of card\n\n Return:\n (str): The string of card's color and trait\n '''\n return self.type+ '-'+ self.trait\n\n def set_index_num(self, index_num):\n\n self.index_num = index_num\n \n\n\n\n# ./mahjong/dealer.py\nfrom utils import init_deck\n\n\nclass MahjongDealer:\n ''' Initialize a mahjong dealer class\n '''\n def __init__(self, np_random):\n self.np_random = np_random\n self.deck = init_deck()\n self.shuffle()\n self.table = []\n\n def shuffle(self):\n ''' Shuffle the deck\n '''\n self.np_random.shuffle(self.deck)\n\n def deal_cards(self, player, num):\n ''' Deal some cards from deck to one player\n\n Args:\n player (object): The object of DoudizhuPlayer\n num (int): The number of cards to be dealed\n '''\n for _ in range(num):\n player.hand.append(self.deck.pop())\n\n\n## For test\n#if __name__ == '__main__':\n# dealer = MahjongDealer()\n# for card in dealer.deck:\n# print(card.get_str())\n# print(len(dealer.deck))\n\n\n# ./mahjong/game.py\nimport numpy as np\nfrom copy import deepcopy\n\nfrom mahjong import Dealer\nfrom mahjong import Player\nfrom mahjong import Round\nfrom mahjong import Judger\n\nclass MahjongGame:\n\n def __init__(self, allow_step_back=False):\n '''Initialize the class MajongGame\n '''\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n self.num_players = 4\n\n def init_game(self):\n ''' Initialilze the game of Mahjong\n\n This version supports two-player Mahjong\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state of the game\n (int): Current player's id\n '''\n # Initialize a dealer that can deal cards\n self.dealer = Dealer(self.np_random)\n\n # Initialize four players to play the game\n self.players = [Player(i, self.np_random) for i in range(self.num_players)]\n\n self.judger = Judger(self.np_random)\n self.round = Round(self.judger, self.dealer, self.num_players, self.np_random)\n\n # Deal 13 cards to each player to prepare for the game\n for player in self.players:\n self.dealer.deal_cards(player, 13)\n\n # Save the hisory for stepping back to the last state.\n self.history = []\n\n self.dealer.deal_cards(self.players[self.round.current_player], 1)\n state = self.get_state(self.round.current_player)\n self.cur_state = state\n return state, self.round.current_player\n\n def step(self, action):\n ''' Get the next state\n\n Args:\n action (str): a specific action. (call, raise, fold, or check)\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next plater's id\n '''\n # First snapshot the current state\n if self.allow_step_back:\n hist_dealer = deepcopy(self.dealer)\n hist_round = deepcopy(self.round)\n hist_players = deepcopy(self.players)\n self.history.append((hist_dealer, hist_players, hist_round))\n self.round.proceed_round(self.players, action)\n state = self.get_state(self.round.current_player)\n self.cur_state = state\n return state, self.round.current_player\n\n def step_back(self):\n ''' Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n '''\n if not self.history:\n return False\n self.dealer, self.players, self.round = self.history.pop()\n return True\n\n def get_state(self, player_id):\n ''' Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n (dict): The state of the player\n '''\n state = self.round.get_state(self.players, player_id)\n return state\n\n @staticmethod\n def get_legal_actions(state):\n ''' Return the legal actions for current player\n\n Returns:\n (list): A list of legal actions\n '''\n if state['valid_act'] == ['play']:\n state['valid_act'] = state['action_cards']\n return state['action_cards']\n else:\n return state['valid_act']\n\n @staticmethod\n def get_num_actions():\n ''' Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 4 actions (call, raise, check and fold)\n '''\n return 38\n\n def get_num_players(self):\n ''' return the number of players in Mahjong\n\n returns:\n (int): the number of players in the game\n '''\n return self.num_players\n\n def get_player_id(self):\n ''' return the id of current player in Mahjong\n\n returns:\n (int): the number of players in the game\n '''\n return self.round.current_player\n\n def is_over(self):\n ''' Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n '''\n win, player, _ = self.judger.judge_game(self)\n #pile =[sorted([c.get_str() for c in s ]) for s in self.players[player].pile if self.players[player].pile != None]\n #cards = sorted([c.get_str() for c in self.players[player].hand])\n #count = len(cards) + sum([len(p) for p in pile])\n self.winner = player\n #print(win, player, players_val)\n #print(win, self.round.current_player, player, cards, pile, count)\n return win\n\n\n# ./mahjong/judger.py\n# -*- coding: utf-8 -*-\n''' Implement Mahjong Judger class\n'''\nfrom collections import defaultdict\nimport numpy as np\n\nclass MahjongJudger:\n ''' Determine what cards a player can play\n '''\n\n def __init__(self, np_random):\n ''' Initilize the Judger class for Mahjong\n '''\n self.np_random = np_random\n\n @staticmethod\n def judge_pong_gong(dealer, players, last_player):\n ''' Judge which player has pong/gong\n Args:\n dealer (object): The dealer object.\n players (list): List of all players\n last_player (int): The player id of last player\n\n '''\n last_card = dealer.table[-1]\n last_card_str = last_card.get_str()\n #last_card_value = last_card_str.split(\"-\")[-1]\n #last_card_type = last_card_str.split(\"-\")[0]\n for player in players:\n hand = [card.get_str() for card in player.hand]\n hand_dict = defaultdict(list)\n for card in hand:\n hand_dict[card.split(\"-\")[0]].append(card.split(\"-\")[1])\n #pile = player.pile\n # check gong\n if hand.count(last_card_str) == 3 and last_player != player.player_id:\n return 'gong', player, [last_card]*4\n # check pong\n if hand.count(last_card_str) == 2 and last_player != player.player_id:\n return 'pong', player, [last_card]*3\n return False, None, None\n\n def judge_chow(self, dealer, players, last_player):\n ''' Judge which player has chow\n Args:\n dealer (object): The dealer object.\n players (list): List of all players\n last_player (int): The player id of last player\n '''\n\n last_card = dealer.table[-1]\n last_card_str = last_card.get_str()\n last_card_type = last_card_str.split(\"-\")[0]\n last_card_index = last_card.index_num\n for player in players:\n if last_card_type != \"dragons\" and last_card_type != \"winds\" and last_player == player.get_player_id() - 1:\n # Create 9 dimensional vector where each dimension represent a specific card with the type same as last_card_type\n # Numbers in each dimension represent how many of that card the player has it in hand\n # If the last_card_type is 'characters' for example, and the player has cards: characters_3, characters_6, characters_3,\n # The hand_list vector looks like: [0,0,2,0,0,1,0,0,0]\n hand_list = np.zeros(9)\n\n for card in player.hand:\n if card.get_str().split(\"-\")[0] == last_card_type:\n hand_list[card.index_num] = hand_list[card.index_num]+1\n\n #pile = player.pile\n #check chow\n test_cases = []\n if last_card_index == 0:\n if hand_list[last_card_index+1] > 0 and hand_list[last_card_index+2] > 0:\n test_cases.append([last_card_index+1, last_card_index+2])\n elif last_card_index < 9:\n if hand_list[last_card_index-2] > 0 and hand_list[last_card_index-1] > 0:\n test_cases.append([last_card_index-2, last_card_index-1])\n else:\n if hand_list[last_card_index-1] > 0 and hand_list[last_card_index+1] > 0:\n test_cases.append([last_card_index-1, last_card_index+1])\n\n if not test_cases:\n continue \n\n for l in test_cases:\n cards = []\n for i in l:\n for card in player.hand:\n if card.index_num == i and card.get_str().split(\"-\")[0] == last_card_type:\n cards.append(card)\n break\n cards.append(last_card)\n return 'chow', player, cards\n return False, None, None\n\n def judge_game(self, game):\n ''' Judge which player has win the game\n Args:\n dealer (object): The dealer object.\n players (list): List of all players\n last_player (int): The player id of last player\n '''\n players_val = []\n win_player = -1\n for player in game.players:\n win, val = self.judge_hu(player)\n players_val.append(val)\n if win:\n win_player = player.player_id\n if win_player != -1 or len(game.dealer.deck) == 0:\n return True, win_player, players_val\n else:\n #player_id = players_val.index(max(players_val))\n return False, win_player, players_val\n\n def judge_hu(self, player):\n ''' Judge whether the player has win the game\n Args:\n player (object): Target player\n\n Return:\n Result (bool): Win or not\n Maximum_score (int): Set count score of the player\n '''\n set_count = 0\n hand = [card.get_str() for card in player.hand]\n count_dict = {card: hand.count(card) for card in hand}\n set_count = len(player.pile)\n if set_count >= 4:\n return True, set_count\n used = []\n maximum = 0\n for each in count_dict:\n if each in used:\n continue\n tmp_set_count = 0\n tmp_hand = hand.copy()\n if count_dict[each] == 2:\n for _ in range(count_dict[each]):\n tmp_hand.pop(tmp_hand.index(each))\n tmp_set_count, _set = self.cal_set(tmp_hand)\n used.extend(_set)\n if tmp_set_count + set_count > maximum:\n maximum = tmp_set_count + set_count\n if tmp_set_count + set_count >= 4:\n #print(player.get_player_id(), sorted([card.get_str() for card in player.hand]))\n #print([[c.get_str() for c in s] for s in player.pile])\n #print(len(player.hand), sum([len(s) for s in player.pile]))\n #exit()\n return True, maximum\n return False, maximum\n\n @staticmethod\n def check_consecutive(_list):\n ''' Check if list is consecutive\n Args:\n _list (list): The target list\n\n Return:\n Result (bool): consecutive or not\n '''\n l = list(map(int, _list))\n if sorted(l) == list(range(min(l), max(l)+1)):\n return True\n return False\n\n def cal_set(self, cards):\n ''' Calculate the set for given cards\n Args:\n Cards (list): List of cards.\n\n Return:\n Set_count (int):\n Sets (list): List of cards that has been pop from user's hand\n '''\n tmp_cards = cards.copy()\n sets = []\n set_count = 0\n _dict = {card: tmp_cards.count(card) for card in tmp_cards}\n # check pong/gang\n for each in _dict:\n if _dict[each] == 3 or _dict[each] == 4:\n set_count += 1\n for _ in range(_dict[each]):\n tmp_cards.pop(tmp_cards.index(each))\n\n # get all of the traits of each type in hand (except dragons and winds)\n _dict_by_type = defaultdict(list)\n for card in tmp_cards:\n _type = card.split(\"-\")[0]\n _trait = card.split(\"-\")[1]\n if _type == 'dragons' or _type == 'winds':\n continue\n else:\n _dict_by_type[_type].append(_trait)\n for _type in _dict_by_type.keys():\n values = sorted(_dict_by_type[_type])\n if len(values) > 2:\n for index, _ in enumerate(values):\n if index == 0:\n test_case = [values[index], values[index+1], values[index+2]]\n elif index == len(values)-1:\n test_case = [values[index-2], values[index-1], values[index]]\n else:\n test_case = [values[index-1], values[index], values[index+1]]\n if self.check_consecutive(test_case):\n set_count += 1\n for each in test_case:\n values.pop(values.index(each))\n c = _type+\"-\"+str(each)\n sets.append(c)\n if c in tmp_cards:\n tmp_cards.pop(tmp_cards.index(c))\n return set_count, sets\n\n#if __name__ == \"__main__\":\n# judger = MahjongJudger()\n# player = Player(0)\n# card_info = Card.info\n# #print(card_info)\n# player.pile.append([Card(card_info['type'][0], card_info['trait'][0])]*3)\n# #player.hand.extend([Card(card_info['type'][0], card_info['trait'][0])]*2)\n# player.hand.extend([Card(card_info['type'][1], card_info['trait'][1])]*4)\n# player.hand.extend([Card(card_info['type'][2], card_info['trait'][1])]*3)\n# player.hand.extend([Card(card_info['type'][0], card_info['trait'][2])]*3)\n# player.hand.extend([Card(card_info['type'][3], card_info['trait'][9])]*2)\n# #player.hand.extend([Card(card_info['type'][2], card_info['trait'][4])]*1)\n# print([card.get_str() for card in player.hand])\n# print(judger.judge_hu(player))\n\n\n# ./mahjong/player.py\n\nclass MahjongPlayer:\n\n def __init__(self, player_id, np_random):\n ''' Initilize a player.\n\n Args:\n player_id (int): The id of the player\n '''\n self.np_random = np_random\n self.player_id = player_id\n self.hand = []\n self.pile = []\n\n def get_player_id(self):\n ''' Return the id of the player\n '''\n\n return self.player_id\n\n def print_hand(self):\n ''' Print the cards in hand in string.\n '''\n print([c.get_str() for c in self.hand])\n\n def print_pile(self):\n ''' Print the cards in pile of the player in string.\n '''\n print([[c.get_str() for c in s]for s in self.pile])\n\n def play_card(self, dealer, card):\n ''' Play one card\n Args:\n dealer (object): Dealer\n Card (object): The card to be play.\n '''\n card = self.hand.pop(self.hand.index(card))\n dealer.table.append(card)\n\n def chow(self, dealer, cards):\n ''' Perform Chow\n Args:\n dealer (object): Dealer\n Cards (object): The cards to be Chow.\n '''\n last_card = dealer.table.pop(-1)\n for card in cards:\n if card in self.hand and card != last_card:\n self.hand.pop(self.hand.index(card))\n self.pile.append(cards)\n\n def gong(self, dealer, cards):\n ''' Perform Gong\n Args:\n dealer (object): Dealer\n Cards (object): The cards to be Gong.\n '''\n for card in cards:\n if card in self.hand:\n self.hand.pop(self.hand.index(card))\n self.pile.append(cards)\n\n def pong(self, dealer, cards):\n ''' Perform Pong\n Args:\n dealer (object): Dealer\n Cards (object): The cards to be Pong.\n '''\n for card in cards:\n if card in self.hand:\n self.hand.pop(self.hand.index(card))\n self.pile.append(cards)\n\n\n# ./mahjong/round.py\n\nclass MahjongRound:\n\n def __init__(self, judger, dealer, num_players, np_random):\n ''' Initialize the round class\n\n Args:\n judger (object): the object of MahjongJudger\n dealer (object): the object of MahjongDealer\n num_players (int): the number of players in game\n '''\n self.np_random = np_random\n self.judger = judger\n self.dealer = dealer\n self.target = None\n self.current_player = 0\n self.last_player = None\n self.num_players = num_players\n self.direction = 1\n self.played_cards = []\n self.is_over = False\n self.player_before_act = 0\n self.prev_status = None\n self.valid_act = False\n self.last_cards = []\n\n def proceed_round(self, players, action):\n ''' Call other Classes's functions to keep one round running\n\n Args:\n player (object): object of UnoPlayer\n action (str): string of legal action\n '''\n #hand_len = [len(p.hand) for p in players]\n #pile_len = [sum([len([c for c in p]) for p in pp.pile]) for pp in players]\n #total_len = [i + j for i, j in zip(hand_len, pile_len)]\n if action == 'stand':\n (valid_act, player, cards) = self.judger.judge_chow(self.dealer, players, self.last_player)\n if valid_act:\n self.valid_act = valid_act\n self.last_cards = cards\n self.last_player = self.current_player\n self.current_player = player.player_id\n else:\n self.last_player = self.current_player\n self.current_player = (self.player_before_act + 1) % 4\n self.dealer.deal_cards(players[self.current_player], 1)\n self.valid_act = False\n\n elif action == 'gong':\n players[self.current_player].gong(self.dealer, self.last_cards)\n self.last_player = self.current_player\n self.valid_act = False\n\n elif action == 'pong':\n players[self.current_player].pong(self.dealer, self.last_cards)\n self.last_player = self.current_player\n self.valid_act = False\n\n elif action == 'chow':\n players[self.current_player].chow(self.dealer, self.last_cards)\n self.last_player = self.current_player\n self.valid_act = False\n\n else: # Play game: Proceed to next player\n players[self.current_player].play_card(self.dealer, action)\n self.player_before_act = self.current_player\n self.last_player = self.current_player\n (valid_act, player, cards) = self.judger.judge_pong_gong(self.dealer, players, self.last_player)\n if valid_act:\n self.valid_act = valid_act\n self.last_cards = cards\n self.last_player = self.current_player\n self.current_player = player.player_id\n else:\n self.last_player = self.current_player\n self.current_player = (self.current_player + 1) % 4\n self.dealer.deal_cards(players[self.current_player], 1)\n\n #hand_len = [len(p.hand) for p in players]\n #pile_len = [sum([len([c for c in p]) for p in pp.pile]) for pp in players]\n #total_len = [i + j for i, j in zip(hand_len, pile_len)]\n\n def get_state(self, players, player_id):\n ''' Get player's state\n\n Args:\n players (list): The list of MahjongPlayer\n player_id (int): The id of the player\n Return:\n state (dict): The information of the state\n '''\n state = {}\n #(valid_act, player, cards) = self.judger.judge_pong_gong(self.dealer, players, self.last_player)\n if self.valid_act: # PONG/GONG/CHOW\n state['valid_act'] = [self.valid_act, 'stand']\n state['table'] = self.dealer.table\n state['player'] = self.current_player\n state['current_hand'] = players[self.current_player].hand\n state['players_pile'] = {p.player_id: p.pile for p in players}\n state['action_cards'] = self.last_cards # For doing action (pong, chow, gong)\n else: # Regular Play\n state['valid_act'] = ['play']\n state['table'] = self.dealer.table\n state['player'] = self.current_player\n state['current_hand'] = players[player_id].hand\n state['players_pile'] = {p.player_id: p.pile for p in players}\n state['action_cards'] = players[player_id].hand # For doing action (pong, chow, gong)\n return state\n\n\n\n# ./mahjong/utils.py\nimport numpy as np\nfrom card import MahjongCard as Card\n\n\ncard_encoding_dict = {}\nnum = 0\nfor _type in ['bamboo', 'characters', 'dots']:\n for _trait in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:\n card = _type+\"-\"+_trait\n card_encoding_dict[card] = num\n num += 1\nfor _trait in ['green', 'red', 'white']:\n card = 'dragons-'+_trait\n card_encoding_dict[card] = num\n num += 1\n\nfor _trait in ['east', 'west', 'north', 'south']:\n card = 'winds-'+_trait\n card_encoding_dict[card] = num\n num += 1\ncard_encoding_dict['pong'] = num\ncard_encoding_dict['chow'] = num + 1\ncard_encoding_dict['gong'] = num + 2\ncard_encoding_dict['stand'] = num + 3\n\ncard_decoding_dict = {card_encoding_dict[key]: key for key in card_encoding_dict.keys()}\n\ndef init_deck():\n deck = []\n info = Card.info\n for _type in info['type']:\n index_num = 0\n if _type != 'dragons' and _type != 'winds':\n for _trait in info['trait'][:9]:\n card = Card(_type, _trait)\n card.set_index_num(index_num)\n index_num = index_num + 1\n deck.append(card)\n elif _type == 'dragons':\n for _trait in info['trait'][9:12]:\n card = Card(_type, _trait)\n card.set_index_num(index_num)\n index_num = index_num + 1\n deck.append(card)\n else:\n for _trait in info['trait'][12:]:\n card = Card(_type, _trait)\n card.set_index_num(index_num)\n index_num = index_num + 1\n deck.append(card)\n deck = deck * 4\n return deck\n\n\ndef pile2list(pile):\n cards_list = []\n for each in pile:\n cards_list.extend(each)\n return cards_list\n\ndef cards2list(cards):\n cards_list = []\n for each in cards:\n cards_list.append(each.get_str())\n return cards_list\n\n\ndef encode_cards(cards):\n plane = np.zeros((34,4), dtype=int)\n cards = cards2list(cards)\n for card in list(set(cards)):\n index = card_encoding_dict[card]\n num = cards.count(card)\n plane[index][:num] = 1\n return plane\n", "num_file": 8, "num_lines": 703, "programming_language": "Python"} {"class_name": "nolimitholdem", "id": "./MultiFileTest/Python/nolimitholdem.py", "original_code": "# ./nolimitholdem/__init__.py\nfrom nolimitholdem.base import Card as Card\n\nfrom nolimitholdem.dealer import NolimitholdemDealer as Dealer\nfrom nolimitholdem.judger import NolimitholdemJudger as Judger\nfrom nolimitholdem.player import NolimitholdemPlayer as Player\nfrom nolimitholdem.player import PlayerStatus\nfrom nolimitholdem.round import Action\nfrom nolimitholdem.round import NolimitholdemRound as Round\nfrom nolimitholdem.game import NolimitholdemGame as Game\n\n\n\n# ./nolimitholdem/base.py\n''' Game-related base classes\n'''\nclass Card:\n '''\n Card stores the suit and rank of a single card\n\n Note:\n The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]\n Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]\n '''\n suit = None\n rank = None\n valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']\n valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n\n def __init__(self, suit, rank):\n ''' Initialize the suit and rank of a card\n\n Args:\n suit: string, suit of the card, should be one of valid_suit\n rank: string, rank of the card, should be one of valid_rank\n '''\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if isinstance(other, Card):\n return self.rank == other.rank and self.suit == other.suit\n else:\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n def __hash__(self):\n suit_index = Card.valid_suit.index(self.suit)\n rank_index = Card.valid_rank.index(self.rank)\n return rank_index + 100 * suit_index\n\n def __str__(self):\n ''' Get string representation of a card.\n\n Returns:\n string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...\n '''\n return self.rank + self.suit\n\n def get_index(self):\n ''' Get index of a card.\n\n Returns:\n string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...\n '''\n return self.suit+self.rank\n\n\n# ./nolimitholdem/dealer.py\nfrom nolimitholdem.utils import init_standard_deck\n\nclass NolimitholdemDealer:\n def __init__(self, np_random):\n self.np_random = np_random\n self.deck = init_standard_deck()\n self.shuffle()\n self.pot = 0\n\n def shuffle(self):\n self.np_random.shuffle(self.deck)\n\n def deal_card(self):\n \"\"\"\n Deal one card from the deck\n\n Returns:\n (Card): The drawn card from the deck\n \"\"\"\n return self.deck.pop()\n\n\n# ./nolimitholdem/game.py\nfrom enum import Enum\n\nimport numpy as np\nfrom copy import deepcopy\nfrom nolimitholdem import PlayerStatus\n\nfrom nolimitholdem import Dealer\nfrom nolimitholdem import Player\nfrom nolimitholdem import Judger\nfrom nolimitholdem import Round, Action\n\n\nfrom copy import deepcopy, copy\n# import numpy as np\n\n# from limitholdem import Dealer\n# from limitholdem import Player, PlayerStatus\n# from limitholdem import Judger\n# from limitholdem import Round\n\n\nclass LimitHoldemGame:\n def __init__(self, allow_step_back=False, num_players=2):\n \"\"\"Initialize the class limit holdem game\"\"\"\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n\n # Some configurations of the game\n # These arguments can be specified for creating new games\n\n # Small blind and big blind\n self.small_blind = 1\n self.big_blind = 2 * self.small_blind\n\n # Raise amount and allowed times\n self.raise_amount = self.big_blind\n self.allowed_raise_num = 4\n\n self.num_players = num_players\n\n # Save betting history\n self.history_raise_nums = [0 for _ in range(4)]\n\n self.dealer = None\n self.players = None\n self.judger = None\n self.public_cards = None\n self.game_pointer = None\n self.round = None\n self.round_counter = None\n self.history = None\n self.history_raises_nums = None\n\n def configure(self, game_config):\n \"\"\"Specify some game specific parameters, such as number of players\"\"\"\n self.num_players = game_config['game_num_players']\n\n def init_game(self):\n \"\"\"\n Initialize the game of limit texas holdem\n\n This version supports two-player limit texas holdem\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state of the game\n (int): Current player's id\n \"\"\"\n # Initialize a dealer that can deal cards\n self.dealer = Dealer(self.np_random)\n\n # Initialize two players to play the game\n self.players = [Player(i, self.np_random) for i in range(self.num_players)]\n\n # Initialize a judger class which will decide who wins in the end\n self.judger = Judger(self.np_random)\n\n # Deal cards to each player to prepare for the first round\n for i in range(2 * self.num_players):\n self.players[i % self.num_players].hand.append(self.dealer.deal_card())\n\n # Initialize public cards\n self.public_cards = []\n\n # Randomly choose a small blind and a big blind\n s = self.np_random.randint(0, self.num_players)\n b = (s + 1) % self.num_players\n self.players[b].in_chips = self.big_blind\n self.players[s].in_chips = self.small_blind\n\n # The player next to the big blind plays the first\n self.game_pointer = (b + 1) % self.num_players\n\n # Initialize a bidding round, in the first round, the big blind and the small blind needs to\n # be passed to the round for processing.\n self.round = Round(raise_amount=self.raise_amount,\n allowed_raise_num=self.allowed_raise_num,\n num_players=self.num_players,\n np_random=self.np_random)\n\n self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])\n\n # Count the round. There are 4 rounds in each game.\n self.round_counter = 0\n\n # Save the history for stepping back to the last state.\n self.history = []\n\n state = self.get_state(self.game_pointer)\n\n # Save betting history\n self.history_raise_nums = [0 for _ in range(4)]\n\n return state, self.game_pointer\n\n def step(self, action):\n \"\"\"\n Get the next state\n\n Args:\n action (str): a specific action. (call, raise, fold, or check)\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next player id\n \"\"\"\n if self.allow_step_back:\n # First snapshot the current state\n r = deepcopy(self.round)\n b = self.game_pointer\n r_c = self.round_counter\n d = deepcopy(self.dealer)\n p = deepcopy(self.public_cards)\n ps = deepcopy(self.players)\n rn = copy(self.history_raise_nums)\n self.history.append((r, b, r_c, d, p, ps, rn))\n\n # Then we proceed to the next round\n self.game_pointer = self.round.proceed_round(self.players, action)\n\n # Save the current raise num to history\n self.history_raise_nums[self.round_counter] = self.round.have_raised\n\n # If a round is over, we deal more public cards\n if self.round.is_over():\n # For the first round, we deal 3 cards\n if self.round_counter == 0:\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n\n # For the following rounds, we deal only 1 card\n elif self.round_counter <= 2:\n self.public_cards.append(self.dealer.deal_card())\n\n # Double the raise amount for the last two rounds\n if self.round_counter == 1:\n self.round.raise_amount = 2 * self.raise_amount\n\n self.round_counter += 1\n self.round.start_new_round(self.game_pointer)\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def step_back(self):\n \"\"\"\n Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n \"\"\"\n if len(self.history) > 0:\n self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \\\n self.players, self.history_raises_nums = self.history.pop()\n return True\n return False\n\n def get_num_players(self):\n \"\"\"\n Return the number of players in limit texas holdem\n\n Returns:\n (int): The number of players in the game\n \"\"\"\n return self.num_players\n\n @staticmethod\n def get_num_actions():\n \"\"\"\n Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 4 actions (call, raise, check and fold)\n \"\"\"\n return 4\n\n def get_player_id(self):\n \"\"\"\n Return the current player's id\n\n Returns:\n (int): current player's id\n \"\"\"\n return self.game_pointer\n\n def get_state(self, player):\n \"\"\"\n Return player's state\n\n Args:\n player (int): player id\n\n Returns:\n (dict): The state of the player\n \"\"\"\n chips = [self.players[i].in_chips for i in range(self.num_players)]\n legal_actions = self.get_legal_actions()\n state = self.players[player].get_state(self.public_cards, chips, legal_actions)\n state['raise_nums'] = self.history_raise_nums\n\n return state\n\n def is_over(self):\n \"\"\"\n Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n \"\"\"\n alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players]\n # If only one player is alive, the game is over.\n if sum(alive_players) == 1:\n return True\n\n # If all rounds are finished\n if self.round_counter >= 4:\n return True\n return False\n\n def get_payoffs(self):\n \"\"\"\n Return the payoffs of the game\n\n Returns:\n (list): Each entry corresponds to the payoff of one player\n \"\"\"\n hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players]\n chips_payoffs = self.judger.judge_game(self.players, hands)\n payoffs = np.array(chips_payoffs) / self.big_blind\n return payoffs\n\n def get_legal_actions(self):\n \"\"\"\n Return the legal actions for current player\n\n Returns:\n (list): A list of legal actions\n \"\"\"\n return self.round.get_legal_actions()\n\n\n\nclass Stage(Enum):\n PREFLOP = 0\n FLOP = 1\n TURN = 2\n RIVER = 3\n END_HIDDEN = 4\n SHOWDOWN = 5\n\n\nclass NolimitholdemGame(LimitHoldemGame):\n def __init__(self, allow_step_back=False, num_players=2):\n \"\"\"Initialize the class no limit holdem Game\"\"\"\n super().__init__(allow_step_back, num_players)\n\n self.np_random = np.random.RandomState()\n\n # small blind and big blind\n self.small_blind = 1\n self.big_blind = 2 * self.small_blind\n\n # config players\n self.init_chips = [100] * num_players\n\n # If None, the dealer will be randomly chosen\n self.dealer_id = None\n\n def configure(self, game_config):\n \"\"\"\n Specify some game specific parameters, such as number of players, initial chips, and dealer id.\n If dealer_id is None, he will be randomly chosen\n \"\"\"\n self.num_players = game_config['game_num_players']\n # must have num_players length\n self.init_chips = [game_config['chips_for_each']] * game_config[\"game_num_players\"]\n self.dealer_id = game_config['dealer_id']\n\n def init_game(self):\n \"\"\"\n Initialize the game of not limit holdem\n\n This version supports two-player no limit texas holdem\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state of the game\n (int): Current player's id\n \"\"\"\n if self.dealer_id is None:\n self.dealer_id = self.np_random.randint(0, self.num_players)\n\n # Initialize a dealer that can deal cards\n self.dealer = Dealer(self.np_random)\n\n # Initialize players to play the game\n self.players = [Player(i, self.init_chips[i], self.np_random) for i in range(self.num_players)]\n\n # Initialize a judger class which will decide who wins in the end\n self.judger = Judger(self.np_random)\n\n # Deal cards to each player to prepare for the first round\n for i in range(2 * self.num_players):\n self.players[i % self.num_players].hand.append(self.dealer.deal_card())\n\n # Initialize public cards\n self.public_cards = []\n self.stage = Stage.PREFLOP\n\n # Big blind and small blind\n s = (self.dealer_id + 1) % self.num_players\n b = (self.dealer_id + 2) % self.num_players\n self.players[b].bet(chips=self.big_blind)\n self.players[s].bet(chips=self.small_blind)\n\n # The player next to the big blind plays the first\n self.game_pointer = (b + 1) % self.num_players\n\n # Initialize a bidding round, in the first round, the big blind and the small blind needs to\n # be passed to the round for processing.\n self.round = Round(self.num_players, self.big_blind, dealer=self.dealer, np_random=self.np_random)\n\n self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])\n\n # Count the round. There are 4 rounds in each game.\n self.round_counter = 0\n\n # Save the history for stepping back to the last state.\n self.history = []\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def get_legal_actions(self):\n \"\"\"\n Return the legal actions for current player\n\n Returns:\n (list): A list of legal actions\n \"\"\"\n return self.round.get_nolimit_legal_actions(players=self.players)\n\n def step(self, action):\n \"\"\"\n Get the next state\n\n Args:\n action (str): a specific action. (call, raise, fold, or check)\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next player id\n \"\"\"\n\n if action not in self.get_legal_actions():\n print(action, self.get_legal_actions())\n print(self.get_state(self.game_pointer))\n raise Exception('Action not allowed')\n\n if self.allow_step_back:\n # First snapshot the current state\n r = deepcopy(self.round)\n b = self.game_pointer\n r_c = self.round_counter\n d = deepcopy(self.dealer)\n p = deepcopy(self.public_cards)\n ps = deepcopy(self.players)\n self.history.append((r, b, r_c, d, p, ps))\n\n # Then we proceed to the next round\n self.game_pointer = self.round.proceed_round(self.players, action)\n\n players_in_bypass = [1 if player.status in (PlayerStatus.FOLDED, PlayerStatus.ALLIN) else 0 for player in self.players]\n if self.num_players - sum(players_in_bypass) == 1:\n last_player = players_in_bypass.index(0)\n if self.round.raised[last_player] >= max(self.round.raised):\n # If the last player has put enough chips, he is also bypassed\n players_in_bypass[last_player] = 1\n\n # If a round is over, we deal more public cards\n if self.round.is_over():\n # Game pointer goes to the first player not in bypass after the dealer, if there is one\n self.game_pointer = (self.dealer_id + 1) % self.num_players\n if sum(players_in_bypass) < self.num_players:\n while players_in_bypass[self.game_pointer]:\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n # For the first round, we deal 3 cards\n if self.round_counter == 0:\n self.stage = Stage.FLOP\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n self.public_cards.append(self.dealer.deal_card())\n if len(self.players) == np.sum(players_in_bypass):\n self.round_counter += 1\n # For the following rounds, we deal only 1 card\n if self.round_counter == 1:\n self.stage = Stage.TURN\n self.public_cards.append(self.dealer.deal_card())\n if len(self.players) == np.sum(players_in_bypass):\n self.round_counter += 1\n if self.round_counter == 2:\n self.stage = Stage.RIVER\n self.public_cards.append(self.dealer.deal_card())\n if len(self.players) == np.sum(players_in_bypass):\n self.round_counter += 1\n\n self.round_counter += 1\n self.round.start_new_round(self.game_pointer)\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def get_state(self, player_id):\n \"\"\"\n Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n (dict): The state of the player\n \"\"\"\n self.dealer.pot = np.sum([player.in_chips for player in self.players])\n\n chips = [self.players[i].in_chips for i in range(self.num_players)]\n legal_actions = self.get_legal_actions()\n state = self.players[player_id].get_state(self.public_cards, chips, legal_actions)\n state['stakes'] = [self.players[i].remained_chips for i in range(self.num_players)]\n state['current_player'] = self.game_pointer\n state['pot'] = self.dealer.pot\n state['stage'] = self.stage\n return state\n\n def step_back(self):\n \"\"\"\n Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n \"\"\"\n if len(self.history) > 0:\n self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, self.players = self.history.pop()\n self.stage = Stage(self.round_counter)\n return True\n return False\n\n def get_num_players(self):\n \"\"\"\n Return the number of players in no limit texas holdem\n\n Returns:\n (int): The number of players in the game\n \"\"\"\n return self.num_players\n\n def get_payoffs(self):\n \"\"\"\n Return the payoffs of the game\n\n Returns:\n (list): Each entry corresponds to the payoff of one player\n \"\"\"\n hands = [p.hand + self.public_cards if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else None for p in self.players]\n chips_payoffs = self.judger.judge_game(self.players, hands)\n return chips_payoffs\n\n @staticmethod\n def get_num_actions():\n \"\"\"\n Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 6 actions (call, raise_half_pot, raise_pot, all_in, check and fold)\n \"\"\"\n return len(Action)\n\n\n# ./nolimitholdem/judger.py\nfrom nolimitholdem.utils import compare_hands\nimport numpy as np\n\n\nclass NolimitholdemJudger:\n \"\"\"The Judger class for limit texas holdem\"\"\"\n\n def __init__(self, np_random):\n self.np_random = np_random\n\n def judge_game(self, players, hands):\n \"\"\"\n Judge the winner of the game.\n\n Args:\n players (list): The list of players who play the game\n hands (list): The list of hands that from the players\n\n Returns:\n (list): Each entry of the list corresponds to one entry of the\n \"\"\"\n # Convert the hands into card indexes\n hands = [[card.get_index() for card in hand] if hand is not None else None for hand in hands]\n \n in_chips = [p.in_chips for p in players]\n remaining = sum(in_chips)\n payoffs = [0] * len(hands)\n while remaining > 0:\n winners = compare_hands(hands)\n each_win = self.split_pots_among_players(in_chips, winners)\n \n for i in range(len(players)):\n if winners[i]:\n remaining -= each_win[i]\n payoffs[i] += each_win[i] - in_chips[i]\n hands[i] = None\n in_chips[i] = 0\n elif in_chips[i] > 0:\n payoffs[i] += each_win[i] - in_chips[i]\n in_chips[i] = each_win[i]\n \n assert sum(payoffs) == 0\n return payoffs\n\n def split_pot_among_players(self, in_chips, winners):\n \"\"\"\n Splits the next (side) pot among players.\n Function is called in loop by distribute_pots_among_players until all chips are allocated.\n\n Args:\n in_chips (list): List with number of chips bet not yet distributed for each player\n winners (list): List with 1 if the player is among winners else 0\n\n Returns:\n (list): Of how much chips each player get after this pot has been split and list of chips left to distribute\n \"\"\"\n nb_winners_in_pot = sum((winners[i] and in_chips[i] > 0) for i in range(len(in_chips)))\n nb_players_in_pot = sum(in_chips[i] > 0 for i in range(len(in_chips)))\n if nb_winners_in_pot == 0 or nb_winners_in_pot == nb_players_in_pot:\n # no winner or all winners for this pot\n allocated = list(in_chips) # we give back their chips to each players in this pot\n in_chips_after = len(in_chips) * [0] # no more chips to distribute\n else:\n amount_in_pot_by_player = min(v for v in in_chips if v > 0)\n how_much_one_win, remaining = divmod(amount_in_pot_by_player * nb_players_in_pot, nb_winners_in_pot)\n '''\n In the event of a split pot that cannot be divided equally for every winner, the winner who is sitting \n closest to the left of the dealer receives the remaining differential in chips cf \n https://www.betclic.fr/poker/house-rules--play-safely--betclic-poker-cpok_rules to simplify and as this \n case is very rare, we will give the remaining differential in chips to a random winner\n '''\n allocated = len(in_chips) * [0]\n in_chips_after = list(in_chips)\n for i in range(len(in_chips)): # iterate on all players\n if in_chips[i] == 0: # player not in pot\n continue\n if winners[i]:\n allocated[i] += how_much_one_win\n in_chips_after[i] -= amount_in_pot_by_player\n if remaining > 0:\n random_winning_player = self.np_random.choice(\n [i for i in range(len(winners)) if winners[i] and in_chips[i] > 0])\n allocated[random_winning_player] += remaining\n assert sum(in_chips[i] - in_chips_after[i] for i in range(len(in_chips))) == sum(allocated)\n return allocated, in_chips_after\n\n def split_pots_among_players(self, in_chips_initial, winners):\n \"\"\"\n Splits main pot and side pots among players (to handle special case of all-in players).\n\n Args:\n in_chips_initial (list): List with number of chips bet for each player\n winners (list): List with 1 if the player is among winners else 0\n\n Returns:\n (list): List of how much chips each player get back after all pots have been split\n \"\"\"\n in_chips = list(in_chips_initial)\n assert len(in_chips) == len(winners)\n assert all(v == 0 or v == 1 for v in winners)\n assert sum(winners) >= 1 # there must be at least one winner\n allocated = np.zeros(len(in_chips), dtype=int)\n while any(v > 0 for v in in_chips): # while there are still chips to allocate\n allocated_current_pot, in_chips = self.split_pot_among_players(in_chips, winners)\n allocated += allocated_current_pot # element-wise addition\n assert all(chips >= 0 for chips in allocated) # check that all players got a non negative amount of chips\n assert sum(in_chips_initial) == sum(allocated) # check that all chips bet have been allocated\n return list(allocated)\n\n\n# ./nolimitholdem/player.py\nfrom enum import Enum\n\n\nclass PlayerStatus(Enum):\n ALIVE = 0\n FOLDED = 1\n ALLIN = 2\n\n\nclass LimitHoldemPlayer:\n\n def __init__(self, player_id, np_random):\n \"\"\"\n Initialize a player.\n\n Args:\n player_id (int): The id of the player\n \"\"\"\n self.np_random = np_random\n self.player_id = player_id\n self.hand = []\n self.status = PlayerStatus.ALIVE\n\n # The chips that this player has put in until now\n self.in_chips = 0\n\n def get_state(self, public_cards, all_chips, legal_actions):\n \"\"\"\n Encode the state for the player\n\n Args:\n public_cards (list): A list of public cards that seen by all the players\n all_chips (int): The chips that all players have put in\n\n Returns:\n (dict): The state of the player\n \"\"\"\n return {\n 'hand': [c.get_index() for c in self.hand],\n 'public_cards': [c.get_index() for c in public_cards],\n 'all_chips': all_chips,\n 'my_chips': self.in_chips,\n 'legal_actions': legal_actions\n }\n\n def get_player_id(self):\n return self.player_id\n\n\n\nclass NolimitholdemPlayer(LimitHoldemPlayer):\n def __init__(self, player_id, init_chips, np_random):\n \"\"\"\n Initialize a player.\n\n Args:\n player_id (int): The id of the player\n init_chips (int): The number of chips the player has initially\n \"\"\"\n super().__init__(player_id, np_random)\n self.remained_chips = init_chips\n\n def bet(self, chips):\n quantity = chips if chips <= self.remained_chips else self.remained_chips\n self.in_chips += quantity\n self.remained_chips -= quantity\n\n\n# ./nolimitholdem/round.py\n# -*- coding: utf-8 -*-\n\"\"\"Implement no limit texas holdem Round class\"\"\"\nfrom enum import Enum\n\nfrom nolimitholdem import PlayerStatus\n\n\nclass Action(Enum):\n FOLD = 0\n CHECK_CALL = 1\n #CALL = 2\n # RAISE_3BB = 3\n RAISE_HALF_POT = 2\n RAISE_POT = 3\n # RAISE_2POT = 5\n ALL_IN = 4\n # SMALL_BLIND = 7\n # BIG_BLIND = 8\n\n\nclass NolimitholdemRound:\n \"\"\"Round can call functions from other classes to keep the game running\"\"\"\n\n def __init__(self, num_players, init_raise_amount, dealer, np_random):\n \"\"\"\n Initialize the round class\n\n Args:\n num_players (int): The number of players\n init_raise_amount (int): The min raise amount when every round starts\n \"\"\"\n self.np_random = np_random\n self.game_pointer = None\n self.num_players = num_players\n self.init_raise_amount = init_raise_amount\n\n self.dealer = dealer\n\n # Count the number without raise\n # If every player agree to not raise, the round is over\n self.not_raise_num = 0\n\n # Count players that are not playing anymore (folded or all-in)\n self.not_playing_num = 0\n\n # Raised amount for each player\n self.raised = [0 for _ in range(self.num_players)]\n\n def start_new_round(self, game_pointer, raised=None):\n \"\"\"\n Start a new bidding round\n\n Args:\n game_pointer (int): The game_pointer that indicates the next player\n raised (list): Initialize the chips for each player\n\n Note: For the first round of the game, we need to setup the big/small blind\n \"\"\"\n self.game_pointer = game_pointer\n self.not_raise_num = 0\n if raised:\n self.raised = raised\n else:\n self.raised = [0 for _ in range(self.num_players)]\n\n def proceed_round(self, players, action):\n \"\"\"\n Call functions from other classes to keep one round running\n\n Args:\n players (list): The list of players that play the game\n action (str/int): An legal action taken by the player\n\n Returns:\n (int): The game_pointer that indicates the next player\n \"\"\"\n player = players[self.game_pointer]\n\n if action == Action.CHECK_CALL:\n diff = max(self.raised) - self.raised[self.game_pointer]\n self.raised[self.game_pointer] = max(self.raised)\n player.bet(chips=diff)\n self.not_raise_num += 1\n\n elif action == Action.ALL_IN:\n all_in_quantity = player.remained_chips\n self.raised[self.game_pointer] = all_in_quantity + self.raised[self.game_pointer]\n player.bet(chips=all_in_quantity)\n\n self.not_raise_num = 1\n\n elif action == Action.RAISE_POT:\n self.raised[self.game_pointer] += self.dealer.pot\n player.bet(chips=self.dealer.pot)\n self.not_raise_num = 1\n\n elif action == Action.RAISE_HALF_POT:\n quantity = int(self.dealer.pot / 2)\n self.raised[self.game_pointer] += quantity\n player.bet(chips=quantity)\n self.not_raise_num = 1\n\n elif action == Action.FOLD:\n player.status = PlayerStatus.FOLDED\n\n if player.remained_chips < 0:\n raise Exception(\"Player in negative stake\")\n\n if player.remained_chips == 0 and player.status != PlayerStatus.FOLDED:\n player.status = PlayerStatus.ALLIN\n\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n if player.status == PlayerStatus.ALLIN:\n self.not_playing_num += 1\n self.not_raise_num -= 1 # Because already counted in not_playing_num\n if player.status == PlayerStatus.FOLDED:\n self.not_playing_num += 1\n\n # Skip the folded players\n while players[self.game_pointer].status == PlayerStatus.FOLDED:\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n return self.game_pointer\n\n def get_nolimit_legal_actions(self, players):\n \"\"\"\n Obtain the legal actions for the current player\n\n Args:\n players (list): The players in the game\n\n Returns:\n (list): A list of legal actions\n \"\"\"\n\n full_actions = list(Action)\n\n # The player can always check or call\n player = players[self.game_pointer]\n\n diff = max(self.raised) - self.raised[self.game_pointer]\n # If the current player has no more chips after call, we cannot raise\n if diff > 0 and diff >= player.remained_chips:\n full_actions.remove(Action.RAISE_HALF_POT)\n full_actions.remove(Action.RAISE_POT)\n full_actions.remove(Action.ALL_IN)\n # Even if we can raise, we have to check remained chips\n else:\n if self.dealer.pot > player.remained_chips:\n full_actions.remove(Action.RAISE_POT)\n\n if int(self.dealer.pot / 2) > player.remained_chips:\n full_actions.remove(Action.RAISE_HALF_POT)\n\n # Can't raise if the total raise amount is leq than the max raise amount of this round\n # If raise by pot, there is no such concern\n if Action.RAISE_HALF_POT in full_actions and \\\n int(self.dealer.pot / 2) + self.raised[self.game_pointer] <= max(self.raised):\n full_actions.remove(Action.RAISE_HALF_POT)\n\n return full_actions\n\n def is_over(self):\n \"\"\"\n Check whether the round is over\n\n Returns:\n (boolean): True if the current round is over\n \"\"\"\n if self.not_raise_num + self.not_playing_num >= self.num_players:\n return True\n return False\n\n\n# ./nolimitholdem/utils.py\nimport numpy as np\nfrom nolimitholdem import Card\n\ndef init_standard_deck():\n ''' Initialize a standard deck of 52 cards\n\n Returns:\n (list): A list of Card object\n '''\n suit_list = ['S', 'H', 'D', 'C']\n rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']\n res = [Card(suit, rank) for suit in suit_list for rank in rank_list]\n return res\n\n \nclass Hand:\n def __init__(self, all_cards):\n self.all_cards = all_cards # two hand cards + five public cards\n self.category = 0\n #type of a players' best five cards, greater combination has higher number eg: 0:\"Not_Yet_Evaluated\" 1: \"High_Card\" , 9:\"Straight_Flush\"\n self.best_five = []\n #the largest combination of five cards in all the seven cards\n self.flush_cards = []\n #cards with same suit\n self.cards_by_rank = []\n #cards after sort\n self.product = 1\n #cards’ type indicator\n self.RANK_TO_STRING = {2: \"2\", 3: \"3\", 4: \"4\", 5: \"5\", 6: \"6\",\n 7: \"7\", 8: \"8\", 9: \"9\", 10: \"T\", 11: \"J\", 12: \"Q\", 13: \"K\", 14: \"A\"}\n self.STRING_TO_RANK = {v:k for k, v in self.RANK_TO_STRING.items()}\n self.RANK_LOOKUP = \"23456789TJQKA\"\n self.SUIT_LOOKUP = \"SCDH\"\n\n def get_hand_five_cards(self):\n '''\n Get the best five cards of a player\n Returns:\n (list): the best five cards among the seven cards of a player\n '''\n return self.best_five\n\n def _sort_cards(self):\n '''\n Sort all the seven cards ascendingly according to RANK_LOOKUP\n '''\n self.all_cards = sorted(\n self.all_cards, key=lambda card: self.RANK_LOOKUP.index(card[1]))\n\n def evaluateHand(self):\n \"\"\"\n Evaluate all the seven cards, get the best combination catagory\n And pick the best five cards (for comparing in case 2 hands have the same Category) .\n \"\"\"\n if len(self.all_cards) != 7:\n raise Exception(\n \"There are not enough 7 cards in this hand, quit evaluation now ! \")\n\n self._sort_cards()\n self.cards_by_rank, self.product = self._getcards_by_rank(\n self.all_cards)\n\n if self._has_straight_flush():\n self.category = 9\n #Straight Flush\n elif self._has_four():\n self.category = 8\n #Four of a Kind\n self.best_five = self._get_Four_of_a_kind_cards()\n elif self._has_fullhouse():\n self.category = 7\n #Full house\n self.best_five = self._get_Fullhouse_cards()\n elif self._has_flush():\n self.category = 6\n #Flush\n i = len(self.flush_cards)\n self.best_five = [card for card in self.flush_cards[i-5:i]]\n elif self._has_straight(self.all_cards):\n self.category = 5\n #Straight\n elif self._has_three():\n self.category = 4\n #Three of a Kind\n self.best_five = self._get_Three_of_a_kind_cards()\n elif self._has_two_pairs():\n self.category = 3\n #Two Pairs\n self.best_five = self._get_Two_Pair_cards()\n elif self._has_pair():\n self.category = 2\n #One Pair\n self.best_five = self._get_One_Pair_cards()\n elif self._has_high_card():\n self.category = 1\n #High Card\n self.best_five = self._get_High_cards()\n\n def _has_straight_flush(self):\n '''\n Check the existence of straight_flush cards\n Returns:\n True: exist\n False: not exist\n '''\n self.flush_cards = self._getflush_cards()\n if len(self.flush_cards) > 0:\n straightflush_cards = self._get_straightflush_cards()\n if len(straightflush_cards) > 0:\n self.best_five = straightflush_cards\n return True\n return False\n\n def _get_straightflush_cards(self):\n '''\n Pick straight_flush cards\n Returns:\n (list): the straightflush cards\n '''\n straightflush_cards = self._get_straight_cards(self.flush_cards)\n return straightflush_cards\n\n def _getflush_cards(self):\n '''\n Pick flush cards\n Returns:\n (list): the flush cards\n '''\n card_string = ''.join(self.all_cards)\n for suit in self.SUIT_LOOKUP:\n suit_count = card_string.count(suit)\n if suit_count >= 5:\n flush_cards = [\n card for card in self.all_cards if card[0] == suit]\n return flush_cards\n return []\n\n def _has_flush(self):\n '''\n Check the existence of flush cards\n Returns:\n True: exist\n False: not exist\n '''\n if len(self.flush_cards) > 0:\n return True\n else:\n return False\n\n def _has_straight(self, all_cards):\n '''\n Check the existence of straight cards\n Returns:\n True: exist\n False: not exist\n '''\n diff_rank_cards = self._get_different_rank_list(all_cards)\n self.best_five = self._get_straight_cards(diff_rank_cards)\n if len(self.best_five) != 0:\n return True\n else:\n return False\n @classmethod\n def _get_different_rank_list(self, all_cards):\n '''\n Get cards with different ranks, that is to say, remove duplicate-ranking cards, for picking straight cards' use\n Args:\n (list): two hand cards + five public cards\n Returns:\n (list): a list of cards with duplicate-ranking cards removed\n '''\n different_rank_list = []\n different_rank_list.append(all_cards[0])\n for card in all_cards:\n if(card[1] != different_rank_list[-1][1]):\n different_rank_list.append(card)\n return different_rank_list\n\n def _get_straight_cards(self, Cards):\n '''\n Pick straight cards\n Returns:\n (list): the straight cards\n '''\n ranks = [self.STRING_TO_RANK[c[1]] for c in Cards]\n\n highest_card = Cards[-1]\n if highest_card[1] == 'A':\n Cards.insert(0, highest_card)\n ranks.insert(0, 1)\n\n for i_last in range(len(ranks) - 1, 3, -1):\n if ranks[i_last-4] + 4 == ranks[i_last]: # works because ranks are unique and sorted in ascending order\n return Cards[i_last-4:i_last+1]\n return []\n\n def _getcards_by_rank(self, all_cards):\n '''\n Get cards by rank\n Args:\n (list): # two hand cards + five public cards\n Return:\n card_group(list): cards after sort\n product(int):cards‘ type indicator\n '''\n card_group = []\n card_group_element = []\n product = 1\n prime_lookup = {0: 1, 1: 1, 2: 2, 3: 3, 4: 5}\n count = 0\n current_rank = 0\n\n for card in all_cards:\n rank = self.RANK_LOOKUP.index(card[1])\n if rank == current_rank:\n count += 1\n card_group_element.append(card)\n elif rank != current_rank:\n product *= prime_lookup[count]\n # Explanation :\n # if count == 2, then product *= 2\n # if count == 3, then product *= 3\n # if count == 4, then product *= 5\n # if there is a Quad, then product = 5 ( 4, 1, 1, 1) or product = 10 ( 4, 2, 1) or product= 15 (4,3)\n # if there is a Fullhouse, then product = 12 ( 3, 2, 2) or product = 9 (3, 3, 1) or product = 6 ( 3, 2, 1, 1)\n # if there is a Trip, then product = 3 ( 3, 1, 1, 1, 1)\n # if there is two Pair, then product = 4 ( 2, 1, 2, 1, 1) or product = 8 ( 2, 2, 2, 1)\n # if there is one Pair, then product = 2 (2, 1, 1, 1, 1, 1)\n # if there is HighCard, then product = 1 (1, 1, 1, 1, 1, 1, 1)\n card_group_element.insert(0, count)\n card_group.append(card_group_element)\n # reset counting\n count = 1\n card_group_element = []\n card_group_element.append(card)\n current_rank = rank\n # the For Loop misses operation for the last card\n # These 3 lines below to compensate that\n product *= prime_lookup[count]\n # insert the number of same rank card to the beginning of the\n card_group_element.insert(0, count)\n # after the loop, there is still one last card to add\n card_group.append(card_group_element)\n return card_group, product\n\n def _has_four(self):\n '''\n Check the existence of four cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 5 or self.product == 10 or self.product == 15:\n return True\n else:\n return False\n\n def _has_fullhouse(self):\n '''\n Check the existence of fullhouse cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 6 or self.product == 9 or self.product == 12:\n return True\n else:\n return False\n\n def _has_three(self):\n '''\n Check the existence of three cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 3:\n return True\n else:\n return False\n\n def _has_two_pairs(self):\n '''\n Check the existence of 2 pair cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 4 or self.product == 8:\n return True\n else:\n return False\n\n def _has_pair(self):\n '''\n Check the existence of 1 pair cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 2:\n return True\n else:\n return False\n\n def _has_high_card(self):\n '''\n Check the existence of high cards\n Returns:\n True: exist\n False: not exist\n '''\n if self.product == 1:\n return True\n else:\n return False\n\n def _get_Four_of_a_kind_cards(self):\n '''\n Get the four of a kind cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Four_of_a_Kind = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 4:\n Four_of_a_Kind = cards_by_rank.pop(i)\n break\n # The Last cards_by_rank[The Second element]\n kicker = cards_by_rank[-1][1]\n Four_of_a_Kind[0] = kicker\n\n return Four_of_a_Kind\n\n def _get_Fullhouse_cards(self):\n '''\n Get the fullhouse cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Fullhouse = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 3:\n Trips = cards_by_rank.pop(i)[1:4]\n break\n for i in reversed(range(cards_len - 1)):\n if cards_by_rank[i][0] >= 2:\n TwoPair = cards_by_rank.pop(i)[1:3]\n break\n Fullhouse = TwoPair + Trips\n return Fullhouse\n\n def _get_Three_of_a_kind_cards(self):\n '''\n Get the three of a kind cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Trip_cards = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 3:\n Trip_cards += cards_by_rank.pop(i)[1:4]\n break\n\n Trip_cards += cards_by_rank.pop(-1)[1:2]\n Trip_cards += cards_by_rank.pop(-1)[1:2]\n Trip_cards.reverse()\n return Trip_cards\n\n def _get_Two_Pair_cards(self):\n '''\n Get the two pair cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n Two_Pair_cards = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 2 and len(Two_Pair_cards) < 3:\n Two_Pair_cards += cards_by_rank.pop(i)[1:3]\n\n Two_Pair_cards += cards_by_rank.pop(-1)[1:2]\n Two_Pair_cards.reverse()\n return Two_Pair_cards\n\n def _get_One_Pair_cards(self):\n '''\n Get the one pair cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n One_Pair_cards = []\n cards_by_rank = self.cards_by_rank\n cards_len = len(cards_by_rank)\n for i in reversed(range(cards_len)):\n if cards_by_rank[i][0] == 2:\n One_Pair_cards += cards_by_rank.pop(i)[1:3]\n break\n\n One_Pair_cards += cards_by_rank.pop(-1)[1:2]\n One_Pair_cards += cards_by_rank.pop(-1)[1:2]\n One_Pair_cards += cards_by_rank.pop(-1)[1:2]\n One_Pair_cards.reverse()\n return One_Pair_cards\n\n def _get_High_cards(self):\n '''\n Get the high cards among a player's cards\n Returns:\n (list): best five hand cards after sort\n '''\n High_cards = self.all_cards[2:7]\n return High_cards\n\ndef compare_ranks(position, hands, winner):\n '''\n Compare cards in same position of plays' five handcards\n Args:\n position(int): the position of a card in a sorted handcard\n hands(list): cards of those players.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n winner: array of same length than hands with 1 if the hand is among winners and 0 among losers\n Returns:\n new updated winner array\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n '''\n assert len(hands) == len(winner)\n RANKS = '23456789TJQKA'\n cards_figure_all_players = [None]*len(hands) #cards without suit\n for i, hand in enumerate(hands):\n if winner[i]:\n cards = hands[i].get_hand_five_cards()\n if len(cards[0]) != 1:# remove suit\n for p in range(5):\n cards[p] = cards[p][1:]\n cards_figure_all_players[i] = cards\n\n rival_ranks = [] # ranks of rival_figures\n for i, cards_figure in enumerate(cards_figure_all_players):\n if winner[i]:\n rank = cards_figure_all_players[i][position]\n rival_ranks.append(RANKS.index(rank))\n else:\n rival_ranks.append(-1) # player has already lost\n new_winner = list(winner)\n for i, rival_rank in enumerate(rival_ranks):\n if rival_rank != max(rival_ranks):\n new_winner[i] = 0\n return new_winner\n\ndef determine_winner(key_index, hands, all_players, potential_winner_index):\n '''\n Find out who wins in the situation of having players with same highest hand_catagory\n Args:\n key_index(int): the position of a card in a sorted handcard\n hands(list): cards of those players with same highest hand_catagory.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n all_players(list): all the players in this round, 0 for losing and 1 for winning or draw\n potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n '''\n winner = [1]*len(hands)\n i_index = 0\n while i_index < len(key_index) and sum(winner) > 1:\n index_break_tie = key_index[i_index]\n winner = compare_ranks(index_break_tie, hands, winner)\n i_index += 1\n for i in range(len(potential_winner_index)):\n if winner[i]:\n all_players[potential_winner_index[i]] = 1\n return all_players\n\ndef determine_winner_straight(hands, all_players, potential_winner_index):\n '''\n Find out who wins in the situation of having players all having a straight or straight flush\n Args:\n key_index(int): the position of a card in a sorted handcard\n hands(list): cards of those players which all have a straight or straight flush\n all_players(list): all the players in this round, 0 for losing and 1 for winning or draw\n potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n '''\n highest_ranks = []\n for hand in hands:\n highest_rank = hand.STRING_TO_RANK[hand.best_five[-1][1]] # cards are sorted in ascending order\n highest_ranks.append(highest_rank)\n max_highest_rank = max(highest_ranks)\n for i_player in range(len(highest_ranks)):\n if highest_ranks[i_player] == max_highest_rank:\n all_players[potential_winner_index[i_player]] = 1\n return all_players\n\ndef determine_winner_four_of_a_kind(hands, all_players, potential_winner_index):\n '''\n Find out who wins in the situation of having players which all have a four of a kind\n Args:\n key_index(int): the position of a card in a sorted handcard\n hands(list): cards of those players with a four of a kind\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n all_players(list): all the players in this round, 0 for losing and 1 for winning or draw\n potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n '''\n ranks = []\n for hand in hands:\n rank_1 = hand.STRING_TO_RANK[hand.best_five[-1][1]] # rank of the four of a kind\n rank_2 = hand.STRING_TO_RANK[hand.best_five[0][1]] # rank of the kicker\n ranks.append((rank_1, rank_2))\n max_rank = max(ranks)\n for i, rank in enumerate(ranks):\n if rank == max_rank:\n all_players[potential_winner_index[i]] = 1\n return all_players\n\ndef compare_hands(hands):\n '''\n Compare all palyer's all seven cards\n Args:\n hands(list): cards of those players with same highest hand_catagory.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n if hands[0] == None:\n return [0, 1]\n elif hands[1] == None:\n return [1, 0]\n '''\n hand_category = [] #such as high_card, straight_flush, etc\n all_players = [0]*len(hands) #all the players in this round, 0 for losing and 1 for winning or draw\n if None in hands:\n fold_players = [i for i, j in enumerate(hands) if j is None]\n if len(fold_players) == len(all_players) - 1:\n for _ in enumerate(hands):\n if _[0] in fold_players:\n all_players[_[0]] = 0\n else:\n all_players[_[0]] = 1\n return all_players\n else:\n for _ in enumerate(hands):\n if hands[_[0]] is not None:\n hand = Hand(hands[_[0]])\n hand.evaluateHand()\n hand_category.append(hand.category)\n elif hands[_[0]] is None:\n hand_category.append(0)\n else:\n for i in enumerate(hands):\n hand = Hand(hands[i[0]])\n hand.evaluateHand()\n hand_category.append(hand.category)\n potential_winner_index = [i for i, j in enumerate(hand_category) if j == max(hand_category)]# potential winner are those with same max card_catagory\n\n return final_compare(hands, potential_winner_index, all_players)\n\ndef final_compare(hands, potential_winner_index, all_players):\n '''\n Find out the winners from those who didn't fold\n Args:\n hands(list): cards of those players with same highest hand_catagory.\n e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]\n potential_winner_index(list): index of those with same max card_catagory in all_players\n all_players(list): a list of all the player's win/lose situation, 0 for lose and 1 for win\n Returns:\n [0, 1, 0]: player1 wins\n [1, 0, 0]: player0 wins\n [1, 1, 1]: draw\n [1, 1, 0]: player1 and player0 draws\n\n if hands[0] == None:\n return [0, 1]\n elif hands[1] == None:\n return [1, 0]\n '''\n if len(potential_winner_index) == 1:\n all_players[potential_winner_index[0]] = 1\n return all_players\n elif len(potential_winner_index) > 1:\n # compare when having equal max categories\n equal_hands = []\n for _ in potential_winner_index:\n hand = Hand(hands[_])\n hand.evaluateHand()\n equal_hands.append(hand)\n hand = equal_hands[0]\n if hand.category == 8:\n return determine_winner_four_of_a_kind(equal_hands, all_players, potential_winner_index)\n if hand.category == 7:\n return determine_winner([2, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 4:\n return determine_winner([2, 1, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 3:\n return determine_winner([4, 2, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 2:\n return determine_winner([4, 2, 1, 0], equal_hands, all_players, potential_winner_index)\n if hand.category == 1 or hand.category == 6:\n return determine_winner([4, 3, 2, 1, 0], equal_hands, all_players, potential_winner_index)\n if hand.category in [5, 9]:\n return determine_winner_straight(equal_hands, all_players, potential_winner_index)\n", "num_file": 8, "num_lines": 1562, "programming_language": "Python"} {"class_name": "slugify", "id": "./MultiFileTest/Python/slugify.py", "original_code": "# ./slugify/__init__.py\nfrom slugify.special import *\nfrom slugify.slugify import *\n\n\n# ./slugify/slugify.py\nfrom __future__ import annotations\n\nimport re\nimport unicodedata\nfrom collections.abc import Iterable\nfrom html.entities import name2codepoint\n\ntry:\n import unidecode\nexcept ImportError:\n import text_unidecode as unidecode\n\n__all__ = ['slugify', 'smart_truncate']\n\n\nCHAR_ENTITY_PATTERN = re.compile(r'&(%s);' % '|'.join(name2codepoint))\nDECIMAL_PATTERN = re.compile(r'&#(\\d+);')\nHEX_PATTERN = re.compile(r'&#x([\\da-fA-F]+);')\nQUOTE_PATTERN = re.compile(r'[\\']+')\nDISALLOWED_CHARS_PATTERN = re.compile(r'[^-a-zA-Z0-9]+')\nDISALLOWED_UNICODE_CHARS_PATTERN = re.compile(r'[\\W_]+')\nDUPLICATE_DASH_PATTERN = re.compile(r'-{2,}')\nNUMBERS_PATTERN = re.compile(r'(?<=\\d),(?=\\d)')\nDEFAULT_SEPARATOR = '-'\n\n\ndef smart_truncate(\n string: str,\n max_length: int = 0,\n word_boundary: bool = False,\n separator: str = \" \",\n save_order: bool = False,\n) -> str:\n \"\"\"\n Truncate a string.\n :param string (str): string for modification\n :param max_length (int): output string length\n :param word_boundary (bool):\n :param save_order (bool): if True then word order of output string is like input string\n :param separator (str): separator between words\n :return:\n \"\"\"\n\n string = string.strip(separator)\n\n if not max_length:\n return string\n\n if len(string) < max_length:\n return string\n\n if not word_boundary:\n return string[:max_length].strip(separator)\n\n if separator not in string:\n return string[:max_length]\n\n truncated = ''\n for word in string.split(separator):\n if word:\n next_len = len(truncated) + len(word)\n if next_len < max_length:\n truncated += '{}{}'.format(word, separator)\n elif next_len == max_length:\n truncated += '{}'.format(word)\n break\n else:\n if save_order:\n break\n if not truncated: # pragma: no cover\n truncated = string[:max_length]\n return truncated.strip(separator)\n\n\ndef slugify(\n text: str,\n entities: bool = True,\n decimal: bool = True,\n hexadecimal: bool = True,\n max_length: int = 0,\n word_boundary: bool = False,\n separator: str = DEFAULT_SEPARATOR,\n save_order: bool = False,\n stopwords: Iterable[str] = (),\n regex_pattern: re.Pattern[str] | str | None = None,\n lowercase: bool = True,\n replacements: Iterable[Iterable[str]] = (),\n allow_unicode: bool = False,\n) -> str:\n \"\"\"\n Make a slug from the given text.\n :param text (str): initial text\n :param entities (bool): converts html entities to unicode\n :param decimal (bool): converts html decimal to unicode\n :param hexadecimal (bool): converts html hexadecimal to unicode\n :param max_length (int): output string length\n :param word_boundary (bool): truncates to complete word even if length ends up shorter than max_length\n :param save_order (bool): if parameter is True and max_length > 0 return whole words in the initial order\n :param separator (str): separator between words\n :param stopwords (iterable): words to discount\n :param regex_pattern (str): regex pattern for disallowed characters\n :param lowercase (bool): activate case sensitivity by setting it to False\n :param replacements (iterable): list of replacement rules e.g. [['|', 'or'], ['%', 'percent']]\n :param allow_unicode (bool): allow unicode characters\n :return (str):\n \"\"\"\n\n # user-specific replacements\n if replacements:\n for old, new in replacements:\n text = text.replace(old, new)\n\n # ensure text is unicode\n if not isinstance(text, str):\n text = str(text, 'utf-8', 'ignore')\n\n # replace quotes with dashes - pre-process\n text = QUOTE_PATTERN.sub(DEFAULT_SEPARATOR, text)\n\n # normalize text, convert to unicode if required\n if allow_unicode:\n text = unicodedata.normalize('NFKC', text)\n else:\n text = unicodedata.normalize('NFKD', text)\n text = unidecode.unidecode(text)\n\n # ensure text is still in unicode\n if not isinstance(text, str):\n text = str(text, 'utf-8', 'ignore')\n\n # character entity reference\n if entities:\n text = CHAR_ENTITY_PATTERN.sub(lambda m: chr(name2codepoint[m.group(1)]), text)\n\n # decimal character reference\n if decimal:\n try:\n text = DECIMAL_PATTERN.sub(lambda m: chr(int(m.group(1))), text)\n except Exception:\n pass\n\n # hexadecimal character reference\n if hexadecimal:\n try:\n text = HEX_PATTERN.sub(lambda m: chr(int(m.group(1), 16)), text)\n except Exception:\n pass\n\n # re normalize text\n if allow_unicode:\n text = unicodedata.normalize('NFKC', text)\n else:\n text = unicodedata.normalize('NFKD', text)\n\n # make the text lowercase (optional)\n if lowercase:\n text = text.lower()\n\n # remove generated quotes -- post-process\n text = QUOTE_PATTERN.sub('', text)\n\n # cleanup numbers\n text = NUMBERS_PATTERN.sub('', text)\n\n # replace all other unwanted characters\n if allow_unicode:\n pattern = regex_pattern or DISALLOWED_UNICODE_CHARS_PATTERN\n else:\n pattern = regex_pattern or DISALLOWED_CHARS_PATTERN\n\n text = re.sub(pattern, DEFAULT_SEPARATOR, text)\n\n # remove redundant\n text = DUPLICATE_DASH_PATTERN.sub(DEFAULT_SEPARATOR, text).strip(DEFAULT_SEPARATOR)\n\n # remove stopwords\n if stopwords:\n if lowercase:\n stopwords_lower = [s.lower() for s in stopwords]\n words = [w for w in text.split(DEFAULT_SEPARATOR) if w not in stopwords_lower]\n else:\n words = [w for w in text.split(DEFAULT_SEPARATOR) if w not in stopwords]\n text = DEFAULT_SEPARATOR.join(words)\n\n # finalize user-specific replacements\n if replacements:\n for old, new in replacements:\n text = text.replace(old, new)\n\n # smart truncate if requested\n if max_length > 0:\n text = smart_truncate(text, max_length, word_boundary, DEFAULT_SEPARATOR, save_order)\n\n if separator != DEFAULT_SEPARATOR:\n text = text.replace(DEFAULT_SEPARATOR, separator)\n\n return text\n\n\n# ./slugify/special.py\nfrom __future__ import annotations\n\n\ndef add_uppercase_char(char_list: list[tuple[str, str]]) -> list[tuple[str, str]]:\n \"\"\" Given a replacement char list, this adds uppercase chars to the list \"\"\"\n\n for item in char_list:\n char, xlate = item\n upper_dict = char.upper(), xlate.capitalize()\n if upper_dict not in char_list and char != upper_dict[0]:\n char_list.insert(0, upper_dict)\n return char_list\n\n\n# Language specific pre translations\n# Source awesome-slugify\n\n_CYRILLIC = [ # package defaults:\n (u'ё', u'e'), # io / yo\n (u'я', u'ya'), # ia\n (u'х', u'h'), # kh\n (u'у', u'y'), # u\n (u'щ', u'sch'), # sch\n (u'ю', u'u'), # iu / yu\n]\nCYRILLIC = add_uppercase_char(_CYRILLIC)\n\n_GERMAN = [ # package defaults:\n (u'ä', u'ae'), # a\n (u'ö', u'oe'), # o\n (u'ü', u'ue'), # u\n]\nGERMAN = add_uppercase_char(_GERMAN)\n\n_GREEK = [ # package defaults:\n (u'χ', u'ch'), # kh\n (u'Ξ', u'X'), # Ks\n (u'ϒ', u'Y'), # U\n (u'υ', u'y'), # u\n (u'ύ', u'y'),\n (u'ϋ', u'y'),\n (u'ΰ', u'y'),\n]\nGREEK = add_uppercase_char(_GREEK)\n\n# Pre translations\nPRE_TRANSLATIONS = CYRILLIC + GERMAN + GREEK\n", "num_file": 3, "num_lines": 246, "programming_language": "Python"} {"class_name": "stock", "id": "./MultiFileTest/Python/stock.py", "original_code": "# ./stock/stock.py\n# stock.py\n\nfrom structure import Structure\nfrom validate import String, PositiveInteger, PositiveFloat\n\nclass Stock(Structure):\n name = String()\n shares = PositiveInteger()\n price = PositiveFloat()\n\n @property\n def cost(self):\n return self.shares * self.price\n\n def sell(self, nshares: PositiveInteger):\n self.shares -= nshares\n\n\n# ./stock/structure.py\n# structure.py\n\nfrom validate import Validator, validated\n\nclass Structure:\n _fields = ()\n _types = ()\n\n def __setattr__(self, name, value):\n if name.startswith('_') or name in self._fields:\n super().__setattr__(name, value)\n else:\n raise AttributeError('No attribute %s' % name)\n\n def __repr__(self):\n return '%s(%s)' % (type(self).__name__,\n ', '.join(repr(getattr(self, name)) for name in self._fields))\n\n @classmethod\n def from_row(cls, row):\n rowdata = [ func(val) for func, val in zip(cls._types, row) ]\n return cls(*rowdata)\n\n @classmethod\n def create_init(cls):\n '''\n Create an __init__ method from _fields\n '''\n args = ','.join(cls._fields)\n code = f'def __init__(self, {args}):\\n'\n for name in cls._fields:\n code += f' self.{name} = {name}\\n'\n locs = { }\n exec(code, locs)\n cls.__init__ = locs['__init__']\n\n @classmethod\n def __init_subclass__(cls):\n # Apply the validated decorator to subclasses\n validate_attributes(cls)\n\ndef validate_attributes(cls):\n '''\n Class decorator that scans a class definition for Validators\n and builds a _fields variable that captures their definition order.\n '''\n validators = []\n for name, val in vars(cls).items():\n if isinstance(val, Validator):\n validators.append(val)\n\n # Apply validated decorator to any callable with annotations\n elif callable(val) and val.__annotations__:\n setattr(cls, name, validated(val))\n\n # Collect all of the field names\n cls._fields = tuple([v.name for v in validators])\n\n # Collect type conversions. The lambda x:x is an identity\n # function that's used in case no expected_type is found.\n cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)\n for v in validators ])\n\n # Create the __init__ method\n if cls._fields:\n cls.create_init()\n\n \n return cls\n\n\n\n# ./stock/validate.py\n# validate.py\n\nclass Validator:\n def __init__(self, name=None):\n self.name = name\n\n def __set_name__(self, cls, name):\n self.name = name\n\n @classmethod\n def check(cls, value):\n return value\n\n def __set__(self, instance, value):\n instance.__dict__[self.name] = self.check(value)\n\nclass Typed(Validator):\n expected_type = object\n @classmethod\n def check(cls, value):\n if not isinstance(value, cls.expected_type):\n raise TypeError(f'expected {cls.expected_type}')\n return super().check(value)\n\nclass Integer(Typed):\n expected_type = int\n\nclass Float(Typed):\n expected_type = float\n\nclass String(Typed):\n expected_type = str\n\nclass Positive(Validator):\n @classmethod\n def check(cls, value):\n if value < 0:\n raise ValueError('must be >= 0')\n return super().check(value)\n\nclass NonEmpty(Validator):\n @classmethod\n def check(cls, value):\n if len(value) == 0:\n raise ValueError('must be non-empty')\n return super().check(value)\n\nclass PositiveInteger(Integer, Positive):\n pass\n\nclass PositiveFloat(Float, Positive):\n pass\n\nclass NonEmptyString(String, NonEmpty):\n pass\n\nfrom inspect import signature\nfrom functools import wraps\n\ndef isvalidator(item):\n return isinstance(item, type) and issubclass(item, Validator)\n\ndef validated(func):\n sig = signature(func)\n\n # Gather the function annotations\n annotations = { name:val for name, val in func.__annotations__.items()\n if isvalidator(val) }\n\n # Get the return annotation (if any)\n retcheck = annotations.pop('return', None)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n # Enforce return check (if any)\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n\n return wrapper\n\ndef enforce(**annotations):\n retcheck = annotations.pop('return_', None)\n\n def decorate(func):\n sig = signature(func)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n return wrapper\n return decorate\n\n", "num_file": 3, "num_lines": 217, "programming_language": "Python"} {"class_name": "stock2", "id": "./MultiFileTest/Python/stock2.py", "original_code": "# ./stock2/reader.py\n# reader.py\n\nimport csv\nimport logging\n\nlog = logging.getLogger(__name__)\n\ndef convert_csv(lines, converter, *, headers=None):\n rows = csv.reader(lines)\n if headers is None:\n headers = next(rows)\n\n records = []\n for rowno, row in enumerate(rows, start=1):\n try:\n records.append(converter(headers, row))\n except ValueError as e:\n log.warning('Row %s: Bad row: %s', rowno, row)\n log.debug('Row %s: Reason: %s', rowno, row)\n return records\n\ndef csv_as_dicts(lines, types, *, headers=None):\n return convert_csv(lines, \n lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) })\n\ndef csv_as_instances(lines, cls, *, headers=None):\n return convert_csv(lines,\n lambda headers, row: cls.from_row(row))\n\ndef read_csv_as_dicts(filename, types, *, headers=None):\n '''\n Read CSV data into a list of dictionaries with optional type conversion\n '''\n with open(filename) as file:\n return csv_as_dicts(file, types, headers=headers)\n\ndef read_csv_as_instances(filename, cls, *, headers=None):\n '''\n Read CSV data into a list of instances\n '''\n with open(filename) as file:\n return csv_as_instances(file, cls, headers=headers)\n\n\n\n# ./stock2/stock.py\n# stock.py\n\nfrom structure import Structure\n\nclass Stock(Structure):\n name = String()\n shares = PositiveInteger()\n price = PositiveFloat()\n\n @property\n def cost(self):\n return self.shares * self.price\n\n def sell(self, nshares: PositiveInteger):\n self.shares -= nshares\n\n\n\n# ./stock2/structure.py\n# structure.py\n\nfrom validate import Validator, validated\nfrom collections import ChainMap\n\nclass StructureMeta(type):\n @classmethod\n def __prepare__(meta, clsname, bases):\n return ChainMap({}, Validator.validators)\n \n @staticmethod\n def __new__(meta, name, bases, methods):\n methods = methods.maps[0]\n return super().__new__(meta, name, bases, methods)\n\nclass Structure(metaclass=StructureMeta):\n _fields = ()\n _types = ()\n\n def __setattr__(self, name, value):\n if name.startswith('_') or name in self._fields:\n super().__setattr__(name, value)\n else:\n raise AttributeError('No attribute %s' % name)\n\n def __repr__(self):\n return '%s(%s)' % (type(self).__name__,\n ', '.join(repr(getattr(self, name)) for name in self._fields))\n\n @classmethod\n def from_row(cls, row):\n rowdata = [ func(val) for func, val in zip(cls._types, row) ]\n return cls(*rowdata)\n\n\n @classmethod\n def create_init(cls):\n '''\n Create an __init__ method from _fields\n '''\n args = ','.join(cls._fields)\n code = f'def __init__(self, {args}):\\n'\n for name in cls._fields:\n code += f' self.{name} = {name}\\n'\n locs = { }\n exec(code, locs)\n cls.__init__ = locs['__init__']\n\n @classmethod\n def __init_subclass__(cls):\n # Apply the validated decorator to subclasses\n validate_attributes(cls)\n\ndef validate_attributes(cls):\n '''\n Class decorator that scans a class definition for Validators\n and builds a _fields variable that captures their definition order.\n '''\n validators = []\n for name, val in vars(cls).items():\n if isinstance(val, Validator):\n validators.append(val)\n\n # Apply validated decorator to any callable with annotations\n elif callable(val) and val.__annotations__:\n setattr(cls, name, validated(val))\n\n # Collect all of the field names\n cls._fields = tuple([v.name for v in validators])\n\n # Collect type conversions. The lambda x:x is an identity\n # function that's used in case no expected_type is found.\n cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)\n for v in validators ])\n\n # Create the __init__ method\n if cls._fields:\n cls.create_init()\n\n \n return cls\n\ndef typed_structure(clsname, **validators):\n cls = type(clsname, (Structure,), validators)\n return cls\n\n\n# ./stock2/tableformat.py\n# tableformat.py\nfrom abc import ABC, abstractmethod\n\ndef print_table(records, fields, formatter):\n if not isinstance(formatter, TableFormatter):\n raise RuntimeError('Expected a TableFormatter')\n\n formatter.headings(fields)\n for r in records:\n rowdata = [getattr(r, fieldname) for fieldname in fields]\n formatter.row(rowdata)\n\nclass TableFormatter(ABC):\n @abstractmethod\n def headings(self, headers):\n pass\n\n @abstractmethod\n def row(self, rowdata):\n pass\n\nclass TextTableFormatter(TableFormatter):\n def headings(self, headers):\n print(' '.join('%10s' % h for h in headers))\n print(('-'*10 + ' ')*len(headers))\n \n def row(self, rowdata):\n print(' '.join('%10s' % d for d in rowdata))\n\nclass CSVTableFormatter(TableFormatter):\n def headings(self, headers):\n print(','.join(headers))\n\n def row(self, rowdata):\n print(','.join(str(d) for d in rowdata))\n\nclass HTMLTableFormatter(TableFormatter):\n def headings(self, headers):\n print('', end=' ')\n for h in headers:\n print('%s' % h, end=' ')\n print('')\n\n def row(self, rowdata):\n print('', end=' ')\n for d in rowdata:\n print('%s' % d, end=' ')\n print('')\n\nclass ColumnFormatMixin:\n formats = []\n def row(self, rowdata):\n rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)]\n super().row(rowdata)\n\nclass UpperHeadersMixin:\n def headings(self, headers):\n super().headings([h.upper() for h in headers])\n\ndef create_formatter(name, column_formats=None, upper_headers=False):\n if name == 'text':\n formatter_cls = TextTableFormatter\n elif name == 'csv':\n formatter_cls = CSVTableFormatter\n elif name == 'html':\n formatter_cls = HTMLTableFormatter\n else:\n raise RuntimeError('Unknown format %s' % name)\n\n if column_formats:\n class formatter_cls(ColumnFormatMixin, formatter_cls):\n formats = column_formats\n\n if upper_headers:\n class formatter_cls(UpperHeadersMixin, formatter_cls):\n pass\n\n return formatter_cls()\n\n\n\n\n\n\n# ./stock2/validate.py\n# validate.py\n\nclass Validator:\n def __init__(self, name=None):\n self.name = name\n\n def __set_name__(self, cls, name):\n self.name = name\n\n @classmethod\n def check(cls, value):\n return value\n\n def __set__(self, instance, value):\n instance.__dict__[self.name] = self.check(value)\n\n # Collect all derived classes into a dict\n validators = { }\n @classmethod\n def __init_subclass__(cls):\n cls.validators[cls.__name__] = cls\n\nclass Typed(Validator):\n expected_type = object\n @classmethod\n def check(cls, value):\n if not isinstance(value, cls.expected_type):\n raise TypeError(f'expected {cls.expected_type}')\n return super().check(value)\n\n_typed_classes = [\n ('Integer', int),\n ('Float', float),\n ('String', str) ]\n\nglobals().update((name, type(name, (Typed,), {'expected_type':ty}))\n for name, ty in _typed_classes)\n\nclass Positive(Validator):\n @classmethod\n def check(cls, value):\n if value < 0:\n raise ValueError('must be >= 0')\n return super().check(value)\n\nclass NonEmpty(Validator):\n @classmethod\n def check(cls, value):\n if len(value) == 0:\n raise ValueError('must be non-empty')\n return super().check(value)\n\nclass PositiveInteger(Integer, Positive):\n pass\n\nclass PositiveFloat(Float, Positive):\n pass\n\nclass NonEmptyString(String, NonEmpty):\n pass\n\nfrom inspect import signature\nfrom functools import wraps\n\ndef isvalidator(item):\n return isinstance(item, type) and issubclass(item, Validator)\n\ndef validated(func):\n sig = signature(func)\n\n # Gather the function annotations\n annotations = { name:val for name, val in func.__annotations__.items()\n if isvalidator(val) }\n\n # Get the return annotation (if any)\n retcheck = annotations.pop('return', None)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n # Enforce return check (if any)\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n\n return wrapper\n\ndef enforce(**annotations):\n retcheck = annotations.pop('return_', None)\n\n def decorate(func):\n sig = signature(func)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n return wrapper\n return decorate\n", "num_file": 5, "num_lines": 361, "programming_language": "Python"} {"class_name": "stock3", "id": "./MultiFileTest/Python/stock3.py", "original_code": "# ./stock3/reader.py\n# reader.py\n\nimport csv\nimport logging\n\nlog = logging.getLogger(__name__)\n\ndef convert_csv(lines, converter, *, headers=None):\n rows = csv.reader(lines)\n if headers is None:\n headers = next(rows)\n\n records = []\n for rowno, row in enumerate(rows, start=1):\n try:\n records.append(converter(headers, row))\n except ValueError as e:\n log.warning('Row %s: Bad row: %s', rowno, row)\n log.debug('Row %s: Reason: %s', rowno, row)\n return records\n\ndef csv_as_dicts(lines, types, *, headers=None):\n return convert_csv(lines, \n lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) })\n\ndef csv_as_instances(lines, cls, *, headers=None):\n return convert_csv(lines,\n lambda headers, row: cls.from_row(row))\n\ndef read_csv_as_dicts(filename, types, *, headers=None):\n '''\n Read CSV data into a list of dictionaries with optional type conversion\n '''\n with open(filename) as file:\n return csv_as_dicts(file, types, headers=headers)\n\ndef read_csv_as_instances(filename, cls, *, headers=None):\n '''\n Read CSV data into a list of instances\n '''\n with open(filename) as file:\n return csv_as_instances(file, cls, headers=headers)\n\n\n\n# ./stock3/stock.py\n# stock.py\n\nfrom structure import Structure\nfrom validate import String, PositiveInteger, PositiveFloat\n\nclass Stock(Structure):\n name = String('name')\n shares = PositiveInteger('shares')\n price = PositiveFloat('price')\n\n @property\n def cost(self):\n return self.shares * self.price\n\n def sell(self, nshares):\n self.shares -= nshares\n\n\n# ./stock3/structure.py\n# structure.py\n\nfrom validate import Validator, validated\nfrom collections import ChainMap\n\nclass StructureMeta(type):\n @classmethod\n def __prepare__(meta, clsname, bases):\n return ChainMap({}, Validator.validators)\n \n @staticmethod\n def __new__(meta, name, bases, methods):\n methods = methods.maps[0]\n return super().__new__(meta, name, bases, methods)\n\nclass Structure(metaclass=StructureMeta):\n _fields = ()\n _types = ()\n\n def __setattr__(self, name, value):\n if name.startswith('_') or name in self._fields:\n super().__setattr__(name, value)\n else:\n raise AttributeError('No attribute %s' % name)\n\n def __repr__(self):\n return '%s(%s)' % (type(self).__name__,\n ', '.join(repr(getattr(self, name)) for name in self._fields))\n\n def __iter__(self):\n for name in self._fields:\n yield getattr(self, name)\n\n def __eq__(self, other):\n return isinstance(other, type(self)) and tuple(self) == tuple(other)\n\n @classmethod\n def from_row(cls, row):\n rowdata = [ func(val) for func, val in zip(cls._types, row) ]\n return cls(*rowdata)\n\n\n @classmethod\n def create_init(cls):\n '''\n Create an __init__ method from _fields\n '''\n args = ','.join(cls._fields)\n code = f'def __init__(self, {args}):\\n'\n for name in cls._fields:\n code += f' self.{name} = {name}\\n'\n locs = { }\n exec(code, locs)\n cls.__init__ = locs['__init__']\n\n @classmethod\n def __init_subclass__(cls):\n # Apply the validated decorator to subclasses\n validate_attributes(cls)\n\ndef validate_attributes(cls):\n '''\n Class decorator that scans a class definition for Validators\n and builds a _fields variable that captures their definition order.\n '''\n validators = []\n for name, val in vars(cls).items():\n if isinstance(val, Validator):\n validators.append(val)\n\n # Apply validated decorator to any callable with annotations\n elif callable(val) and val.__annotations__:\n setattr(cls, name, validated(val))\n\n # Collect all of the field names\n cls._fields = tuple([v.name for v in validators])\n\n # Collect type conversions. The lambda x:x is an identity\n # function that's used in case no expected_type is found.\n cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)\n for v in validators ])\n\n # Create the __init__ method\n if cls._fields:\n cls.create_init()\n\n \n return cls\n\ndef typed_structure(clsname, **validators):\n cls = type(clsname, (Structure,), validators)\n return cls\n\n\n# ./stock3/validate.py\n# validate.py\n\nclass Validator:\n def __init__(self, name=None):\n self.name = name\n\n def __set_name__(self, cls, name):\n self.name = name\n\n @classmethod\n def check(cls, value):\n return value\n\n def __set__(self, instance, value):\n instance.__dict__[self.name] = self.check(value)\n\n # Collect all derived classes into a dict\n validators = { }\n @classmethod\n def __init_subclass__(cls):\n cls.validators[cls.__name__] = cls\n\nclass Typed(Validator):\n expected_type = object\n @classmethod\n def check(cls, value):\n if not isinstance(value, cls.expected_type):\n raise TypeError(f'expected {cls.expected_type}')\n return super().check(value)\n\n_typed_classes = [\n ('Integer', int),\n ('Float', float),\n ('String', str) ]\n\nglobals().update((name, type(name, (Typed,), {'expected_type':ty}))\n for name, ty in _typed_classes)\n\nclass Positive(Validator):\n @classmethod\n def check(cls, value):\n if value < 0:\n raise ValueError('must be >= 0')\n return super().check(value)\n\nclass NonEmpty(Validator):\n @classmethod\n def check(cls, value):\n if len(value) == 0:\n raise ValueError('must be non-empty')\n return super().check(value)\n\nclass PositiveInteger(Integer, Positive):\n pass\n\nclass PositiveFloat(Float, Positive):\n pass\n\nclass NonEmptyString(String, NonEmpty):\n pass\n\nfrom inspect import signature\nfrom functools import wraps\n\ndef isvalidator(item):\n return isinstance(item, type) and issubclass(item, Validator)\n\ndef validated(func):\n sig = signature(func)\n\n # Gather the function annotations\n annotations = { name:val for name, val in func.__annotations__.items()\n if isvalidator(val) }\n\n # Get the return annotation (if any)\n retcheck = annotations.pop('return', None)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n # Enforce return check (if any)\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n\n return wrapper\n\ndef enforce(**annotations):\n retcheck = annotations.pop('return_', None)\n\n def decorate(func):\n sig = signature(func)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n return wrapper\n return decorate\n", "num_file": 4, "num_lines": 286, "programming_language": "Python"} {"class_name": "stock4", "id": "./MultiFileTest/Python/stock4.py", "original_code": "# ./stock4/structure.py\n# structure.py\n\nfrom validate import Validator, validated\nfrom collections import ChainMap\n\nclass StructureMeta(type):\n @classmethod\n def __prepare__(meta, clsname, bases):\n return ChainMap({}, Validator.validators)\n \n @staticmethod\n def __new__(meta, name, bases, methods):\n methods = methods.maps[0]\n return super().__new__(meta, name, bases, methods)\n\nclass Structure(metaclass=StructureMeta):\n _fields = ()\n _types = ()\n\n def __setattr__(self, name, value):\n if name.startswith('_') or name in self._fields:\n super().__setattr__(name, value)\n else:\n raise AttributeError('No attribute %s' % name)\n\n def __repr__(self):\n return '%s(%s)' % (type(self).__name__,\n ', '.join(repr(getattr(self, name)) for name in self._fields))\n\n def __iter__(self):\n for name in self._fields:\n yield getattr(self, name)\n\n def __eq__(self, other):\n return isinstance(other, type(self)) and tuple(self) == tuple(other)\n\n @classmethod\n def from_row(cls, row):\n rowdata = [ func(val) for func, val in zip(cls._types, row) ]\n return cls(*rowdata)\n\n @classmethod\n def create_init(cls):\n '''\n Create an __init__ method from _fields\n '''\n args = ','.join(cls._fields)\n code = f'def __init__(self, {args}):\\n'\n for name in cls._fields:\n code += f' self.{name} = {name}\\n'\n locs = { }\n exec(code, locs)\n cls.__init__ = locs['__init__']\n\n @classmethod\n def __init_subclass__(cls):\n # Apply the validated decorator to subclasses\n validate_attributes(cls)\n\ndef validate_attributes(cls):\n '''\n Class decorator that scans a class definition for Validators\n and builds a _fields variable that captures their definition order.\n '''\n validators = []\n for name, val in vars(cls).items():\n if isinstance(val, Validator):\n validators.append(val)\n\n # Apply validated decorator to any callable with annotations\n elif callable(val) and val.__annotations__:\n setattr(cls, name, validated(val))\n\n # Collect all of the field names\n cls._fields = tuple([v.name for v in validators])\n\n # Collect type conversions. The lambda x:x is an identity\n # function that's used in case no expected_type is found.\n cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)\n for v in validators ])\n\n # Create the __init__ method\n if cls._fields:\n cls.create_init()\n\n \n return cls\n\ndef typed_structure(clsname, **validators):\n cls = type(clsname, (Structure,), validators)\n return cls\n\n\n# ./stock4/tableformat.py\n# tableformat.py\nfrom abc import ABC, abstractmethod\n\ndef print_table(records, fields, formatter):\n if not isinstance(formatter, TableFormatter):\n raise RuntimeError('Expected a TableFormatter')\n\n formatter.headings(fields)\n for r in records:\n rowdata = [getattr(r, fieldname) for fieldname in fields]\n formatter.row(rowdata)\n\nclass TableFormatter(ABC):\n @abstractmethod\n def headings(self, headers):\n pass\n\n @abstractmethod\n def row(self, rowdata):\n pass\n\nclass TextTableFormatter(TableFormatter):\n def headings(self, headers):\n print(' '.join('%10s' % h for h in headers))\n print(('-'*10 + ' ')*len(headers))\n \n def row(self, rowdata):\n print(' '.join('%10s' % d for d in rowdata))\n\nclass CSVTableFormatter(TableFormatter):\n def headings(self, headers):\n print(','.join(headers))\n\n def row(self, rowdata):\n print(','.join(str(d) for d in rowdata))\n\nclass HTMLTableFormatter(TableFormatter):\n def headings(self, headers):\n print('', end=' ')\n for h in headers:\n print('%s' % h, end=' ')\n print('')\n\n def row(self, rowdata):\n print('', end=' ')\n for d in rowdata:\n print('%s' % d, end=' ')\n print('')\n\nclass ColumnFormatMixin:\n formats = []\n def row(self, rowdata):\n rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)]\n super().row(rowdata)\n\nclass UpperHeadersMixin:\n def headings(self, headers):\n super().headings([h.upper() for h in headers])\n\ndef create_formatter(name, column_formats=None, upper_headers=False):\n if name == 'text':\n formatter_cls = TextTableFormatter\n elif name == 'csv':\n formatter_cls = CSVTableFormatter\n elif name == 'html':\n formatter_cls = HTMLTableFormatter\n else:\n raise RuntimeError('Unknown format %s' % name)\n\n if column_formats:\n class formatter_cls(ColumnFormatMixin, formatter_cls):\n formats = column_formats\n\n if upper_headers:\n class formatter_cls(UpperHeadersMixin, formatter_cls):\n pass\n\n return formatter_cls()\n\n\n\n\n\n\n# ./stock4/ticker.py\n# ticker.py\nfrom structure import Structure\n\nclass Ticker(Structure):\n name = String()\n price = Float()\n date = String()\n time = String()\n change = Float()\n open = Float()\n high = Float()\n low = Float()\n volume = Integer()\n\n\n# ./stock4/validate.py\n# validate.py\n\nclass Validator:\n def __init__(self, name=None):\n self.name = name\n\n def __set_name__(self, cls, name):\n self.name = name\n\n @classmethod\n def check(cls, value):\n return value\n\n def __set__(self, instance, value):\n instance.__dict__[self.name] = self.check(value)\n\n # Collect all derived classes into a dict\n validators = { }\n @classmethod\n def __init_subclass__(cls):\n cls.validators[cls.__name__] = cls\n\nclass Typed(Validator):\n expected_type = object\n @classmethod\n def check(cls, value):\n if not isinstance(value, cls.expected_type):\n raise TypeError(f'expected {cls.expected_type}')\n return super().check(value)\n\n_typed_classes = [\n ('Integer', int),\n ('Float', float),\n ('String', str) ]\n\nglobals().update((name, type(name, (Typed,), {'expected_type':ty}))\n for name, ty in _typed_classes)\n\nclass Positive(Validator):\n @classmethod\n def check(cls, value):\n if value < 0:\n raise ValueError('must be >= 0')\n return super().check(value)\n\nclass NonEmpty(Validator):\n @classmethod\n def check(cls, value):\n if len(value) == 0:\n raise ValueError('must be non-empty')\n return super().check(value)\n\nclass PositiveInteger(Integer, Positive):\n pass\n\nclass PositiveFloat(Float, Positive):\n pass\n\nclass NonEmptyString(String, NonEmpty):\n pass\n\nfrom inspect import signature\nfrom functools import wraps\n\ndef isvalidator(item):\n return isinstance(item, type) and issubclass(item, Validator)\n\ndef validated(func):\n sig = signature(func)\n\n # Gather the function annotations\n annotations = { name:val for name, val in func.__annotations__.items()\n if isvalidator(val) }\n\n # Get the return annotation (if any)\n retcheck = annotations.pop('return', None)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n # Enforce return check (if any)\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n\n return wrapper\n\ndef enforce(**annotations):\n retcheck = annotations.pop('return_', None)\n\n def decorate(func):\n sig = signature(func)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n return wrapper\n return decorate\n\n \n", "num_file": 4, "num_lines": 323, "programming_language": "Python"} {"class_name": "structly", "id": "./MultiFileTest/Python/structly.py", "original_code": "# ./structly/stock.py\n# stock.py\n\nfrom structly.structure import Structure\n\nclass Stock(Structure):\n name = String()\n shares = PositiveInteger()\n price = PositiveFloat()\n \n @property\n def cost(self):\n return self.shares * self.price\n\n def sell(self, nshares: PositiveInteger):\n self.shares -= nshares\n\n\n\n# ./structly/structly/__init__.py\n\n\n# ./structly/structly/reader.py\n# reader.py\n\nimport csv\nimport logging\n\nlog = logging.getLogger(__name__)\n\ndef convert_csv(lines, converter, *, headers=None):\n rows = csv.reader(lines)\n if headers is None:\n headers = next(rows)\n\n records = []\n for rowno, row in enumerate(rows, start=1):\n try:\n records.append(converter(headers, row))\n except ValueError as e:\n log.warning('Row %s: Bad row: %s', rowno, row)\n log.debug('Row %s: Reason: %s', rowno, row)\n return records\n\ndef csv_as_dicts(lines, types, *, headers=None):\n return convert_csv(lines, \n lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) })\n\ndef csv_as_instances(lines, cls, *, headers=None):\n return convert_csv(lines,\n lambda headers, row: cls.from_row(row))\n\ndef read_csv_as_dicts(filename, types, *, headers=None):\n '''\n Read CSV data into a list of dictionaries with optional type conversion\n '''\n with open(filename) as file:\n return csv_as_dicts(file, types, headers=headers)\n\ndef read_csv_as_instances(filename, cls, *, headers=None):\n '''\n Read CSV data into a list of instances\n '''\n with open(filename) as file:\n return csv_as_instances(file, cls, headers=headers)\n\n\n\n# ./structly/structly/structure.py\n# structure.py\n\nfrom structly.validate import Validator, validated\nfrom collections import ChainMap\n\nclass StructureMeta(type):\n @classmethod\n def __prepare__(meta, clsname, bases):\n return ChainMap({}, Validator.validators)\n \n @staticmethod\n def __new__(meta, name, bases, methods):\n methods = methods.maps[0]\n return super().__new__(meta, name, bases, methods)\n\nclass Structure(metaclass=StructureMeta):\n _fields = ()\n _types = ()\n\n def __setattr__(self, name, value):\n if name.startswith('_') or name in self._fields:\n super().__setattr__(name, value)\n else:\n raise AttributeError('No attribute %s' % name)\n\n def __repr__(self):\n return '%s(%s)' % (type(self).__name__,\n ', '.join(repr(getattr(self, name)) for name in self._fields))\n\n def __iter__(self):\n for name in self._fields:\n yield getattr(self, name)\n\n def __eq__(self, other):\n return isinstance(other, type(self)) and tuple(self) == tuple(other)\n\n @classmethod\n def from_row(cls, row):\n rowdata = [ func(val) for func, val in zip(cls._types, row) ]\n return cls(*rowdata)\n\n @classmethod\n def create_init(cls):\n '''\n Create an __init__ method from _fields\n '''\n args = ','.join(cls._fields)\n code = f'def __init__(self, {args}):\\n'\n for name in cls._fields:\n code += f' self.{name} = {name}\\n'\n locs = { }\n exec(code, locs)\n cls.__init__ = locs['__init__']\n\n @classmethod\n def __init_subclass__(cls):\n # Apply the validated decorator to subclasses\n validate_attributes(cls)\n\ndef validate_attributes(cls):\n '''\n Class decorator that scans a class definition for Validators\n and builds a _fields variable that captures their definition order.\n '''\n validators = []\n for name, val in vars(cls).items():\n if isinstance(val, Validator):\n validators.append(val)\n\n # Apply validated decorator to any callable with annotations\n elif callable(val) and val.__annotations__:\n setattr(cls, name, validated(val))\n\n # Collect all of the field names\n cls._fields = tuple([v.name for v in validators])\n\n # Collect type conversions. The lambda x:x is an identity\n # function that's used in case no expected_type is found.\n cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)\n for v in validators ])\n\n # Create the __init__ method\n if cls._fields:\n cls.create_init()\n\n \n return cls\n\ndef typed_structure(clsname, **validators):\n cls = type(clsname, (Structure,), validators)\n return cls\n\n\n# ./structly/structly/tableformat.py\n# tableformat.py\nfrom abc import ABC, abstractmethod\n\ndef print_table(records, fields, formatter):\n if not isinstance(formatter, TableFormatter):\n raise RuntimeError('Expected a TableFormatter')\n\n formatter.headings(fields)\n for r in records:\n rowdata = [getattr(r, fieldname) for fieldname in fields]\n formatter.row(rowdata)\n\nclass TableFormatter(ABC):\n @abstractmethod\n def headings(self, headers):\n pass\n\n @abstractmethod\n def row(self, rowdata):\n pass\n\n\nclass TextTableFormatter(TableFormatter):\n def headings(self, headers):\n print(' '.join('%10s' % h for h in headers))\n print(('-'*10 + ' ')*len(headers))\n \n def row(self, rowdata):\n print(' '.join('%10s' % d for d in rowdata))\n\nclass CSVTableFormatter(TableFormatter):\n def headings(self, headers):\n print(','.join(headers))\n\n def row(self, rowdata):\n print(','.join(str(d) for d in rowdata))\n\nclass HTMLTableFormatter(TableFormatter):\n def headings(self, headers):\n print('', end=' ')\n for h in headers:\n print('%s' % h, end=' ')\n print('')\n\n def row(self, rowdata):\n print('', end=' ')\n for d in rowdata:\n print('%s' % d, end=' ')\n print('')\n\nclass ColumnFormatMixin:\n formats = []\n def row(self, rowdata):\n rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)]\n super().row(rowdata)\n\nclass UpperHeadersMixin:\n def headings(self, headers):\n super().headings([h.upper() for h in headers])\n\ndef create_formatter(name, column_formats=None, upper_headers=False):\n if name == 'text':\n formatter_cls = TextTableFormatter\n elif name == 'csv':\n formatter_cls = CSVTableFormatter\n elif name == 'html':\n formatter_cls = HTMLTableFormatter\n else:\n raise RuntimeError('Unknown format %s' % name)\n\n if column_formats:\n class formatter_cls(ColumnFormatMixin, formatter_cls):\n formats = column_formats\n\n if upper_headers:\n class formatter_cls(UpperHeadersMixin, formatter_cls):\n pass\n\n return formatter_cls()\n\n\n\n\n\n\n# ./structly/structly/validate.py\n# validate.py\n\nclass Validator:\n def __init__(self, name=None):\n self.name = name\n\n def __set_name__(self, cls, name):\n self.name = name\n\n @classmethod\n def check(cls, value):\n return value\n\n def __set__(self, instance, value):\n instance.__dict__[self.name] = self.check(value)\n\n # Collect all derived classes into a dict\n validators = { }\n @classmethod\n def __init_subclass__(cls):\n cls.validators[cls.__name__] = cls\n\nclass Typed(Validator):\n expected_type = object\n @classmethod\n def check(cls, value):\n if not isinstance(value, cls.expected_type):\n raise TypeError(f'expected {cls.expected_type}')\n return super().check(value)\n\n_typed_classes = [\n ('Integer', int),\n ('Float', float),\n ('String', str) ]\n\nglobals().update((name, type(name, (Typed,), {'expected_type':ty}))\n for name, ty in _typed_classes)\n\nclass Positive(Validator):\n @classmethod\n def check(cls, value):\n if value < 0:\n raise ValueError('must be >= 0')\n return super().check(value)\n\nclass NonEmpty(Validator):\n @classmethod\n def check(cls, value):\n if len(value) == 0:\n raise ValueError('must be non-empty')\n return super().check(value)\n\nclass PositiveInteger(Integer, Positive):\n pass\n\nclass PositiveFloat(Float, Positive):\n pass\n\nclass NonEmptyString(String, NonEmpty):\n pass\n\nfrom inspect import signature\nfrom functools import wraps\n\ndef isvalidator(item):\n return isinstance(item, type) and issubclass(item, Validator)\n\ndef validated(func):\n sig = signature(func)\n\n # Gather the function annotations\n annotations = { name:val for name, val in func.__annotations__.items()\n if isvalidator(val) }\n\n # Get the return annotation (if any)\n retcheck = annotations.pop('return', None)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n # Enforce return check (if any)\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n\n return wrapper\n\ndef enforce(**annotations):\n retcheck = annotations.pop('return_', None)\n\n def decorate(func):\n sig = signature(func)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound = sig.bind(*args, **kwargs)\n errors = []\n\n # Enforce argument checks\n for name, validator in annotations.items():\n try:\n validator.check(bound.arguments[name])\n except Exception as e:\n errors.append(f' {name}: {e}')\n\n if errors:\n raise TypeError('Bad Arguments\\n' + '\\n'.join(errors))\n\n result = func(*args, **kwargs)\n\n if retcheck:\n try:\n retcheck.check(result)\n except Exception as e:\n raise TypeError(f'Bad return: {e}') from None\n return result\n return wrapper\n return decorate\n\n", "num_file": 6, "num_lines": 369, "programming_language": "Python"} {"class_name": "svm", "id": "./MultiFileTest/Python/svm.py", "original_code": "# ./svm/__init__.py\n# coding:utf-8\n\n\n# ./svm/base.py\n# coding:utf-8\nimport numpy as np\n\n\nclass BaseEstimator:\n y_required = True\n fit_required = True\n\n def _setup_input(self, X, y=None):\n \"\"\"Ensure inputs to an estimator are in the expected format.\n\n Ensures X and y are stored as numpy ndarrays by converting from an\n array-like object if necessary. Enables estimators to define whether\n they require a set of y target values or not with y_required, e.g.\n kmeans clustering requires no target labels and is fit against only X.\n\n Parameters\n ----------\n X : array-like\n Feature dataset.\n y : array-like\n Target values. By default is required, but if y_required = false\n then may be omitted.\n \"\"\"\n if not isinstance(X, np.ndarray):\n X = np.array(X)\n\n if X.size == 0:\n raise ValueError(\"Got an empty matrix.\")\n\n if X.ndim == 1:\n self.n_samples, self.n_features = 1, X.shape\n else:\n self.n_samples, self.n_features = X.shape[0], np.prod(X.shape[1:])\n\n self.X = X\n\n if self.y_required:\n if y is None:\n raise ValueError(\"Missed required argument y\")\n\n if not isinstance(y, np.ndarray):\n y = np.array(y)\n\n if y.size == 0:\n raise ValueError(\"The targets array must be no-empty.\")\n\n self.y = y\n\n def fit(self, X, y=None):\n self._setup_input(X, y)\n\n def predict(self, X=None):\n if not isinstance(X, np.ndarray):\n X = np.array(X)\n\n if self.X is not None or not self.fit_required:\n return self._predict(X)\n else:\n raise ValueError(\"You must call `fit` before `predict`\")\n\n def _predict(self, X=None):\n raise NotImplementedError()\n\n\n# ./svm/kernerls.py\n# coding:utf-8\nimport numpy as np\nimport scipy.spatial.distance as dist\n\n\nclass Linear(object):\n def __call__(self, x, y):\n return np.dot(x, y.T)\n\n def __repr__(self):\n return \"Linear kernel\"\n\n\nclass Poly(object):\n def __init__(self, degree=2):\n self.degree = degree\n\n def __call__(self, x, y):\n return np.dot(x, y.T) ** self.degree\n\n def __repr__(self):\n return \"Poly kernel\"\n\n\nclass RBF(object):\n def __init__(self, gamma=0.1):\n self.gamma = gamma\n\n def __call__(self, x, y):\n x = np.atleast_2d(x)\n y = np.atleast_2d(y)\n return np.exp(-self.gamma * dist.cdist(x, y) ** 2).flatten()\n\n def __repr__(self):\n return \"RBF kernel\"\n\n\n# ./svm/svm.py\n# coding:utf-8\nimport logging\n\nimport numpy as np\n\nfrom base import BaseEstimator\nfrom kernerls import Linear\n\nnp.random.seed(9999)\n\n\"\"\"\nReferences:\nThe Simplified SMO Algorithm http://cs229.stanford.edu/materials/smo.pdf\n\"\"\"\n\n\nclass SVM(BaseEstimator):\n def __init__(self, C=1.0, kernel=None, tol=1e-3, max_iter=100):\n \"\"\"Support vector machines implementation using simplified SMO optimization.\n\n Parameters\n ----------\n C : float, default 1.0\n kernel : Kernel object\n tol : float , default 1e-3\n max_iter : int, default 100\n \"\"\"\n self.C = C\n self.tol = tol\n self.max_iter = max_iter\n if kernel is None:\n self.kernel = Linear()\n else:\n self.kernel = kernel\n\n self.b = 0\n self.alpha = None\n self.K = None\n\n def fit(self, X, y=None):\n self._setup_input(X, y)\n self.K = np.zeros((self.n_samples, self.n_samples))\n for i in range(self.n_samples):\n self.K[:, i] = self.kernel(self.X, self.X[i, :])\n self.alpha = np.zeros(self.n_samples)\n self.sv_idx = np.arange(0, self.n_samples)\n return self._train()\n\n def _train(self):\n iters = 0\n while iters < self.max_iter:\n iters += 1\n alpha_prev = np.copy(self.alpha)\n\n for j in range(self.n_samples):\n # Pick random i\n i = self.random_index(j)\n\n eta = 2.0 * self.K[i, j] - self.K[i, i] - self.K[j, j]\n if eta >= 0:\n continue\n L, H = self._find_bounds(i, j)\n\n # Error for current examples\n e_i, e_j = self._error(i), self._error(j)\n\n # Save old alphas\n alpha_io, alpha_jo = self.alpha[i], self.alpha[j]\n\n # Update alpha\n self.alpha[j] -= (self.y[j] * (e_i - e_j)) / eta\n self.alpha[j] = self.clip(self.alpha[j], H, L)\n\n self.alpha[i] = self.alpha[i] + self.y[i] * self.y[j] * (alpha_jo - self.alpha[j])\n\n # Find intercept\n b1 = (\n self.b - e_i - self.y[i] * (self.alpha[i] - alpha_io) * self.K[i, i]\n - self.y[j] * (self.alpha[j] - alpha_jo) * self.K[i, j]\n )\n b2 = (\n self.b - e_j - self.y[j] * (self.alpha[j] - alpha_jo) * self.K[j, j]\n - self.y[i] * (self.alpha[i] - alpha_io) * self.K[i, j]\n )\n if 0 < self.alpha[i] < self.C:\n self.b = b1\n elif 0 < self.alpha[j] < self.C:\n self.b = b2\n else:\n self.b = 0.5 * (b1 + b2)\n\n # Check convergence\n diff = np.linalg.norm(self.alpha - alpha_prev)\n if diff < self.tol:\n break\n logging.info(\"Convergence has reached after %s.\" % iters)\n\n # Save support vectors index\n self.sv_idx = np.where(self.alpha > 0)[0]\n\n def _predict(self, X=None):\n n = X.shape[0]\n result = np.zeros(n)\n for i in range(n):\n result[i] = np.sign(self._predict_row(X[i, :]))\n return result\n\n def _predict_row(self, X):\n k_v = self.kernel(self.X[self.sv_idx], X)\n return np.dot((self.alpha[self.sv_idx] * self.y[self.sv_idx]).T, k_v.T) + self.b\n\n def clip(self, alpha, H, L):\n if alpha > H:\n alpha = H\n if alpha < L:\n alpha = L\n return alpha\n\n def _error(self, i):\n \"\"\"Error for single example.\"\"\"\n return self._predict_row(self.X[i]) - self.y[i]\n\n def _find_bounds(self, i, j):\n \"\"\"Find L and H such that L <= alpha <= H.\n Also, alpha must satisfy the constraint 0 <= αlpha <= C.\n \"\"\"\n if self.y[i] != self.y[j]:\n L = max(0, self.alpha[j] - self.alpha[i])\n H = min(self.C, self.C - self.alpha[i] + self.alpha[j])\n else:\n L = max(0, self.alpha[i] + self.alpha[j] - self.C)\n H = min(self.C, self.alpha[i] + self.alpha[j])\n return L, H\n\n def random_index(self, z):\n i = z\n while i == z:\n i = np.random.randint(0, self.n_samples)\n return i\n", "num_file": 4, "num_lines": 238, "programming_language": "Python"} {"class_name": "thefuzz", "id": "./MultiFileTest/Python/thefuzz.py", "original_code": "# ./thefuzz/__init__.py\n__version__ = '0.22.1'\n\n\n# ./thefuzz/fuzz.py\n#!/usr/bin/env python\n\nfrom rapidfuzz.fuzz import (\n ratio as _ratio,\n partial_ratio as _partial_ratio,\n token_set_ratio as _token_set_ratio,\n token_sort_ratio as _token_sort_ratio,\n partial_token_set_ratio as _partial_token_set_ratio,\n partial_token_sort_ratio as _partial_token_sort_ratio,\n WRatio as _WRatio,\n QRatio as _QRatio,\n)\n\nimport utils\n\n###########################\n# Basic Scoring Functions #\n###########################\n\n\ndef _rapidfuzz_scorer(scorer, s1, s2, force_ascii, full_process):\n \"\"\"\n wrapper around rapidfuzz function to be compatible with the API of thefuzz\n \"\"\"\n if full_process:\n if s1 is None or s2 is None:\n return 0\n\n s1 = utils.full_process(s1, force_ascii=force_ascii)\n s2 = utils.full_process(s2, force_ascii=force_ascii)\n\n return int(round(scorer(s1, s2)))\n\n\ndef ratio(s1, s2):\n return _rapidfuzz_scorer(_ratio, s1, s2, False, False)\n\n\ndef partial_ratio(s1, s2):\n \"\"\"\n Return the ratio of the most similar substring\n as a number between 0 and 100.\n \"\"\"\n return _rapidfuzz_scorer(_partial_ratio, s1, s2, False, False)\n\n\n##############################\n# Advanced Scoring Functions #\n##############################\n\n# Sorted Token\n# find all alphanumeric tokens in the string\n# sort those tokens and take ratio of resulting joined strings\n# controls for unordered string elements\ndef token_sort_ratio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Return a measure of the sequences' similarity between 0 and 100\n but sorting the token before comparing.\n \"\"\"\n return _rapidfuzz_scorer(_token_sort_ratio, s1, s2, force_ascii, full_process)\n\n\ndef partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Return the ratio of the most similar substring as a number between\n 0 and 100 but sorting the token before comparing.\n \"\"\"\n return _rapidfuzz_scorer(\n _partial_token_sort_ratio, s1, s2, force_ascii, full_process\n )\n\n\ndef token_set_ratio(s1, s2, force_ascii=True, full_process=True):\n return _rapidfuzz_scorer(_token_set_ratio, s1, s2, force_ascii, full_process)\n\n\ndef partial_token_set_ratio(s1, s2, force_ascii=True, full_process=True):\n return _rapidfuzz_scorer(\n _partial_token_set_ratio, s1, s2, force_ascii, full_process\n )\n\n\n###################\n# Combination API #\n###################\n\n# q is for quick\ndef QRatio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Quick ratio comparison between two strings.\n\n Runs full_process from utils on both strings\n Short circuits if either of the strings is empty after processing.\n\n :param s1:\n :param s2:\n :param force_ascii: Allow only ASCII characters (Default: True)\n :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)\n :return: similarity ratio\n \"\"\"\n return _rapidfuzz_scorer(_QRatio, s1, s2, force_ascii, full_process)\n\n\ndef UQRatio(s1, s2, full_process=True):\n \"\"\"\n Unicode quick ratio\n\n Calls QRatio with force_ascii set to False\n\n :param s1:\n :param s2:\n :return: similarity ratio\n \"\"\"\n return QRatio(s1, s2, force_ascii=False, full_process=full_process)\n\n\n# w is for weighted\ndef WRatio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Return a measure of the sequences' similarity between 0 and 100, using different algorithms.\n\n **Steps in the order they occur**\n\n #. Run full_process from utils on both strings\n #. Short circuit if this makes either string empty\n #. Take the ratio of the two processed strings (fuzz.ratio)\n #. Run checks to compare the length of the strings\n * If one of the strings is more than 1.5 times as long as the other\n use partial_ratio comparisons - scale partial results by 0.9\n (this makes sure only full results can return 100)\n * If one of the strings is over 8 times as long as the other\n instead scale by 0.6\n\n #. Run the other ratio functions\n * if using partial ratio functions call partial_ratio,\n partial_token_sort_ratio and partial_token_set_ratio\n scale all of these by the ratio based on length\n * otherwise call token_sort_ratio and token_set_ratio\n * all token based comparisons are scaled by 0.95\n (on top of any partial scalars)\n\n #. Take the highest value from these results\n round it and return it as an integer.\n\n :param s1:\n :param s2:\n :param force_ascii: Allow only ascii characters\n :type force_ascii: bool\n :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)\n :return:\n \"\"\"\n return _rapidfuzz_scorer(_WRatio, s1, s2, force_ascii, full_process)\n\n\ndef UWRatio(s1, s2, full_process=True):\n \"\"\"\n Return a measure of the sequences' similarity between 0 and 100,\n using different algorithms. Same as WRatio but preserving unicode.\n \"\"\"\n return WRatio(s1, s2, force_ascii=False, full_process=full_process)\n\n\n# ./thefuzz/utils.py\nfrom rapidfuzz.utils import default_process as _default_process\n\ntranslation_table = {i: None for i in range(128, 256)} # ascii dammit!\n\n\ndef ascii_only(s):\n return s.translate(translation_table)\n\n\ndef full_process(s, force_ascii=False):\n \"\"\"\n Process string by\n -- removing all but letters and numbers\n -- trim whitespace\n -- force to lower case\n if force_ascii == True, force convert to ascii\n \"\"\"\n\n if force_ascii:\n s = ascii_only(str(s))\n\n return _default_process(s)\n", "num_file": 3, "num_lines": 183, "programming_language": "Python"} {"class_name": "tree", "id": "./MultiFileTest/Python/tree.py", "original_code": "# ./tree/base.py\n# coding:utf-8\nimport numpy as np\nfrom scipy import stats\n\n\ndef f_entropy(p):\n # Convert values to probability\n p = np.bincount(p) / float(p.shape[0])\n\n ep = stats.entropy(p)\n if ep == -float(\"inf\"):\n return 0.0\n return ep\n\n\ndef information_gain(y, splits):\n splits_entropy = sum([f_entropy(split) * (float(split.shape[0]) / y.shape[0]) for split in splits])\n return f_entropy(y) - splits_entropy\n\n\ndef mse_criterion(y, splits):\n y_mean = np.mean(y)\n return -sum([np.sum((split - y_mean) ** 2) * (float(split.shape[0]) / y.shape[0]) for split in splits])\n\n\ndef xgb_criterion(y, left, right, loss):\n left = loss.gain(left[\"actual\"], left[\"y_pred\"])\n right = loss.gain(right[\"actual\"], right[\"y_pred\"])\n initial = loss.gain(y[\"actual\"], y[\"y_pred\"])\n gain = left + right - initial\n return gain\n\n\ndef get_split_mask(X, column, value):\n left_mask = X[:, column] < value\n right_mask = X[:, column] >= value\n return left_mask, right_mask\n\n\ndef split(X, y, value):\n left_mask = X < value\n right_mask = X >= value\n return y[left_mask], y[right_mask]\n\n\ndef split_dataset(X, target, column, value, return_X=True):\n left_mask, right_mask = get_split_mask(X, column, value)\n\n left, right = {}, {}\n for key in target.keys():\n left[key] = target[key][left_mask]\n right[key] = target[key][right_mask]\n\n if return_X:\n left_X, right_X = X[left_mask], X[right_mask]\n return left_X, right_X, left, right\n else:\n return left, right\n\n\n# ./tree/tree.py\n# coding:utf-8\nimport random\n\nimport numpy as np\nfrom scipy import stats\n\nfrom base import split, split_dataset, xgb_criterion\n\nrandom.seed(111)\n\n\nclass Tree(object):\n \"\"\"Recursive implementation of decision tree.\"\"\"\n\n def __init__(self, regression=False, criterion=None, n_classes=None):\n self.regression = regression\n self.impurity = None\n self.threshold = None\n self.column_index = None\n self.outcome = None\n self.criterion = criterion\n self.loss = None\n self.n_classes = n_classes # Only for classification\n\n self.left_child = None\n self.right_child = None\n\n @property\n def is_terminal(self):\n return not bool(self.left_child and self.right_child)\n\n def _find_splits(self, X):\n \"\"\"Find all possible split values.\"\"\"\n split_values = set()\n\n # Get unique values in a sorted order\n x_unique = list(np.unique(X))\n for i in range(1, len(x_unique)):\n # Find a point between two values\n average = (x_unique[i - 1] + x_unique[i]) / 2.0\n split_values.add(average)\n\n return list(split_values)\n\n def _find_best_split(self, X, target, n_features):\n \"\"\"Find best feature and value for a split. Greedy algorithm.\"\"\"\n\n # Sample random subset of features\n subset = random.sample(list(range(0, X.shape[1])), n_features)\n max_gain, max_col, max_val = None, None, None\n\n for column in subset:\n split_values = self._find_splits(X[:, column])\n for value in split_values:\n if self.loss is None:\n # Random forest\n splits = split(X[:, column], target[\"y\"], value)\n gain = self.criterion(target[\"y\"], splits)\n else:\n # Gradient boosting\n left, right = split_dataset(X, target, column, value, return_X=False)\n gain = xgb_criterion(target, left, right, self.loss)\n\n if (max_gain is None) or (gain > max_gain):\n max_col, max_val, max_gain = column, value, gain\n return max_col, max_val, max_gain\n\n def _train(self, X, target, max_features=None, min_samples_split=10, max_depth=None, minimum_gain=0.01):\n try:\n # Exit from recursion using assert syntax\n assert X.shape[0] > min_samples_split\n assert max_depth > 0\n\n if max_features is None:\n max_features = X.shape[1]\n\n column, value, gain = self._find_best_split(X, target, max_features)\n assert gain is not None\n if self.regression:\n assert gain != 0\n else:\n assert gain > minimum_gain\n\n self.column_index = column\n self.threshold = value\n self.impurity = gain\n\n # Split dataset\n left_X, right_X, left_target, right_target = split_dataset(X, target, column, value)\n\n # Grow left and right child\n self.left_child = Tree(self.regression, self.criterion, self.n_classes)\n self.left_child._train(\n left_X, left_target, max_features, min_samples_split, max_depth - 1, minimum_gain\n )\n\n self.right_child = Tree(self.regression, self.criterion, self.n_classes)\n self.right_child._train(\n right_X, right_target, max_features, min_samples_split, max_depth - 1, minimum_gain\n )\n except AssertionError:\n self._calculate_leaf_value(target)\n\n def train(self, X, target, max_features=None, min_samples_split=10, max_depth=None, minimum_gain=0.01, loss=None):\n \"\"\"Build a decision tree from training set.\n\n Parameters\n ----------\n\n X : array-like\n Feature dataset.\n target : dictionary or array-like\n Target values.\n max_features : int or None\n The number of features to consider when looking for the best split.\n min_samples_split : int\n The minimum number of samples required to split an internal node.\n max_depth : int\n Maximum depth of the tree.\n minimum_gain : float, default 0.01\n Minimum gain required for splitting.\n loss : function, default None\n Loss function for gradient boosting.\n \"\"\"\n\n if not isinstance(target, dict):\n target = {\"y\": target}\n\n # Loss for gradient boosting\n if loss is not None:\n self.loss = loss\n\n if not self.regression:\n self.n_classes = len(np.unique(target['y']))\n\n self._train(X, target, max_features=max_features, min_samples_split=min_samples_split,\n max_depth=max_depth, minimum_gain=minimum_gain)\n\n\n def _calculate_leaf_value(self, targets):\n \"\"\"Find optimal value for leaf.\"\"\"\n if self.loss is not None:\n # Gradient boosting\n self.outcome = self.loss.approximate(targets[\"actual\"], targets[\"y_pred\"])\n else:\n # Random Forest\n if self.regression:\n # Mean value for regression task\n self.outcome = np.mean(targets[\"y\"])\n else:\n # Probability for classification task\n self.outcome = np.bincount(targets[\"y\"], minlength=self.n_classes) / targets[\"y\"].shape[0]\n\n def predict_row(self, row):\n \"\"\"Predict single row.\"\"\"\n if not self.is_terminal:\n if row[self.column_index] < self.threshold:\n return self.left_child.predict_row(row)\n else:\n return self.right_child.predict_row(row)\n return self.outcome\n\n def predict(self, X):\n result = np.zeros(X.shape[0])\n for i in range(X.shape[0]):\n result[i] = self.predict_row(X[i, :])\n return result\n", "num_file": 2, "num_lines": 225, "programming_language": "Python"} {"class_name": "uno", "id": "./MultiFileTest/Python/uno.py", "original_code": "# ./uno/__init__.py\nfrom uno.dealer import UnoDealer as Dealer\nfrom uno.judger import UnoJudger as Judger\nfrom uno.player import UnoPlayer as Player\nfrom uno.round import UnoRound as Round\nfrom uno.game import UnoGame as Game\n\n\n\n# ./uno/card.py\nfrom termcolor import colored\n\nclass UnoCard:\n\n info = {'type': ['number', 'action', 'wild'],\n 'color': ['r', 'g', 'b', 'y'],\n 'trait': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'skip', 'reverse', 'draw_2', 'wild', 'wild_draw_4']\n }\n\n def __init__(self, card_type, color, trait):\n ''' Initialize the class of UnoCard\n\n Args:\n card_type (str): The type of card\n color (str): The color of card\n trait (str): The trait of card\n '''\n self.type = card_type\n self.color = color\n self.trait = trait\n self.str = self.get_str()\n\n def get_str(self):\n ''' Get the string representation of card\n\n Return:\n (str): The string of card's color and trait\n '''\n return self.color + '-' + self.trait\n\n\n @staticmethod\n def print_cards(cards, wild_color=False):\n ''' Print out card in a nice form\n\n Args:\n card (str or list): The string form or a list of a UNO card\n wild_color (boolean): True if assign collor to wild cards\n '''\n if isinstance(cards, str):\n cards = [cards]\n for i, card in enumerate(cards):\n if card == 'draw':\n trait = 'Draw'\n else:\n color, trait = card.split('-')\n if trait == 'skip':\n trait = 'Skip'\n elif trait == 'reverse':\n trait = 'Reverse'\n elif trait == 'draw_2':\n trait = 'Draw-2'\n elif trait == 'wild':\n trait = 'Wild'\n elif trait == 'wild_draw_4':\n trait = 'Wild-Draw-4'\n\n if trait == 'Draw' or (trait[:4] == 'Wild' and not wild_color):\n print(trait, end='')\n elif color == 'r':\n print(colored(trait, 'red'), end='')\n elif color == 'g':\n print(colored(trait, 'green'), end='')\n elif color == 'b':\n print(colored(trait, 'blue'), end='')\n elif color == 'y':\n print(colored(trait, 'yellow'), end='')\n\n if i < len(cards) - 1:\n print(', ', end='')\n\n\n# ./uno/dealer.py\n\nfrom utils import init_deck\n\n\nclass UnoDealer:\n ''' Initialize a uno dealer class\n '''\n def __init__(self, np_random):\n self.np_random = np_random\n self.deck = init_deck()\n self.shuffle()\n\n def shuffle(self):\n ''' Shuffle the deck\n '''\n self.np_random.shuffle(self.deck)\n\n def deal_cards(self, player, num):\n ''' Deal some cards from deck to one player\n\n Args:\n player (object): The object of DoudizhuPlayer\n num (int): The number of cards to be dealed\n '''\n for _ in range(num):\n player.hand.append(self.deck.pop())\n\n def flip_top_card(self):\n ''' Flip top card when a new game starts\n\n Returns:\n (object): The object of UnoCard at the top of the deck\n '''\n top_card = self.deck.pop()\n while top_card.trait == 'wild_draw_4':\n self.deck.append(top_card)\n self.shuffle()\n top_card = self.deck.pop()\n return top_card\n\n\n# ./uno/game.py\nfrom copy import deepcopy\nimport numpy as np\n\nfrom uno import Dealer\nfrom uno import Player\nfrom uno import Round\n\n\nclass UnoGame:\n\n def __init__(self, allow_step_back=False, num_players=2):\n self.allow_step_back = allow_step_back\n self.np_random = np.random.RandomState()\n self.num_players = num_players\n self.payoffs = [0 for _ in range(self.num_players)]\n\n def configure(self, game_config):\n ''' Specifiy some game specific parameters, such as number of players\n '''\n self.num_players = game_config['game_num_players']\n\n def init_game(self):\n ''' Initialize players and state\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state in one game\n (int): Current player's id\n '''\n # Initalize payoffs\n self.payoffs = [0 for _ in range(self.num_players)]\n\n # Initialize a dealer that can deal cards\n self.dealer = Dealer(self.np_random)\n\n # Initialize four players to play the game\n self.players = [Player(i, self.np_random) for i in range(self.num_players)]\n\n # Deal 7 cards to each player to prepare for the game\n for player in self.players:\n self.dealer.deal_cards(player, 7)\n\n # Initialize a Round\n self.round = Round(self.dealer, self.num_players, self.np_random)\n\n # flip and perfrom top card\n top_card = self.round.flip_top_card()\n self.round.perform_top_card(self.players, top_card)\n\n # Save the hisory for stepping back to the last state.\n self.history = []\n\n player_id = self.round.current_player\n state = self.get_state(player_id)\n return state, player_id\n\n def step(self, action):\n ''' Get the next state\n\n Args:\n action (str): A specific action\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next plater's id\n '''\n\n if self.allow_step_back:\n # First snapshot the current state\n his_dealer = deepcopy(self.dealer)\n his_round = deepcopy(self.round)\n his_players = deepcopy(self.players)\n self.history.append((his_dealer, his_players, his_round))\n\n self.round.proceed_round(self.players, action)\n player_id = self.round.current_player\n state = self.get_state(player_id)\n return state, player_id\n\n def step_back(self):\n ''' Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n '''\n if not self.history:\n return False\n self.dealer, self.players, self.round = self.history.pop()\n return True\n\n def get_state(self, player_id):\n ''' Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n (dict): The state of the player\n '''\n state = self.round.get_state(self.players, player_id)\n state['num_players'] = self.get_num_players()\n state['current_player'] = self.round.current_player\n return state\n\n def get_payoffs(self):\n ''' Return the payoffs of the game\n\n Returns:\n (list): Each entry corresponds to the payoff of one player\n '''\n winner = self.round.winner\n if winner is not None and len(winner) == 1:\n self.payoffs[winner[0]] = 1\n self.payoffs[1 - winner[0]] = -1\n return self.payoffs\n\n def get_legal_actions(self):\n ''' Return the legal actions for current player\n\n Returns:\n (list): A list of legal actions\n '''\n\n return self.round.get_legal_actions(self.players, self.round.current_player)\n\n def get_num_players(self):\n ''' Return the number of players in Limit Texas Hold'em\n\n Returns:\n (int): The number of players in the game\n '''\n return self.num_players\n\n @staticmethod\n def get_num_actions():\n ''' Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 61 actions\n '''\n return 61\n\n def get_player_id(self):\n ''' Return the current player's id\n\n Returns:\n (int): current player's id\n '''\n return self.round.current_player\n\n def is_over(self):\n ''' Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n '''\n return self.round.is_over\n\n\n# ./uno/judger.py\n\nclass UnoJudger:\n\n @staticmethod\n def judge_winner(players, np_random):\n ''' Judge the winner of the game\n\n Args:\n players (list): The list of players who play the game\n\n Returns:\n (list): The player id of the winner\n '''\n count_1 = len(players[0].hand)\n count_2 = len(players[1].hand)\n if count_1 == count_2:\n return [0, 1]\n if count_1 < count_2:\n return [0]\n return [1]\n\n\n# ./uno/player.py\n\nclass UnoPlayer:\n\n def __init__(self, player_id, np_random):\n ''' Initilize a player.\n\n Args:\n player_id (int): The id of the player\n '''\n self.np_random = np_random\n self.player_id = player_id\n self.hand = []\n self.stack = []\n\n def get_player_id(self):\n ''' Return the id of the player\n '''\n\n return self.player_id\n\n\n# ./uno/round.py\nfrom card import UnoCard\nfrom utils import cards2list, WILD, WILD_DRAW_4\n\n\nclass UnoRound:\n\n def __init__(self, dealer, num_players, np_random):\n ''' Initialize the round class\n\n Args:\n dealer (object): the object of UnoDealer\n num_players (int): the number of players in game\n '''\n self.np_random = np_random\n self.dealer = dealer\n self.target = None\n self.current_player = 0\n self.num_players = num_players\n self.direction = 1\n self.played_cards = []\n self.is_over = False\n self.winner = None\n\n def flip_top_card(self):\n ''' Flip the top card of the card pile\n\n Returns:\n (object of UnoCard): the top card in game\n\n '''\n top = self.dealer.flip_top_card()\n if top.trait == 'wild':\n top.color = self.np_random.choice(UnoCard.info['color'])\n self.target = top\n self.played_cards.append(top)\n return top\n\n def perform_top_card(self, players, top_card):\n ''' Perform the top card\n\n Args:\n players (list): list of UnoPlayer objects\n top_card (object): object of UnoCard\n '''\n if top_card.trait == 'skip':\n self.current_player = 1\n elif top_card.trait == 'reverse':\n self.direction = -1\n self.current_player = (0 + self.direction) % self.num_players\n elif top_card.trait == 'draw_2':\n player = players[self.current_player]\n self.dealer.deal_cards(player, 2)\n\n def proceed_round(self, players, action):\n ''' Call other Classes' functions to keep one round running\n\n Args:\n player (object): object of UnoPlayer\n action (str): string of legal action\n '''\n if action == 'draw':\n self._perform_draw_action(players)\n return None\n player = players[self.current_player]\n card_info = action.split('-')\n color = card_info[0]\n trait = card_info[1]\n # remove corresponding card\n remove_index = None\n if trait == 'wild' or trait == 'wild_draw_4':\n for index, card in enumerate(player.hand):\n if trait == card.trait:\n card.color = color # update the color of wild card to match the action\n remove_index = index\n break\n else:\n for index, card in enumerate(player.hand):\n if color == card.color and trait == card.trait:\n remove_index = index\n break\n card = player.hand.pop(remove_index)\n if not player.hand:\n self.is_over = True\n self.winner = [self.current_player]\n self.played_cards.append(card)\n\n # perform the number action\n if card.type == 'number':\n self.current_player = (self.current_player + self.direction) % self.num_players\n self.target = card\n\n # perform non-number action\n else:\n self._preform_non_number_action(players, card)\n\n def get_legal_actions(self, players, player_id):\n wild_flag = 0\n wild_draw_4_flag = 0\n legal_actions = []\n wild_4_actions = []\n hand = players[player_id].hand\n target = self.target\n if target.type == 'wild':\n for card in hand:\n if card.type == 'wild':\n if card.trait == 'wild_draw_4':\n if wild_draw_4_flag == 0:\n wild_draw_4_flag = 1\n wild_4_actions.extend(WILD_DRAW_4)\n else:\n if wild_flag == 0:\n wild_flag = 1\n legal_actions.extend(WILD)\n elif card.color == target.color:\n legal_actions.append(card.str)\n\n # target is aciton card or number card\n else:\n for card in hand:\n if card.type == 'wild':\n if card.trait == 'wild_draw_4':\n if wild_draw_4_flag == 0:\n wild_draw_4_flag = 1\n wild_4_actions.extend(WILD_DRAW_4)\n else:\n if wild_flag == 0:\n wild_flag = 1\n legal_actions.extend(WILD)\n elif card.color == target.color or card.trait == target.trait:\n legal_actions.append(card.str)\n if not legal_actions:\n legal_actions = wild_4_actions\n if not legal_actions:\n legal_actions = ['draw']\n return legal_actions\n\n def get_state(self, players, player_id):\n ''' Get player's state\n\n Args:\n players (list): The list of UnoPlayer\n player_id (int): The id of the player\n '''\n state = {}\n player = players[player_id]\n state['hand'] = cards2list(player.hand)\n state['target'] = self.target.str\n state['played_cards'] = cards2list(self.played_cards)\n state['legal_actions'] = self.get_legal_actions(players, player_id)\n state['num_cards'] = []\n for player in players:\n state['num_cards'].append(len(player.hand))\n return state\n\n def replace_deck(self):\n ''' Add cards have been played to deck\n '''\n self.dealer.deck.extend(self.played_cards)\n self.dealer.shuffle()\n self.played_cards = []\n\n def _perform_draw_action(self, players):\n # replace deck if there is no card in draw pile\n if not self.dealer.deck:\n self.replace_deck()\n #self.is_over = True\n #self.winner = UnoJudger.judge_winner(players)\n #return None\n\n card = self.dealer.deck.pop()\n\n # draw a wild card\n if card.type == 'wild':\n card.color = self.np_random.choice(UnoCard.info['color'])\n self.target = card\n self.played_cards.append(card)\n self.current_player = (self.current_player + self.direction) % self.num_players\n\n # draw a card with the same color of target\n elif card.color == self.target.color:\n if card.type == 'number':\n self.target = card\n self.played_cards.append(card)\n self.current_player = (self.current_player + self.direction) % self.num_players\n else:\n self.played_cards.append(card)\n self._preform_non_number_action(players, card)\n\n # draw a card with the diffrent color of target\n else:\n players[self.current_player].hand.append(card)\n self.current_player = (self.current_player + self.direction) % self.num_players\n\n def _preform_non_number_action(self, players, card):\n current = self.current_player\n direction = self.direction\n num_players = self.num_players\n\n # perform reverse card\n if card.trait == 'reverse':\n self.direction = -1 * direction\n\n # perfrom skip card\n elif card.trait == 'skip':\n current = (current + direction) % num_players\n\n # perform draw_2 card\n elif card.trait == 'draw_2':\n if len(self.dealer.deck) < 2:\n self.replace_deck()\n #self.is_over = True\n #self.winner = UnoJudger.judge_winner(players)\n #return None\n self.dealer.deal_cards(players[(current + direction) % num_players], 2)\n current = (current + direction) % num_players\n\n # perfrom wild_draw_4 card\n elif card.trait == 'wild_draw_4':\n if len(self.dealer.deck) < 4:\n self.replace_deck()\n #self.is_over = True\n #self.winner = UnoJudger.judge_winner(players)\n #return None\n self.dealer.deal_cards(players[(current + direction) % num_players], 4)\n current = (current + direction) % num_players\n self.current_player = (current + self.direction) % num_players\n self.target = card\n\n\n# ./uno/utils.py\nimport os\nimport json\nimport numpy as np\nfrom collections import OrderedDict\n\nimport rlcard\n\nfrom uno.card import UnoCard as Card\n\n# Read required docs\nROOT_PATH = rlcard.__path__[0]\n\n# a map of abstract action to its index and a list of abstract action\nwith open(os.path.join(ROOT_PATH, 'games/uno/jsondata/action_space.json'), 'r') as file:\n ACTION_SPACE = json.load(file, object_pairs_hook=OrderedDict)\n ACTION_LIST = list(ACTION_SPACE.keys())\n\n# a map of color to its index\nCOLOR_MAP = {'r': 0, 'g': 1, 'b': 2, 'y': 3}\n\n# a map of trait to its index\nTRAIT_MAP = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,\n '8': 8, '9': 9, 'skip': 10, 'reverse': 11, 'draw_2': 12,\n 'wild': 13, 'wild_draw_4': 14}\n\nWILD = ['r-wild', 'g-wild', 'b-wild', 'y-wild']\n\nWILD_DRAW_4 = ['r-wild_draw_4', 'g-wild_draw_4', 'b-wild_draw_4', 'y-wild_draw_4']\n\n\ndef init_deck():\n ''' Generate uno deck of 108 cards\n '''\n deck = []\n card_info = Card.info\n for color in card_info['color']:\n\n # init number cards\n for num in card_info['trait'][:10]:\n deck.append(Card('number', color, num))\n if num != '0':\n deck.append(Card('number', color, num))\n\n # init action cards\n for action in card_info['trait'][10:13]:\n deck.append(Card('action', color, action))\n deck.append(Card('action', color, action))\n\n # init wild cards\n for wild in card_info['trait'][-2:]:\n deck.append(Card('wild', color, wild))\n return deck\n\n\ndef cards2list(cards):\n ''' Get the corresponding string representation of cards\n\n Args:\n cards (list): list of UnoCards objects\n\n Returns:\n (string): string representation of cards\n '''\n cards_list = []\n for card in cards:\n cards_list.append(card.get_str())\n return cards_list\n\ndef hand2dict(hand):\n ''' Get the corresponding dict representation of hand\n\n Args:\n hand (list): list of string of hand's card\n\n Returns:\n (dict): dict of hand\n '''\n hand_dict = {}\n for card in hand:\n if card not in hand_dict:\n hand_dict[card] = 1\n else:\n hand_dict[card] += 1\n return hand_dict\n\ndef encode_hand(plane, hand):\n ''' Encode hand and represerve it into plane\n\n Args:\n plane (array): 3*4*15 numpy array\n hand (list): list of string of hand's card\n\n Returns:\n (array): 3*4*15 numpy array\n '''\n # plane = np.zeros((3, 4, 15), dtype=int)\n plane[0] = np.ones((4, 15), dtype=int)\n hand = hand2dict(hand)\n for card, count in hand.items():\n card_info = card.split('-')\n color = COLOR_MAP[card_info[0]]\n trait = TRAIT_MAP[card_info[1]]\n if trait >= 13:\n if plane[1][0][trait] == 0:\n for index in range(4):\n plane[0][index][trait] = 0\n plane[1][index][trait] = 1\n else:\n plane[0][color][trait] = 0\n plane[count][color][trait] = 1\n return plane\n\ndef encode_target(plane, target):\n ''' Encode target and represerve it into plane\n\n Args:\n plane (array): 1*4*15 numpy array\n target(str): string of target card\n\n Returns:\n (array): 1*4*15 numpy array\n '''\n target_info = target.split('-')\n color = COLOR_MAP[target_info[0]]\n trait = TRAIT_MAP[target_info[1]]\n plane[color][trait] = 1\n return plane\n", "num_file": 8, "num_lines": 669, "programming_language": "Python"}