diff --git "a/Python.csv" "b/Python.csv" deleted file mode 100644--- "a/Python.csv" +++ /dev/null @@ -1,13702 +0,0 @@ -classname,id,original_code,num_file,num_line -uno,./ProjectTest/Python/uno.py,"''' -uno/player.py -''' - -class UnoPlayer: - - def __init__(self, player_id, np_random): - ''' Initilize a player. - - Args: - player_id (int): The id of the player - ''' - self.np_random = np_random - self.player_id = player_id - self.hand = [] - self.stack = [] - - def get_player_id(self): - ''' Return the id of the player - ''' - - return self.player_id - - -''' -uno/dealer.py -''' - -from utils import init_deck - - -class UnoDealer: - ''' Initialize a uno dealer class - ''' - def __init__(self, np_random): - self.np_random = np_random - self.deck = init_deck() - self.shuffle() - - def shuffle(self): - ''' Shuffle the deck - ''' - self.np_random.shuffle(self.deck) - - def deal_cards(self, player, num): - ''' Deal some cards from deck to one player - - Args: - player (object): The object of DoudizhuPlayer - num (int): The number of cards to be dealed - ''' - for _ in range(num): - player.hand.append(self.deck.pop()) - - def flip_top_card(self): - ''' Flip top card when a new game starts - - Returns: - (object): The object of UnoCard at the top of the deck - ''' - top_card = self.deck.pop() - while top_card.trait == 'wild_draw_4': - self.deck.append(top_card) - self.shuffle() - top_card = self.deck.pop() - return top_card - - -''' -uno/card.py -''' -from termcolor import colored - -class UnoCard: - - info = {'type': ['number', 'action', 'wild'], - 'color': ['r', 'g', 'b', 'y'], - 'trait': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'skip', 'reverse', 'draw_2', 'wild', 'wild_draw_4'] - } - - def __init__(self, card_type, color, trait): - ''' Initialize the class of UnoCard - - Args: - card_type (str): The type of card - color (str): The color of card - trait (str): The trait of card - ''' - self.type = card_type - self.color = color - self.trait = trait - self.str = self.get_str() - - def get_str(self): - ''' Get the string representation of card - - Return: - (str): The string of card's color and trait - ''' - return self.color + '-' + self.trait - - - @staticmethod - def print_cards(cards, wild_color=False): - ''' Print out card in a nice form - - Args: - card (str or list): The string form or a list of a UNO card - wild_color (boolean): True if assign collor to wild cards - ''' - if isinstance(cards, str): - cards = [cards] - for i, card in enumerate(cards): - if card == 'draw': - trait = 'Draw' - else: - color, trait = card.split('-') - if trait == 'skip': - trait = 'Skip' - elif trait == 'reverse': - trait = 'Reverse' - elif trait == 'draw_2': - trait = 'Draw-2' - elif trait == 'wild': - trait = 'Wild' - elif trait == 'wild_draw_4': - trait = 'Wild-Draw-4' - - if trait == 'Draw' or (trait[:4] == 'Wild' and not wild_color): - print(trait, end='') - elif color == 'r': - print(colored(trait, 'red'), end='') - elif color == 'g': - print(colored(trait, 'green'), end='') - elif color == 'b': - print(colored(trait, 'blue'), end='') - elif color == 'y': - print(colored(trait, 'yellow'), end='') - - if i < len(cards) - 1: - print(', ', end='') - - -''' -uno/judger.py -''' - -class UnoJudger: - - @staticmethod - def judge_winner(players, np_random): - ''' Judge the winner of the game - - Args: - players (list): The list of players who play the game - - Returns: - (list): The player id of the winner - ''' - count_1 = len(players[0].hand) - count_2 = len(players[1].hand) - if count_1 == count_2: - return [0, 1] - if count_1 < count_2: - return [0] - return [1] - - -''' -uno/game.py -''' -from copy import deepcopy -import numpy as np - -from uno import Dealer -from uno import Player -from uno import Round - - -class UnoGame: - - def __init__(self, allow_step_back=False, num_players=2): - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - self.num_players = num_players - self.payoffs = [0 for _ in range(self.num_players)] - - def configure(self, game_config): - ''' Specifiy some game specific parameters, such as number of players - ''' - self.num_players = game_config['game_num_players'] - - def init_game(self): - ''' Initialize players and state - - Returns: - (tuple): Tuple containing: - - (dict): The first state in one game - (int): Current player's id - ''' - # Initalize payoffs - self.payoffs = [0 for _ in range(self.num_players)] - - # Initialize a dealer that can deal cards - self.dealer = Dealer(self.np_random) - - # Initialize four players to play the game - self.players = [Player(i, self.np_random) for i in range(self.num_players)] - - # Deal 7 cards to each player to prepare for the game - for player in self.players: - self.dealer.deal_cards(player, 7) - - # Initialize a Round - self.round = Round(self.dealer, self.num_players, self.np_random) - - # flip and perfrom top card - top_card = self.round.flip_top_card() - self.round.perform_top_card(self.players, top_card) - - # Save the hisory for stepping back to the last state. - self.history = [] - - player_id = self.round.current_player - state = self.get_state(player_id) - return state, player_id - - def step(self, action): - ''' Get the next state - - Args: - action (str): A specific action - - Returns: - (tuple): Tuple containing: - - (dict): next player's state - (int): next plater's id - ''' - - if self.allow_step_back: - # First snapshot the current state - his_dealer = deepcopy(self.dealer) - his_round = deepcopy(self.round) - his_players = deepcopy(self.players) - self.history.append((his_dealer, his_players, his_round)) - - self.round.proceed_round(self.players, action) - player_id = self.round.current_player - state = self.get_state(player_id) - return state, player_id - - def step_back(self): - ''' Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - ''' - if not self.history: - return False - self.dealer, self.players, self.round = self.history.pop() - return True - - def get_state(self, player_id): - ''' Return player's state - - Args: - player_id (int): player id - - Returns: - (dict): The state of the player - ''' - state = self.round.get_state(self.players, player_id) - state['num_players'] = self.get_num_players() - state['current_player'] = self.round.current_player - return state - - def get_payoffs(self): - ''' Return the payoffs of the game - - Returns: - (list): Each entry corresponds to the payoff of one player - ''' - winner = self.round.winner - if winner is not None and len(winner) == 1: - self.payoffs[winner[0]] = 1 - self.payoffs[1 - winner[0]] = -1 - return self.payoffs - - def get_legal_actions(self): - ''' Return the legal actions for current player - - Returns: - (list): A list of legal actions - ''' - - return self.round.get_legal_actions(self.players, self.round.current_player) - - def get_num_players(self): - ''' Return the number of players in Limit Texas Hold'em - - Returns: - (int): The number of players in the game - ''' - return self.num_players - - @staticmethod - def get_num_actions(): - ''' Return the number of applicable actions - - Returns: - (int): The number of actions. There are 61 actions - ''' - return 61 - - def get_player_id(self): - ''' Return the current player's id - - Returns: - (int): current player's id - ''' - return self.round.current_player - - def is_over(self): - ''' Check if the game is over - - Returns: - (boolean): True if the game is over - ''' - return self.round.is_over - - -''' -uno/utils.py -''' -import os -import json -import numpy as np -from collections import OrderedDict - -import rlcard - -from uno.card import UnoCard as Card - -# Read required docs -ROOT_PATH = rlcard.__path__[0] - -# a map of abstract action to its index and a list of abstract action -with open(os.path.join(ROOT_PATH, 'games/uno/jsondata/action_space.json'), 'r') as file: - ACTION_SPACE = json.load(file, object_pairs_hook=OrderedDict) - ACTION_LIST = list(ACTION_SPACE.keys()) - -# a map of color to its index -COLOR_MAP = {'r': 0, 'g': 1, 'b': 2, 'y': 3} - -# a map of trait to its index -TRAIT_MAP = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, - '8': 8, '9': 9, 'skip': 10, 'reverse': 11, 'draw_2': 12, - 'wild': 13, 'wild_draw_4': 14} - -WILD = ['r-wild', 'g-wild', 'b-wild', 'y-wild'] - -WILD_DRAW_4 = ['r-wild_draw_4', 'g-wild_draw_4', 'b-wild_draw_4', 'y-wild_draw_4'] - - -def init_deck(): - ''' Generate uno deck of 108 cards - ''' - deck = [] - card_info = Card.info - for color in card_info['color']: - - # init number cards - for num in card_info['trait'][:10]: - deck.append(Card('number', color, num)) - if num != '0': - deck.append(Card('number', color, num)) - - # init action cards - for action in card_info['trait'][10:13]: - deck.append(Card('action', color, action)) - deck.append(Card('action', color, action)) - - # init wild cards - for wild in card_info['trait'][-2:]: - deck.append(Card('wild', color, wild)) - return deck - - -def cards2list(cards): - ''' Get the corresponding string representation of cards - - Args: - cards (list): list of UnoCards objects - - Returns: - (string): string representation of cards - ''' - cards_list = [] - for card in cards: - cards_list.append(card.get_str()) - return cards_list - -def hand2dict(hand): - ''' Get the corresponding dict representation of hand - - Args: - hand (list): list of string of hand's card - - Returns: - (dict): dict of hand - ''' - hand_dict = {} - for card in hand: - if card not in hand_dict: - hand_dict[card] = 1 - else: - hand_dict[card] += 1 - return hand_dict - -def encode_hand(plane, hand): - ''' Encode hand and represerve it into plane - - Args: - plane (array): 3*4*15 numpy array - hand (list): list of string of hand's card - - Returns: - (array): 3*4*15 numpy array - ''' - # plane = np.zeros((3, 4, 15), dtype=int) - plane[0] = np.ones((4, 15), dtype=int) - hand = hand2dict(hand) - for card, count in hand.items(): - card_info = card.split('-') - color = COLOR_MAP[card_info[0]] - trait = TRAIT_MAP[card_info[1]] - if trait >= 13: - if plane[1][0][trait] == 0: - for index in range(4): - plane[0][index][trait] = 0 - plane[1][index][trait] = 1 - else: - plane[0][color][trait] = 0 - plane[count][color][trait] = 1 - return plane - -def encode_target(plane, target): - ''' Encode target and represerve it into plane - - Args: - plane (array): 1*4*15 numpy array - target(str): string of target card - - Returns: - (array): 1*4*15 numpy array - ''' - target_info = target.split('-') - color = COLOR_MAP[target_info[0]] - trait = TRAIT_MAP[target_info[1]] - plane[color][trait] = 1 - return plane - - -''' -uno/__init__.py -''' -from uno.dealer import UnoDealer as Dealer -from uno.judger import UnoJudger as Judger -from uno.player import UnoPlayer as Player -from uno.round import UnoRound as Round -from uno.game import UnoGame as Game - - - -''' -uno/round.py -''' -from card import UnoCard -from utils import cards2list, WILD, WILD_DRAW_4 - - -class UnoRound: - - def __init__(self, dealer, num_players, np_random): - ''' Initialize the round class - - Args: - dealer (object): the object of UnoDealer - num_players (int): the number of players in game - ''' - self.np_random = np_random - self.dealer = dealer - self.target = None - self.current_player = 0 - self.num_players = num_players - self.direction = 1 - self.played_cards = [] - self.is_over = False - self.winner = None - - def flip_top_card(self): - ''' Flip the top card of the card pile - - Returns: - (object of UnoCard): the top card in game - - ''' - top = self.dealer.flip_top_card() - if top.trait == 'wild': - top.color = self.np_random.choice(UnoCard.info['color']) - self.target = top - self.played_cards.append(top) - return top - - def perform_top_card(self, players, top_card): - ''' Perform the top card - - Args: - players (list): list of UnoPlayer objects - top_card (object): object of UnoCard - ''' - if top_card.trait == 'skip': - self.current_player = 1 - elif top_card.trait == 'reverse': - self.direction = -1 - self.current_player = (0 + self.direction) % self.num_players - elif top_card.trait == 'draw_2': - player = players[self.current_player] - self.dealer.deal_cards(player, 2) - - def proceed_round(self, players, action): - ''' Call other Classes' functions to keep one round running - - Args: - player (object): object of UnoPlayer - action (str): string of legal action - ''' - if action == 'draw': - self._perform_draw_action(players) - return None - player = players[self.current_player] - card_info = action.split('-') - color = card_info[0] - trait = card_info[1] - # remove corresponding card - remove_index = None - if trait == 'wild' or trait == 'wild_draw_4': - for index, card in enumerate(player.hand): - if trait == card.trait: - card.color = color # update the color of wild card to match the action - remove_index = index - break - else: - for index, card in enumerate(player.hand): - if color == card.color and trait == card.trait: - remove_index = index - break - card = player.hand.pop(remove_index) - if not player.hand: - self.is_over = True - self.winner = [self.current_player] - self.played_cards.append(card) - - # perform the number action - if card.type == 'number': - self.current_player = (self.current_player + self.direction) % self.num_players - self.target = card - - # perform non-number action - else: - self._preform_non_number_action(players, card) - - def get_legal_actions(self, players, player_id): - wild_flag = 0 - wild_draw_4_flag = 0 - legal_actions = [] - wild_4_actions = [] - hand = players[player_id].hand - target = self.target - if target.type == 'wild': - for card in hand: - if card.type == 'wild': - if card.trait == 'wild_draw_4': - if wild_draw_4_flag == 0: - wild_draw_4_flag = 1 - wild_4_actions.extend(WILD_DRAW_4) - else: - if wild_flag == 0: - wild_flag = 1 - legal_actions.extend(WILD) - elif card.color == target.color: - legal_actions.append(card.str) - - # target is aciton card or number card - else: - for card in hand: - if card.type == 'wild': - if card.trait == 'wild_draw_4': - if wild_draw_4_flag == 0: - wild_draw_4_flag = 1 - wild_4_actions.extend(WILD_DRAW_4) - else: - if wild_flag == 0: - wild_flag = 1 - legal_actions.extend(WILD) - elif card.color == target.color or card.trait == target.trait: - legal_actions.append(card.str) - if not legal_actions: - legal_actions = wild_4_actions - if not legal_actions: - legal_actions = ['draw'] - return legal_actions - - def get_state(self, players, player_id): - ''' Get player's state - - Args: - players (list): The list of UnoPlayer - player_id (int): The id of the player - ''' - state = {} - player = players[player_id] - state['hand'] = cards2list(player.hand) - state['target'] = self.target.str - state['played_cards'] = cards2list(self.played_cards) - state['legal_actions'] = self.get_legal_actions(players, player_id) - state['num_cards'] = [] - for player in players: - state['num_cards'].append(len(player.hand)) - return state - - def replace_deck(self): - ''' Add cards have been played to deck - ''' - self.dealer.deck.extend(self.played_cards) - self.dealer.shuffle() - self.played_cards = [] - - def _perform_draw_action(self, players): - # replace deck if there is no card in draw pile - if not self.dealer.deck: - self.replace_deck() - #self.is_over = True - #self.winner = UnoJudger.judge_winner(players) - #return None - - card = self.dealer.deck.pop() - - # draw a wild card - if card.type == 'wild': - card.color = self.np_random.choice(UnoCard.info['color']) - self.target = card - self.played_cards.append(card) - self.current_player = (self.current_player + self.direction) % self.num_players - - # draw a card with the same color of target - elif card.color == self.target.color: - if card.type == 'number': - self.target = card - self.played_cards.append(card) - self.current_player = (self.current_player + self.direction) % self.num_players - else: - self.played_cards.append(card) - self._preform_non_number_action(players, card) - - # draw a card with the diffrent color of target - else: - players[self.current_player].hand.append(card) - self.current_player = (self.current_player + self.direction) % self.num_players - - def _preform_non_number_action(self, players, card): - current = self.current_player - direction = self.direction - num_players = self.num_players - - # perform reverse card - if card.trait == 'reverse': - self.direction = -1 * direction - - # perfrom skip card - elif card.trait == 'skip': - current = (current + direction) % num_players - - # perform draw_2 card - elif card.trait == 'draw_2': - if len(self.dealer.deck) < 2: - self.replace_deck() - #self.is_over = True - #self.winner = UnoJudger.judge_winner(players) - #return None - self.dealer.deal_cards(players[(current + direction) % num_players], 2) - current = (current + direction) % num_players - - # perfrom wild_draw_4 card - elif card.trait == 'wild_draw_4': - if len(self.dealer.deck) < 4: - self.replace_deck() - #self.is_over = True - #self.winner = UnoJudger.judge_winner(players) - #return None - self.dealer.deal_cards(players[(current + direction) % num_players], 4) - current = (current + direction) % num_players - self.current_player = (current + self.direction) % num_players - self.target = card - - -",8,669 -tree,./ProjectTest/Python/tree.py,"''' -tree/base.py -''' -# coding:utf-8 -import numpy as np -from scipy import stats - - -def f_entropy(p): - # Convert values to probability - p = np.bincount(p) / float(p.shape[0]) - - ep = stats.entropy(p) - if ep == -float(""inf""): - return 0.0 - return ep - - -def information_gain(y, splits): - splits_entropy = sum([f_entropy(split) * (float(split.shape[0]) / y.shape[0]) for split in splits]) - return f_entropy(y) - splits_entropy - - -def mse_criterion(y, splits): - y_mean = np.mean(y) - return -sum([np.sum((split - y_mean) ** 2) * (float(split.shape[0]) / y.shape[0]) for split in splits]) - - -def xgb_criterion(y, left, right, loss): - left = loss.gain(left[""actual""], left[""y_pred""]) - right = loss.gain(right[""actual""], right[""y_pred""]) - initial = loss.gain(y[""actual""], y[""y_pred""]) - gain = left + right - initial - return gain - - -def get_split_mask(X, column, value): - left_mask = X[:, column] < value - right_mask = X[:, column] >= value - return left_mask, right_mask - - -def split(X, y, value): - left_mask = X < value - right_mask = X >= value - return y[left_mask], y[right_mask] - - -def split_dataset(X, target, column, value, return_X=True): - left_mask, right_mask = get_split_mask(X, column, value) - - left, right = {}, {} - for key in target.keys(): - left[key] = target[key][left_mask] - right[key] = target[key][right_mask] - - if return_X: - left_X, right_X = X[left_mask], X[right_mask] - return left_X, right_X, left, right - else: - return left, right - - -''' -tree/tree.py -''' -# coding:utf-8 -import random - -import numpy as np -from scipy import stats - -from base import split, split_dataset, xgb_criterion - -random.seed(111) - - -class Tree(object): - """"""Recursive implementation of decision tree."""""" - - def __init__(self, regression=False, criterion=None, n_classes=None): - self.regression = regression - self.impurity = None - self.threshold = None - self.column_index = None - self.outcome = None - self.criterion = criterion - self.loss = None - self.n_classes = n_classes # Only for classification - - self.left_child = None - self.right_child = None - - @property - def is_terminal(self): - return not bool(self.left_child and self.right_child) - - def _find_splits(self, X): - """"""Find all possible split values."""""" - split_values = set() - - # Get unique values in a sorted order - x_unique = list(np.unique(X)) - for i in range(1, len(x_unique)): - # Find a point between two values - average = (x_unique[i - 1] + x_unique[i]) / 2.0 - split_values.add(average) - - return list(split_values) - - def _find_best_split(self, X, target, n_features): - """"""Find best feature and value for a split. Greedy algorithm."""""" - - # Sample random subset of features - subset = random.sample(list(range(0, X.shape[1])), n_features) - max_gain, max_col, max_val = None, None, None - - for column in subset: - split_values = self._find_splits(X[:, column]) - for value in split_values: - if self.loss is None: - # Random forest - splits = split(X[:, column], target[""y""], value) - gain = self.criterion(target[""y""], splits) - else: - # Gradient boosting - left, right = split_dataset(X, target, column, value, return_X=False) - gain = xgb_criterion(target, left, right, self.loss) - - if (max_gain is None) or (gain > max_gain): - max_col, max_val, max_gain = column, value, gain - return max_col, max_val, max_gain - - def _train(self, X, target, max_features=None, min_samples_split=10, max_depth=None, minimum_gain=0.01): - try: - # Exit from recursion using assert syntax - assert X.shape[0] > min_samples_split - assert max_depth > 0 - - if max_features is None: - max_features = X.shape[1] - - column, value, gain = self._find_best_split(X, target, max_features) - assert gain is not None - if self.regression: - assert gain != 0 - else: - assert gain > minimum_gain - - self.column_index = column - self.threshold = value - self.impurity = gain - - # Split dataset - left_X, right_X, left_target, right_target = split_dataset(X, target, column, value) - - # Grow left and right child - self.left_child = Tree(self.regression, self.criterion, self.n_classes) - self.left_child._train( - left_X, left_target, max_features, min_samples_split, max_depth - 1, minimum_gain - ) - - self.right_child = Tree(self.regression, self.criterion, self.n_classes) - self.right_child._train( - right_X, right_target, max_features, min_samples_split, max_depth - 1, minimum_gain - ) - except AssertionError: - self._calculate_leaf_value(target) - - def train(self, X, target, max_features=None, min_samples_split=10, max_depth=None, minimum_gain=0.01, loss=None): - """"""Build a decision tree from training set. - - Parameters - ---------- - - X : array-like - Feature dataset. - target : dictionary or array-like - Target values. - max_features : int or None - The number of features to consider when looking for the best split. - min_samples_split : int - The minimum number of samples required to split an internal node. - max_depth : int - Maximum depth of the tree. - minimum_gain : float, default 0.01 - Minimum gain required for splitting. - loss : function, default None - Loss function for gradient boosting. - """""" - - if not isinstance(target, dict): - target = {""y"": target} - - # Loss for gradient boosting - if loss is not None: - self.loss = loss - - if not self.regression: - self.n_classes = len(np.unique(target['y'])) - - self._train(X, target, max_features=max_features, min_samples_split=min_samples_split, - max_depth=max_depth, minimum_gain=minimum_gain) - - - def _calculate_leaf_value(self, targets): - """"""Find optimal value for leaf."""""" - if self.loss is not None: - # Gradient boosting - self.outcome = self.loss.approximate(targets[""actual""], targets[""y_pred""]) - else: - # Random Forest - if self.regression: - # Mean value for regression task - self.outcome = np.mean(targets[""y""]) - else: - # Probability for classification task - self.outcome = np.bincount(targets[""y""], minlength=self.n_classes) / targets[""y""].shape[0] - - def predict_row(self, row): - """"""Predict single row."""""" - if not self.is_terminal: - if row[self.column_index] < self.threshold: - return self.left_child.predict_row(row) - else: - return self.right_child.predict_row(row) - return self.outcome - - def predict(self, X): - result = np.zeros(X.shape[0]) - for i in range(X.shape[0]): - result[i] = self.predict_row(X[i, :]) - return result - - -",2,225 -mahjong,./ProjectTest/Python/mahjong.py,"''' -mahjong/player.py -''' - -class MahjongPlayer: - - def __init__(self, player_id, np_random): - ''' Initilize a player. - - Args: - player_id (int): The id of the player - ''' - self.np_random = np_random - self.player_id = player_id - self.hand = [] - self.pile = [] - - def get_player_id(self): - ''' Return the id of the player - ''' - - return self.player_id - - def print_hand(self): - ''' Print the cards in hand in string. - ''' - print([c.get_str() for c in self.hand]) - - def print_pile(self): - ''' Print the cards in pile of the player in string. - ''' - print([[c.get_str() for c in s]for s in self.pile]) - - def play_card(self, dealer, card): - ''' Play one card - Args: - dealer (object): Dealer - Card (object): The card to be play. - ''' - card = self.hand.pop(self.hand.index(card)) - dealer.table.append(card) - - def chow(self, dealer, cards): - ''' Perform Chow - Args: - dealer (object): Dealer - Cards (object): The cards to be Chow. - ''' - last_card = dealer.table.pop(-1) - for card in cards: - if card in self.hand and card != last_card: - self.hand.pop(self.hand.index(card)) - self.pile.append(cards) - - def gong(self, dealer, cards): - ''' Perform Gong - Args: - dealer (object): Dealer - Cards (object): The cards to be Gong. - ''' - for card in cards: - if card in self.hand: - self.hand.pop(self.hand.index(card)) - self.pile.append(cards) - - def pong(self, dealer, cards): - ''' Perform Pong - Args: - dealer (object): Dealer - Cards (object): The cards to be Pong. - ''' - for card in cards: - if card in self.hand: - self.hand.pop(self.hand.index(card)) - self.pile.append(cards) - - -''' -mahjong/dealer.py -''' -from utils import init_deck - - -class MahjongDealer: - ''' Initialize a mahjong dealer class - ''' - def __init__(self, np_random): - self.np_random = np_random - self.deck = init_deck() - self.shuffle() - self.table = [] - - def shuffle(self): - ''' Shuffle the deck - ''' - self.np_random.shuffle(self.deck) - - def deal_cards(self, player, num): - ''' Deal some cards from deck to one player - - Args: - player (object): The object of DoudizhuPlayer - num (int): The number of cards to be dealed - ''' - for _ in range(num): - player.hand.append(self.deck.pop()) - - -## For test - - -''' -mahjong/card.py -''' - -class MahjongCard: - - info = {'type': ['dots', 'bamboo', 'characters', 'dragons', 'winds'], - 'trait': ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'green', 'red', 'white', 'east', 'west', 'north', 'south'] - } - - def __init__(self, card_type, trait): - ''' Initialize the class of MahjongCard - - Args: - card_type (str): The type of card - trait (str): The trait of card - ''' - self.type = card_type - self.trait = trait - self.index_num = 0 - - def get_str(self): - ''' Get the string representation of card - - Return: - (str): The string of card's color and trait - ''' - return self.type+ '-'+ self.trait - - def set_index_num(self, index_num): - - self.index_num = index_num - - - - -''' -mahjong/judger.py -''' -# -*- coding: utf-8 -*- -''' Implement Mahjong Judger class -''' -from collections import defaultdict -import numpy as np - -class MahjongJudger: - ''' Determine what cards a player can play - ''' - - def __init__(self, np_random): - ''' Initilize the Judger class for Mahjong - ''' - self.np_random = np_random - - @staticmethod - def judge_pong_gong(dealer, players, last_player): - ''' Judge which player has pong/gong - Args: - dealer (object): The dealer object. - players (list): List of all players - last_player (int): The player id of last player - - ''' - last_card = dealer.table[-1] - last_card_str = last_card.get_str() - #last_card_value = last_card_str.split(""-"")[-1] - #last_card_type = last_card_str.split(""-"")[0] - for player in players: - hand = [card.get_str() for card in player.hand] - hand_dict = defaultdict(list) - for card in hand: - hand_dict[card.split(""-"")[0]].append(card.split(""-"")[1]) - #pile = player.pile - # check gong - if hand.count(last_card_str) == 3 and last_player != player.player_id: - return 'gong', player, [last_card]*4 - # check pong - if hand.count(last_card_str) == 2 and last_player != player.player_id: - return 'pong', player, [last_card]*3 - return False, None, None - - def judge_chow(self, dealer, players, last_player): - ''' Judge which player has chow - Args: - dealer (object): The dealer object. - players (list): List of all players - last_player (int): The player id of last player - ''' - - last_card = dealer.table[-1] - last_card_str = last_card.get_str() - last_card_type = last_card_str.split(""-"")[0] - last_card_index = last_card.index_num - for player in players: - if last_card_type != ""dragons"" and last_card_type != ""winds"" and last_player == player.get_player_id() - 1: - # Create 9 dimensional vector where each dimension represent a specific card with the type same as last_card_type - # Numbers in each dimension represent how many of that card the player has it in hand - # If the last_card_type is 'characters' for example, and the player has cards: characters_3, characters_6, characters_3, - # The hand_list vector looks like: [0,0,2,0,0,1,0,0,0] - hand_list = np.zeros(9) - - for card in player.hand: - if card.get_str().split(""-"")[0] == last_card_type: - hand_list[card.index_num] = hand_list[card.index_num]+1 - - #pile = player.pile - #check chow - test_cases = [] - if last_card_index == 0: - if hand_list[last_card_index+1] > 0 and hand_list[last_card_index+2] > 0: - test_cases.append([last_card_index+1, last_card_index+2]) - elif last_card_index < 9: - if hand_list[last_card_index-2] > 0 and hand_list[last_card_index-1] > 0: - test_cases.append([last_card_index-2, last_card_index-1]) - else: - if hand_list[last_card_index-1] > 0 and hand_list[last_card_index+1] > 0: - test_cases.append([last_card_index-1, last_card_index+1]) - - if not test_cases: - continue - - for l in test_cases: - cards = [] - for i in l: - for card in player.hand: - if card.index_num == i and card.get_str().split(""-"")[0] == last_card_type: - cards.append(card) - break - cards.append(last_card) - return 'chow', player, cards - return False, None, None - - def judge_game(self, game): - ''' Judge which player has win the game - Args: - dealer (object): The dealer object. - players (list): List of all players - last_player (int): The player id of last player - ''' - players_val = [] - win_player = -1 - for player in game.players: - win, val = self.judge_hu(player) - players_val.append(val) - if win: - win_player = player.player_id - if win_player != -1 or len(game.dealer.deck) == 0: - return True, win_player, players_val - else: - #player_id = players_val.index(max(players_val)) - return False, win_player, players_val - - def judge_hu(self, player): - ''' Judge whether the player has win the game - Args: - player (object): Target player - - Return: - Result (bool): Win or not - Maximum_score (int): Set count score of the player - ''' - set_count = 0 - hand = [card.get_str() for card in player.hand] - count_dict = {card: hand.count(card) for card in hand} - set_count = len(player.pile) - if set_count >= 4: - return True, set_count - used = [] - maximum = 0 - for each in count_dict: - if each in used: - continue - tmp_set_count = 0 - tmp_hand = hand.copy() - if count_dict[each] == 2: - for _ in range(count_dict[each]): - tmp_hand.pop(tmp_hand.index(each)) - tmp_set_count, _set = self.cal_set(tmp_hand) - used.extend(_set) - if tmp_set_count + set_count > maximum: - maximum = tmp_set_count + set_count - if tmp_set_count + set_count >= 4: - #print(player.get_player_id(), sorted([card.get_str() for card in player.hand])) - #print([[c.get_str() for c in s] for s in player.pile]) - #print(len(player.hand), sum([len(s) for s in player.pile])) - #exit() - return True, maximum - return False, maximum - - @staticmethod - def check_consecutive(_list): - ''' Check if list is consecutive - Args: - _list (list): The target list - - Return: - Result (bool): consecutive or not - ''' - l = list(map(int, _list)) - if sorted(l) == list(range(min(l), max(l)+1)): - return True - return False - - def cal_set(self, cards): - ''' Calculate the set for given cards - Args: - Cards (list): List of cards. - - Return: - Set_count (int): - Sets (list): List of cards that has been pop from user's hand - ''' - tmp_cards = cards.copy() - sets = [] - set_count = 0 - _dict = {card: tmp_cards.count(card) for card in tmp_cards} - # check pong/gang - for each in _dict: - if _dict[each] == 3 or _dict[each] == 4: - set_count += 1 - for _ in range(_dict[each]): - tmp_cards.pop(tmp_cards.index(each)) - - # get all of the traits of each type in hand (except dragons and winds) - _dict_by_type = defaultdict(list) - for card in tmp_cards: - _type = card.split(""-"")[0] - _trait = card.split(""-"")[1] - if _type == 'dragons' or _type == 'winds': - continue - else: - _dict_by_type[_type].append(_trait) - for _type in _dict_by_type.keys(): - values = sorted(_dict_by_type[_type]) - if len(values) > 2: - for index, _ in enumerate(values): - if index == 0: - test_case = [values[index], values[index+1], values[index+2]] - elif index == len(values)-1: - test_case = [values[index-2], values[index-1], values[index]] - else: - test_case = [values[index-1], values[index], values[index+1]] - if self.check_consecutive(test_case): - set_count += 1 - for each in test_case: - values.pop(values.index(each)) - c = _type+""-""+str(each) - sets.append(c) - if c in tmp_cards: - tmp_cards.pop(tmp_cards.index(c)) - return set_count, sets - - - -''' -mahjong/game.py -''' -import numpy as np -from copy import deepcopy - -from mahjong import Dealer -from mahjong import Player -from mahjong import Round -from mahjong import Judger - -class MahjongGame: - - def __init__(self, allow_step_back=False): - '''Initialize the class MajongGame - ''' - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - self.num_players = 4 - - def init_game(self): - ''' Initialilze the game of Mahjong - - This version supports two-player Mahjong - - Returns: - (tuple): Tuple containing: - - (dict): The first state of the game - (int): Current player's id - ''' - # Initialize a dealer that can deal cards - self.dealer = Dealer(self.np_random) - - # Initialize four players to play the game - self.players = [Player(i, self.np_random) for i in range(self.num_players)] - - self.judger = Judger(self.np_random) - self.round = Round(self.judger, self.dealer, self.num_players, self.np_random) - - # Deal 13 cards to each player to prepare for the game - for player in self.players: - self.dealer.deal_cards(player, 13) - - # Save the hisory for stepping back to the last state. - self.history = [] - - self.dealer.deal_cards(self.players[self.round.current_player], 1) - state = self.get_state(self.round.current_player) - self.cur_state = state - return state, self.round.current_player - - def step(self, action): - ''' Get the next state - - Args: - action (str): a specific action. (call, raise, fold, or check) - - Returns: - (tuple): Tuple containing: - - (dict): next player's state - (int): next plater's id - ''' - # First snapshot the current state - if self.allow_step_back: - hist_dealer = deepcopy(self.dealer) - hist_round = deepcopy(self.round) - hist_players = deepcopy(self.players) - self.history.append((hist_dealer, hist_players, hist_round)) - self.round.proceed_round(self.players, action) - state = self.get_state(self.round.current_player) - self.cur_state = state - return state, self.round.current_player - - def step_back(self): - ''' Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - ''' - if not self.history: - return False - self.dealer, self.players, self.round = self.history.pop() - return True - - def get_state(self, player_id): - ''' Return player's state - - Args: - player_id (int): player id - - Returns: - (dict): The state of the player - ''' - state = self.round.get_state(self.players, player_id) - return state - - @staticmethod - def get_legal_actions(state): - ''' Return the legal actions for current player - - Returns: - (list): A list of legal actions - ''' - if state['valid_act'] == ['play']: - state['valid_act'] = state['action_cards'] - return state['action_cards'] - else: - return state['valid_act'] - - @staticmethod - def get_num_actions(): - ''' Return the number of applicable actions - - Returns: - (int): The number of actions. There are 4 actions (call, raise, check and fold) - ''' - return 38 - - def get_num_players(self): - ''' return the number of players in Mahjong - - returns: - (int): the number of players in the game - ''' - return self.num_players - - def get_player_id(self): - ''' return the id of current player in Mahjong - - returns: - (int): the number of players in the game - ''' - return self.round.current_player - - def is_over(self): - ''' Check if the game is over - - Returns: - (boolean): True if the game is over - ''' - win, player, _ = self.judger.judge_game(self) - #pile =[sorted([c.get_str() for c in s ]) for s in self.players[player].pile if self.players[player].pile != None] - #cards = sorted([c.get_str() for c in self.players[player].hand]) - #count = len(cards) + sum([len(p) for p in pile]) - self.winner = player - #print(win, player, players_val) - #print(win, self.round.current_player, player, cards, pile, count) - return win - - -''' -mahjong/utils.py -''' -import numpy as np -from card import MahjongCard as Card - - -card_encoding_dict = {} -num = 0 -for _type in ['bamboo', 'characters', 'dots']: - for _trait in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: - card = _type+""-""+_trait - card_encoding_dict[card] = num - num += 1 -for _trait in ['green', 'red', 'white']: - card = 'dragons-'+_trait - card_encoding_dict[card] = num - num += 1 - -for _trait in ['east', 'west', 'north', 'south']: - card = 'winds-'+_trait - card_encoding_dict[card] = num - num += 1 -card_encoding_dict['pong'] = num -card_encoding_dict['chow'] = num + 1 -card_encoding_dict['gong'] = num + 2 -card_encoding_dict['stand'] = num + 3 - -card_decoding_dict = {card_encoding_dict[key]: key for key in card_encoding_dict.keys()} - -def init_deck(): - deck = [] - info = Card.info - for _type in info['type']: - index_num = 0 - if _type != 'dragons' and _type != 'winds': - for _trait in info['trait'][:9]: - card = Card(_type, _trait) - card.set_index_num(index_num) - index_num = index_num + 1 - deck.append(card) - elif _type == 'dragons': - for _trait in info['trait'][9:12]: - card = Card(_type, _trait) - card.set_index_num(index_num) - index_num = index_num + 1 - deck.append(card) - else: - for _trait in info['trait'][12:]: - card = Card(_type, _trait) - card.set_index_num(index_num) - index_num = index_num + 1 - deck.append(card) - deck = deck * 4 - return deck - - -def pile2list(pile): - cards_list = [] - for each in pile: - cards_list.extend(each) - return cards_list - -def cards2list(cards): - cards_list = [] - for each in cards: - cards_list.append(each.get_str()) - return cards_list - - -def encode_cards(cards): - plane = np.zeros((34,4), dtype=int) - cards = cards2list(cards) - for card in list(set(cards)): - index = card_encoding_dict[card] - num = cards.count(card) - plane[index][:num] = 1 - return plane - - -''' -mahjong/__init__.py -''' -from mahjong.dealer import MahjongDealer as Dealer -from mahjong.card import MahjongCard as Card -from mahjong.player import MahjongPlayer as Player -from mahjong.judger import MahjongJudger as Judger -from mahjong.round import MahjongRound as Round -from mahjong.game import MahjongGame as Game - - - -''' -mahjong/round.py -''' - -class MahjongRound: - - def __init__(self, judger, dealer, num_players, np_random): - ''' Initialize the round class - - Args: - judger (object): the object of MahjongJudger - dealer (object): the object of MahjongDealer - num_players (int): the number of players in game - ''' - self.np_random = np_random - self.judger = judger - self.dealer = dealer - self.target = None - self.current_player = 0 - self.last_player = None - self.num_players = num_players - self.direction = 1 - self.played_cards = [] - self.is_over = False - self.player_before_act = 0 - self.prev_status = None - self.valid_act = False - self.last_cards = [] - - def proceed_round(self, players, action): - ''' Call other Classes's functions to keep one round running - - Args: - player (object): object of UnoPlayer - action (str): string of legal action - ''' - #hand_len = [len(p.hand) for p in players] - #pile_len = [sum([len([c for c in p]) for p in pp.pile]) for pp in players] - #total_len = [i + j for i, j in zip(hand_len, pile_len)] - if action == 'stand': - (valid_act, player, cards) = self.judger.judge_chow(self.dealer, players, self.last_player) - if valid_act: - self.valid_act = valid_act - self.last_cards = cards - self.last_player = self.current_player - self.current_player = player.player_id - else: - self.last_player = self.current_player - self.current_player = (self.player_before_act + 1) % 4 - self.dealer.deal_cards(players[self.current_player], 1) - self.valid_act = False - - elif action == 'gong': - players[self.current_player].gong(self.dealer, self.last_cards) - self.last_player = self.current_player - self.valid_act = False - - elif action == 'pong': - players[self.current_player].pong(self.dealer, self.last_cards) - self.last_player = self.current_player - self.valid_act = False - - elif action == 'chow': - players[self.current_player].chow(self.dealer, self.last_cards) - self.last_player = self.current_player - self.valid_act = False - - else: # Play game: Proceed to next player - players[self.current_player].play_card(self.dealer, action) - self.player_before_act = self.current_player - self.last_player = self.current_player - (valid_act, player, cards) = self.judger.judge_pong_gong(self.dealer, players, self.last_player) - if valid_act: - self.valid_act = valid_act - self.last_cards = cards - self.last_player = self.current_player - self.current_player = player.player_id - else: - self.last_player = self.current_player - self.current_player = (self.current_player + 1) % 4 - self.dealer.deal_cards(players[self.current_player], 1) - - #hand_len = [len(p.hand) for p in players] - #pile_len = [sum([len([c for c in p]) for p in pp.pile]) for pp in players] - #total_len = [i + j for i, j in zip(hand_len, pile_len)] - - def get_state(self, players, player_id): - ''' Get player's state - - Args: - players (list): The list of MahjongPlayer - player_id (int): The id of the player - Return: - state (dict): The information of the state - ''' - state = {} - #(valid_act, player, cards) = self.judger.judge_pong_gong(self.dealer, players, self.last_player) - if self.valid_act: # PONG/GONG/CHOW - state['valid_act'] = [self.valid_act, 'stand'] - state['table'] = self.dealer.table - state['player'] = self.current_player - state['current_hand'] = players[self.current_player].hand - state['players_pile'] = {p.player_id: p.pile for p in players} - state['action_cards'] = self.last_cards # For doing action (pong, chow, gong) - else: # Regular Play - state['valid_act'] = ['play'] - state['table'] = self.dealer.table - state['player'] = self.current_player - state['current_hand'] = players[player_id].hand - state['players_pile'] = {p.player_id: p.pile for p in players} - state['action_cards'] = players[player_id].hand # For doing action (pong, chow, gong) - return state - - - -",8,703 -thefuzz,./ProjectTest/Python/thefuzz.py,"''' -thefuzz/fuzz.py -''' -#!/usr/bin/env python - -from rapidfuzz.fuzz import ( - ratio as _ratio, - partial_ratio as _partial_ratio, - token_set_ratio as _token_set_ratio, - token_sort_ratio as _token_sort_ratio, - partial_token_set_ratio as _partial_token_set_ratio, - partial_token_sort_ratio as _partial_token_sort_ratio, - WRatio as _WRatio, - QRatio as _QRatio, -) - -import utils - -########################### -# Basic Scoring Functions # -########################### - - -def _rapidfuzz_scorer(scorer, s1, s2, force_ascii, full_process): - """""" - wrapper around rapidfuzz function to be compatible with the API of thefuzz - """""" - if full_process: - if s1 is None or s2 is None: - return 0 - - s1 = utils.full_process(s1, force_ascii=force_ascii) - s2 = utils.full_process(s2, force_ascii=force_ascii) - - return int(round(scorer(s1, s2))) - - -def ratio(s1, s2): - return _rapidfuzz_scorer(_ratio, s1, s2, False, False) - - -def partial_ratio(s1, s2): - """""" - Return the ratio of the most similar substring - as a number between 0 and 100. - """""" - return _rapidfuzz_scorer(_partial_ratio, s1, s2, False, False) - - -############################## -# Advanced Scoring Functions # -############################## - -# Sorted Token -# find all alphanumeric tokens in the string -# sort those tokens and take ratio of resulting joined strings -# controls for unordered string elements -def token_sort_ratio(s1, s2, force_ascii=True, full_process=True): - """""" - Return a measure of the sequences' similarity between 0 and 100 - but sorting the token before comparing. - """""" - return _rapidfuzz_scorer(_token_sort_ratio, s1, s2, force_ascii, full_process) - - -def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True): - """""" - Return the ratio of the most similar substring as a number between - 0 and 100 but sorting the token before comparing. - """""" - return _rapidfuzz_scorer( - _partial_token_sort_ratio, s1, s2, force_ascii, full_process - ) - - -def token_set_ratio(s1, s2, force_ascii=True, full_process=True): - return _rapidfuzz_scorer(_token_set_ratio, s1, s2, force_ascii, full_process) - - -def partial_token_set_ratio(s1, s2, force_ascii=True, full_process=True): - return _rapidfuzz_scorer( - _partial_token_set_ratio, s1, s2, force_ascii, full_process - ) - - -################### -# Combination API # -################### - -# q is for quick -def QRatio(s1, s2, force_ascii=True, full_process=True): - """""" - Quick ratio comparison between two strings. - - Runs full_process from utils on both strings - Short circuits if either of the strings is empty after processing. - - :param s1: - :param s2: - :param force_ascii: Allow only ASCII characters (Default: True) - :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True) - :return: similarity ratio - """""" - return _rapidfuzz_scorer(_QRatio, s1, s2, force_ascii, full_process) - - -def UQRatio(s1, s2, full_process=True): - """""" - Unicode quick ratio - - Calls QRatio with force_ascii set to False - - :param s1: - :param s2: - :return: similarity ratio - """""" - return QRatio(s1, s2, force_ascii=False, full_process=full_process) - - -# w is for weighted -def WRatio(s1, s2, force_ascii=True, full_process=True): - """""" - Return a measure of the sequences' similarity between 0 and 100, using different algorithms. - - **Steps in the order they occur** - - #. Run full_process from utils on both strings - #. Short circuit if this makes either string empty - #. Take the ratio of the two processed strings (fuzz.ratio) - #. Run checks to compare the length of the strings - * If one of the strings is more than 1.5 times as long as the other - use partial_ratio comparisons - scale partial results by 0.9 - (this makes sure only full results can return 100) - * If one of the strings is over 8 times as long as the other - instead scale by 0.6 - - #. Run the other ratio functions - * if using partial ratio functions call partial_ratio, - partial_token_sort_ratio and partial_token_set_ratio - scale all of these by the ratio based on length - * otherwise call token_sort_ratio and token_set_ratio - * all token based comparisons are scaled by 0.95 - (on top of any partial scalars) - - #. Take the highest value from these results - round it and return it as an integer. - - :param s1: - :param s2: - :param force_ascii: Allow only ascii characters - :type force_ascii: bool - :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True) - :return: - """""" - return _rapidfuzz_scorer(_WRatio, s1, s2, force_ascii, full_process) - - -def UWRatio(s1, s2, full_process=True): - """""" - Return a measure of the sequences' similarity between 0 and 100, - using different algorithms. Same as WRatio but preserving unicode. - """""" - return WRatio(s1, s2, force_ascii=False, full_process=full_process) - - -''' -thefuzz/utils.py -''' -from rapidfuzz.utils import default_process as _default_process - -translation_table = {i: None for i in range(128, 256)} # ascii dammit! - - -def ascii_only(s): - return s.translate(translation_table) - - -def full_process(s, force_ascii=False): - """""" - Process string by - -- removing all but letters and numbers - -- trim whitespace - -- force to lower case - if force_ascii == True, force convert to ascii - """""" - - if force_ascii: - s = ascii_only(str(s)) - - return _default_process(s) - - -''' -thefuzz/__init__.py -''' -__version__ = '0.22.1' - - -",3,183 -nolimitholdem,./ProjectTest/Python/nolimitholdem.py,"''' -nolimitholdem/base.py -''' -''' Game-related base classes -''' -class Card: - ''' - Card stores the suit and rank of a single card - - Note: - 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] - Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] - ''' - suit = None - rank = None - valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ'] - valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - - def __init__(self, suit, rank): - ''' Initialize the suit and rank of a card - - Args: - suit: string, suit of the card, should be one of valid_suit - rank: string, rank of the card, should be one of valid_rank - ''' - self.suit = suit - self.rank = rank - - def __eq__(self, other): - if isinstance(other, Card): - return self.rank == other.rank and self.suit == other.suit - else: - # don't attempt to compare against unrelated types - return NotImplemented - - def __hash__(self): - suit_index = Card.valid_suit.index(self.suit) - rank_index = Card.valid_rank.index(self.rank) - return rank_index + 100 * suit_index - - def __str__(self): - ''' Get string representation of a card. - - Returns: - string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... - ''' - return self.rank + self.suit - - def get_index(self): - ''' Get index of a card. - - Returns: - string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ... - ''' - return self.suit+self.rank - - -''' -nolimitholdem/player.py -''' -from enum import Enum - - -class PlayerStatus(Enum): - ALIVE = 0 - FOLDED = 1 - ALLIN = 2 - - -class LimitHoldemPlayer: - - def __init__(self, player_id, np_random): - """""" - Initialize a player. - - Args: - player_id (int): The id of the player - """""" - self.np_random = np_random - self.player_id = player_id - self.hand = [] - self.status = PlayerStatus.ALIVE - - # The chips that this player has put in until now - self.in_chips = 0 - - def get_state(self, public_cards, all_chips, legal_actions): - """""" - Encode the state for the player - - Args: - public_cards (list): A list of public cards that seen by all the players - all_chips (int): The chips that all players have put in - - Returns: - (dict): The state of the player - """""" - return { - 'hand': [c.get_index() for c in self.hand], - 'public_cards': [c.get_index() for c in public_cards], - 'all_chips': all_chips, - 'my_chips': self.in_chips, - 'legal_actions': legal_actions - } - - def get_player_id(self): - return self.player_id - - - -class NolimitholdemPlayer(LimitHoldemPlayer): - def __init__(self, player_id, init_chips, np_random): - """""" - Initialize a player. - - Args: - player_id (int): The id of the player - init_chips (int): The number of chips the player has initially - """""" - super().__init__(player_id, np_random) - self.remained_chips = init_chips - - def bet(self, chips): - quantity = chips if chips <= self.remained_chips else self.remained_chips - self.in_chips += quantity - self.remained_chips -= quantity - - -''' -nolimitholdem/dealer.py -''' -from nolimitholdem.utils import init_standard_deck - -class NolimitholdemDealer: - def __init__(self, np_random): - self.np_random = np_random - self.deck = init_standard_deck() - self.shuffle() - self.pot = 0 - - def shuffle(self): - self.np_random.shuffle(self.deck) - - def deal_card(self): - """""" - Deal one card from the deck - - Returns: - (Card): The drawn card from the deck - """""" - return self.deck.pop() - - -''' -nolimitholdem/judger.py -''' -from nolimitholdem.utils import compare_hands -import numpy as np - - -class NolimitholdemJudger: - """"""The Judger class for limit texas holdem"""""" - - def __init__(self, np_random): - self.np_random = np_random - - def judge_game(self, players, hands): - """""" - Judge the winner of the game. - - Args: - players (list): The list of players who play the game - hands (list): The list of hands that from the players - - Returns: - (list): Each entry of the list corresponds to one entry of the - """""" - # Convert the hands into card indexes - hands = [[card.get_index() for card in hand] if hand is not None else None for hand in hands] - - in_chips = [p.in_chips for p in players] - remaining = sum(in_chips) - payoffs = [0] * len(hands) - while remaining > 0: - winners = compare_hands(hands) - each_win = self.split_pots_among_players(in_chips, winners) - - for i in range(len(players)): - if winners[i]: - remaining -= each_win[i] - payoffs[i] += each_win[i] - in_chips[i] - hands[i] = None - in_chips[i] = 0 - elif in_chips[i] > 0: - payoffs[i] += each_win[i] - in_chips[i] - in_chips[i] = each_win[i] - - assert sum(payoffs) == 0 - return payoffs - - def split_pot_among_players(self, in_chips, winners): - """""" - Splits the next (side) pot among players. - Function is called in loop by distribute_pots_among_players until all chips are allocated. - - Args: - in_chips (list): List with number of chips bet not yet distributed for each player - winners (list): List with 1 if the player is among winners else 0 - - Returns: - (list): Of how much chips each player get after this pot has been split and list of chips left to distribute - """""" - nb_winners_in_pot = sum((winners[i] and in_chips[i] > 0) for i in range(len(in_chips))) - nb_players_in_pot = sum(in_chips[i] > 0 for i in range(len(in_chips))) - if nb_winners_in_pot == 0 or nb_winners_in_pot == nb_players_in_pot: - # no winner or all winners for this pot - allocated = list(in_chips) # we give back their chips to each players in this pot - in_chips_after = len(in_chips) * [0] # no more chips to distribute - else: - amount_in_pot_by_player = min(v for v in in_chips if v > 0) - how_much_one_win, remaining = divmod(amount_in_pot_by_player * nb_players_in_pot, nb_winners_in_pot) - ''' - In the event of a split pot that cannot be divided equally for every winner, the winner who is sitting - closest to the left of the dealer receives the remaining differential in chips cf - https://www.betclic.fr/poker/house-rules--play-safely--betclic-poker-cpok_rules to simplify and as this - case is very rare, we will give the remaining differential in chips to a random winner - ''' - allocated = len(in_chips) * [0] - in_chips_after = list(in_chips) - for i in range(len(in_chips)): # iterate on all players - if in_chips[i] == 0: # player not in pot - continue - if winners[i]: - allocated[i] += how_much_one_win - in_chips_after[i] -= amount_in_pot_by_player - if remaining > 0: - random_winning_player = self.np_random.choice( - [i for i in range(len(winners)) if winners[i] and in_chips[i] > 0]) - allocated[random_winning_player] += remaining - assert sum(in_chips[i] - in_chips_after[i] for i in range(len(in_chips))) == sum(allocated) - return allocated, in_chips_after - - def split_pots_among_players(self, in_chips_initial, winners): - """""" - Splits main pot and side pots among players (to handle special case of all-in players). - - Args: - in_chips_initial (list): List with number of chips bet for each player - winners (list): List with 1 if the player is among winners else 0 - - Returns: - (list): List of how much chips each player get back after all pots have been split - """""" - in_chips = list(in_chips_initial) - assert len(in_chips) == len(winners) - assert all(v == 0 or v == 1 for v in winners) - assert sum(winners) >= 1 # there must be at least one winner - allocated = np.zeros(len(in_chips), dtype=int) - while any(v > 0 for v in in_chips): # while there are still chips to allocate - allocated_current_pot, in_chips = self.split_pot_among_players(in_chips, winners) - allocated += allocated_current_pot # element-wise addition - assert all(chips >= 0 for chips in allocated) # check that all players got a non negative amount of chips - assert sum(in_chips_initial) == sum(allocated) # check that all chips bet have been allocated - return list(allocated) - - -''' -nolimitholdem/game.py -''' -from enum import Enum - -import numpy as np -from copy import deepcopy -from nolimitholdem import PlayerStatus - -from nolimitholdem import Dealer -from nolimitholdem import Player -from nolimitholdem import Judger -from nolimitholdem import Round, Action - - -from copy import deepcopy, copy -# import numpy as np - -# from limitholdem import Dealer -# from limitholdem import Player, PlayerStatus -# from limitholdem import Judger -# from limitholdem import Round - - -class LimitHoldemGame: - def __init__(self, allow_step_back=False, num_players=2): - """"""Initialize the class limit holdem game"""""" - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - - # Some configurations of the game - # These arguments can be specified for creating new games - - # Small blind and big blind - self.small_blind = 1 - self.big_blind = 2 * self.small_blind - - # Raise amount and allowed times - self.raise_amount = self.big_blind - self.allowed_raise_num = 4 - - self.num_players = num_players - - # Save betting history - self.history_raise_nums = [0 for _ in range(4)] - - self.dealer = None - self.players = None - self.judger = None - self.public_cards = None - self.game_pointer = None - self.round = None - self.round_counter = None - self.history = None - self.history_raises_nums = None - - def configure(self, game_config): - """"""Specify some game specific parameters, such as number of players"""""" - self.num_players = game_config['game_num_players'] - - def init_game(self): - """""" - Initialize the game of limit texas holdem - - This version supports two-player limit texas holdem - - Returns: - (tuple): Tuple containing: - - (dict): The first state of the game - (int): Current player's id - """""" - # Initialize a dealer that can deal cards - self.dealer = Dealer(self.np_random) - - # Initialize two players to play the game - self.players = [Player(i, self.np_random) for i in range(self.num_players)] - - # Initialize a judger class which will decide who wins in the end - self.judger = Judger(self.np_random) - - # Deal cards to each player to prepare for the first round - for i in range(2 * self.num_players): - self.players[i % self.num_players].hand.append(self.dealer.deal_card()) - - # Initialize public cards - self.public_cards = [] - - # Randomly choose a small blind and a big blind - s = self.np_random.randint(0, self.num_players) - b = (s + 1) % self.num_players - self.players[b].in_chips = self.big_blind - self.players[s].in_chips = self.small_blind - - # The player next to the big blind plays the first - self.game_pointer = (b + 1) % self.num_players - - # Initialize a bidding round, in the first round, the big blind and the small blind needs to - # be passed to the round for processing. - self.round = Round(raise_amount=self.raise_amount, - allowed_raise_num=self.allowed_raise_num, - num_players=self.num_players, - np_random=self.np_random) - - self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players]) - - # Count the round. There are 4 rounds in each game. - self.round_counter = 0 - - # Save the history for stepping back to the last state. - self.history = [] - - state = self.get_state(self.game_pointer) - - # Save betting history - self.history_raise_nums = [0 for _ in range(4)] - - return state, self.game_pointer - - def step(self, action): - """""" - Get the next state - - Args: - action (str): a specific action. (call, raise, fold, or check) - - Returns: - (tuple): Tuple containing: - - (dict): next player's state - (int): next player id - """""" - if self.allow_step_back: - # First snapshot the current state - r = deepcopy(self.round) - b = self.game_pointer - r_c = self.round_counter - d = deepcopy(self.dealer) - p = deepcopy(self.public_cards) - ps = deepcopy(self.players) - rn = copy(self.history_raise_nums) - self.history.append((r, b, r_c, d, p, ps, rn)) - - # Then we proceed to the next round - self.game_pointer = self.round.proceed_round(self.players, action) - - # Save the current raise num to history - self.history_raise_nums[self.round_counter] = self.round.have_raised - - # If a round is over, we deal more public cards - if self.round.is_over(): - # For the first round, we deal 3 cards - if self.round_counter == 0: - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - - # For the following rounds, we deal only 1 card - elif self.round_counter <= 2: - self.public_cards.append(self.dealer.deal_card()) - - # Double the raise amount for the last two rounds - if self.round_counter == 1: - self.round.raise_amount = 2 * self.raise_amount - - self.round_counter += 1 - self.round.start_new_round(self.game_pointer) - - state = self.get_state(self.game_pointer) - - return state, self.game_pointer - - def step_back(self): - """""" - Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - """""" - if len(self.history) > 0: - self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \ - self.players, self.history_raises_nums = self.history.pop() - return True - return False - - def get_num_players(self): - """""" - Return the number of players in limit texas holdem - - Returns: - (int): The number of players in the game - """""" - return self.num_players - - @staticmethod - def get_num_actions(): - """""" - Return the number of applicable actions - - Returns: - (int): The number of actions. There are 4 actions (call, raise, check and fold) - """""" - return 4 - - def get_player_id(self): - """""" - Return the current player's id - - Returns: - (int): current player's id - """""" - return self.game_pointer - - def get_state(self, player): - """""" - Return player's state - - Args: - player (int): player id - - Returns: - (dict): The state of the player - """""" - chips = [self.players[i].in_chips for i in range(self.num_players)] - legal_actions = self.get_legal_actions() - state = self.players[player].get_state(self.public_cards, chips, legal_actions) - state['raise_nums'] = self.history_raise_nums - - return state - - def is_over(self): - """""" - Check if the game is over - - Returns: - (boolean): True if the game is over - """""" - alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players] - # If only one player is alive, the game is over. - if sum(alive_players) == 1: - return True - - # If all rounds are finished - if self.round_counter >= 4: - return True - return False - - def get_payoffs(self): - """""" - Return the payoffs of the game - - Returns: - (list): Each entry corresponds to the payoff of one player - """""" - hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players] - chips_payoffs = self.judger.judge_game(self.players, hands) - payoffs = np.array(chips_payoffs) / self.big_blind - return payoffs - - def get_legal_actions(self): - """""" - Return the legal actions for current player - - Returns: - (list): A list of legal actions - """""" - return self.round.get_legal_actions() - - - -class Stage(Enum): - PREFLOP = 0 - FLOP = 1 - TURN = 2 - RIVER = 3 - END_HIDDEN = 4 - SHOWDOWN = 5 - - -class NolimitholdemGame(LimitHoldemGame): - def __init__(self, allow_step_back=False, num_players=2): - """"""Initialize the class no limit holdem Game"""""" - super().__init__(allow_step_back, num_players) - - self.np_random = np.random.RandomState() - - # small blind and big blind - self.small_blind = 1 - self.big_blind = 2 * self.small_blind - - # config players - self.init_chips = [100] * num_players - - # If None, the dealer will be randomly chosen - self.dealer_id = None - - def configure(self, game_config): - """""" - Specify some game specific parameters, such as number of players, initial chips, and dealer id. - If dealer_id is None, he will be randomly chosen - """""" - self.num_players = game_config['game_num_players'] - # must have num_players length - self.init_chips = [game_config['chips_for_each']] * game_config[""game_num_players""] - self.dealer_id = game_config['dealer_id'] - - def init_game(self): - """""" - Initialize the game of not limit holdem - - This version supports two-player no limit texas holdem - - Returns: - (tuple): Tuple containing: - - (dict): The first state of the game - (int): Current player's id - """""" - if self.dealer_id is None: - self.dealer_id = self.np_random.randint(0, self.num_players) - - # Initialize a dealer that can deal cards - self.dealer = Dealer(self.np_random) - - # Initialize players to play the game - self.players = [Player(i, self.init_chips[i], self.np_random) for i in range(self.num_players)] - - # Initialize a judger class which will decide who wins in the end - self.judger = Judger(self.np_random) - - # Deal cards to each player to prepare for the first round - for i in range(2 * self.num_players): - self.players[i % self.num_players].hand.append(self.dealer.deal_card()) - - # Initialize public cards - self.public_cards = [] - self.stage = Stage.PREFLOP - - # Big blind and small blind - s = (self.dealer_id + 1) % self.num_players - b = (self.dealer_id + 2) % self.num_players - self.players[b].bet(chips=self.big_blind) - self.players[s].bet(chips=self.small_blind) - - # The player next to the big blind plays the first - self.game_pointer = (b + 1) % self.num_players - - # Initialize a bidding round, in the first round, the big blind and the small blind needs to - # be passed to the round for processing. - self.round = Round(self.num_players, self.big_blind, dealer=self.dealer, np_random=self.np_random) - - self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players]) - - # Count the round. There are 4 rounds in each game. - self.round_counter = 0 - - # Save the history for stepping back to the last state. - self.history = [] - - state = self.get_state(self.game_pointer) - - return state, self.game_pointer - - def get_legal_actions(self): - """""" - Return the legal actions for current player - - Returns: - (list): A list of legal actions - """""" - return self.round.get_nolimit_legal_actions(players=self.players) - - def step(self, action): - """""" - Get the next state - - Args: - action (str): a specific action. (call, raise, fold, or check) - - Returns: - (tuple): Tuple containing: - - (dict): next player's state - (int): next player id - """""" - - if action not in self.get_legal_actions(): - print(action, self.get_legal_actions()) - print(self.get_state(self.game_pointer)) - raise Exception('Action not allowed') - - if self.allow_step_back: - # First snapshot the current state - r = deepcopy(self.round) - b = self.game_pointer - r_c = self.round_counter - d = deepcopy(self.dealer) - p = deepcopy(self.public_cards) - ps = deepcopy(self.players) - self.history.append((r, b, r_c, d, p, ps)) - - # Then we proceed to the next round - self.game_pointer = self.round.proceed_round(self.players, action) - - players_in_bypass = [1 if player.status in (PlayerStatus.FOLDED, PlayerStatus.ALLIN) else 0 for player in self.players] - if self.num_players - sum(players_in_bypass) == 1: - last_player = players_in_bypass.index(0) - if self.round.raised[last_player] >= max(self.round.raised): - # If the last player has put enough chips, he is also bypassed - players_in_bypass[last_player] = 1 - - # If a round is over, we deal more public cards - if self.round.is_over(): - # Game pointer goes to the first player not in bypass after the dealer, if there is one - self.game_pointer = (self.dealer_id + 1) % self.num_players - if sum(players_in_bypass) < self.num_players: - while players_in_bypass[self.game_pointer]: - self.game_pointer = (self.game_pointer + 1) % self.num_players - - # For the first round, we deal 3 cards - if self.round_counter == 0: - self.stage = Stage.FLOP - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - if len(self.players) == np.sum(players_in_bypass): - self.round_counter += 1 - # For the following rounds, we deal only 1 card - if self.round_counter == 1: - self.stage = Stage.TURN - self.public_cards.append(self.dealer.deal_card()) - if len(self.players) == np.sum(players_in_bypass): - self.round_counter += 1 - if self.round_counter == 2: - self.stage = Stage.RIVER - self.public_cards.append(self.dealer.deal_card()) - if len(self.players) == np.sum(players_in_bypass): - self.round_counter += 1 - - self.round_counter += 1 - self.round.start_new_round(self.game_pointer) - - state = self.get_state(self.game_pointer) - - return state, self.game_pointer - - def get_state(self, player_id): - """""" - Return player's state - - Args: - player_id (int): player id - - Returns: - (dict): The state of the player - """""" - self.dealer.pot = np.sum([player.in_chips for player in self.players]) - - chips = [self.players[i].in_chips for i in range(self.num_players)] - legal_actions = self.get_legal_actions() - state = self.players[player_id].get_state(self.public_cards, chips, legal_actions) - state['stakes'] = [self.players[i].remained_chips for i in range(self.num_players)] - state['current_player'] = self.game_pointer - state['pot'] = self.dealer.pot - state['stage'] = self.stage - return state - - def step_back(self): - """""" - Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - """""" - if len(self.history) > 0: - self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, self.players = self.history.pop() - self.stage = Stage(self.round_counter) - return True - return False - - def get_num_players(self): - """""" - Return the number of players in no limit texas holdem - - Returns: - (int): The number of players in the game - """""" - return self.num_players - - def get_payoffs(self): - """""" - Return the payoffs of the game - - Returns: - (list): Each entry corresponds to the payoff of one player - """""" - hands = [p.hand + self.public_cards if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else None for p in self.players] - chips_payoffs = self.judger.judge_game(self.players, hands) - return chips_payoffs - - @staticmethod - def get_num_actions(): - """""" - Return the number of applicable actions - - Returns: - (int): The number of actions. There are 6 actions (call, raise_half_pot, raise_pot, all_in, check and fold) - """""" - return len(Action) - - -''' -nolimitholdem/utils.py -''' -import numpy as np -from nolimitholdem import Card - -def init_standard_deck(): - ''' Initialize a standard deck of 52 cards - - Returns: - (list): A list of Card object - ''' - suit_list = ['S', 'H', 'D', 'C'] - rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - res = [Card(suit, rank) for suit in suit_list for rank in rank_list] - return res - - -class Hand: - def __init__(self, all_cards): - self.all_cards = all_cards # two hand cards + five public cards - self.category = 0 - #type of a players' best five cards, greater combination has higher number eg: 0:""Not_Yet_Evaluated"" 1: ""High_Card"" , 9:""Straight_Flush"" - self.best_five = [] - #the largest combination of five cards in all the seven cards - self.flush_cards = [] - #cards with same suit - self.cards_by_rank = [] - #cards after sort - self.product = 1 - #cards’ type indicator - self.RANK_TO_STRING = {2: ""2"", 3: ""3"", 4: ""4"", 5: ""5"", 6: ""6"", - 7: ""7"", 8: ""8"", 9: ""9"", 10: ""T"", 11: ""J"", 12: ""Q"", 13: ""K"", 14: ""A""} - self.STRING_TO_RANK = {v:k for k, v in self.RANK_TO_STRING.items()} - self.RANK_LOOKUP = ""23456789TJQKA"" - self.SUIT_LOOKUP = ""SCDH"" - - def get_hand_five_cards(self): - ''' - Get the best five cards of a player - Returns: - (list): the best five cards among the seven cards of a player - ''' - return self.best_five - - def _sort_cards(self): - ''' - Sort all the seven cards ascendingly according to RANK_LOOKUP - ''' - self.all_cards = sorted( - self.all_cards, key=lambda card: self.RANK_LOOKUP.index(card[1])) - - def evaluateHand(self): - """""" - Evaluate all the seven cards, get the best combination catagory - And pick the best five cards (for comparing in case 2 hands have the same Category) . - """""" - if len(self.all_cards) != 7: - raise Exception( - ""There are not enough 7 cards in this hand, quit evaluation now ! "") - - self._sort_cards() - self.cards_by_rank, self.product = self._getcards_by_rank( - self.all_cards) - - if self._has_straight_flush(): - self.category = 9 - #Straight Flush - elif self._has_four(): - self.category = 8 - #Four of a Kind - self.best_five = self._get_Four_of_a_kind_cards() - elif self._has_fullhouse(): - self.category = 7 - #Full house - self.best_five = self._get_Fullhouse_cards() - elif self._has_flush(): - self.category = 6 - #Flush - i = len(self.flush_cards) - self.best_five = [card for card in self.flush_cards[i-5:i]] - elif self._has_straight(self.all_cards): - self.category = 5 - #Straight - elif self._has_three(): - self.category = 4 - #Three of a Kind - self.best_five = self._get_Three_of_a_kind_cards() - elif self._has_two_pairs(): - self.category = 3 - #Two Pairs - self.best_five = self._get_Two_Pair_cards() - elif self._has_pair(): - self.category = 2 - #One Pair - self.best_five = self._get_One_Pair_cards() - elif self._has_high_card(): - self.category = 1 - #High Card - self.best_five = self._get_High_cards() - - def _has_straight_flush(self): - ''' - Check the existence of straight_flush cards - Returns: - True: exist - False: not exist - ''' - self.flush_cards = self._getflush_cards() - if len(self.flush_cards) > 0: - straightflush_cards = self._get_straightflush_cards() - if len(straightflush_cards) > 0: - self.best_five = straightflush_cards - return True - return False - - def _get_straightflush_cards(self): - ''' - Pick straight_flush cards - Returns: - (list): the straightflush cards - ''' - straightflush_cards = self._get_straight_cards(self.flush_cards) - return straightflush_cards - - def _getflush_cards(self): - ''' - Pick flush cards - Returns: - (list): the flush cards - ''' - card_string = ''.join(self.all_cards) - for suit in self.SUIT_LOOKUP: - suit_count = card_string.count(suit) - if suit_count >= 5: - flush_cards = [ - card for card in self.all_cards if card[0] == suit] - return flush_cards - return [] - - def _has_flush(self): - ''' - Check the existence of flush cards - Returns: - True: exist - False: not exist - ''' - if len(self.flush_cards) > 0: - return True - else: - return False - - def _has_straight(self, all_cards): - ''' - Check the existence of straight cards - Returns: - True: exist - False: not exist - ''' - diff_rank_cards = self._get_different_rank_list(all_cards) - self.best_five = self._get_straight_cards(diff_rank_cards) - if len(self.best_five) != 0: - return True - else: - return False - @classmethod - def _get_different_rank_list(self, all_cards): - ''' - Get cards with different ranks, that is to say, remove duplicate-ranking cards, for picking straight cards' use - Args: - (list): two hand cards + five public cards - Returns: - (list): a list of cards with duplicate-ranking cards removed - ''' - different_rank_list = [] - different_rank_list.append(all_cards[0]) - for card in all_cards: - if(card[1] != different_rank_list[-1][1]): - different_rank_list.append(card) - return different_rank_list - - def _get_straight_cards(self, Cards): - ''' - Pick straight cards - Returns: - (list): the straight cards - ''' - ranks = [self.STRING_TO_RANK[c[1]] for c in Cards] - - highest_card = Cards[-1] - if highest_card[1] == 'A': - Cards.insert(0, highest_card) - ranks.insert(0, 1) - - for i_last in range(len(ranks) - 1, 3, -1): - if ranks[i_last-4] + 4 == ranks[i_last]: # works because ranks are unique and sorted in ascending order - return Cards[i_last-4:i_last+1] - return [] - - def _getcards_by_rank(self, all_cards): - ''' - Get cards by rank - Args: - (list): # two hand cards + five public cards - Return: - card_group(list): cards after sort - product(int):cards‘ type indicator - ''' - card_group = [] - card_group_element = [] - product = 1 - prime_lookup = {0: 1, 1: 1, 2: 2, 3: 3, 4: 5} - count = 0 - current_rank = 0 - - for card in all_cards: - rank = self.RANK_LOOKUP.index(card[1]) - if rank == current_rank: - count += 1 - card_group_element.append(card) - elif rank != current_rank: - product *= prime_lookup[count] - # Explanation : - # if count == 2, then product *= 2 - # if count == 3, then product *= 3 - # if count == 4, then product *= 5 - # if there is a Quad, then product = 5 ( 4, 1, 1, 1) or product = 10 ( 4, 2, 1) or product= 15 (4,3) - # if there is a Fullhouse, then product = 12 ( 3, 2, 2) or product = 9 (3, 3, 1) or product = 6 ( 3, 2, 1, 1) - # if there is a Trip, then product = 3 ( 3, 1, 1, 1, 1) - # if there is two Pair, then product = 4 ( 2, 1, 2, 1, 1) or product = 8 ( 2, 2, 2, 1) - # if there is one Pair, then product = 2 (2, 1, 1, 1, 1, 1) - # if there is HighCard, then product = 1 (1, 1, 1, 1, 1, 1, 1) - card_group_element.insert(0, count) - card_group.append(card_group_element) - # reset counting - count = 1 - card_group_element = [] - card_group_element.append(card) - current_rank = rank - # the For Loop misses operation for the last card - # These 3 lines below to compensate that - product *= prime_lookup[count] - # insert the number of same rank card to the beginning of the - card_group_element.insert(0, count) - # after the loop, there is still one last card to add - card_group.append(card_group_element) - return card_group, product - - def _has_four(self): - ''' - Check the existence of four cards - Returns: - True: exist - False: not exist - ''' - if self.product == 5 or self.product == 10 or self.product == 15: - return True - else: - return False - - def _has_fullhouse(self): - ''' - Check the existence of fullhouse cards - Returns: - True: exist - False: not exist - ''' - if self.product == 6 or self.product == 9 or self.product == 12: - return True - else: - return False - - def _has_three(self): - ''' - Check the existence of three cards - Returns: - True: exist - False: not exist - ''' - if self.product == 3: - return True - else: - return False - - def _has_two_pairs(self): - ''' - Check the existence of 2 pair cards - Returns: - True: exist - False: not exist - ''' - if self.product == 4 or self.product == 8: - return True - else: - return False - - def _has_pair(self): - ''' - Check the existence of 1 pair cards - Returns: - True: exist - False: not exist - ''' - if self.product == 2: - return True - else: - return False - - def _has_high_card(self): - ''' - Check the existence of high cards - Returns: - True: exist - False: not exist - ''' - if self.product == 1: - return True - else: - return False - - def _get_Four_of_a_kind_cards(self): - ''' - Get the four of a kind cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Four_of_a_Kind = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 4: - Four_of_a_Kind = cards_by_rank.pop(i) - break - # The Last cards_by_rank[The Second element] - kicker = cards_by_rank[-1][1] - Four_of_a_Kind[0] = kicker - - return Four_of_a_Kind - - def _get_Fullhouse_cards(self): - ''' - Get the fullhouse cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Fullhouse = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 3: - Trips = cards_by_rank.pop(i)[1:4] - break - for i in reversed(range(cards_len - 1)): - if cards_by_rank[i][0] >= 2: - TwoPair = cards_by_rank.pop(i)[1:3] - break - Fullhouse = TwoPair + Trips - return Fullhouse - - def _get_Three_of_a_kind_cards(self): - ''' - Get the three of a kind cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Trip_cards = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 3: - Trip_cards += cards_by_rank.pop(i)[1:4] - break - - Trip_cards += cards_by_rank.pop(-1)[1:2] - Trip_cards += cards_by_rank.pop(-1)[1:2] - Trip_cards.reverse() - return Trip_cards - - def _get_Two_Pair_cards(self): - ''' - Get the two pair cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Two_Pair_cards = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 2 and len(Two_Pair_cards) < 3: - Two_Pair_cards += cards_by_rank.pop(i)[1:3] - - Two_Pair_cards += cards_by_rank.pop(-1)[1:2] - Two_Pair_cards.reverse() - return Two_Pair_cards - - def _get_One_Pair_cards(self): - ''' - Get the one pair cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - One_Pair_cards = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 2: - One_Pair_cards += cards_by_rank.pop(i)[1:3] - break - - One_Pair_cards += cards_by_rank.pop(-1)[1:2] - One_Pair_cards += cards_by_rank.pop(-1)[1:2] - One_Pair_cards += cards_by_rank.pop(-1)[1:2] - One_Pair_cards.reverse() - return One_Pair_cards - - def _get_High_cards(self): - ''' - Get the high cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - High_cards = self.all_cards[2:7] - return High_cards - -def compare_ranks(position, hands, winner): - ''' - Compare cards in same position of plays' five handcards - Args: - position(int): the position of a card in a sorted handcard - hands(list): cards of those players. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - winner: array of same length than hands with 1 if the hand is among winners and 0 among losers - Returns: - new updated winner array - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - ''' - assert len(hands) == len(winner) - RANKS = '23456789TJQKA' - cards_figure_all_players = [None]*len(hands) #cards without suit - for i, hand in enumerate(hands): - if winner[i]: - cards = hands[i].get_hand_five_cards() - if len(cards[0]) != 1:# remove suit - for p in range(5): - cards[p] = cards[p][1:] - cards_figure_all_players[i] = cards - - rival_ranks = [] # ranks of rival_figures - for i, cards_figure in enumerate(cards_figure_all_players): - if winner[i]: - rank = cards_figure_all_players[i][position] - rival_ranks.append(RANKS.index(rank)) - else: - rival_ranks.append(-1) # player has already lost - new_winner = list(winner) - for i, rival_rank in enumerate(rival_ranks): - if rival_rank != max(rival_ranks): - new_winner[i] = 0 - return new_winner - -def determine_winner(key_index, hands, all_players, potential_winner_index): - ''' - Find out who wins in the situation of having players with same highest hand_catagory - Args: - key_index(int): the position of a card in a sorted handcard - hands(list): cards of those players with same highest hand_catagory. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - all_players(list): all the players in this round, 0 for losing and 1 for winning or draw - potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - ''' - winner = [1]*len(hands) - i_index = 0 - while i_index < len(key_index) and sum(winner) > 1: - index_break_tie = key_index[i_index] - winner = compare_ranks(index_break_tie, hands, winner) - i_index += 1 - for i in range(len(potential_winner_index)): - if winner[i]: - all_players[potential_winner_index[i]] = 1 - return all_players - -def determine_winner_straight(hands, all_players, potential_winner_index): - ''' - Find out who wins in the situation of having players all having a straight or straight flush - Args: - key_index(int): the position of a card in a sorted handcard - hands(list): cards of those players which all have a straight or straight flush - all_players(list): all the players in this round, 0 for losing and 1 for winning or draw - potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - ''' - highest_ranks = [] - for hand in hands: - highest_rank = hand.STRING_TO_RANK[hand.best_five[-1][1]] # cards are sorted in ascending order - highest_ranks.append(highest_rank) - max_highest_rank = max(highest_ranks) - for i_player in range(len(highest_ranks)): - if highest_ranks[i_player] == max_highest_rank: - all_players[potential_winner_index[i_player]] = 1 - return all_players - -def determine_winner_four_of_a_kind(hands, all_players, potential_winner_index): - ''' - Find out who wins in the situation of having players which all have a four of a kind - Args: - key_index(int): the position of a card in a sorted handcard - hands(list): cards of those players with a four of a kind - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - all_players(list): all the players in this round, 0 for losing and 1 for winning or draw - potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - ''' - ranks = [] - for hand in hands: - rank_1 = hand.STRING_TO_RANK[hand.best_five[-1][1]] # rank of the four of a kind - rank_2 = hand.STRING_TO_RANK[hand.best_five[0][1]] # rank of the kicker - ranks.append((rank_1, rank_2)) - max_rank = max(ranks) - for i, rank in enumerate(ranks): - if rank == max_rank: - all_players[potential_winner_index[i]] = 1 - return all_players - -def compare_hands(hands): - ''' - Compare all palyer's all seven cards - Args: - hands(list): cards of those players with same highest hand_catagory. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - if hands[0] == None: - return [0, 1] - elif hands[1] == None: - return [1, 0] - ''' - hand_category = [] #such as high_card, straight_flush, etc - all_players = [0]*len(hands) #all the players in this round, 0 for losing and 1 for winning or draw - if None in hands: - fold_players = [i for i, j in enumerate(hands) if j is None] - if len(fold_players) == len(all_players) - 1: - for _ in enumerate(hands): - if _[0] in fold_players: - all_players[_[0]] = 0 - else: - all_players[_[0]] = 1 - return all_players - else: - for _ in enumerate(hands): - if hands[_[0]] is not None: - hand = Hand(hands[_[0]]) - hand.evaluateHand() - hand_category.append(hand.category) - elif hands[_[0]] is None: - hand_category.append(0) - else: - for i in enumerate(hands): - hand = Hand(hands[i[0]]) - hand.evaluateHand() - hand_category.append(hand.category) - 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 - - return final_compare(hands, potential_winner_index, all_players) - -def final_compare(hands, potential_winner_index, all_players): - ''' - Find out the winners from those who didn't fold - Args: - hands(list): cards of those players with same highest hand_catagory. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - potential_winner_index(list): index of those with same max card_catagory in all_players - all_players(list): a list of all the player's win/lose situation, 0 for lose and 1 for win - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - if hands[0] == None: - return [0, 1] - elif hands[1] == None: - return [1, 0] - ''' - if len(potential_winner_index) == 1: - all_players[potential_winner_index[0]] = 1 - return all_players - elif len(potential_winner_index) > 1: - # compare when having equal max categories - equal_hands = [] - for _ in potential_winner_index: - hand = Hand(hands[_]) - hand.evaluateHand() - equal_hands.append(hand) - hand = equal_hands[0] - if hand.category == 8: - return determine_winner_four_of_a_kind(equal_hands, all_players, potential_winner_index) - if hand.category == 7: - return determine_winner([2, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 4: - return determine_winner([2, 1, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 3: - return determine_winner([4, 2, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 2: - return determine_winner([4, 2, 1, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 1 or hand.category == 6: - return determine_winner([4, 3, 2, 1, 0], equal_hands, all_players, potential_winner_index) - if hand.category in [5, 9]: - return determine_winner_straight(equal_hands, all_players, potential_winner_index) - - -''' -nolimitholdem/__init__.py -''' -from nolimitholdem.base import Card as Card - -from nolimitholdem.dealer import NolimitholdemDealer as Dealer -from nolimitholdem.judger import NolimitholdemJudger as Judger -from nolimitholdem.player import NolimitholdemPlayer as Player -from nolimitholdem.player import PlayerStatus -from nolimitholdem.round import Action -from nolimitholdem.round import NolimitholdemRound as Round -from nolimitholdem.game import NolimitholdemGame as Game - - - -''' -nolimitholdem/round.py -''' -# -*- coding: utf-8 -*- -""""""Implement no limit texas holdem Round class"""""" -from enum import Enum - -from nolimitholdem import PlayerStatus - - -class Action(Enum): - FOLD = 0 - CHECK_CALL = 1 - #CALL = 2 - # RAISE_3BB = 3 - RAISE_HALF_POT = 2 - RAISE_POT = 3 - # RAISE_2POT = 5 - ALL_IN = 4 - # SMALL_BLIND = 7 - # BIG_BLIND = 8 - - -class NolimitholdemRound: - """"""Round can call functions from other classes to keep the game running"""""" - - def __init__(self, num_players, init_raise_amount, dealer, np_random): - """""" - Initialize the round class - - Args: - num_players (int): The number of players - init_raise_amount (int): The min raise amount when every round starts - """""" - self.np_random = np_random - self.game_pointer = None - self.num_players = num_players - self.init_raise_amount = init_raise_amount - - self.dealer = dealer - - # Count the number without raise - # If every player agree to not raise, the round is over - self.not_raise_num = 0 - - # Count players that are not playing anymore (folded or all-in) - self.not_playing_num = 0 - - # Raised amount for each player - self.raised = [0 for _ in range(self.num_players)] - - def start_new_round(self, game_pointer, raised=None): - """""" - Start a new bidding round - - Args: - game_pointer (int): The game_pointer that indicates the next player - raised (list): Initialize the chips for each player - - Note: For the first round of the game, we need to setup the big/small blind - """""" - self.game_pointer = game_pointer - self.not_raise_num = 0 - if raised: - self.raised = raised - else: - self.raised = [0 for _ in range(self.num_players)] - - def proceed_round(self, players, action): - """""" - Call functions from other classes to keep one round running - - Args: - players (list): The list of players that play the game - action (str/int): An legal action taken by the player - - Returns: - (int): The game_pointer that indicates the next player - """""" - player = players[self.game_pointer] - - if action == Action.CHECK_CALL: - diff = max(self.raised) - self.raised[self.game_pointer] - self.raised[self.game_pointer] = max(self.raised) - player.bet(chips=diff) - self.not_raise_num += 1 - - elif action == Action.ALL_IN: - all_in_quantity = player.remained_chips - self.raised[self.game_pointer] = all_in_quantity + self.raised[self.game_pointer] - player.bet(chips=all_in_quantity) - - self.not_raise_num = 1 - - elif action == Action.RAISE_POT: - self.raised[self.game_pointer] += self.dealer.pot - player.bet(chips=self.dealer.pot) - self.not_raise_num = 1 - - elif action == Action.RAISE_HALF_POT: - quantity = int(self.dealer.pot / 2) - self.raised[self.game_pointer] += quantity - player.bet(chips=quantity) - self.not_raise_num = 1 - - elif action == Action.FOLD: - player.status = PlayerStatus.FOLDED - - if player.remained_chips < 0: - raise Exception(""Player in negative stake"") - - if player.remained_chips == 0 and player.status != PlayerStatus.FOLDED: - player.status = PlayerStatus.ALLIN - - self.game_pointer = (self.game_pointer + 1) % self.num_players - - if player.status == PlayerStatus.ALLIN: - self.not_playing_num += 1 - self.not_raise_num -= 1 # Because already counted in not_playing_num - if player.status == PlayerStatus.FOLDED: - self.not_playing_num += 1 - - # Skip the folded players - while players[self.game_pointer].status == PlayerStatus.FOLDED: - self.game_pointer = (self.game_pointer + 1) % self.num_players - - return self.game_pointer - - def get_nolimit_legal_actions(self, players): - """""" - Obtain the legal actions for the current player - - Args: - players (list): The players in the game - - Returns: - (list): A list of legal actions - """""" - - full_actions = list(Action) - - # The player can always check or call - player = players[self.game_pointer] - - diff = max(self.raised) - self.raised[self.game_pointer] - # If the current player has no more chips after call, we cannot raise - if diff > 0 and diff >= player.remained_chips: - full_actions.remove(Action.RAISE_HALF_POT) - full_actions.remove(Action.RAISE_POT) - full_actions.remove(Action.ALL_IN) - # Even if we can raise, we have to check remained chips - else: - if self.dealer.pot > player.remained_chips: - full_actions.remove(Action.RAISE_POT) - - if int(self.dealer.pot / 2) > player.remained_chips: - full_actions.remove(Action.RAISE_HALF_POT) - - # Can't raise if the total raise amount is leq than the max raise amount of this round - # If raise by pot, there is no such concern - if Action.RAISE_HALF_POT in full_actions and \ - int(self.dealer.pot / 2) + self.raised[self.game_pointer] <= max(self.raised): - full_actions.remove(Action.RAISE_HALF_POT) - - return full_actions - - def is_over(self): - """""" - Check whether the round is over - - Returns: - (boolean): True if the current round is over - """""" - if self.not_raise_num + self.not_playing_num >= self.num_players: - return True - return False - - -",8,1562 -stock3,./ProjectTest/Python/stock3.py,"''' -stock3/stock.py -''' -# stock.py - -from structure import Structure -from validate import String, PositiveInteger, PositiveFloat - -class Stock(Structure): - name = String('name') - shares = PositiveInteger('shares') - price = PositiveFloat('price') - - @property - def cost(self): - return self.shares * self.price - - def sell(self, nshares): - self.shares -= nshares - - -''' -stock3/reader.py -''' -# reader.py - -import csv -import logging - -log = logging.getLogger(__name__) - -def convert_csv(lines, converter, *, headers=None): - rows = csv.reader(lines) - if headers is None: - headers = next(rows) - - records = [] - for rowno, row in enumerate(rows, start=1): - try: - records.append(converter(headers, row)) - except ValueError as e: - log.warning('Row %s: Bad row: %s', rowno, row) - log.debug('Row %s: Reason: %s', rowno, row) - return records - -def csv_as_dicts(lines, types, *, headers=None): - return convert_csv(lines, - lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) }) - -def csv_as_instances(lines, cls, *, headers=None): - return convert_csv(lines, - lambda headers, row: cls.from_row(row)) - -def read_csv_as_dicts(filename, types, *, headers=None): - ''' - Read CSV data into a list of dictionaries with optional type conversion - ''' - with open(filename) as file: - return csv_as_dicts(file, types, headers=headers) - -def read_csv_as_instances(filename, cls, *, headers=None): - ''' - Read CSV data into a list of instances - ''' - with open(filename) as file: - return csv_as_instances(file, cls, headers=headers) - - - -''' -stock3/validate.py -''' -# validate.py - -class Validator: - def __init__(self, name=None): - self.name = name - - def __set_name__(self, cls, name): - self.name = name - - @classmethod - def check(cls, value): - return value - - def __set__(self, instance, value): - instance.__dict__[self.name] = self.check(value) - - # Collect all derived classes into a dict - validators = { } - @classmethod - def __init_subclass__(cls): - cls.validators[cls.__name__] = cls - -class Typed(Validator): - expected_type = object - @classmethod - def check(cls, value): - if not isinstance(value, cls.expected_type): - raise TypeError(f'expected {cls.expected_type}') - return super().check(value) - -_typed_classes = [ - ('Integer', int), - ('Float', float), - ('String', str) ] - -globals().update((name, type(name, (Typed,), {'expected_type':ty})) - for name, ty in _typed_classes) - -class Positive(Validator): - @classmethod - def check(cls, value): - if value < 0: - raise ValueError('must be >= 0') - return super().check(value) - -class NonEmpty(Validator): - @classmethod - def check(cls, value): - if len(value) == 0: - raise ValueError('must be non-empty') - return super().check(value) - -class PositiveInteger(Integer, Positive): - pass - -class PositiveFloat(Float, Positive): - pass - -class NonEmptyString(String, NonEmpty): - pass - -from inspect import signature -from functools import wraps - -def isvalidator(item): - return isinstance(item, type) and issubclass(item, Validator) - -def validated(func): - sig = signature(func) - - # Gather the function annotations - annotations = { name:val for name, val in func.__annotations__.items() - if isvalidator(val) } - - # Get the return annotation (if any) - retcheck = annotations.pop('return', None) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - # Enforce return check (if any) - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - - return wrapper - -def enforce(**annotations): - retcheck = annotations.pop('return_', None) - - def decorate(func): - sig = signature(func) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - return wrapper - return decorate - - -''' -stock3/structure.py -''' -# structure.py - -from validate import Validator, validated -from collections import ChainMap - -class StructureMeta(type): - @classmethod - def __prepare__(meta, clsname, bases): - return ChainMap({}, Validator.validators) - - @staticmethod - def __new__(meta, name, bases, methods): - methods = methods.maps[0] - return super().__new__(meta, name, bases, methods) - -class Structure(metaclass=StructureMeta): - _fields = () - _types = () - - def __setattr__(self, name, value): - if name.startswith('_') or name in self._fields: - super().__setattr__(name, value) - else: - raise AttributeError('No attribute %s' % name) - - def __repr__(self): - return '%s(%s)' % (type(self).__name__, - ', '.join(repr(getattr(self, name)) for name in self._fields)) - - def __iter__(self): - for name in self._fields: - yield getattr(self, name) - - def __eq__(self, other): - return isinstance(other, type(self)) and tuple(self) == tuple(other) - - @classmethod - def from_row(cls, row): - rowdata = [ func(val) for func, val in zip(cls._types, row) ] - return cls(*rowdata) - - - @classmethod - def create_init(cls): - ''' - Create an __init__ method from _fields - ''' - args = ','.join(cls._fields) - code = f'def __init__(self, {args}):\n' - for name in cls._fields: - code += f' self.{name} = {name}\n' - locs = { } - exec(code, locs) - cls.__init__ = locs['__init__'] - - @classmethod - def __init_subclass__(cls): - # Apply the validated decorator to subclasses - validate_attributes(cls) - -def validate_attributes(cls): - ''' - Class decorator that scans a class definition for Validators - and builds a _fields variable that captures their definition order. - ''' - validators = [] - for name, val in vars(cls).items(): - if isinstance(val, Validator): - validators.append(val) - - # Apply validated decorator to any callable with annotations - elif callable(val) and val.__annotations__: - setattr(cls, name, validated(val)) - - # Collect all of the field names - cls._fields = tuple([v.name for v in validators]) - - # Collect type conversions. The lambda x:x is an identity - # function that's used in case no expected_type is found. - cls._types = tuple([ getattr(v, 'expected_type', lambda x: x) - for v in validators ]) - - # Create the __init__ method - if cls._fields: - cls.create_init() - - - return cls - -def typed_structure(clsname, **validators): - cls = type(clsname, (Structure,), validators) - return cls - - -",4,286 -slugify,./ProjectTest/Python/slugify.py,"''' -slugify/slugify.py -''' -from __future__ import annotations - -import re -import unicodedata -from collections.abc import Iterable -from html.entities import name2codepoint - -try: - import unidecode -except ImportError: - import text_unidecode as unidecode - -__all__ = ['slugify', 'smart_truncate'] - - -CHAR_ENTITY_PATTERN = re.compile(r'&(%s);' % '|'.join(name2codepoint)) -DECIMAL_PATTERN = re.compile(r'&#(\d+);') -HEX_PATTERN = re.compile(r'&#x([\da-fA-F]+);') -QUOTE_PATTERN = re.compile(r'[\']+') -DISALLOWED_CHARS_PATTERN = re.compile(r'[^-a-zA-Z0-9]+') -DISALLOWED_UNICODE_CHARS_PATTERN = re.compile(r'[\W_]+') -DUPLICATE_DASH_PATTERN = re.compile(r'-{2,}') -NUMBERS_PATTERN = re.compile(r'(?<=\d),(?=\d)') -DEFAULT_SEPARATOR = '-' - - -def smart_truncate( - string: str, - max_length: int = 0, - word_boundary: bool = False, - separator: str = "" "", - save_order: bool = False, -) -> str: - """""" - Truncate a string. - :param string (str): string for modification - :param max_length (int): output string length - :param word_boundary (bool): - :param save_order (bool): if True then word order of output string is like input string - :param separator (str): separator between words - :return: - """""" - - string = string.strip(separator) - - if not max_length: - return string - - if len(string) < max_length: - return string - - if not word_boundary: - return string[:max_length].strip(separator) - - if separator not in string: - return string[:max_length] - - truncated = '' - for word in string.split(separator): - if word: - next_len = len(truncated) + len(word) - if next_len < max_length: - truncated += '{}{}'.format(word, separator) - elif next_len == max_length: - truncated += '{}'.format(word) - break - else: - if save_order: - break - if not truncated: # pragma: no cover - truncated = string[:max_length] - return truncated.strip(separator) - - -def slugify( - text: str, - entities: bool = True, - decimal: bool = True, - hexadecimal: bool = True, - max_length: int = 0, - word_boundary: bool = False, - separator: str = DEFAULT_SEPARATOR, - save_order: bool = False, - stopwords: Iterable[str] = (), - regex_pattern: re.Pattern[str] | str | None = None, - lowercase: bool = True, - replacements: Iterable[Iterable[str]] = (), - allow_unicode: bool = False, -) -> str: - """""" - Make a slug from the given text. - :param text (str): initial text - :param entities (bool): converts html entities to unicode - :param decimal (bool): converts html decimal to unicode - :param hexadecimal (bool): converts html hexadecimal to unicode - :param max_length (int): output string length - :param word_boundary (bool): truncates to complete word even if length ends up shorter than max_length - :param save_order (bool): if parameter is True and max_length > 0 return whole words in the initial order - :param separator (str): separator between words - :param stopwords (iterable): words to discount - :param regex_pattern (str): regex pattern for disallowed characters - :param lowercase (bool): activate case sensitivity by setting it to False - :param replacements (iterable): list of replacement rules e.g. [['|', 'or'], ['%', 'percent']] - :param allow_unicode (bool): allow unicode characters - :return (str): - """""" - - # user-specific replacements - if replacements: - for old, new in replacements: - text = text.replace(old, new) - - # ensure text is unicode - if not isinstance(text, str): - text = str(text, 'utf-8', 'ignore') - - # replace quotes with dashes - pre-process - text = QUOTE_PATTERN.sub(DEFAULT_SEPARATOR, text) - - # normalize text, convert to unicode if required - if allow_unicode: - text = unicodedata.normalize('NFKC', text) - else: - text = unicodedata.normalize('NFKD', text) - text = unidecode.unidecode(text) - - # ensure text is still in unicode - if not isinstance(text, str): - text = str(text, 'utf-8', 'ignore') - - # character entity reference - if entities: - text = CHAR_ENTITY_PATTERN.sub(lambda m: chr(name2codepoint[m.group(1)]), text) - - # decimal character reference - if decimal: - try: - text = DECIMAL_PATTERN.sub(lambda m: chr(int(m.group(1))), text) - except Exception: - pass - - # hexadecimal character reference - if hexadecimal: - try: - text = HEX_PATTERN.sub(lambda m: chr(int(m.group(1), 16)), text) - except Exception: - pass - - # re normalize text - if allow_unicode: - text = unicodedata.normalize('NFKC', text) - else: - text = unicodedata.normalize('NFKD', text) - - # make the text lowercase (optional) - if lowercase: - text = text.lower() - - # remove generated quotes -- post-process - text = QUOTE_PATTERN.sub('', text) - - # cleanup numbers - text = NUMBERS_PATTERN.sub('', text) - - # replace all other unwanted characters - if allow_unicode: - pattern = regex_pattern or DISALLOWED_UNICODE_CHARS_PATTERN - else: - pattern = regex_pattern or DISALLOWED_CHARS_PATTERN - - text = re.sub(pattern, DEFAULT_SEPARATOR, text) - - # remove redundant - text = DUPLICATE_DASH_PATTERN.sub(DEFAULT_SEPARATOR, text).strip(DEFAULT_SEPARATOR) - - # remove stopwords - if stopwords: - if lowercase: - stopwords_lower = [s.lower() for s in stopwords] - words = [w for w in text.split(DEFAULT_SEPARATOR) if w not in stopwords_lower] - else: - words = [w for w in text.split(DEFAULT_SEPARATOR) if w not in stopwords] - text = DEFAULT_SEPARATOR.join(words) - - # finalize user-specific replacements - if replacements: - for old, new in replacements: - text = text.replace(old, new) - - # smart truncate if requested - if max_length > 0: - text = smart_truncate(text, max_length, word_boundary, DEFAULT_SEPARATOR, save_order) - - if separator != DEFAULT_SEPARATOR: - text = text.replace(DEFAULT_SEPARATOR, separator) - - return text - - -''' -slugify/__init__.py -''' -from slugify.special import * -from slugify.slugify import * - - -''' -slugify/special.py -''' -from __future__ import annotations - - -def add_uppercase_char(char_list: list[tuple[str, str]]) -> list[tuple[str, str]]: - """""" Given a replacement char list, this adds uppercase chars to the list """""" - - for item in char_list: - char, xlate = item - upper_dict = char.upper(), xlate.capitalize() - if upper_dict not in char_list and char != upper_dict[0]: - char_list.insert(0, upper_dict) - return char_list - - -# Language specific pre translations -# Source awesome-slugify - -_CYRILLIC = [ # package defaults: - (u'ё', u'e'), # io / yo - (u'я', u'ya'), # ia - (u'х', u'h'), # kh - (u'у', u'y'), # u - (u'щ', u'sch'), # sch - (u'ю', u'u'), # iu / yu -] -CYRILLIC = add_uppercase_char(_CYRILLIC) - -_GERMAN = [ # package defaults: - (u'ä', u'ae'), # a - (u'ö', u'oe'), # o - (u'ü', u'ue'), # u -] -GERMAN = add_uppercase_char(_GERMAN) - -_GREEK = [ # package defaults: - (u'χ', u'ch'), # kh - (u'Ξ', u'X'), # Ks - (u'ϒ', u'Y'), # U - (u'υ', u'y'), # u - (u'ύ', u'y'), - (u'ϋ', u'y'), - (u'ΰ', u'y'), -] -GREEK = add_uppercase_char(_GREEK) - -# Pre translations -PRE_TRANSLATIONS = CYRILLIC + GERMAN + GREEK - - -",3,246 -keras_preprocessing,./ProjectTest/Python/keras_preprocessing.py,"''' -keras_preprocessing/text.py -''' -# -*- coding: utf-8 -*- -""""""Utilities for text input preprocessing. -"""""" -import json -import warnings -from collections import OrderedDict, defaultdict -from hashlib import md5 - -import numpy as np - -maketrans = str.maketrans - - -def text_to_word_sequence(text, - filters='!""#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', - lower=True, split="" ""): - """"""Converts a text to a sequence of words (or tokens). - - # Arguments - text: Input text (string). - filters: list (or concatenation) of characters to filter out, such as - punctuation. Default: ``!""#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n``, - includes basic punctuation, tabs, and newlines. - lower: boolean. Whether to convert the input to lowercase. - split: str. Separator for word splitting. - - # Returns - A list of words (or tokens). - """""" - if lower: - text = text.lower() - - translate_dict = {c: split for c in filters} - translate_map = maketrans(translate_dict) - text = text.translate(translate_map) - - seq = text.split(split) - return [i for i in seq if i] - - -def one_hot(text, n, - filters='!""#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', - lower=True, - split=' ', - analyzer=None): - """"""One-hot encodes a text into a list of word indexes of size n. - - This is a wrapper to the `hashing_trick` function using `hash` as the - hashing function; unicity of word to index mapping non-guaranteed. - - # Arguments - text: Input text (string). - n: int. Size of vocabulary. - filters: list (or concatenation) of characters to filter out, such as - punctuation. Default: ``!""#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n``, - includes basic punctuation, tabs, and newlines. - lower: boolean. Whether to set the text to lowercase. - split: str. Separator for word splitting. - analyzer: function. Custom analyzer to split the text - - # Returns - List of integers in [1, n]. Each integer encodes a word - (unicity non-guaranteed). - """""" - return hashing_trick(text, n, - hash_function=hash, - filters=filters, - lower=lower, - split=split, - analyzer=analyzer) - - -def hashing_trick(text, n, - hash_function=None, - filters='!""#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', - lower=True, - split=' ', - analyzer=None): - """"""Converts a text to a sequence of indexes in a fixed-size hashing space. - - # Arguments - text: Input text (string). - n: Dimension of the hashing space. - hash_function: defaults to python `hash` function, can be 'md5' or - any function that takes in input a string and returns a int. - Note that 'hash' is not a stable hashing function, so - it is not consistent across different runs, while 'md5' - is a stable hashing function. - filters: list (or concatenation) of characters to filter out, such as - punctuation. Default: ``!""#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n``, - includes basic punctuation, tabs, and newlines. - lower: boolean. Whether to set the text to lowercase. - split: str. Separator for word splitting. - analyzer: function. Custom analyzer to split the text - - # Returns - A list of integer word indices (unicity non-guaranteed). - - `0` is a reserved index that won't be assigned to any word. - - Two or more words may be assigned to the same index, due to possible - collisions by the hashing function. - The [probability]( - https://en.wikipedia.org/wiki/Birthday_problem#Probability_table) - of a collision is in relation to the dimension of the hashing space and - the number of distinct objects. - """""" - if hash_function is None: - hash_function = hash - elif hash_function == 'md5': - def hash_function(w): - return int(md5(w.encode()).hexdigest(), 16) - - if analyzer is None: - seq = text_to_word_sequence(text, - filters=filters, - lower=lower, - split=split) - else: - seq = analyzer(text) - - return [(hash_function(w) % (n - 1) + 1) for w in seq] - - -class Tokenizer(object): - """"""Text tokenization utility class. - - This class allows to vectorize a text corpus, by turning each - text into either a sequence of integers (each integer being the index - of a token in a dictionary) or into a vector where the coefficient - for each token could be binary, based on word count, based on tf-idf... - - # Arguments - num_words: the maximum number of words to keep, based - on word frequency. Only the most common `num_words-1` words will - be kept. - filters: a string where each element is a character that will be - filtered from the texts. The default is all punctuation, plus - tabs and line breaks, minus the `'` character. - lower: boolean. Whether to convert the texts to lowercase. - split: str. Separator for word splitting. - char_level: if True, every character will be treated as a token. - oov_token: if given, it will be added to word_index and used to - replace out-of-vocabulary words during text_to_sequence calls - analyzer: function. Custom analyzer to split the text. - The default analyzer is text_to_word_sequence - - By default, all punctuation is removed, turning the texts into - space-separated sequences of words - (words maybe include the `'` character). These sequences are then - split into lists of tokens. They will then be indexed or vectorized. - - `0` is a reserved index that won't be assigned to any word. - """""" - - def __init__(self, num_words=None, - filters='!""#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', - lower=True, - split=' ', - char_level=False, - oov_token=None, - analyzer=None, - **kwargs): - # Legacy support - if 'nb_words' in kwargs: - warnings.warn('The `nb_words` argument in `Tokenizer` ' - 'has been renamed `num_words`.') - num_words = kwargs.pop('nb_words') - document_count = kwargs.pop('document_count', 0) - if kwargs: - raise TypeError('Unrecognized keyword arguments: ' + str(kwargs)) - - self.word_counts = OrderedDict() - self.word_docs = defaultdict(int) - self.filters = filters - self.split = split - self.lower = lower - self.num_words = num_words - self.document_count = document_count - self.char_level = char_level - self.oov_token = oov_token - self.index_docs = defaultdict(int) - self.word_index = {} - self.index_word = {} - self.analyzer = analyzer - - def fit_on_texts(self, texts): - """"""Updates internal vocabulary based on a list of texts. - - In the case where texts contains lists, - we assume each entry of the lists to be a token. - - Required before using `texts_to_sequences` or `texts_to_matrix`. - - # Arguments - texts: can be a list of strings, - a generator of strings (for memory-efficiency), - or a list of list of strings. - """""" - for text in texts: - self.document_count += 1 - if self.char_level or isinstance(text, list): - if self.lower: - if isinstance(text, list): - text = [text_elem.lower() for text_elem in text] - else: - text = text.lower() - seq = text - else: - if self.analyzer is None: - seq = text_to_word_sequence(text, - filters=self.filters, - lower=self.lower, - split=self.split) - else: - seq = self.analyzer(text) - for w in seq: - if w in self.word_counts: - self.word_counts[w] += 1 - else: - self.word_counts[w] = 1 - for w in set(seq): - # In how many documents each word occurs - self.word_docs[w] += 1 - - wcounts = list(self.word_counts.items()) - wcounts.sort(key=lambda x: x[1], reverse=True) - # forcing the oov_token to index 1 if it exists - if self.oov_token is None: - sorted_voc = [] - else: - sorted_voc = [self.oov_token] - sorted_voc.extend(wc[0] for wc in wcounts) - - # note that index 0 is reserved, never assigned to an existing word - self.word_index = dict( - zip(sorted_voc, list(range(1, len(sorted_voc) + 1)))) - - self.index_word = {c: w for w, c in self.word_index.items()} - - for w, c in list(self.word_docs.items()): - self.index_docs[self.word_index[w]] = c - - def fit_on_sequences(self, sequences): - """"""Updates internal vocabulary based on a list of sequences. - - Required before using `sequences_to_matrix` - (if `fit_on_texts` was never called). - - # Arguments - sequences: A list of sequence. - A ""sequence"" is a list of integer word indices. - """""" - self.document_count += len(sequences) - for seq in sequences: - seq = set(seq) - for i in seq: - self.index_docs[i] += 1 - - def texts_to_sequences(self, texts): - """"""Transforms each text in texts to a sequence of integers. - - Only top `num_words-1` most frequent words will be taken into account. - Only words known by the tokenizer will be taken into account. - - # Arguments - texts: A list of texts (strings). - - # Returns - A list of sequences. - """""" - return list(self.texts_to_sequences_generator(texts)) - - def texts_to_sequences_generator(self, texts): - """"""Transforms each text in `texts` to a sequence of integers. - - Each item in texts can also be a list, - in which case we assume each item of that list to be a token. - - Only top `num_words-1` most frequent words will be taken into account. - Only words known by the tokenizer will be taken into account. - - # Arguments - texts: A list of texts (strings). - - # Yields - Yields individual sequences. - """""" - num_words = self.num_words - oov_token_index = self.word_index.get(self.oov_token) - for text in texts: - if self.char_level or isinstance(text, list): - if self.lower: - if isinstance(text, list): - text = [text_elem.lower() for text_elem in text] - else: - text = text.lower() - seq = text - else: - if self.analyzer is None: - seq = text_to_word_sequence(text, - filters=self.filters, - lower=self.lower, - split=self.split) - else: - seq = self.analyzer(text) - vect = [] - for w in seq: - i = self.word_index.get(w) - if i is not None: - if num_words and i >= num_words: - if oov_token_index is not None: - vect.append(oov_token_index) - else: - vect.append(i) - elif self.oov_token is not None: - vect.append(oov_token_index) - yield vect - - def sequences_to_texts(self, sequences): - """"""Transforms each sequence into a list of text. - - Only top `num_words-1` most frequent words will be taken into account. - Only words known by the tokenizer will be taken into account. - - # Arguments - sequences: A list of sequences (list of integers). - - # Returns - A list of texts (strings) - """""" - return list(self.sequences_to_texts_generator(sequences)) - - def sequences_to_texts_generator(self, sequences): - """"""Transforms each sequence in `sequences` to a list of texts(strings). - - Each sequence has to a list of integers. - In other words, sequences should be a list of sequences - - Only top `num_words-1` most frequent words will be taken into account. - Only words known by the tokenizer will be taken into account. - - # Arguments - sequences: A list of sequences. - - # Yields - Yields individual texts. - """""" - num_words = self.num_words - oov_token_index = self.word_index.get(self.oov_token) - for seq in sequences: - vect = [] - for num in seq: - word = self.index_word.get(num) - if word is not None: - if num_words and num >= num_words: - if oov_token_index is not None: - vect.append(self.index_word[oov_token_index]) - else: - vect.append(word) - elif self.oov_token is not None: - vect.append(self.index_word[oov_token_index]) - vect = ' '.join(vect) - yield vect - - def texts_to_matrix(self, texts, mode='binary'): - """"""Convert a list of texts to a Numpy matrix. - - # Arguments - texts: list of strings. - mode: one of ""binary"", ""count"", ""tfidf"", ""freq"". - - # Returns - A Numpy matrix. - """""" - sequences = self.texts_to_sequences(texts) - return self.sequences_to_matrix(sequences, mode=mode) - - def sequences_to_matrix(self, sequences, mode='binary'): - """"""Converts a list of sequences into a Numpy matrix. - - # Arguments - sequences: list of sequences - (a sequence is a list of integer word indices). - mode: one of ""binary"", ""count"", ""tfidf"", ""freq"" - - # Returns - A Numpy matrix. - - # Raises - ValueError: In case of invalid `mode` argument, - or if the Tokenizer requires to be fit to sample data. - """""" - if not self.num_words: - if self.word_index: - num_words = len(self.word_index) + 1 - else: - raise ValueError('Specify a dimension (`num_words` argument), ' - 'or fit on some text data first.') - else: - num_words = self.num_words - - if mode == 'tfidf' and not self.document_count: - raise ValueError('Fit the Tokenizer on some data ' - 'before using tfidf mode.') - - x = np.zeros((len(sequences), num_words)) - for i, seq in enumerate(sequences): - if not seq: - continue - counts = defaultdict(int) - for j in seq: - if j >= num_words: - continue - counts[j] += 1 - for j, c in list(counts.items()): - if mode == 'count': - x[i][j] = c - elif mode == 'freq': - x[i][j] = c / len(seq) - elif mode == 'binary': - x[i][j] = 1 - elif mode == 'tfidf': - # Use weighting scheme 2 in - # https://en.wikipedia.org/wiki/Tf%E2%80%93idf - tf = 1 + np.log(c) - idf = np.log(1 + self.document_count / - (1 + self.index_docs.get(j, 0))) - x[i][j] = tf * idf - else: - raise ValueError('Unknown vectorization mode:', mode) - return x - - def get_config(self): - '''Returns the tokenizer configuration as Python dictionary. - The word count dictionaries used by the tokenizer get serialized - into plain JSON, so that the configuration can be read by other - projects. - - # Returns - A Python dictionary with the tokenizer configuration. - ''' - json_word_counts = json.dumps(self.word_counts) - json_word_docs = json.dumps(self.word_docs) - json_index_docs = json.dumps(self.index_docs) - json_word_index = json.dumps(self.word_index) - json_index_word = json.dumps(self.index_word) - - return { - 'num_words': self.num_words, - 'filters': self.filters, - 'lower': self.lower, - 'split': self.split, - 'char_level': self.char_level, - 'oov_token': self.oov_token, - 'document_count': self.document_count, - 'word_counts': json_word_counts, - 'word_docs': json_word_docs, - 'index_docs': json_index_docs, - 'index_word': json_index_word, - 'word_index': json_word_index - } - - def to_json(self, **kwargs): - """"""Returns a JSON string containing the tokenizer configuration. - To load a tokenizer from a JSON string, use - `keras.preprocessing.text.tokenizer_from_json(json_string)`. - - # Arguments - **kwargs: Additional keyword arguments - to be passed to `json.dumps()`. - - # Returns - A JSON string containing the tokenizer configuration. - """""" - config = self.get_config() - tokenizer_config = { - 'class_name': self.__class__.__name__, - 'config': config - } - return json.dumps(tokenizer_config, **kwargs) - - -def tokenizer_from_json(json_string): - """"""Parses a JSON tokenizer configuration file and returns a - tokenizer instance. - - # Arguments - json_string: JSON string encoding a tokenizer configuration. - - # Returns - A Keras Tokenizer instance - """""" - tokenizer_config = json.loads(json_string) - config = tokenizer_config.get('config') - - word_counts = json.loads(config.pop('word_counts')) - word_docs = json.loads(config.pop('word_docs')) - index_docs = json.loads(config.pop('index_docs')) - # Integer indexing gets converted to strings with json.dumps() - index_docs = {int(k): v for k, v in index_docs.items()} - index_word = json.loads(config.pop('index_word')) - index_word = {int(k): v for k, v in index_word.items()} - word_index = json.loads(config.pop('word_index')) - - tokenizer = Tokenizer(**config) - tokenizer.word_counts = word_counts - tokenizer.word_docs = word_docs - tokenizer.index_docs = index_docs - tokenizer.word_index = word_index - tokenizer.index_word = index_word - - return tokenizer - - -''' -keras_preprocessing/sequence.py -''' -# -*- coding: utf-8 -*- -""""""Utilities for preprocessing sequence data. -"""""" -import json -import random - -import numpy as np - - -def pad_sequences(sequences, maxlen=None, dtype='int32', - padding='pre', truncating='pre', value=0.): - """"""Pads sequences to the same length. - - This function transforms a list of - `num_samples` sequences (lists of integers) - into a 2D Numpy array of shape `(num_samples, num_timesteps)`. - `num_timesteps` is either the `maxlen` argument if provided, - or the length of the longest sequence otherwise. - - Sequences that are shorter than `num_timesteps` - are padded with `value` at the beginning or the end - if padding='post. - - Sequences longer than `num_timesteps` are truncated - so that they fit the desired length. - The position where padding or truncation happens is determined by - the arguments `padding` and `truncating`, respectively. - - Pre-padding is the default. - - # Arguments - sequences: List of lists, where each element is a sequence. - maxlen: Int, maximum length of all sequences. - dtype: Type of the output sequences. - To pad sequences with variable length strings, you can use `object`. - padding: String, 'pre' or 'post': - pad either before or after each sequence. - truncating: String, 'pre' or 'post': - remove values from sequences larger than - `maxlen`, either at the beginning or at the end of the sequences. - value: Float or String, padding value. - - # Returns - x: Numpy array with shape `(len(sequences), maxlen)` - - # Raises - ValueError: In case of invalid values for `truncating` or `padding`, - or in case of invalid shape for a `sequences` entry. - """""" - if not hasattr(sequences, '__len__'): - raise ValueError('`sequences` must be iterable.') - num_samples = len(sequences) - - lengths = [] - sample_shape = () - flag = True - - # take the sample shape from the first non empty sequence - # checking for consistency in the main loop below. - - for x in sequences: - try: - lengths.append(len(x)) - if flag and len(x): - sample_shape = np.asarray(x).shape[1:] - flag = False - except TypeError: - raise ValueError('`sequences` must be a list of iterables. ' - 'Found non-iterable: ' + str(x)) - - if maxlen is None: - maxlen = np.max(lengths) - - is_dtype_str = np.issubdtype(dtype, np.str_) or np.issubdtype(dtype, np.unicode_) - if isinstance(value, str) and dtype != object and not is_dtype_str: - raise ValueError(""`dtype` {} is not compatible with `value`'s type: {}\n"" - ""You should set `dtype=object` for variable length strings."" - .format(dtype, type(value))) - - x = np.full((num_samples, maxlen) + sample_shape, value, dtype=dtype) - for idx, s in enumerate(sequences): - if not len(s): - continue # empty list/array was found - if truncating == 'pre': - trunc = s[-maxlen:] - elif truncating == 'post': - trunc = s[:maxlen] - else: - raise ValueError('Truncating type ""%s"" ' - 'not understood' % truncating) - - # check `trunc` has expected shape - trunc = np.asarray(trunc, dtype=dtype) - if trunc.shape[1:] != sample_shape: - raise ValueError('Shape of sample %s of sequence at position %s ' - 'is different from expected shape %s' % - (trunc.shape[1:], idx, sample_shape)) - - if padding == 'post': - x[idx, :len(trunc)] = trunc - elif padding == 'pre': - x[idx, -len(trunc):] = trunc - else: - raise ValueError('Padding type ""%s"" not understood' % padding) - return x - - -def make_sampling_table(size, sampling_factor=1e-5): - """"""Generates a word rank-based probabilistic sampling table. - - Used for generating the `sampling_table` argument for `skipgrams`. - `sampling_table[i]` is the probability of sampling - the word i-th most common word in a dataset - (more common words should be sampled less frequently, for balance). - - The sampling probabilities are generated according - to the sampling distribution used in word2vec: - - ``` - p(word) = (min(1, sqrt(word_frequency / sampling_factor) / - (word_frequency / sampling_factor))) - ``` - - We assume that the word frequencies follow Zipf's law (s=1) to derive - a numerical approximation of frequency(rank): - - `frequency(rank) ~ 1/(rank * (log(rank) + gamma) + 1/2 - 1/(12*rank))` - where `gamma` is the Euler-Mascheroni constant. - - # Arguments - size: Int, number of possible words to sample. - sampling_factor: The sampling factor in the word2vec formula. - - # Returns - A 1D Numpy array of length `size` where the ith entry - is the probability that a word of rank i should be sampled. - """""" - gamma = 0.577 - rank = np.arange(size) - rank[0] = 1 - inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1. / (12. * rank) - f = sampling_factor * inv_fq - - return np.minimum(1., f / np.sqrt(f)) - - -def skipgrams(sequence, vocabulary_size, - window_size=4, negative_samples=1., shuffle=True, - categorical=False, sampling_table=None, seed=None): - """"""Generates skipgram word pairs. - - This function transforms a sequence of word indexes (list of integers) - into tuples of words of the form: - - - (word, word in the same window), with label 1 (positive samples). - - (word, random word from the vocabulary), with label 0 (negative samples). - - Read more about Skipgram in this gnomic paper by Mikolov et al.: - [Efficient Estimation of Word Representations in - Vector Space](http://arxiv.org/pdf/1301.3781v3.pdf) - - # Arguments - sequence: A word sequence (sentence), encoded as a list - of word indices (integers). If using a `sampling_table`, - word indices are expected to match the rank - of the words in a reference dataset (e.g. 10 would encode - the 10-th most frequently occurring token). - Note that index 0 is expected to be a non-word and will be skipped. - vocabulary_size: Int, maximum possible word index + 1 - window_size: Int, size of sampling windows (technically half-window). - The window of a word `w_i` will be - `[i - window_size, i + window_size+1]`. - negative_samples: Float >= 0. 0 for no negative (i.e. random) samples. - 1 for same number as positive samples. - shuffle: Whether to shuffle the word couples before returning them. - categorical: bool. if False, labels will be - integers (eg. `[0, 1, 1 .. ]`), - if `True`, labels will be categorical, e.g. - `[[1,0],[0,1],[0,1] .. ]`. - sampling_table: 1D array of size `vocabulary_size` where the entry i - encodes the probability to sample a word of rank i. - seed: Random seed. - - # Returns - couples, labels: where `couples` are int pairs and - `labels` are either 0 or 1. - - # Note - By convention, index 0 in the vocabulary is - a non-word and will be skipped. - """""" - couples = [] - labels = [] - for i, wi in enumerate(sequence): - if not wi: - continue - if sampling_table is not None: - if sampling_table[wi] < random.random(): - continue - - window_start = max(0, i - window_size) - window_end = min(len(sequence), i + window_size + 1) - for j in range(window_start, window_end): - if j != i: - wj = sequence[j] - if not wj: - continue - couples.append([wi, wj]) - if categorical: - labels.append([0, 1]) - else: - labels.append(1) - - if negative_samples > 0: - num_negative_samples = int(len(labels) * negative_samples) - words = [c[0] for c in couples] - random.shuffle(words) - - couples += [[words[i % len(words)], - random.randint(1, vocabulary_size - 1)] - for i in range(num_negative_samples)] - if categorical: - labels += [[1, 0]] * num_negative_samples - else: - labels += [0] * num_negative_samples - - if shuffle: - if seed is None: - seed = random.randint(0, 10e6) - random.seed(seed) - random.shuffle(couples) - random.seed(seed) - random.shuffle(labels) - - return couples, labels - - -def _remove_long_seq(maxlen, seq, label): - """"""Removes sequences that exceed the maximum length. - - # Arguments - maxlen: Int, maximum length of the output sequences. - seq: List of lists, where each sublist is a sequence. - label: List where each element is an integer. - - # Returns - new_seq, new_label: shortened lists for `seq` and `label`. - """""" - new_seq, new_label = [], [] - for x, y in zip(seq, label): - if len(x) < maxlen: - new_seq.append(x) - new_label.append(y) - return new_seq, new_label - - -class TimeseriesGenerator(object): - """"""Utility class for generating batches of temporal data. - - This class takes in a sequence of data-points gathered at - equal intervals, along with time series parameters such as - stride, length of history, etc., to produce batches for - training/validation. - - # Arguments - data: Indexable generator (such as list or Numpy array) - containing consecutive data points (timesteps). - The data should be at 2D, and axis 0 is expected - to be the time dimension. - targets: Targets corresponding to timesteps in `data`. - It should have same length as `data`. - length: Length of the output sequences (in number of timesteps). - sampling_rate: Period between successive individual timesteps - within sequences. For rate `r`, timesteps - `data[i]`, `data[i-r]`, ... `data[i - length]` - are used for create a sample sequence. - stride: Period between successive output sequences. - For stride `s`, consecutive output samples would - be centered around `data[i]`, `data[i+s]`, `data[i+2*s]`, etc. - start_index: Data points earlier than `start_index` will not be used - in the output sequences. This is useful to reserve part of the - data for test or validation. - end_index: Data points later than `end_index` will not be used - in the output sequences. This is useful to reserve part of the - data for test or validation. - shuffle: Whether to shuffle output samples, - or instead draw them in chronological order. - reverse: Boolean: if `true`, timesteps in each output sample will be - in reverse chronological order. - batch_size: Number of timeseries samples in each batch - (except maybe the last one). - - # Returns - A [Sequence](/utils/#sequence) instance. - - # Examples - - ```python - from keras.preprocessing.sequence import TimeseriesGenerator - import numpy as np - - data = np.array([[i] for i in range(50)]) - targets = np.array([[i] for i in range(50)]) - - data_gen = TimeseriesGenerator(data, targets, - length=10, sampling_rate=2, - batch_size=2) - assert len(data_gen) == 20 - - batch_0 = data_gen[0] - x, y = batch_0 - assert np.array_equal(x, - np.array([[[0], [2], [4], [6], [8]], - [[1], [3], [5], [7], [9]]])) - assert np.array_equal(y, - np.array([[10], [11]])) - ``` - """""" - - def __init__(self, data, targets, length, - sampling_rate=1, - stride=1, - start_index=0, - end_index=None, - shuffle=False, - reverse=False, - batch_size=128): - - if len(data) != len(targets): - raise ValueError('Data and targets have to be' + - ' of same length. ' - 'Data length is {}'.format(len(data)) + - ' while target length is {}'.format(len(targets))) - - self.data = data - self.targets = targets - self.length = length - self.sampling_rate = sampling_rate - self.stride = stride - self.start_index = start_index + length - if end_index is None: - end_index = len(data) - 1 - self.end_index = end_index - self.shuffle = shuffle - self.reverse = reverse - self.batch_size = batch_size - - if self.start_index > self.end_index: - raise ValueError('`start_index+length=%i > end_index=%i` ' - 'is disallowed, as no part of the sequence ' - 'would be left to be used as current step.' - % (self.start_index, self.end_index)) - - def __len__(self): - return (self.end_index - self.start_index + - self.batch_size * self.stride) // (self.batch_size * self.stride) - - def __getitem__(self, index): - if self.shuffle: - rows = np.random.randint( - self.start_index, self.end_index + 1, size=self.batch_size) - else: - i = self.start_index + self.batch_size * self.stride * index - rows = np.arange(i, min(i + self.batch_size * - self.stride, self.end_index + 1), self.stride) - - samples = np.array([self.data[row - self.length:row:self.sampling_rate] - for row in rows]) - targets = np.array([self.targets[row] for row in rows]) - - if self.reverse: - return samples[:, ::-1, ...], targets - return samples, targets - - def get_config(self): - '''Returns the TimeseriesGenerator configuration as Python dictionary. - - # Returns - A Python dictionary with the TimeseriesGenerator configuration. - ''' - data = self.data - if type(self.data).__module__ == np.__name__: - data = self.data.tolist() - try: - json_data = json.dumps(data) - except TypeError: - raise TypeError('Data not JSON Serializable:', data) - - targets = self.targets - if type(self.targets).__module__ == np.__name__: - targets = self.targets.tolist() - try: - json_targets = json.dumps(targets) - except TypeError: - raise TypeError('Targets not JSON Serializable:', targets) - - return { - 'data': json_data, - 'targets': json_targets, - 'length': self.length, - 'sampling_rate': self.sampling_rate, - 'stride': self.stride, - 'start_index': self.start_index, - 'end_index': self.end_index, - 'shuffle': self.shuffle, - 'reverse': self.reverse, - 'batch_size': self.batch_size - } - - def to_json(self, **kwargs): - """"""Returns a JSON string containing the timeseries generator - configuration. To load a generator from a JSON string, use - `keras.preprocessing.sequence.timeseries_generator_from_json(json_string)`. - - # Arguments - **kwargs: Additional keyword arguments - to be passed to `json.dumps()`. - - # Returns - A JSON string containing the tokenizer configuration. - """""" - config = self.get_config() - timeseries_generator_config = { - 'class_name': self.__class__.__name__, - 'config': config - } - return json.dumps(timeseries_generator_config, **kwargs) - - -def timeseries_generator_from_json(json_string): - """"""Parses a JSON timeseries generator configuration file and - returns a timeseries generator instance. - - # Arguments - json_string: JSON string encoding a timeseries - generator configuration. - - # Returns - A Keras TimeseriesGenerator instance - """""" - full_config = json.loads(json_string) - config = full_config.get('config') - - data = json.loads(config.pop('data')) - config['data'] = data - targets = json.loads(config.pop('targets')) - config['targets'] = targets - - return TimeseriesGenerator(**config) - - -''' -keras_preprocessing/__init__.py -''' -""""""Enables dynamic setting of underlying Keras module. -"""""" - -_KERAS_BACKEND = None -_KERAS_UTILS = None - - -def set_keras_submodules(backend, utils): - # Deprecated, will be removed in the future. - global _KERAS_BACKEND - global _KERAS_UTILS - _KERAS_BACKEND = backend - _KERAS_UTILS = utils - - -def get_keras_submodule(name): - # Deprecated, will be removed in the future. - if name not in {'backend', 'utils'}: - raise ImportError( - 'Can only retrieve ""backend"" and ""utils"". ' - 'Requested: %s' % name) - if _KERAS_BACKEND is None: - raise ImportError('You need to first `import keras` ' - 'in order to use `keras_preprocessing`. ' - 'For instance, you can do:\n\n' - '```\n' - 'import keras\n' - 'from keras_preprocessing import image\n' - '```\n\n' - 'Or, preferably, this equivalent formulation:\n\n' - '```\n' - 'from keras import preprocessing\n' - '```\n') - if name == 'backend': - return _KERAS_BACKEND - elif name == 'utils': - return _KERAS_UTILS - - -__version__ = '1.1.2' - - -",3,1002 -blackjack,./ProjectTest/Python/blackjack.py,"''' -blackjack/base.py -''' -''' Game-related base classes -''' -class Card: - ''' - Card stores the suit and rank of a single card - - Note: - 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] - Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] - ''' - suit = None - rank = None - valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ'] - valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - - def __init__(self, suit, rank): - ''' Initialize the suit and rank of a card - - Args: - suit: string, suit of the card, should be one of valid_suit - rank: string, rank of the card, should be one of valid_rank - ''' - self.suit = suit - self.rank = rank - - def __eq__(self, other): - if isinstance(other, Card): - return self.rank == other.rank and self.suit == other.suit - else: - # don't attempt to compare against unrelated types - return NotImplemented - - def __hash__(self): - suit_index = Card.valid_suit.index(self.suit) - rank_index = Card.valid_rank.index(self.rank) - return rank_index + 100 * suit_index - - def __str__(self): - ''' Get string representation of a card. - - Returns: - string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... - ''' - return self.rank + self.suit - - def get_index(self): - ''' Get index of a card. - - Returns: - string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ... - ''' - return self.suit+self.rank - - -''' -blackjack/player.py -''' -class BlackjackPlayer: - - def __init__(self, player_id, np_random): - ''' Initialize a Blackjack player class - - Args: - player_id (int): id for the player - ''' - self.np_random = np_random - self.player_id = player_id - self.hand = [] - self.status = 'alive' - self.score = 0 - - def get_player_id(self): - ''' Return player's id - ''' - return self.player_id - - -''' -blackjack/dealer.py -''' -import numpy as np -from blackjack import Card - -def init_standard_deck(): - ''' Initialize a standard deck of 52 cards - - Returns: - (list): A list of Card object - ''' - suit_list = ['S', 'H', 'D', 'C'] - rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - res = [Card(suit, rank) for suit in suit_list for rank in rank_list] - return res - -class BlackjackDealer: - - def __init__(self, np_random, num_decks=1): - ''' Initialize a Blackjack dealer class - ''' - self.np_random = np_random - self.num_decks = num_decks - self.deck = init_standard_deck() - if self.num_decks not in [0, 1]: # 0 indicates infinite decks of cards - self.deck = self.deck * self.num_decks # copy m standard decks of cards - self.shuffle() - self.hand = [] - self.status = 'alive' - self.score = 0 - - def shuffle(self): - ''' Shuffle the deck - ''' - shuffle_deck = np.array(self.deck) - self.np_random.shuffle(shuffle_deck) - self.deck = list(shuffle_deck) - - def deal_card(self, player): - ''' Distribute one card to the player - - Args: - player_id (int): the target player's id - ''' - idx = self.np_random.choice(len(self.deck)) - card = self.deck[idx] - if self.num_decks != 0: # If infinite decks, do not pop card from deck - self.deck.pop(idx) - # card = self.deck.pop() - player.hand.append(card) - - -''' -blackjack/judger.py -''' -class BlackjackJudger: - def __init__(self, np_random): - ''' Initialize a BlackJack judger class - ''' - self.np_random = np_random - 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} - - def judge_round(self, player): - ''' Judge the target player's status - - Args: - player (int): target player's id - - Returns: - status (str): the status of the target player - score (int): the current score of the player - ''' - score = self.judge_score(player.hand) - if score <= 21: - return ""alive"", score - else: - return ""bust"", score - - def judge_game(self, game, game_pointer): - ''' Judge the winner of the game - - Args: - game (class): target game class - ''' - ''' - game.winner['dealer'] doesn't need anymore if we change code like this - - player bust (whether dealer bust or not) => game.winner[playerX] = -1 - player and dealer tie => game.winner[playerX] = 1 - dealer bust and player not bust => game.winner[playerX] = 2 - player get higher score than dealer => game.winner[playerX] = 2 - dealer get higher score than player => game.winner[playerX] = -1 - game.winner[playerX] = 0 => the game is still ongoing - ''' - - if game.players[game_pointer].status == 'bust': - game.winner['player' + str(game_pointer)] = -1 - elif game.dealer.status == 'bust': - game.winner['player' + str(game_pointer)] = 2 - else: - if game.players[game_pointer].score > game.dealer.score: - game.winner['player' + str(game_pointer)] = 2 - elif game.players[game_pointer].score < game.dealer.score: - game.winner['player' + str(game_pointer)] = -1 - else: - game.winner['player' + str(game_pointer)] = 1 - - def judge_score(self, cards): - ''' Judge the score of a given cards set - - Args: - cards (list): a list of cards - - Returns: - score (int): the score of the given cards set - ''' - score = 0 - count_a = 0 - for card in cards: - card_score = self.rank2score[card.rank] - score += card_score - if card.rank == 'A': - count_a += 1 - while score > 21 and count_a > 0: - count_a -= 1 - score -= 10 - return score - - -''' -blackjack/game.py -''' -from copy import deepcopy -import numpy as np - -from blackjack import Dealer -from blackjack import Player -from blackjack import Judger - -class BlackjackGame: - - def __init__(self, allow_step_back=False): - ''' Initialize the class Blackjack Game - ''' - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - - def configure(self, game_config): - ''' Specifiy some game specific parameters, such as number of players - ''' - self.num_players = game_config['game_num_players'] - self.num_decks = game_config['game_num_decks'] - - def init_game(self): - ''' Initialilze the game - - Returns: - state (dict): the first state of the game - player_id (int): current player's id - ''' - self.dealer = Dealer(self.np_random, self.num_decks) - - self.players = [] - for i in range(self.num_players): - self.players.append(Player(i, self.np_random)) - - self.judger = Judger(self.np_random) - - for i in range(2): - for j in range(self.num_players): - self.dealer.deal_card(self.players[j]) - self.dealer.deal_card(self.dealer) - - for i in range(self.num_players): - self.players[i].status, self.players[i].score = self.judger.judge_round(self.players[i]) - - self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer) - - self.winner = {'dealer': 0} - for i in range(self.num_players): - self.winner['player' + str(i)] = 0 - - self.history = [] - self.game_pointer = 0 - - return self.get_state(self.game_pointer), self.game_pointer - - def step(self, action): - ''' Get the next state - - Args: - action (str): a specific action of blackjack. (Hit or Stand) - - Returns:/ - dict: next player's state - int: next plater's id - ''' - if self.allow_step_back: - p = deepcopy(self.players[self.game_pointer]) - d = deepcopy(self.dealer) - w = deepcopy(self.winner) - self.history.append((d, p, w)) - - next_state = {} - # Play hit - if action != ""stand"": - self.dealer.deal_card(self.players[self.game_pointer]) - self.players[self.game_pointer].status, self.players[self.game_pointer].score = self.judger.judge_round( - self.players[self.game_pointer]) - if self.players[self.game_pointer].status == 'bust': - # game over, set up the winner, print out dealer's hand # If bust, pass the game pointer - if self.game_pointer >= self.num_players - 1: - while self.judger.judge_score(self.dealer.hand) < 17: - self.dealer.deal_card(self.dealer) - self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer) - for i in range(self.num_players): - self.judger.judge_game(self, i) - self.game_pointer = 0 - else: - self.game_pointer += 1 - - - 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 - self.players[self.game_pointer].status, self.players[self.game_pointer].score = self.judger.judge_round( - self.players[self.game_pointer]) - if self.game_pointer >= self.num_players - 1: - while self.judger.judge_score(self.dealer.hand) < 17: - self.dealer.deal_card(self.dealer) - self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer) - for i in range(self.num_players): - self.judger.judge_game(self, i) - self.game_pointer = 0 - else: - self.game_pointer += 1 - - - - - - hand = [card.get_index() for card in self.players[self.game_pointer].hand] - - if self.is_over(): - dealer_hand = [card.get_index() for card in self.dealer.hand] - else: - dealer_hand = [card.get_index() for card in self.dealer.hand[1:]] - - for i in range(self.num_players): - next_state['player' + str(i) + ' hand'] = [card.get_index() for card in self.players[i].hand] - next_state['dealer hand'] = dealer_hand - next_state['actions'] = ('hit', 'stand') - next_state['state'] = (hand, dealer_hand) - - - - return next_state, self.game_pointer - - def step_back(self): - ''' Return to the previous state of the game - - Returns: - Status (bool): check if the step back is success or not - ''' - #while len(self.history) > 0: - if len(self.history) > 0: - self.dealer, self.players[self.game_pointer], self.winner = self.history.pop() - return True - return False - - def get_num_players(self): - ''' Return the number of players in blackjack - - Returns: - number_of_player (int): blackjack only have 1 player - ''' - return self.num_players - - @staticmethod - def get_num_actions(): - ''' Return the number of applicable actions - - Returns: - number_of_actions (int): there are only two actions (hit and stand) - ''' - return 2 - - def get_player_id(self): - ''' Return the current player's id - - Returns: - player_id (int): current player's id - ''' - return self.game_pointer - - def get_state(self, player_id): - ''' Return player's state - - Args: - player_id (int): player id - - Returns: - state (dict): corresponding player's state - ''' - ''' - before change state only have two keys (action, state) - but now have more than 4 keys (action, state, player0 hand, player1 hand, ... , dealer hand) - Although key 'state' have duplicated information with key 'player hand' and 'dealer hand', I couldn't remove it because of other codes - To remove it, we need to change dqn agent too in my opinion - ''' - state = {} - state['actions'] = ('hit', 'stand') - hand = [card.get_index() for card in self.players[player_id].hand] - if self.is_over(): - dealer_hand = [card.get_index() for card in self.dealer.hand] - else: - dealer_hand = [card.get_index() for card in self.dealer.hand[1:]] - - for i in range(self.num_players): - state['player' + str(i) + ' hand'] = [card.get_index() for card in self.players[i].hand] - state['dealer hand'] = dealer_hand - state['state'] = (hand, dealer_hand) - - return state - - def is_over(self): - ''' Check if the game is over - - Returns: - status (bool): True/False - ''' - ''' - I should change here because judger and self.winner is changed too - ''' - for i in range(self.num_players): - if self.winner['player' + str(i)] == 0: - return False - - return True - - -''' -blackjack/__init__.py -''' -from blackjack.base import Card as Card -from blackjack.dealer import BlackjackDealer as Dealer -from blackjack.judger import BlackjackJudger as Judger -from blackjack.player import BlackjackPlayer as Player -from blackjack.game import BlackjackGame as Game - - - -",6,401 -fuzzywuzzy,./ProjectTest/Python/fuzzywuzzy.py,"''' -fuzzywuzzy/string_processing.py -''' -from __future__ import unicode_literals -import re -import string -import sys - -PY3 = sys.version_info[0] == 3 -if PY3: - string = str - - -class StringProcessor(object): - """""" - This class defines method to process strings in the most - efficient way. Ideally all the methods below use unicode strings - for both input and output. - """""" - - regex = re.compile(r""(?ui)\W"") - - @classmethod - def replace_non_letters_non_numbers_with_whitespace(cls, a_string): - """""" - This function replaces any sequence of non letters and non - numbers with a single white space. - """""" - return cls.regex.sub("" "", a_string) - - strip = staticmethod(string.strip) - to_lower_case = staticmethod(string.lower) - to_upper_case = staticmethod(string.upper) - - -''' -fuzzywuzzy/fuzz.py -''' -#!/usr/bin/env python -# encoding: utf-8 -from __future__ import unicode_literals -import platform -import warnings - -try: - from .StringMatcher import StringMatcher as SequenceMatcher -except ImportError: - if platform.python_implementation() != ""PyPy"": - warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning') - from difflib import SequenceMatcher - -import utils - - -########################### -# Basic Scoring Functions # -########################### - -@utils.check_for_none -@utils.check_for_equivalence -@utils.check_empty_string -def ratio(s1, s2): - s1, s2 = utils.make_type_consistent(s1, s2) - - m = SequenceMatcher(None, s1, s2) - return utils.intr(100 * m.ratio()) - - -@utils.check_for_none -@utils.check_for_equivalence -@utils.check_empty_string -def partial_ratio(s1, s2): - """"""""Return the ratio of the most similar substring - as a number between 0 and 100."""""" - s1, s2 = utils.make_type_consistent(s1, s2) - - if len(s1) <= len(s2): - shorter = s1 - longer = s2 - else: - shorter = s2 - longer = s1 - - m = SequenceMatcher(None, shorter, longer) - blocks = m.get_matching_blocks() - - # each block represents a sequence of matching characters in a string - # of the form (idx_1, idx_2, len) - # the best partial match will block align with at least one of those blocks - # e.g. shorter = ""abcd"", longer = XXXbcdeEEE - # block = (1,3,3) - # best score === ratio(""abcd"", ""Xbcd"") - scores = [] - for block in blocks: - long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0 - long_end = long_start + len(shorter) - long_substr = longer[long_start:long_end] - - m2 = SequenceMatcher(None, shorter, long_substr) - r = m2.ratio() - if r > .995: - return 100 - else: - scores.append(r) - - return utils.intr(100 * max(scores)) - - -############################## -# Advanced Scoring Functions # -############################## - -def _process_and_sort(s, force_ascii, full_process=True): - """"""Return a cleaned string with token sorted."""""" - # pull tokens - ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s - tokens = ts.split() - - # sort tokens and join - sorted_string = u"" "".join(sorted(tokens)) - return sorted_string.strip() - - -# Sorted Token -# find all alphanumeric tokens in the string -# sort those tokens and take ratio of resulting joined strings -# controls for unordered string elements -@utils.check_for_none -def _token_sort(s1, s2, partial=True, force_ascii=True, full_process=True): - sorted1 = _process_and_sort(s1, force_ascii, full_process=full_process) - sorted2 = _process_and_sort(s2, force_ascii, full_process=full_process) - - if partial: - return partial_ratio(sorted1, sorted2) - else: - return ratio(sorted1, sorted2) - - -def token_sort_ratio(s1, s2, force_ascii=True, full_process=True): - """"""Return a measure of the sequences' similarity between 0 and 100 - but sorting the token before comparing. - """""" - return _token_sort(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process) - - -def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True): - """"""Return the ratio of the most similar substring as a number between - 0 and 100 but sorting the token before comparing. - """""" - return _token_sort(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process) - - -@utils.check_for_none -def _token_set(s1, s2, partial=True, force_ascii=True, full_process=True): - """"""Find all alphanumeric tokens in each string... - - treat them as a set - - construct two strings of the form: - - - take ratios of those two strings - - controls for unordered partial matches"""""" - - if not full_process and s1 == s2: - return 100 - - p1 = utils.full_process(s1, force_ascii=force_ascii) if full_process else s1 - p2 = utils.full_process(s2, force_ascii=force_ascii) if full_process else s2 - - if not utils.validate_string(p1): - return 0 - if not utils.validate_string(p2): - return 0 - - # pull tokens - tokens1 = set(p1.split()) - tokens2 = set(p2.split()) - - intersection = tokens1.intersection(tokens2) - diff1to2 = tokens1.difference(tokens2) - diff2to1 = tokens2.difference(tokens1) - - sorted_sect = "" "".join(sorted(intersection)) - sorted_1to2 = "" "".join(sorted(diff1to2)) - sorted_2to1 = "" "".join(sorted(diff2to1)) - - combined_1to2 = sorted_sect + "" "" + sorted_1to2 - combined_2to1 = sorted_sect + "" "" + sorted_2to1 - - # strip - sorted_sect = sorted_sect.strip() - combined_1to2 = combined_1to2.strip() - combined_2to1 = combined_2to1.strip() - - if partial: - ratio_func = partial_ratio - else: - ratio_func = ratio - - pairwise = [ - ratio_func(sorted_sect, combined_1to2), - ratio_func(sorted_sect, combined_2to1), - ratio_func(combined_1to2, combined_2to1) - ] - return max(pairwise) - - -def token_set_ratio(s1, s2, force_ascii=True, full_process=True): - return _token_set(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process) - - -def partial_token_set_ratio(s1, s2, force_ascii=True, full_process=True): - return _token_set(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process) - - -################### -# Combination API # -################### - -# q is for quick -def QRatio(s1, s2, force_ascii=True, full_process=True): - """""" - Quick ratio comparison between two strings. - - Runs full_process from utils on both strings - Short circuits if either of the strings is empty after processing. - - :param s1: - :param s2: - :param force_ascii: Allow only ASCII characters (Default: True) - :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True) - :return: similarity ratio - """""" - - if full_process: - p1 = utils.full_process(s1, force_ascii=force_ascii) - p2 = utils.full_process(s2, force_ascii=force_ascii) - else: - p1 = s1 - p2 = s2 - - if not utils.validate_string(p1): - return 0 - if not utils.validate_string(p2): - return 0 - - return ratio(p1, p2) - - -def UQRatio(s1, s2, full_process=True): - """""" - Unicode quick ratio - - Calls QRatio with force_ascii set to False - - :param s1: - :param s2: - :return: similarity ratio - """""" - return QRatio(s1, s2, force_ascii=False, full_process=full_process) - - -# w is for weighted -def WRatio(s1, s2, force_ascii=True, full_process=True): - """""" - Return a measure of the sequences' similarity between 0 and 100, using different algorithms. - - **Steps in the order they occur** - - #. Run full_process from utils on both strings - #. Short circuit if this makes either string empty - #. Take the ratio of the two processed strings (fuzz.ratio) - #. Run checks to compare the length of the strings - * If one of the strings is more than 1.5 times as long as the other - use partial_ratio comparisons - scale partial results by 0.9 - (this makes sure only full results can return 100) - * If one of the strings is over 8 times as long as the other - instead scale by 0.6 - - #. Run the other ratio functions - * if using partial ratio functions call partial_ratio, - partial_token_sort_ratio and partial_token_set_ratio - scale all of these by the ratio based on length - * otherwise call token_sort_ratio and token_set_ratio - * all token based comparisons are scaled by 0.95 - (on top of any partial scalars) - - #. Take the highest value from these results - round it and return it as an integer. - - :param s1: - :param s2: - :param force_ascii: Allow only ascii characters - :type force_ascii: bool - :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True) - :return: - """""" - - if full_process: - p1 = utils.full_process(s1, force_ascii=force_ascii) - p2 = utils.full_process(s2, force_ascii=force_ascii) - else: - p1 = s1 - p2 = s2 - - if not utils.validate_string(p1): - return 0 - if not utils.validate_string(p2): - return 0 - - # should we look at partials? - try_partial = True - unbase_scale = .95 - partial_scale = .90 - - base = ratio(p1, p2) - len_ratio = float(max(len(p1), len(p2))) / min(len(p1), len(p2)) - - # if strings are similar length, don't use partials - if len_ratio < 1.5: - try_partial = False - - # if one string is much much shorter than the other - if len_ratio > 8: - partial_scale = .6 - - if try_partial: - partial = partial_ratio(p1, p2) * partial_scale - ptsor = partial_token_sort_ratio(p1, p2, full_process=False) \ - * unbase_scale * partial_scale - ptser = partial_token_set_ratio(p1, p2, full_process=False) \ - * unbase_scale * partial_scale - - return utils.intr(max(base, partial, ptsor, ptser)) - else: - tsor = token_sort_ratio(p1, p2, full_process=False) * unbase_scale - tser = token_set_ratio(p1, p2, full_process=False) * unbase_scale - - return utils.intr(max(base, tsor, tser)) - - -def UWRatio(s1, s2, full_process=True): - """"""Return a measure of the sequences' similarity between 0 and 100, - using different algorithms. Same as WRatio but preserving unicode. - """""" - return WRatio(s1, s2, force_ascii=False, full_process=full_process) - - -''' -fuzzywuzzy/utils.py -''' -from __future__ import unicode_literals -import sys -import functools - -from string_processing import StringProcessor - - -PY3 = sys.version_info[0] == 3 - - -def validate_string(s): - """""" - Check input has length and that length > 0 - - :param s: - :return: True if len(s) > 0 else False - """""" - try: - return len(s) > 0 - except TypeError: - return False - - -def check_for_equivalence(func): - @functools.wraps(func) - def decorator(*args, **kwargs): - if args[0] == args[1]: - return 100 - return func(*args, **kwargs) - return decorator - - -def check_for_none(func): - @functools.wraps(func) - def decorator(*args, **kwargs): - if args[0] is None or args[1] is None: - return 0 - return func(*args, **kwargs) - return decorator - - -def check_empty_string(func): - @functools.wraps(func) - def decorator(*args, **kwargs): - if len(args[0]) == 0 or len(args[1]) == 0: - return 0 - return func(*args, **kwargs) - return decorator - - -bad_chars = str("""").join([chr(i) for i in range(128, 256)]) # ascii dammit! -if PY3: - translation_table = dict((ord(c), None) for c in bad_chars) - unicode = str - - -def asciionly(s): - if PY3: - return s.translate(translation_table) - else: - return s.translate(None, bad_chars) - - -def asciidammit(s): - if type(s) is str: - return asciionly(s) - elif type(s) is unicode: - return asciionly(s.encode('ascii', 'ignore')) - else: - return asciidammit(unicode(s)) - - -def make_type_consistent(s1, s2): - """"""If both objects aren't either both string or unicode instances force them to unicode"""""" - if isinstance(s1, str) and isinstance(s2, str): - return s1, s2 - - elif isinstance(s1, unicode) and isinstance(s2, unicode): - return s1, s2 - - else: - return unicode(s1), unicode(s2) - - -def full_process(s, force_ascii=False): - """"""Process string by - -- removing all but letters and numbers - -- trim whitespace - -- force to lower case - if force_ascii == True, force convert to ascii"""""" - - if force_ascii: - s = asciidammit(s) - # Keep only Letters and Numbers (see Unicode docs). - string_out = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s) - # Force into lowercase. - string_out = StringProcessor.to_lower_case(string_out) - # Remove leading and trailing whitespaces. - string_out = StringProcessor.strip(string_out) - return string_out - - -def intr(n): - '''Returns a correctly rounded integer''' - return int(round(n)) - - -''' -fuzzywuzzy/__init__.py -''' -# -*- coding: utf-8 -*- -__version__ = '0.18.0' - - -''' -fuzzywuzzy/StringMatcher.py -''' -#!/usr/bin/env python -# encoding: utf-8 -"""""" -StringMatcher.py - -ported from python-Levenshtein -[https://github.com/miohtama/python-Levenshtein] -License available here: https://github.com/miohtama/python-Levenshtein/blob/master/COPYING -"""""" - -from Levenshtein import * -from warnings import warn - - -class StringMatcher: - """"""A SequenceMatcher-like class built on the top of Levenshtein"""""" - - def _reset_cache(self): - self._ratio = self._distance = None - self._opcodes = self._editops = self._matching_blocks = None - - def __init__(self, isjunk=None, seq1='', seq2=''): - if isjunk: - warn(""isjunk not NOT implemented, it will be ignored"") - self._str1, self._str2 = seq1, seq2 - self._reset_cache() - - def set_seqs(self, seq1, seq2): - self._str1, self._str2 = seq1, seq2 - self._reset_cache() - - def set_seq1(self, seq1): - self._str1 = seq1 - self._reset_cache() - - def set_seq2(self, seq2): - self._str2 = seq2 - self._reset_cache() - - def get_opcodes(self): - if not self._opcodes: - if self._editops: - self._opcodes = opcodes(self._editops, self._str1, self._str2) - else: - self._opcodes = opcodes(self._str1, self._str2) - return self._opcodes - - def get_editops(self): - if not self._editops: - if self._opcodes: - self._editops = editops(self._opcodes, self._str1, self._str2) - else: - self._editops = editops(self._str1, self._str2) - return self._editops - - def get_matching_blocks(self): - if not self._matching_blocks: - self._matching_blocks = matching_blocks(self.get_opcodes(), - self._str1, self._str2) - return self._matching_blocks - - def ratio(self): - if not self._ratio: - self._ratio = ratio(self._str1, self._str2) - return self._ratio - - def quick_ratio(self): - # This is usually quick enough :o) - if not self._ratio: - self._ratio = ratio(self._str1, self._str2) - return self._ratio - - def real_quick_ratio(self): - len1, len2 = len(self._str1), len(self._str2) - return 2.0 * min(len1, len2) / (len1 + len2) - - def distance(self): - if not self._distance: - self._distance = distance(self._str1, self._str2) - return self._distance - - -''' -fuzzywuzzy/process.py -''' -#!/usr/bin/env python -# encoding: utf-8 -import fuzz -import utils -import heapq -import logging -from functools import partial - - -default_scorer = fuzz.WRatio - - -default_processor = utils.full_process - - -def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0): - """"""Select the best match in a list or dictionary of choices. - - Find best matches in a list or dictionary of choices, return a - generator of tuples containing the match and its score. If a dictionary - is used, also returns the key for each match. - - Arguments: - query: An object representing the thing we want to find. - choices: An iterable or dictionary-like object containing choices - to be matched against the query. Dictionary arguments of - {key: value} pairs will attempt to match the query against - each value. - processor: Optional function of the form f(a) -> b, where a is the query or - individual choice and b is the choice to be used in matching. - - This can be used to match against, say, the first element of - a list: - - lambda x: x[0] - - Defaults to fuzzywuzzy.utils.full_process(). - scorer: Optional function for scoring matches between the query and - an individual processed choice. This should be a function - of the form f(query, choice) -> int. - - By default, fuzz.WRatio() is used and expects both query and - choice to be strings. - score_cutoff: Optional argument for score threshold. No matches with - a score less than this number will be returned. Defaults to 0. - - Returns: - Generator of tuples containing the match and its score. - - If a list is used for choices, then the result will be 2-tuples. - If a dictionary is used, then the result will be 3-tuples containing - the key for each match. - - For example, searching for 'bird' in the dictionary - - {'bard': 'train', 'dog': 'man'} - - may return - - ('train', 22, 'bard'), ('man', 0, 'dog') - """""" - # Catch generators without lengths - def no_process(x): - return x - - try: - if choices is None or len(choices) == 0: - return - except TypeError: - pass - - # If the processor was removed by setting it to None - # perfom a noop as it still needs to be a function - if processor is None: - processor = no_process - - # Run the processor on the input query. - processed_query = processor(query) - - if len(processed_query) == 0: - logging.warning(u""Applied processor reduces input query to empty string, "" - ""all comparisons will have score 0. "" - ""[Query: \'{0}\']"".format(query)) - - # Don't run full_process twice - if scorer in [fuzz.WRatio, fuzz.QRatio, - fuzz.token_set_ratio, fuzz.token_sort_ratio, - fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio, - fuzz.UWRatio, fuzz.UQRatio] \ - and processor == utils.full_process: - processor = no_process - - # Only process the query once instead of for every choice - if scorer in [fuzz.UWRatio, fuzz.UQRatio]: - pre_processor = partial(utils.full_process, force_ascii=False) - scorer = partial(scorer, full_process=False) - elif scorer in [fuzz.WRatio, fuzz.QRatio, - fuzz.token_set_ratio, fuzz.token_sort_ratio, - fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio]: - pre_processor = partial(utils.full_process, force_ascii=True) - scorer = partial(scorer, full_process=False) - else: - pre_processor = no_process - processed_query = pre_processor(processed_query) - - try: - # See if choices is a dictionary-like object. - for key, choice in choices.items(): - processed = pre_processor(processor(choice)) - score = scorer(processed_query, processed) - if score >= score_cutoff: - yield (choice, score, key) - except AttributeError: - # It's a list; just iterate over it. - for choice in choices: - processed = pre_processor(processor(choice)) - score = scorer(processed_query, processed) - if score >= score_cutoff: - yield (choice, score) - - -def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5): - """"""Select the best match in a list or dictionary of choices. - - Find best matches in a list or dictionary of choices, return a - list of tuples containing the match and its score. If a dictionary - is used, also returns the key for each match. - - Arguments: - query: An object representing the thing we want to find. - choices: An iterable or dictionary-like object containing choices - to be matched against the query. Dictionary arguments of - {key: value} pairs will attempt to match the query against - each value. - processor: Optional function of the form f(a) -> b, where a is the query or - individual choice and b is the choice to be used in matching. - - This can be used to match against, say, the first element of - a list: - - lambda x: x[0] - - Defaults to fuzzywuzzy.utils.full_process(). - scorer: Optional function for scoring matches between the query and - an individual processed choice. This should be a function - of the form f(query, choice) -> int. - By default, fuzz.WRatio() is used and expects both query and - choice to be strings. - limit: Optional maximum for the number of elements returned. Defaults - to 5. - - Returns: - List of tuples containing the match and its score. - - If a list is used for choices, then the result will be 2-tuples. - If a dictionary is used, then the result will be 3-tuples containing - the key for each match. - - For example, searching for 'bird' in the dictionary - - {'bard': 'train', 'dog': 'man'} - - may return - - [('train', 22, 'bard'), ('man', 0, 'dog')] - """""" - sl = extractWithoutOrder(query, choices, processor, scorer) - return heapq.nlargest(limit, sl, key=lambda i: i[1]) if limit is not None else \ - sorted(sl, key=lambda i: i[1], reverse=True) - - -def extractBests(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0, limit=5): - """"""Get a list of the best matches to a collection of choices. - - Convenience function for getting the choices with best scores. - - Args: - query: A string to match against - choices: A list or dictionary of choices, suitable for use with - extract(). - processor: Optional function for transforming choices before matching. - See extract(). - scorer: Scoring function for extract(). - score_cutoff: Optional argument for score threshold. No matches with - a score less than this number will be returned. Defaults to 0. - limit: Optional maximum for the number of elements returned. Defaults - to 5. - - Returns: A a list of (match, score) tuples. - """""" - - best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff) - return heapq.nlargest(limit, best_list, key=lambda i: i[1]) if limit is not None else \ - sorted(best_list, key=lambda i: i[1], reverse=True) - - -def extractOne(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0): - """"""Find the single best match above a score in a list of choices. - - This is a convenience method which returns the single best choice. - See extract() for the full arguments list. - - Args: - query: A string to match against - choices: A list or dictionary of choices, suitable for use with - extract(). - processor: Optional function for transforming choices before matching. - See extract(). - scorer: Scoring function for extract(). - score_cutoff: Optional argument for score threshold. If the best - match is found, but it is not greater than this number, then - return None anyway (""not a good enough match""). Defaults to 0. - - Returns: - A tuple containing a single match and its score, if a match - was found that was above score_cutoff. Otherwise, returns None. - """""" - best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff) - try: - return max(best_list, key=lambda i: i[1]) - except ValueError: - return None - - -def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio): - """"""This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify - and remove duplicates. Specifically, it uses the process.extract to identify duplicates that - score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list - since we assume this item contains the most entity information and returns that. It breaks string - length ties on an alphabetical sort. - - Note: as the threshold DECREASES the number of duplicates that are found INCREASES. This means that the - returned deduplicated list will likely be shorter. Raise the threshold for fuzzy_dedupe to be less - sensitive. - - Args: - contains_dupes: A list of strings that we would like to dedupe. - threshold: the numerical value (0,100) point at which we expect to find duplicates. - Defaults to 70 out of 100 - scorer: Optional function for scoring matches between the query and - an individual processed choice. This should be a function - of the form f(query, choice) -> int. - By default, fuzz.token_set_ratio() is used and expects both query and - choice to be strings. - - Returns: - A deduplicated list. For example: - - In: contains_dupes = ['Frodo Baggin', 'Frodo Baggins', 'F. Baggins', 'Samwise G.', 'Gandalf', 'Bilbo Baggins'] - In: fuzzy_dedupe(contains_dupes) - Out: ['Frodo Baggins', 'Samwise G.', 'Bilbo Baggins', 'Gandalf'] - """""" - - extractor = [] - - # iterate over items in *contains_dupes* - for item in contains_dupes: - # return all duplicate matches found - matches = extract(item, contains_dupes, limit=None, scorer=scorer) - # filter matches based on the threshold - filtered = [x for x in matches if x[1] > threshold] - # if there is only 1 item in *filtered*, no duplicates were found so append to *extracted* - if len(filtered) == 1: - extractor.append(filtered[0][0]) - - else: - # alpha sort - filtered = sorted(filtered, key=lambda x: x[0]) - # length sort - filter_sort = sorted(filtered, key=lambda x: len(x[0]), reverse=True) - # take first item as our 'canonical example' - extractor.append(filter_sort[0][0]) - - # uniquify *extractor* list - keys = {} - for e in extractor: - keys[e] = 1 - extractor = keys.keys() - - # check that extractor differs from contain_dupes (e.g. duplicates were found) - # if not, then return the original list - if len(extractor) == len(contains_dupes): - return contains_dupes - else: - return extractor - - -",6,808 -gin_rummy,./ProjectTest/Python/gin_rummy.py,"''' -gin_rummy/base.py -''' -''' Game-related base classes -''' -class Card: - ''' - Card stores the suit and rank of a single card - - Note: - 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] - Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] - ''' - suit = None - rank = None - valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ'] - valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - - def __init__(self, suit, rank): - ''' Initialize the suit and rank of a card - - Args: - suit: string, suit of the card, should be one of valid_suit - rank: string, rank of the card, should be one of valid_rank - ''' - self.suit = suit - self.rank = rank - - def __eq__(self, other): - if isinstance(other, Card): - return self.rank == other.rank and self.suit == other.suit - else: - # don't attempt to compare against unrelated types - return NotImplemented - - def __hash__(self): - suit_index = Card.valid_suit.index(self.suit) - rank_index = Card.valid_rank.index(self.rank) - return rank_index + 100 * suit_index - - def __str__(self): - ''' Get string representation of a card. - - Returns: - string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... - ''' - return self.rank + self.suit - - def get_index(self): - ''' Get index of a card. - - Returns: - string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ... - ''' - return self.suit+self.rank - - -''' -gin_rummy/player.py -''' -from typing import List - -from gin_rummy import Card - -import utils - -import melding - - -class GinRummyPlayer: - - def __init__(self, player_id: int, np_random): - ''' Initialize a GinRummy player class - - Args: - player_id (int): id for the player - ''' - self.np_random = np_random - self.player_id = player_id - self.hand = [] # type: List[Card] - self.known_cards = [] # type: List[Card] # opponent knows cards picked up by player and not yet discarded - # memoization for speed - self.meld_kinds_by_rank_id = [[] for _ in range(13)] # type: List[List[List[Card]]] - self.meld_run_by_suit_id = [[] for _ in range(4)] # type: List[List[List[Card]]] - - def get_player_id(self) -> int: - ''' Return player's id - ''' - return self.player_id - - def get_meld_clusters(self) -> List[List[List[Card]]]: - result = [] # type: List[List[List[Card]]] - all_run_melds = [frozenset(meld_kind) for meld_kinds in self.meld_kinds_by_rank_id for meld_kind in meld_kinds] - all_set_melds = [frozenset(meld_run) for meld_runs in self.meld_run_by_suit_id for meld_run in meld_runs] - all_melds = all_run_melds + all_set_melds - all_melds_count = len(all_melds) - for i in range(0, all_melds_count): - first_meld = all_melds[i] - first_meld_list = list(first_meld) - meld_cluster_1 = [first_meld_list] - result.append(meld_cluster_1) - for j in range(i + 1, all_melds_count): - second_meld = all_melds[j] - second_meld_list = list(second_meld) - if not second_meld.isdisjoint(first_meld): - continue - meld_cluster_2 = [first_meld_list, second_meld_list] - result.append(meld_cluster_2) - for k in range(j + 1, all_melds_count): - third_meld = all_melds[k] - third_meld_list = list(third_meld) - if not third_meld.isdisjoint(first_meld) or not third_meld.isdisjoint(second_meld): - continue - meld_cluster_3 = [first_meld_list, second_meld_list, third_meld_list] - result.append(meld_cluster_3) - return result - - def did_populate_hand(self): - self.meld_kinds_by_rank_id = [[] for _ in range(13)] - self.meld_run_by_suit_id = [[] for _ in range(4)] - all_set_melds = melding.get_all_set_melds(hand=self.hand) - for set_meld in all_set_melds: - rank_id = utils.get_rank_id(set_meld[0]) - self.meld_kinds_by_rank_id[rank_id].append(set_meld) - all_run_melds = melding.get_all_run_melds(hand=self.hand) - for run_meld in all_run_melds: - suit_id = utils.get_suit_id(run_meld[0]) - self.meld_run_by_suit_id[suit_id].append(run_meld) - - def add_card_to_hand(self, card: Card): - self.hand.append(card) - self._increase_meld_kinds_by_rank_id(card=card) - self._increase_run_kinds_by_suit_id(card=card) - - def remove_card_from_hand(self, card: Card): - self.hand.remove(card) - self._reduce_meld_kinds_by_rank_id(card=card) - self._reduce_run_kinds_by_suit_id(card=card) - - def __str__(self): - return ""N"" if self.player_id == 0 else ""S"" - - @staticmethod - def short_name_of(player_id: int) -> str: - return ""N"" if player_id == 0 else ""S"" - - @staticmethod - def opponent_id_of(player_id: int) -> int: - return (player_id + 1) % 2 - - # private methods - - def _increase_meld_kinds_by_rank_id(self, card: Card): - rank_id = utils.get_rank_id(card) - meld_kinds = self.meld_kinds_by_rank_id[rank_id] - if len(meld_kinds) == 0: - card_rank = card.rank - meld_kind = [card for card in self.hand if card.rank == card_rank] - if len(meld_kind) >= 3: - self.meld_kinds_by_rank_id[rank_id].append(meld_kind) - else: # must have all cards of given rank - suits = ['S', 'H', 'D', 'C'] - max_kind_meld = [Card(suit, card.rank) for suit in suits] - self.meld_kinds_by_rank_id[rank_id] = [max_kind_meld] - for meld_card in max_kind_meld: - self.meld_kinds_by_rank_id[rank_id].append([card for card in max_kind_meld if card != meld_card]) - - def _reduce_meld_kinds_by_rank_id(self, card: Card): - rank_id = utils.get_rank_id(card) - meld_kinds = self.meld_kinds_by_rank_id[rank_id] - if len(meld_kinds) > 1: - suits = ['S', 'H', 'D', 'C'] - self.meld_kinds_by_rank_id[rank_id] = [[Card(suit, card.rank) for suit in suits if suit != card.suit]] - else: - self.meld_kinds_by_rank_id[rank_id] = [] - - def _increase_run_kinds_by_suit_id(self, card: Card): - suit_id = utils.get_suit_id(card=card) - self.meld_run_by_suit_id[suit_id] = melding.get_all_run_melds_for_suit(cards=self.hand, suit=card.suit) - - def _reduce_run_kinds_by_suit_id(self, card: Card): - suit_id = utils.get_suit_id(card=card) - meld_runs = self.meld_run_by_suit_id[suit_id] - self.meld_run_by_suit_id[suit_id] = [meld_run for meld_run in meld_runs if card not in meld_run] - - -''' -gin_rummy/judge.py -''' -from typing import TYPE_CHECKING - -from typing import List, Tuple - -from action_event import * -from scorers import GinRummyScorer -import melding -from gin_rummy_error import GinRummyProgramError - -import utils - - -class GinRummyJudge: - - ''' - Judge decides legal actions for current player - ''' - - def __init__(self, game: 'GinRummyGame'): - ''' Initialize the class GinRummyJudge - :param game: GinRummyGame - ''' - self.game = game - self.scorer = GinRummyScorer() - - def get_legal_actions(self) -> List[ActionEvent]: - """""" - :return: List[ActionEvent] of legal actions - """""" - legal_actions = [] # type: List[ActionEvent] - last_action = self.game.get_last_action() - if last_action is None or \ - isinstance(last_action, DrawCardAction) or \ - isinstance(last_action, PickUpDiscardAction): - current_player = self.game.get_current_player() - going_out_deadwood_count = self.game.settings.going_out_deadwood_count - hand = current_player.hand - meld_clusters = current_player.get_meld_clusters() # improve speed 2020-Apr - knock_cards, gin_cards = _get_going_out_cards(meld_clusters=meld_clusters, - hand=hand, - going_out_deadwood_count=going_out_deadwood_count) - if self.game.settings.is_allowed_gin and gin_cards: - legal_actions = [GinAction()] - else: - cards_to_discard = [card for card in hand] - if isinstance(last_action, PickUpDiscardAction): - if not self.game.settings.is_allowed_to_discard_picked_up_card: - picked_up_card = self.game.round.move_sheet[-1].card - cards_to_discard.remove(picked_up_card) - discard_actions = [DiscardAction(card=card) for card in cards_to_discard] - legal_actions = discard_actions - if self.game.settings.is_allowed_knock: - if current_player.player_id == 0 or not self.game.settings.is_south_never_knocks: - if knock_cards: - knock_actions = [KnockAction(card=card) for card in knock_cards] - if not self.game.settings.is_always_knock: - legal_actions.extend(knock_actions) - else: - legal_actions = knock_actions - elif isinstance(last_action, DeclareDeadHandAction): - legal_actions = [ScoreNorthPlayerAction()] - elif isinstance(last_action, GinAction): - legal_actions = [ScoreNorthPlayerAction()] - elif isinstance(last_action, DiscardAction): - can_draw_card = len(self.game.round.dealer.stock_pile) > self.game.settings.stockpile_dead_card_count - if self.game.settings.max_drawn_card_count < 52: # NOTE: this - drawn_card_actions = [action for action in self.game.actions if isinstance(action, DrawCardAction)] - if len(drawn_card_actions) >= self.game.settings.max_drawn_card_count: - can_draw_card = False - move_count = len(self.game.round.move_sheet) - if move_count >= self.game.settings.max_move_count: - legal_actions = [DeclareDeadHandAction()] # prevent unlimited number of moves in a game - elif can_draw_card: - legal_actions = [DrawCardAction()] - if self.game.settings.is_allowed_pick_up_discard: - legal_actions.append(PickUpDiscardAction()) - else: - legal_actions = [DeclareDeadHandAction()] - if self.game.settings.is_allowed_pick_up_discard: - legal_actions.append(PickUpDiscardAction()) - elif isinstance(last_action, KnockAction): - legal_actions = [ScoreNorthPlayerAction()] - elif isinstance(last_action, ScoreNorthPlayerAction): - legal_actions = [ScoreSouthPlayerAction()] - elif isinstance(last_action, ScoreSouthPlayerAction): - pass - else: - raise Exception('get_legal_actions: unknown last_action={}'.format(last_action)) - return legal_actions - - -def get_going_out_cards(hand: List[Card], going_out_deadwood_count: int) -> Tuple[List[Card], List[Card]]: - ''' - :param hand: List[Card] -- must have 11 cards - :param going_out_deadwood_count: int - :return List[Card], List[Card: cards in hand that be knocked, cards in hand that can be ginned - ''' - if not len(hand) == 11: - raise GinRummyProgramError(""len(hand) is {}: should be 11."".format(len(hand))) - meld_clusters = melding.get_meld_clusters(hand=hand) - knock_cards, gin_cards = _get_going_out_cards(meld_clusters=meld_clusters, - hand=hand, - going_out_deadwood_count=going_out_deadwood_count) - return list(knock_cards), list(gin_cards) - - -# -# private methods -# - -def _get_going_out_cards(meld_clusters: List[List[List[Card]]], - hand: List[Card], - going_out_deadwood_count: int) -> Tuple[List[Card], List[Card]]: - ''' - :param meld_clusters - :param hand: List[Card] -- must have 11 cards - :param going_out_deadwood_count: int - :return List[Card], List[Card: cards in hand that be knocked, cards in hand that can be ginned - ''' - if not len(hand) == 11: - raise GinRummyProgramError(""len(hand) is {}: should be 11."".format(len(hand))) - knock_cards = set() - gin_cards = set() - for meld_cluster in meld_clusters: - meld_cards = [card for meld_pile in meld_cluster for card in meld_pile] - hand_deadwood = [card for card in hand if card not in meld_cards] # hand has 11 cards - if len(hand_deadwood) == 0: - # all 11 cards are melded; - # take gin_card as first card of first 4+ meld; - # could also take gin_card as last card of 4+ meld, but won't do this. - for meld_pile in meld_cluster: - if len(meld_pile) >= 4: - gin_cards.add(meld_pile[0]) - break - elif len(hand_deadwood) == 1: - card = hand_deadwood[0] - gin_cards.add(card) - else: - hand_deadwood_values = [utils.get_deadwood_value(card) for card in hand_deadwood] - hand_deadwood_count = sum(hand_deadwood_values) - max_hand_deadwood_value = max(hand_deadwood_values, default=0) - if hand_deadwood_count <= 10 + max_hand_deadwood_value: - for card in hand_deadwood: - next_deadwood_count = hand_deadwood_count - utils.get_deadwood_value(card) - if next_deadwood_count <= going_out_deadwood_count: - knock_cards.add(card) - return list(knock_cards), list(gin_cards) - - -''' -gin_rummy/move.py -''' -from typing import List - -from gin_rummy import Player - -from action_event import * - -from gin_rummy_error import GinRummyProgramError - - -# -# These classes are used to keep a move_sheet history of the moves in a round. -# - -class GinRummyMove(object): - pass - - -class PlayerMove(GinRummyMove): - - def __init__(self, player: Player, action: ActionEvent): - super().__init__() - self.player = player - self.action = action - - -class DealHandMove(GinRummyMove): - - def __init__(self, player_dealing: Player, shuffled_deck: List[Card]): - super().__init__() - self.player_dealing = player_dealing - self.shuffled_deck = shuffled_deck - - def __str__(self): - shuffled_deck_text = "" "".join([str(card) for card in self.shuffled_deck]) - return ""{} deal shuffled_deck=[{}]"".format(self.player_dealing, shuffled_deck_text) - - -class DrawCardMove(PlayerMove): - - def __init__(self, player: Player, action: DrawCardAction, card: Card): - super().__init__(player, action) - if not isinstance(action, DrawCardAction): - raise GinRummyProgramError(""action must be DrawCardAction."") - self.card = card - - def __str__(self): - return ""{} {} {}"".format(self.player, self.action, str(self.card)) - - -class PickupDiscardMove(PlayerMove): - - def __init__(self, player: Player, action: PickUpDiscardAction, card: Card): - super().__init__(player, action) - if not isinstance(action, PickUpDiscardAction): - raise GinRummyProgramError(""action must be PickUpDiscardAction."") - self.card = card - - def __str__(self): - return ""{} {} {}"".format(self.player, self.action, str(self.card)) - - -class DeclareDeadHandMove(PlayerMove): - - def __init__(self, player: Player, action: DeclareDeadHandAction): - super().__init__(player, action) - if not isinstance(action, DeclareDeadHandAction): - raise GinRummyProgramError(""action must be DeclareDeadHandAction."") - - def __str__(self): - return ""{} {}"".format(self.player, self.action) - - -class DiscardMove(PlayerMove): - - def __init__(self, player: Player, action: DiscardAction): - super().__init__(player, action) - if not isinstance(action, DiscardAction): - raise GinRummyProgramError(""action must be DiscardAction."") - - def __str__(self): - return ""{} {}"".format(self.player, self.action) - - -class KnockMove(PlayerMove): - - def __init__(self, player: Player, action: KnockAction): - super().__init__(player, action) - if not isinstance(action, KnockAction): - raise GinRummyProgramError(""action must be KnockAction."") - - def __str__(self): - return ""{} {}"".format(self.player, self.action) - - -class GinMove(PlayerMove): - - def __init__(self, player: Player, action: GinAction): - super().__init__(player, action) - if not isinstance(action, GinAction): - raise GinRummyProgramError(""action must be GinAction."") - - def __str__(self): - return ""{} {}"".format(self.player, self.action) - - -class ScoreNorthMove(PlayerMove): - - def __init__(self, player: Player, - action: ScoreNorthPlayerAction, - best_meld_cluster: List[List[Card]], - deadwood_count: int): - super().__init__(player, action) - if not isinstance(action, ScoreNorthPlayerAction): - raise GinRummyProgramError(""action must be ScoreNorthPlayerAction."") - self.best_meld_cluster = best_meld_cluster # for information use only - self.deadwood_count = deadwood_count # for information use only - - def __str__(self): - best_meld_cluster_str = [[str(card) for card in meld_pile] for meld_pile in self.best_meld_cluster] - best_meld_cluster_text = ""{}"".format(best_meld_cluster_str) - return ""{} {} {} {}"".format(self.player, self.action, self.deadwood_count, best_meld_cluster_text) - - -class ScoreSouthMove(PlayerMove): - - def __init__(self, player: Player, - action: ScoreSouthPlayerAction, - best_meld_cluster: List[List[Card]], - deadwood_count: int): - super().__init__(player, action) - if not isinstance(action, ScoreSouthPlayerAction): - raise GinRummyProgramError(""action must be ScoreSouthPlayerAction."") - self.best_meld_cluster = best_meld_cluster # for information use only - self.deadwood_count = deadwood_count # for information use only - - def __str__(self): - best_meld_cluster_str = [[str(card) for card in meld_pile] for meld_pile in self.best_meld_cluster] - best_meld_cluster_text = ""{}"".format(best_meld_cluster_str) - return ""{} {} {} {}"".format(self.player, self.action, self.deadwood_count, best_meld_cluster_text) - - -''' -gin_rummy/dealer.py -''' -from gin_rummy import Player -import utils as utils - - -class GinRummyDealer: - ''' Initialize a GinRummy dealer class - ''' - def __init__(self, np_random): - ''' Empty discard_pile, set shuffled_deck, set stock_pile - ''' - self.np_random = np_random - self.discard_pile = [] # type: List[Card] - self.shuffled_deck = utils.get_deck() # keep a copy of the shuffled cards at start of new hand - self.np_random.shuffle(self.shuffled_deck) - self.stock_pile = self.shuffled_deck.copy() # type: List[Card] - - def deal_cards(self, player: Player, num: int): - ''' Deal some cards from stock_pile to one player - - Args: - player (Player): The Player object - num (int): The number of cards to be dealt - ''' - for _ in range(num): - player.hand.append(self.stock_pile.pop()) - player.did_populate_hand() - - -''' -gin_rummy/settings.py -''' -from typing import Dict, Any - -from enum import Enum - - -class DealerForRound(int, Enum): - North = 0 - South = 1 - Random = 2 - - -class Setting(str, Enum): - dealer_for_round = ""dealer_for_round"" - stockpile_dead_card_count = ""stockpile_dead_card_count"" - going_out_deadwood_count = ""going_out_deadwood_count"" - max_drawn_card_count = ""max_drawn_card_count"" - max_move_count = ""max_move_count"" - is_allowed_knock = ""is_allowed_knock"" - is_allowed_gin = ""is_allowed_gin"" - is_allowed_pick_up_discard = ""is_allowed_pick_up_discard"" - is_allowed_to_discard_picked_up_card = ""is_allowed_to_discard_picked_up_card"" - is_always_knock = ""is_always_knock"" - is_south_never_knocks = ""is_south_never_knocks"" - - @staticmethod - def default_setting() -> Dict['Setting', Any]: - return {Setting.dealer_for_round: DealerForRound.Random, - Setting.stockpile_dead_card_count: 2, - Setting.going_out_deadwood_count: 10, # Can specify going_out_deadwood_count before running game. - Setting.max_drawn_card_count: 52, - Setting.max_move_count: 200, # prevent unlimited number of moves in a game - Setting.is_allowed_knock: True, - Setting.is_allowed_gin: True, - Setting.is_allowed_pick_up_discard: True, - Setting.is_allowed_to_discard_picked_up_card: False, - Setting.is_always_knock: False, - Setting.is_south_never_knocks: False - } - - @staticmethod - def simple_gin_rummy_setting(): # speeding up training 200213 - # North should be agent being trained. - # North always deals. - # South never knocks. - # North always knocks when can. - return {Setting.dealer_for_round: DealerForRound.North, - Setting.stockpile_dead_card_count: 2, - Setting.going_out_deadwood_count: 10, # Can specify going_out_deadwood_count before running game. - Setting.max_drawn_card_count: 52, - Setting.max_move_count: 200, # prevent unlimited number of moves in a game - Setting.is_allowed_knock: True, - Setting.is_allowed_gin: True, - Setting.is_allowed_pick_up_discard: True, - Setting.is_allowed_to_discard_picked_up_card: False, - Setting.is_always_knock: True, - Setting.is_south_never_knocks: True - } - - -dealer_for_round = Setting.dealer_for_round -stockpile_dead_card_count = Setting.stockpile_dead_card_count -going_out_deadwood_count = Setting.going_out_deadwood_count -max_drawn_card_count = Setting.max_drawn_card_count -max_move_count = Setting.max_move_count -is_allowed_knock = Setting.is_allowed_knock -is_allowed_gin = Setting.is_allowed_gin -is_allowed_pick_up_discard = Setting.is_allowed_pick_up_discard -is_allowed_to_discard_picked_up_card = Setting.is_allowed_to_discard_picked_up_card -is_always_knock = Setting.is_always_knock -is_south_never_knocks = Setting.is_south_never_knocks - - -class Settings(object): - - def __init__(self): - self.scorer_name = ""GinRummyScorer"" - default_setting = Setting.default_setting() - self.dealer_for_round = default_setting[Setting.dealer_for_round] - self.stockpile_dead_card_count = default_setting[Setting.stockpile_dead_card_count] - self.going_out_deadwood_count = default_setting[Setting.going_out_deadwood_count] - self.max_drawn_card_count = default_setting[Setting.max_drawn_card_count] - self.max_move_count = default_setting[Setting.max_move_count] - self.is_allowed_knock = default_setting[Setting.is_allowed_knock] - self.is_allowed_gin = default_setting[Setting.is_allowed_gin] - self.is_allowed_pick_up_discard = default_setting[Setting.is_allowed_pick_up_discard] - self.is_allowed_to_discard_picked_up_card = default_setting[Setting.is_allowed_to_discard_picked_up_card] - self.is_always_knock = default_setting[Setting.is_always_knock] - self.is_south_never_knocks = default_setting[Setting.is_south_never_knocks] - - def change_settings(self, config: Dict[Setting, Any]): - corrected_config = Settings.get_config_with_invalid_settings_set_to_default_value(config=config) - for key, value in corrected_config.items(): - if key == Setting.dealer_for_round: - self.dealer_for_round = value - elif key == Setting.stockpile_dead_card_count: - self.stockpile_dead_card_count = value - elif key == Setting.going_out_deadwood_count: - self.going_out_deadwood_count = value - elif key == Setting.max_drawn_card_count: - self.max_drawn_card_count = value - elif key == Setting.max_move_count: - self.max_move_count = value - elif key == Setting.is_allowed_knock: - self.is_allowed_knock = value - elif key == Setting.is_allowed_gin: - self.is_allowed_gin = value - elif key == Setting.is_allowed_pick_up_discard: - self.is_allowed_pick_up_discard = value - elif key == Setting.is_allowed_to_discard_picked_up_card: - self.is_allowed_to_discard_picked_up_card = value - elif key == Setting.is_always_knock: - self.is_always_knock = value - elif key == Setting.is_south_never_knocks: - self.is_south_never_knocks = value - - def print_settings(self): - print(""========== Settings =========="") - print(""scorer_name={}"".format(self.scorer_name)) - print(""dealer_for_round={}"".format(self.dealer_for_round)) - print(""stockpile_dead_card_count={}"".format(self.stockpile_dead_card_count)) - print(""going_out_deadwood_count={}"".format(self.going_out_deadwood_count)) - print(""max_drawn_card_count={}"".format(self.max_drawn_card_count)) - print(""max_move_count={}"".format(self.max_move_count)) - - print(""is_allowed_knock={}"".format(self.is_allowed_knock)) - print(""is_allowed_gin={}"".format(self.is_allowed_gin)) - print(""is_allowed_pick_up_discard={}"".format(self.is_allowed_pick_up_discard)) - - print(""is_allowed_to_discard_picked_up_card={}"".format(self.is_allowed_to_discard_picked_up_card)) - - print(""is_always_knock={}"".format(self.is_always_knock)) - print(""is_south_never_knocks={}"".format(self.is_south_never_knocks)) - print(""=============================="") - - @staticmethod - def get_config_with_invalid_settings_set_to_default_value(config: Dict[Setting, Any]) -> Dict[Setting, Any]: - # Set each invalid setting to its default_value. - result = config.copy() - default_setting = Setting.default_setting() - for key, value in config.items(): - if key == dealer_for_round and not isinstance(value, DealerForRound): - result[dealer_for_round] = default_setting[dealer_for_round] - elif key == stockpile_dead_card_count and not isinstance(value, int): - result[stockpile_dead_card_count] = default_setting[stockpile_dead_card_count] - elif key == going_out_deadwood_count and not isinstance(value, int): - result[going_out_deadwood_count] = default_setting[going_out_deadwood_count] - elif key == max_drawn_card_count and not isinstance(value, int): - result[max_drawn_card_count] = default_setting[max_drawn_card_count] - elif key == max_move_count and not isinstance(value, int): - result[max_move_count] = default_setting[max_move_count] - elif key == is_allowed_knock and not isinstance(value, bool): - result[is_allowed_knock] = default_setting[is_allowed_knock] - elif key == is_allowed_gin and not isinstance(value, bool): - result[is_allowed_gin] = default_setting[is_allowed_gin] - elif key == is_allowed_pick_up_discard and not isinstance(value, bool): - result[is_allowed_pick_up_discard] = default_setting[is_allowed_pick_up_discard] - elif key == is_allowed_to_discard_picked_up_card and not isinstance(value, bool): - result[is_allowed_to_discard_picked_up_card] = default_setting[is_allowed_to_discard_picked_up_card] - elif key == is_always_knock and not isinstance(value, bool): - result[is_always_knock] = default_setting[is_always_knock] - elif key == is_south_never_knocks and not isinstance(value, bool): - result[is_south_never_knocks] = default_setting[is_south_never_knocks] - return result - - - -''' -gin_rummy/action_event.py -''' -from gin_rummy import Card - -import utils as utils - -# ==================================== -# Action_ids: -# 0 -> score_player_0_id -# 1 -> score_player_1_id -# 2 -> draw_card_id -# 3 -> pick_up_discard_id -# 4 -> declare_dead_hand_id -# 5 -> gin_id -# 6 to 57 -> discard_id card_id -# 58 to 109 -> knock_id card_id -# ==================================== - -score_player_0_action_id = 0 -score_player_1_action_id = 1 -draw_card_action_id = 2 -pick_up_discard_action_id = 3 -declare_dead_hand_action_id = 4 -gin_action_id = 5 -discard_action_id = 6 -knock_action_id = discard_action_id + 52 - - -class ActionEvent(object): - - def __init__(self, action_id: int): - self.action_id = action_id - - def __eq__(self, other): - result = False - if isinstance(other, ActionEvent): - result = self.action_id == other.action_id - return result - - @staticmethod - def get_num_actions(): - ''' Return the number of possible actions in the game - ''' - return knock_action_id + 52 # FIXME: sensitive to code changes 200213 - - @staticmethod - def decode_action(action_id) -> 'ActionEvent': - ''' Action id -> the action_event in the game. - - Args: - action_id (int): the id of the action - - Returns: - action (ActionEvent): the action that will be passed to the game engine. - ''' - if action_id == score_player_0_action_id: - action_event = ScoreNorthPlayerAction() - elif action_id == score_player_1_action_id: - action_event = ScoreSouthPlayerAction() - elif action_id == draw_card_action_id: - action_event = DrawCardAction() - elif action_id == pick_up_discard_action_id: - action_event = PickUpDiscardAction() - elif action_id == declare_dead_hand_action_id: - action_event = DeclareDeadHandAction() - elif action_id == gin_action_id: - action_event = GinAction() - elif action_id in range(discard_action_id, discard_action_id + 52): - card_id = action_id - discard_action_id - card = utils.get_card(card_id=card_id) - action_event = DiscardAction(card=card) - elif action_id in range(knock_action_id, knock_action_id + 52): - card_id = action_id - knock_action_id - card = utils.get_card(card_id=card_id) - action_event = KnockAction(card=card) - else: - raise Exception(""decode_action: unknown action_id={}"".format(action_id)) - return action_event - - -class ScoreNorthPlayerAction(ActionEvent): - - def __init__(self): - super().__init__(action_id=score_player_0_action_id) - - def __str__(self): - return ""score N"" - - -class ScoreSouthPlayerAction(ActionEvent): - - def __init__(self): - super().__init__(action_id=score_player_1_action_id) - - def __str__(self): - return ""score S"" - - -class DrawCardAction(ActionEvent): - - def __init__(self): - super().__init__(action_id=draw_card_action_id) - - def __str__(self): - return ""draw_card"" - - -class PickUpDiscardAction(ActionEvent): - - def __init__(self): - super().__init__(action_id=pick_up_discard_action_id) - - def __str__(self): - return ""pick_up_discard"" - - -class DeclareDeadHandAction(ActionEvent): - - def __init__(self): - super().__init__(action_id=declare_dead_hand_action_id) - - def __str__(self): - return ""declare_dead_hand"" - - -class GinAction(ActionEvent): - - def __init__(self): - super().__init__(action_id=gin_action_id) - - def __str__(self): - return ""gin"" - - -class DiscardAction(ActionEvent): - - def __init__(self, card: Card): - card_id = utils.get_card_id(card) - super().__init__(action_id=discard_action_id + card_id) - self.card = card - - def __str__(self): - return ""discard {}"".format(str(self.card)) - - -class KnockAction(ActionEvent): - - def __init__(self, card: Card): - card_id = utils.get_card_id(card) - super().__init__(action_id=knock_action_id + card_id) - self.card = card - - def __str__(self): - return ""knock {}"".format(str(self.card)) - - -''' -gin_rummy/scorers.py -''' -from typing import TYPE_CHECKING - -from typing import Callable - -from action_event import * -from gin_rummy import Player -from move import ScoreNorthMove, ScoreSouthMove -from gin_rummy_error import GinRummyProgramError - -import melding -import utils - - -class GinRummyScorer: - - def __init__(self, name: str = None, get_payoff: Callable[[Player, 'GinRummyGame'], int or float] = None): - self.name = name if name is not None else ""GinRummyScorer"" - self.get_payoff = get_payoff if get_payoff else get_payoff_gin_rummy_v1 - - def get_payoffs(self, game: 'GinRummyGame'): - payoffs = [0, 0] - for i in range(2): - player = game.round.players[i] - payoff = self.get_payoff(player=player, game=game) - payoffs[i] = payoff - return payoffs - - -def get_payoff_gin_rummy_v0(player: Player, game: 'GinRummyGame') -> int: - ''' Get the payoff of player: deadwood_count of player - - Returns: - payoff (int or float): payoff for player (lower is better) - ''' - moves = game.round.move_sheet - if player.player_id == 0: - score_player_move = moves[-2] - if not isinstance(score_player_move, ScoreNorthMove): - raise GinRummyProgramError(""score_player_move must be ScoreNorthMove."") - else: - score_player_move = moves[-1] - if not isinstance(score_player_move, ScoreSouthMove): - raise GinRummyProgramError(""score_player_move must be ScoreSouthMove."") - deadwood_count = score_player_move.deadwood_count - return deadwood_count - - -def get_payoff_gin_rummy_v1(player: Player, game: 'GinRummyGame') -> float: - ''' Get the payoff of player: - a) 1.0 if player gins - b) 0.2 if player knocks - c) -deadwood_count / 100 otherwise - - Returns: - payoff (int or float): payoff for player (higher is better) - ''' - # payoff is 1.0 if player gins - # payoff is 0.2 if player knocks - # payoff is -deadwood_count / 100 if otherwise - # The goal is to have the agent learn how to knock and gin. - # The negative payoff when the agent fails to knock or gin should encourage the agent to form melds. - # The payoff is scaled to lie between -1 and 1. - going_out_action = game.round.going_out_action - going_out_player_id = game.round.going_out_player_id - if going_out_player_id == player.player_id and isinstance(going_out_action, KnockAction): - payoff = 0.2 - elif going_out_player_id == player.player_id and isinstance(going_out_action, GinAction): - payoff = 1 - else: - hand = player.hand - best_meld_clusters = melding.get_best_meld_clusters(hand=hand) - best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0] - deadwood_count = utils.get_deadwood_count(hand, best_meld_cluster) - payoff = -deadwood_count / 100 - return payoff - - -''' -gin_rummy/game.py -''' -import numpy as np - -from gin_rummy import Player -from round import GinRummyRound -from gin_rummy import Judger -from settings import Settings, DealerForRound - -from action_event import * - - -class GinRummyGame: - ''' Game class. This class will interact with outer environment. - ''' - - def __init__(self, allow_step_back=False): - '''Initialize the class GinRummyGame - ''' - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - self.judge = Judger(game=self) - self.settings = Settings() - self.actions = None # type: List[ActionEvent] or None # must reset in init_game - self.round = None # round: GinRummyRound or None, must reset in init_game - self.num_players = 2 - - def init_game(self): - ''' Initialize all characters in the game and start round 1 - ''' - dealer_id = self.np_random.choice([0, 1]) - if self.settings.dealer_for_round == DealerForRound.North: - dealer_id = 0 - elif self.settings.dealer_for_round == DealerForRound.South: - dealer_id = 1 - self.actions = [] - self.round = GinRummyRound(dealer_id=dealer_id, np_random=self.np_random) - for i in range(2): - num = 11 if i == 0 else 10 - player = self.round.players[(dealer_id + 1 + i) % 2] - self.round.dealer.deal_cards(player=player, num=num) - current_player_id = self.round.current_player_id - state = self.get_state(player_id=current_player_id) - return state, current_player_id - - def step(self, action: ActionEvent): - ''' Perform game action and return next player number, and the state for next player - ''' - if isinstance(action, ScoreNorthPlayerAction): - self.round.score_player_0(action) - elif isinstance(action, ScoreSouthPlayerAction): - self.round.score_player_1(action) - elif isinstance(action, DrawCardAction): - self.round.draw_card(action) - elif isinstance(action, PickUpDiscardAction): - self.round.pick_up_discard(action) - elif isinstance(action, DeclareDeadHandAction): - self.round.declare_dead_hand(action) - elif isinstance(action, GinAction): - self.round.gin(action, going_out_deadwood_count=self.settings.going_out_deadwood_count) - elif isinstance(action, DiscardAction): - self.round.discard(action) - elif isinstance(action, KnockAction): - self.round.knock(action) - else: - raise Exception('Unknown step action={}'.format(action)) - self.actions.append(action) - next_player_id = self.round.current_player_id - next_state = self.get_state(player_id=next_player_id) - return next_state, next_player_id - - def step_back(self): - ''' Takes one step backward and restore to the last state - ''' - raise NotImplementedError - - def get_num_players(self): - ''' Return the number of players in the game - ''' - return 2 - - def get_num_actions(self): - ''' Return the number of possible actions in the game - ''' - return ActionEvent.get_num_actions() - - def get_player_id(self): - ''' Return the current player that will take actions soon - ''' - return self.round.current_player_id - - def is_over(self): - ''' Return whether the current game is over - ''' - return self.round.is_over - - def get_current_player(self) -> Player or None: - return self.round.get_current_player() - - def get_last_action(self) -> ActionEvent or None: - return self.actions[-1] if self.actions and len(self.actions) > 0 else None - - def get_state(self, player_id: int): - ''' Get player's state - - Return: - state (dict): The information of the state - ''' - state = {} - if not self.is_over(): - discard_pile = self.round.dealer.discard_pile - top_discard = [] if not discard_pile else [discard_pile[-1]] - dead_cards = discard_pile[:-1] - last_action = self.get_last_action() - opponent_id = (player_id + 1) % 2 - opponent = self.round.players[opponent_id] - known_cards = opponent.known_cards - if isinstance(last_action, ScoreNorthPlayerAction) or isinstance(last_action, ScoreSouthPlayerAction): - known_cards = opponent.hand - unknown_cards = self.round.dealer.stock_pile + [card for card in opponent.hand if card not in known_cards] - state['player_id'] = self.round.current_player_id - state['hand'] = [x.get_index() for x in self.round.players[self.round.current_player_id].hand] - state['top_discard'] = [x.get_index() for x in top_discard] - state['dead_cards'] = [x.get_index() for x in dead_cards] - state['opponent_known_cards'] = [x.get_index() for x in known_cards] - state['unknown_cards'] = [x.get_index() for x in unknown_cards] - return state - - @staticmethod - def decode_action(action_id) -> ActionEvent: # FIXME 200213 should return str - ''' Action id -> the action_event in the game. - - Args: - action_id (int): the id of the action - - Returns: - action (ActionEvent): the action that will be passed to the game engine. - ''' - return ActionEvent.decode_action(action_id=action_id) - - -''' -gin_rummy/utils.py -''' -from typing import List, Iterable - -import numpy as np - -from gin_rummy import Card - -from gin_rummy_error import GinRummyProgramError - -valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] -valid_suit = ['S', 'H', 'D', 'C'] - -rank_to_deadwood_value = {""A"": 1, ""2"": 2, ""3"": 3, ""4"": 4, ""5"": 5, ""6"": 6, ""7"": 7, ""8"": 8, ""9"": 9, - ""T"": 10, ""J"": 10, ""Q"": 10, ""K"": 10} - - -def card_from_card_id(card_id: int) -> Card: - ''' Make card from its card_id - - Args: - card_id: int in range(0, 52) - ''' - if not (0 <= card_id < 52): - raise GinRummyProgramError(""card_id is {}: should be 0 <= card_id < 52."".format(card_id)) - rank_id = card_id % 13 - suit_id = card_id // 13 - rank = Card.valid_rank[rank_id] - suit = Card.valid_suit[suit_id] - return Card(rank=rank, suit=suit) - - -# deck is always in order from AS, 2S, ..., AH, 2H, ..., AD, 2D, ..., AC, 2C, ... QC, KC -_deck = [card_from_card_id(card_id) for card_id in range(52)] # want this to be read-only - - -def card_from_text(text: str) -> Card: - if len(text) != 2: - raise GinRummyProgramError(""len(text) is {}: should be 2."".format(len(text))) - return Card(rank=text[0], suit=text[1]) - - -def get_deck() -> List[Card]: - return _deck.copy() - - -def get_card(card_id: int): - return _deck[card_id] - - -def get_card_id(card: Card) -> int: - rank_id = get_rank_id(card) - suit_id = get_suit_id(card) - return rank_id + 13 * suit_id - - -def get_rank_id(card: Card) -> int: - return Card.valid_rank.index(card.rank) - - -def get_suit_id(card: Card) -> int: - return Card.valid_suit.index(card.suit) - - -def get_deadwood_value(card: Card) -> int: - rank = card.rank - deadwood_value = rank_to_deadwood_value.get(rank, 10) # default to 10 is key does not exist - return deadwood_value - - -def get_deadwood(hand: Iterable[Card], meld_cluster: List[Iterable[Card]]) -> List[Card]: - if len(list(hand)) != 10: - raise GinRummyProgramError(""Hand contain {} cards: should be 10 cards."".format(len(list(hand)))) - meld_cards = [card for meld_pile in meld_cluster for card in meld_pile] - deadwood = [card for card in hand if card not in meld_cards] - return deadwood - - -def get_deadwood_count(hand: List[Card], meld_cluster: List[Iterable[Card]]) -> int: - if len(hand) != 10: - raise GinRummyProgramError(""Hand contain {} cards: should be 10 cards."".format(len(hand))) - deadwood = get_deadwood(hand=hand, meld_cluster=meld_cluster) - deadwood_values = [get_deadwood_value(card) for card in deadwood] - return sum(deadwood_values) - - -def decode_cards(env_cards: np.ndarray) -> List[Card]: - result = [] # type: List[Card] - if len(env_cards) != 52: - raise GinRummyProgramError(""len(env_cards) is {}: should be 52."".format(len(env_cards))) - for i in range(52): - if env_cards[i] == 1: - card = _deck[i] - result.append(card) - return result - - -def encode_cards(cards: List[Card]) -> np.ndarray: - plane = np.zeros(52, dtype=int) - for card in cards: - card_id = get_card_id(card) - plane[card_id] = 1 - return plane - - -''' -gin_rummy/__init__.py -''' - -from gin_rummy.base import Card as Card -from gin_rummy.player import GinRummyPlayer as Player -from gin_rummy.dealer import GinRummyDealer as Dealer -from gin_rummy.judge import GinRummyJudge as Judger - - -from gin_rummy.game import GinRummyGame as Game - -''' -gin_rummy/melding.py -''' -from typing import List - -from gin_rummy import Card - -import utils -from gin_rummy_error import GinRummyProgramError - -# =============================================================== -# Terminology: -# run_meld - three or more cards of same suit in sequence -# set_meld - three or more cards of same rank -# meld_pile - a run_meld or a set_meld -# meld_piles - a list of meld_pile -# meld_cluster - same as meld_piles, but usually with the piles being mutually disjoint -# meld_clusters - a list of meld_cluster -# =============================================================== - - -def get_meld_clusters(hand: List[Card]) -> List[List[List[Card]]]: - result = [] # type: List[List[List[Card]]] - all_run_melds = [frozenset(x) for x in get_all_run_melds(hand)] - all_set_melds = [frozenset(x) for x in get_all_set_melds(hand)] - all_melds = all_run_melds + all_set_melds - all_melds_count = len(all_melds) - for i in range(0, all_melds_count): - first_meld = all_melds[i] - first_meld_list = list(first_meld) - meld_cluster_1 = [first_meld_list] - result.append(meld_cluster_1) - for j in range(i + 1, all_melds_count): - second_meld = all_melds[j] - second_meld_list = list(second_meld) - if not second_meld.isdisjoint(first_meld): - continue - meld_cluster_2 = [first_meld_list, second_meld_list] - result.append(meld_cluster_2) - for k in range(j + 1, all_melds_count): - third_meld = all_melds[k] - third_meld_list = list(third_meld) - if not third_meld.isdisjoint(first_meld) or not third_meld.isdisjoint(second_meld): - continue - meld_cluster_3 = [first_meld_list, second_meld_list, third_meld_list] - result.append(meld_cluster_3) - return result - - -def get_best_meld_clusters(hand: List[Card]) -> List[List[List[Card]]]: - if len(hand) != 10: - raise GinRummyProgramError(""Hand contain {} cards: should be 10 cards."".format(len(hand))) - result = [] # type: List[List[List[Card]]] - meld_clusters = get_meld_clusters(hand=hand) # type: List[List[List[Card]]] - meld_clusters_count = len(meld_clusters) - if meld_clusters_count > 0: - deadwood_counts = [utils.get_deadwood_count(hand=hand, meld_cluster=meld_cluster) - for meld_cluster in meld_clusters] - best_deadwood_count = min(deadwood_counts) - for i in range(meld_clusters_count): - if deadwood_counts[i] == best_deadwood_count: - result.append(meld_clusters[i]) - return result - - -def get_all_run_melds(hand: List[Card]) -> List[List[Card]]: - card_count = len(hand) - hand_by_suit = sorted(hand, key=utils.get_card_id) - max_run_melds = [] - - i = 0 - while i < card_count - 2: - card_i = hand_by_suit[i] - j = i + 1 - card_j = hand_by_suit[j] - while utils.get_rank_id(card_j) == utils.get_rank_id(card_i) + j - i and card_j.suit == card_i.suit: - j += 1 - if j < card_count: - card_j = hand_by_suit[j] - else: - break - max_run_meld = hand_by_suit[i:j] - if len(max_run_meld) >= 3: - max_run_melds.append(max_run_meld) - i = j - - result = [] - for max_run_meld in max_run_melds: - max_run_meld_count = len(max_run_meld) - for i in range(max_run_meld_count - 2): - for j in range(i + 3, max_run_meld_count + 1): - result.append(max_run_meld[i:j]) - return result - - -def get_all_set_melds(hand: List[Card]) -> List[List[Card]]: - max_set_melds = [] - hand_by_rank = sorted(hand, key=lambda x: x.rank) - set_meld = [] - current_rank = None - for card in hand_by_rank: - if current_rank is None or current_rank == card.rank: - set_meld.append(card) - else: - if len(set_meld) >= 3: - max_set_melds.append(set_meld) - set_meld = [card] - current_rank = card.rank - if len(set_meld) >= 3: - max_set_melds.append(set_meld) - result = [] - for max_set_meld in max_set_melds: - result.append(max_set_meld) - if len(max_set_meld) == 4: - for meld_card in max_set_meld: - result.append([card for card in max_set_meld if card != meld_card]) - return result - - -def get_all_run_melds_for_suit(cards: List[Card], suit: str) -> List[List[Card]]: - cards_for_suit = [card for card in cards if card.suit == suit] - cards_for_suit_count = len(cards_for_suit) - cards_for_suit = sorted(cards_for_suit, key=utils.get_card_id) - max_run_melds = [] - - i = 0 - while i < cards_for_suit_count - 2: - card_i = cards_for_suit[i] - j = i + 1 - card_j = cards_for_suit[j] - while utils.get_rank_id(card_j) == utils.get_rank_id(card_i) + j - i: - j += 1 - if j < cards_for_suit_count: - card_j = cards_for_suit[j] - else: - break - max_run_meld = cards_for_suit[i:j] - if len(max_run_meld) >= 3: - max_run_melds.append(max_run_meld) - i = j - - result = [] - for max_run_meld in max_run_melds: - max_run_meld_count = len(max_run_meld) - for i in range(max_run_meld_count - 2): - for j in range(i + 3, max_run_meld_count + 1): - result.append(max_run_meld[i:j]) - return result - - -''' -gin_rummy/round.py -''' -from typing import TYPE_CHECKING -if TYPE_CHECKING: - from move import GinRummyMove - -from typing import List - -from gin_rummy import Dealer - -from action_event import DrawCardAction, PickUpDiscardAction, DeclareDeadHandAction -from action_event import DiscardAction, KnockAction, GinAction -from action_event import ScoreNorthPlayerAction, ScoreSouthPlayerAction - -from move import DealHandMove -from move import DrawCardMove, PickupDiscardMove, DeclareDeadHandMove -from move import DiscardMove, KnockMove, GinMove -from move import ScoreNorthMove, ScoreSouthMove - -from gin_rummy_error import GinRummyProgramError - -from gin_rummy import Player -import judge - -import melding -import utils - - -class GinRummyRound: - - def __init__(self, dealer_id: int, np_random): - ''' Initialize the round class - - The round class maintains the following instances: - 1) dealer: the dealer of the round; dealer has stock_pile and discard_pile - 2) players: the players in the round; each player has his own hand_pile - 3) current_player_id: the id of the current player who has the move - 4) is_over: true if the round is over - 5) going_out_action: knock or gin or None - 6) going_out_player_id: id of player who went out or None - 7) move_sheet: history of the moves of the player (including the deal_hand_move) - - The round class maintains a list of moves made by the players in self.move_sheet. - move_sheet is similar to a chess score sheet. - I didn't want to call it a score_sheet since it is not keeping score. - I could have called move_sheet just moves, but that might conflict with the name moves used elsewhere. - I settled on the longer name ""move_sheet"" to indicate that it is the official list of moves being made. - - Args: - dealer_id: int - ''' - self.np_random = np_random - self.dealer_id = dealer_id - self.dealer = Dealer(self.np_random) - self.players = [Player(player_id=0, np_random=self.np_random), Player(player_id=1, np_random=self.np_random)] - self.current_player_id = (dealer_id + 1) % 2 - self.is_over = False - self.going_out_action = None # going_out_action: int or None - self.going_out_player_id = None # going_out_player_id: int or None - self.move_sheet = [] # type: List[GinRummyMove] - player_dealing = Player(player_id=dealer_id, np_random=self.np_random) - shuffled_deck = self.dealer.shuffled_deck - self.move_sheet.append(DealHandMove(player_dealing=player_dealing, shuffled_deck=shuffled_deck)) - - def get_current_player(self) -> Player or None: - current_player_id = self.current_player_id - return None if current_player_id is None else self.players[current_player_id] - - def draw_card(self, action: DrawCardAction): - # when current_player takes DrawCardAction step, the move is recorded and executed - # current_player keeps turn - current_player = self.players[self.current_player_id] - if not len(current_player.hand) == 10: - raise GinRummyProgramError(""len(current_player.hand) is {}: should be 10."".format(len(current_player.hand))) - card = self.dealer.stock_pile.pop() - self.move_sheet.append(DrawCardMove(current_player, action=action, card=card)) - current_player.add_card_to_hand(card=card) - - def pick_up_discard(self, action: PickUpDiscardAction): - # when current_player takes PickUpDiscardAction step, the move is recorded and executed - # opponent knows that the card is in current_player hand - # current_player keeps turn - current_player = self.players[self.current_player_id] - if not len(current_player.hand) == 10: - raise GinRummyProgramError(""len(current_player.hand) is {}: should be 10."".format(len(current_player.hand))) - card = self.dealer.discard_pile.pop() - self.move_sheet.append(PickupDiscardMove(current_player, action, card=card)) - current_player.add_card_to_hand(card=card) - current_player.known_cards.append(card) - - def declare_dead_hand(self, action: DeclareDeadHandAction): - # when current_player takes DeclareDeadHandAction step, the move is recorded and executed - # north becomes current_player to score his hand - current_player = self.players[self.current_player_id] - self.move_sheet.append(DeclareDeadHandMove(current_player, action)) - self.going_out_action = action - self.going_out_player_id = self.current_player_id - if not len(current_player.hand) == 10: - raise GinRummyProgramError(""len(current_player.hand) is {}: should be 10."".format(len(current_player.hand))) - self.current_player_id = 0 - - def discard(self, action: DiscardAction): - # when current_player takes DiscardAction step, the move is recorded and executed - # opponent knows that the card is no longer in current_player hand - # current_player loses his turn and the opponent becomes the current player - current_player = self.players[self.current_player_id] - if not len(current_player.hand) == 11: - raise GinRummyProgramError(""len(current_player.hand) is {}: should be 11."".format(len(current_player.hand))) - self.move_sheet.append(DiscardMove(current_player, action)) - card = action.card - current_player.remove_card_from_hand(card=card) - if card in current_player.known_cards: - current_player.known_cards.remove(card) - self.dealer.discard_pile.append(card) - self.current_player_id = (self.current_player_id + 1) % 2 - - def knock(self, action: KnockAction): - # when current_player takes KnockAction step, the move is recorded and executed - # opponent knows that the card is no longer in current_player hand - # north becomes current_player to score his hand - current_player = self.players[self.current_player_id] - self.move_sheet.append(KnockMove(current_player, action)) - self.going_out_action = action - self.going_out_player_id = self.current_player_id - if not len(current_player.hand) == 11: - raise GinRummyProgramError(""len(current_player.hand) is {}: should be 11."".format(len(current_player.hand))) - card = action.card - current_player.remove_card_from_hand(card=card) - if card in current_player.known_cards: - current_player.known_cards.remove(card) - self.current_player_id = 0 - - def gin(self, action: GinAction, going_out_deadwood_count: int): - # when current_player takes GinAction step, the move is recorded and executed - # opponent knows that the card is no longer in current_player hand - # north becomes current_player to score his hand - current_player = self.players[self.current_player_id] - self.move_sheet.append(GinMove(current_player, action)) - self.going_out_action = action - self.going_out_player_id = self.current_player_id - if not len(current_player.hand) == 11: - raise GinRummyProgramError(""len(current_player.hand) is {}: should be 11."".format(len(current_player.hand))) - _, gin_cards = judge.get_going_out_cards(current_player.hand, going_out_deadwood_count) - card = gin_cards[0] - current_player.remove_card_from_hand(card=card) - if card in current_player.known_cards: - current_player.known_cards.remove(card) - self.current_player_id = 0 - - def score_player_0(self, action: ScoreNorthPlayerAction): - # when current_player takes ScoreNorthPlayerAction step, the move is recorded and executed - # south becomes current player - if not self.current_player_id == 0: - raise GinRummyProgramError(""current_player_id is {}: should be 0."".format(self.current_player_id)) - current_player = self.get_current_player() - best_meld_clusters = melding.get_best_meld_clusters(hand=current_player.hand) - best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0] - deadwood_count = utils.get_deadwood_count(hand=current_player.hand, meld_cluster=best_meld_cluster) - self.move_sheet.append(ScoreNorthMove(player=current_player, - action=action, - best_meld_cluster=best_meld_cluster, - deadwood_count=deadwood_count)) - self.current_player_id = 1 - - def score_player_1(self, action: ScoreSouthPlayerAction): - # when current_player takes ScoreSouthPlayerAction step, the move is recorded and executed - # south remains current player - # the round is over - if not self.current_player_id == 1: - raise GinRummyProgramError(""current_player_id is {}: should be 1."".format(self.current_player_id)) - current_player = self.get_current_player() - best_meld_clusters = melding.get_best_meld_clusters(hand=current_player.hand) - best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0] - deadwood_count = utils.get_deadwood_count(hand=current_player.hand, meld_cluster=best_meld_cluster) - self.move_sheet.append(ScoreSouthMove(player=current_player, - action=action, - best_meld_cluster=best_meld_cluster, - deadwood_count=deadwood_count)) - self.is_over = True - - -''' -gin_rummy/gin_rummy_error.py -''' -class GinRummyError(Exception): - pass - - -class GinRummyProgramError(GinRummyError): - pass - - -",14,1453 -stock2,./ProjectTest/Python/stock2.py,"''' -stock2/stock.py -''' -# stock.py - -from structure import Structure - -class Stock(Structure): - name = String() - shares = PositiveInteger() - price = PositiveFloat() - - @property - def cost(self): - return self.shares * self.price - - def sell(self, nshares: PositiveInteger): - self.shares -= nshares - - - -''' -stock2/reader.py -''' -# reader.py - -import csv -import logging - -log = logging.getLogger(__name__) - -def convert_csv(lines, converter, *, headers=None): - rows = csv.reader(lines) - if headers is None: - headers = next(rows) - - records = [] - for rowno, row in enumerate(rows, start=1): - try: - records.append(converter(headers, row)) - except ValueError as e: - log.warning('Row %s: Bad row: %s', rowno, row) - log.debug('Row %s: Reason: %s', rowno, row) - return records - -def csv_as_dicts(lines, types, *, headers=None): - return convert_csv(lines, - lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) }) - -def csv_as_instances(lines, cls, *, headers=None): - return convert_csv(lines, - lambda headers, row: cls.from_row(row)) - -def read_csv_as_dicts(filename, types, *, headers=None): - ''' - Read CSV data into a list of dictionaries with optional type conversion - ''' - with open(filename) as file: - return csv_as_dicts(file, types, headers=headers) - -def read_csv_as_instances(filename, cls, *, headers=None): - ''' - Read CSV data into a list of instances - ''' - with open(filename) as file: - return csv_as_instances(file, cls, headers=headers) - - - -''' -stock2/validate.py -''' -# validate.py - -class Validator: - def __init__(self, name=None): - self.name = name - - def __set_name__(self, cls, name): - self.name = name - - @classmethod - def check(cls, value): - return value - - def __set__(self, instance, value): - instance.__dict__[self.name] = self.check(value) - - # Collect all derived classes into a dict - validators = { } - @classmethod - def __init_subclass__(cls): - cls.validators[cls.__name__] = cls - -class Typed(Validator): - expected_type = object - @classmethod - def check(cls, value): - if not isinstance(value, cls.expected_type): - raise TypeError(f'expected {cls.expected_type}') - return super().check(value) - -_typed_classes = [ - ('Integer', int), - ('Float', float), - ('String', str) ] - -globals().update((name, type(name, (Typed,), {'expected_type':ty})) - for name, ty in _typed_classes) - -class Positive(Validator): - @classmethod - def check(cls, value): - if value < 0: - raise ValueError('must be >= 0') - return super().check(value) - -class NonEmpty(Validator): - @classmethod - def check(cls, value): - if len(value) == 0: - raise ValueError('must be non-empty') - return super().check(value) - -class PositiveInteger(Integer, Positive): - pass - -class PositiveFloat(Float, Positive): - pass - -class NonEmptyString(String, NonEmpty): - pass - -from inspect import signature -from functools import wraps - -def isvalidator(item): - return isinstance(item, type) and issubclass(item, Validator) - -def validated(func): - sig = signature(func) - - # Gather the function annotations - annotations = { name:val for name, val in func.__annotations__.items() - if isvalidator(val) } - - # Get the return annotation (if any) - retcheck = annotations.pop('return', None) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - # Enforce return check (if any) - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - - return wrapper - -def enforce(**annotations): - retcheck = annotations.pop('return_', None) - - def decorate(func): - sig = signature(func) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - return wrapper - return decorate - - -''' -stock2/tableformat.py -''' -# tableformat.py -from abc import ABC, abstractmethod - -def print_table(records, fields, formatter): - if not isinstance(formatter, TableFormatter): - raise RuntimeError('Expected a TableFormatter') - - formatter.headings(fields) - for r in records: - rowdata = [getattr(r, fieldname) for fieldname in fields] - formatter.row(rowdata) - -class TableFormatter(ABC): - @abstractmethod - def headings(self, headers): - pass - - @abstractmethod - def row(self, rowdata): - pass - -class TextTableFormatter(TableFormatter): - def headings(self, headers): - print(' '.join('%10s' % h for h in headers)) - print(('-'*10 + ' ')*len(headers)) - - def row(self, rowdata): - print(' '.join('%10s' % d for d in rowdata)) - -class CSVTableFormatter(TableFormatter): - def headings(self, headers): - print(','.join(headers)) - - def row(self, rowdata): - print(','.join(str(d) for d in rowdata)) - -class HTMLTableFormatter(TableFormatter): - def headings(self, headers): - print('', end=' ') - for h in headers: - print('%s' % h, end=' ') - print('') - - def row(self, rowdata): - print('', end=' ') - for d in rowdata: - print('%s' % d, end=' ') - print('') - -class ColumnFormatMixin: - formats = [] - def row(self, rowdata): - rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)] - super().row(rowdata) - -class UpperHeadersMixin: - def headings(self, headers): - super().headings([h.upper() for h in headers]) - -def create_formatter(name, column_formats=None, upper_headers=False): - if name == 'text': - formatter_cls = TextTableFormatter - elif name == 'csv': - formatter_cls = CSVTableFormatter - elif name == 'html': - formatter_cls = HTMLTableFormatter - else: - raise RuntimeError('Unknown format %s' % name) - - if column_formats: - class formatter_cls(ColumnFormatMixin, formatter_cls): - formats = column_formats - - if upper_headers: - class formatter_cls(UpperHeadersMixin, formatter_cls): - pass - - return formatter_cls() - - - - - - -''' -stock2/structure.py -''' -# structure.py - -from validate import Validator, validated -from collections import ChainMap - -class StructureMeta(type): - @classmethod - def __prepare__(meta, clsname, bases): - return ChainMap({}, Validator.validators) - - @staticmethod - def __new__(meta, name, bases, methods): - methods = methods.maps[0] - return super().__new__(meta, name, bases, methods) - -class Structure(metaclass=StructureMeta): - _fields = () - _types = () - - def __setattr__(self, name, value): - if name.startswith('_') or name in self._fields: - super().__setattr__(name, value) - else: - raise AttributeError('No attribute %s' % name) - - def __repr__(self): - return '%s(%s)' % (type(self).__name__, - ', '.join(repr(getattr(self, name)) for name in self._fields)) - - @classmethod - def from_row(cls, row): - rowdata = [ func(val) for func, val in zip(cls._types, row) ] - return cls(*rowdata) - - - @classmethod - def create_init(cls): - ''' - Create an __init__ method from _fields - ''' - args = ','.join(cls._fields) - code = f'def __init__(self, {args}):\n' - for name in cls._fields: - code += f' self.{name} = {name}\n' - locs = { } - exec(code, locs) - cls.__init__ = locs['__init__'] - - @classmethod - def __init_subclass__(cls): - # Apply the validated decorator to subclasses - validate_attributes(cls) - -def validate_attributes(cls): - ''' - Class decorator that scans a class definition for Validators - and builds a _fields variable that captures their definition order. - ''' - validators = [] - for name, val in vars(cls).items(): - if isinstance(val, Validator): - validators.append(val) - - # Apply validated decorator to any callable with annotations - elif callable(val) and val.__annotations__: - setattr(cls, name, validated(val)) - - # Collect all of the field names - cls._fields = tuple([v.name for v in validators]) - - # Collect type conversions. The lambda x:x is an identity - # function that's used in case no expected_type is found. - cls._types = tuple([ getattr(v, 'expected_type', lambda x: x) - for v in validators ]) - - # Create the __init__ method - if cls._fields: - cls.create_init() - - - return cls - -def typed_structure(clsname, **validators): - cls = type(clsname, (Structure,), validators) - return cls - - -",5,361 -stock,./ProjectTest/Python/stock.py,"''' -stock/stock.py -''' -# stock.py - -from structure import Structure -from validate import String, PositiveInteger, PositiveFloat - -class Stock(Structure): - name = String() - shares = PositiveInteger() - price = PositiveFloat() - - @property - def cost(self): - return self.shares * self.price - - def sell(self, nshares: PositiveInteger): - self.shares -= nshares - - -''' -stock/validate.py -''' -# validate.py - -class Validator: - def __init__(self, name=None): - self.name = name - - def __set_name__(self, cls, name): - self.name = name - - @classmethod - def check(cls, value): - return value - - def __set__(self, instance, value): - instance.__dict__[self.name] = self.check(value) - -class Typed(Validator): - expected_type = object - @classmethod - def check(cls, value): - if not isinstance(value, cls.expected_type): - raise TypeError(f'expected {cls.expected_type}') - return super().check(value) - -class Integer(Typed): - expected_type = int - -class Float(Typed): - expected_type = float - -class String(Typed): - expected_type = str - -class Positive(Validator): - @classmethod - def check(cls, value): - if value < 0: - raise ValueError('must be >= 0') - return super().check(value) - -class NonEmpty(Validator): - @classmethod - def check(cls, value): - if len(value) == 0: - raise ValueError('must be non-empty') - return super().check(value) - -class PositiveInteger(Integer, Positive): - pass - -class PositiveFloat(Float, Positive): - pass - -class NonEmptyString(String, NonEmpty): - pass - -from inspect import signature -from functools import wraps - -def isvalidator(item): - return isinstance(item, type) and issubclass(item, Validator) - -def validated(func): - sig = signature(func) - - # Gather the function annotations - annotations = { name:val for name, val in func.__annotations__.items() - if isvalidator(val) } - - # Get the return annotation (if any) - retcheck = annotations.pop('return', None) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - # Enforce return check (if any) - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - - return wrapper - -def enforce(**annotations): - retcheck = annotations.pop('return_', None) - - def decorate(func): - sig = signature(func) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - return wrapper - return decorate - - - -''' -stock/structure.py -''' -# structure.py - -from validate import Validator, validated - -class Structure: - _fields = () - _types = () - - def __setattr__(self, name, value): - if name.startswith('_') or name in self._fields: - super().__setattr__(name, value) - else: - raise AttributeError('No attribute %s' % name) - - def __repr__(self): - return '%s(%s)' % (type(self).__name__, - ', '.join(repr(getattr(self, name)) for name in self._fields)) - - @classmethod - def from_row(cls, row): - rowdata = [ func(val) for func, val in zip(cls._types, row) ] - return cls(*rowdata) - - @classmethod - def create_init(cls): - ''' - Create an __init__ method from _fields - ''' - args = ','.join(cls._fields) - code = f'def __init__(self, {args}):\n' - for name in cls._fields: - code += f' self.{name} = {name}\n' - locs = { } - exec(code, locs) - cls.__init__ = locs['__init__'] - - @classmethod - def __init_subclass__(cls): - # Apply the validated decorator to subclasses - validate_attributes(cls) - -def validate_attributes(cls): - ''' - Class decorator that scans a class definition for Validators - and builds a _fields variable that captures their definition order. - ''' - validators = [] - for name, val in vars(cls).items(): - if isinstance(val, Validator): - validators.append(val) - - # Apply validated decorator to any callable with annotations - elif callable(val) and val.__annotations__: - setattr(cls, name, validated(val)) - - # Collect all of the field names - cls._fields = tuple([v.name for v in validators]) - - # Collect type conversions. The lambda x:x is an identity - # function that's used in case no expected_type is found. - cls._types = tuple([ getattr(v, 'expected_type', lambda x: x) - for v in validators ]) - - # Create the __init__ method - if cls._fields: - cls.create_init() - - - return cls - - - -",3,217 -structly,./ProjectTest/Python/structly.py,"''' -structly/stock.py -''' -# stock.py - -from structly.structure import Structure - -class Stock(Structure): - name = String() - shares = PositiveInteger() - price = PositiveFloat() - - @property - def cost(self): - return self.shares * self.price - - def sell(self, nshares: PositiveInteger): - self.shares -= nshares - - - -''' -structly/structly/reader.py -''' -# reader.py - -import csv -import logging - -log = logging.getLogger(__name__) - -def convert_csv(lines, converter, *, headers=None): - rows = csv.reader(lines) - if headers is None: - headers = next(rows) - - records = [] - for rowno, row in enumerate(rows, start=1): - try: - records.append(converter(headers, row)) - except ValueError as e: - log.warning('Row %s: Bad row: %s', rowno, row) - log.debug('Row %s: Reason: %s', rowno, row) - return records - -def csv_as_dicts(lines, types, *, headers=None): - return convert_csv(lines, - lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) }) - -def csv_as_instances(lines, cls, *, headers=None): - return convert_csv(lines, - lambda headers, row: cls.from_row(row)) - -def read_csv_as_dicts(filename, types, *, headers=None): - ''' - Read CSV data into a list of dictionaries with optional type conversion - ''' - with open(filename) as file: - return csv_as_dicts(file, types, headers=headers) - -def read_csv_as_instances(filename, cls, *, headers=None): - ''' - Read CSV data into a list of instances - ''' - with open(filename) as file: - return csv_as_instances(file, cls, headers=headers) - - - -''' -structly/structly/validate.py -''' -# validate.py - -class Validator: - def __init__(self, name=None): - self.name = name - - def __set_name__(self, cls, name): - self.name = name - - @classmethod - def check(cls, value): - return value - - def __set__(self, instance, value): - instance.__dict__[self.name] = self.check(value) - - # Collect all derived classes into a dict - validators = { } - @classmethod - def __init_subclass__(cls): - cls.validators[cls.__name__] = cls - -class Typed(Validator): - expected_type = object - @classmethod - def check(cls, value): - if not isinstance(value, cls.expected_type): - raise TypeError(f'expected {cls.expected_type}') - return super().check(value) - -_typed_classes = [ - ('Integer', int), - ('Float', float), - ('String', str) ] - -globals().update((name, type(name, (Typed,), {'expected_type':ty})) - for name, ty in _typed_classes) - -class Positive(Validator): - @classmethod - def check(cls, value): - if value < 0: - raise ValueError('must be >= 0') - return super().check(value) - -class NonEmpty(Validator): - @classmethod - def check(cls, value): - if len(value) == 0: - raise ValueError('must be non-empty') - return super().check(value) - -class PositiveInteger(Integer, Positive): - pass - -class PositiveFloat(Float, Positive): - pass - -class NonEmptyString(String, NonEmpty): - pass - -from inspect import signature -from functools import wraps - -def isvalidator(item): - return isinstance(item, type) and issubclass(item, Validator) - -def validated(func): - sig = signature(func) - - # Gather the function annotations - annotations = { name:val for name, val in func.__annotations__.items() - if isvalidator(val) } - - # Get the return annotation (if any) - retcheck = annotations.pop('return', None) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - # Enforce return check (if any) - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - - return wrapper - -def enforce(**annotations): - retcheck = annotations.pop('return_', None) - - def decorate(func): - sig = signature(func) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - return wrapper - return decorate - - - -''' -structly/structly/__init__.py -''' - - -''' -structly/structly/tableformat.py -''' -# tableformat.py -from abc import ABC, abstractmethod - -def print_table(records, fields, formatter): - if not isinstance(formatter, TableFormatter): - raise RuntimeError('Expected a TableFormatter') - - formatter.headings(fields) - for r in records: - rowdata = [getattr(r, fieldname) for fieldname in fields] - formatter.row(rowdata) - -class TableFormatter(ABC): - @abstractmethod - def headings(self, headers): - pass - - @abstractmethod - def row(self, rowdata): - pass - - -class TextTableFormatter(TableFormatter): - def headings(self, headers): - print(' '.join('%10s' % h for h in headers)) - print(('-'*10 + ' ')*len(headers)) - - def row(self, rowdata): - print(' '.join('%10s' % d for d in rowdata)) - -class CSVTableFormatter(TableFormatter): - def headings(self, headers): - print(','.join(headers)) - - def row(self, rowdata): - print(','.join(str(d) for d in rowdata)) - -class HTMLTableFormatter(TableFormatter): - def headings(self, headers): - print('', end=' ') - for h in headers: - print('%s' % h, end=' ') - print('') - - def row(self, rowdata): - print('', end=' ') - for d in rowdata: - print('%s' % d, end=' ') - print('') - -class ColumnFormatMixin: - formats = [] - def row(self, rowdata): - rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)] - super().row(rowdata) - -class UpperHeadersMixin: - def headings(self, headers): - super().headings([h.upper() for h in headers]) - -def create_formatter(name, column_formats=None, upper_headers=False): - if name == 'text': - formatter_cls = TextTableFormatter - elif name == 'csv': - formatter_cls = CSVTableFormatter - elif name == 'html': - formatter_cls = HTMLTableFormatter - else: - raise RuntimeError('Unknown format %s' % name) - - if column_formats: - class formatter_cls(ColumnFormatMixin, formatter_cls): - formats = column_formats - - if upper_headers: - class formatter_cls(UpperHeadersMixin, formatter_cls): - pass - - return formatter_cls() - - - - - - -''' -structly/structly/structure.py -''' -# structure.py - -from structly.validate import Validator, validated -from collections import ChainMap - -class StructureMeta(type): - @classmethod - def __prepare__(meta, clsname, bases): - return ChainMap({}, Validator.validators) - - @staticmethod - def __new__(meta, name, bases, methods): - methods = methods.maps[0] - return super().__new__(meta, name, bases, methods) - -class Structure(metaclass=StructureMeta): - _fields = () - _types = () - - def __setattr__(self, name, value): - if name.startswith('_') or name in self._fields: - super().__setattr__(name, value) - else: - raise AttributeError('No attribute %s' % name) - - def __repr__(self): - return '%s(%s)' % (type(self).__name__, - ', '.join(repr(getattr(self, name)) for name in self._fields)) - - def __iter__(self): - for name in self._fields: - yield getattr(self, name) - - def __eq__(self, other): - return isinstance(other, type(self)) and tuple(self) == tuple(other) - - @classmethod - def from_row(cls, row): - rowdata = [ func(val) for func, val in zip(cls._types, row) ] - return cls(*rowdata) - - @classmethod - def create_init(cls): - ''' - Create an __init__ method from _fields - ''' - args = ','.join(cls._fields) - code = f'def __init__(self, {args}):\n' - for name in cls._fields: - code += f' self.{name} = {name}\n' - locs = { } - exec(code, locs) - cls.__init__ = locs['__init__'] - - @classmethod - def __init_subclass__(cls): - # Apply the validated decorator to subclasses - validate_attributes(cls) - -def validate_attributes(cls): - ''' - Class decorator that scans a class definition for Validators - and builds a _fields variable that captures their definition order. - ''' - validators = [] - for name, val in vars(cls).items(): - if isinstance(val, Validator): - validators.append(val) - - # Apply validated decorator to any callable with annotations - elif callable(val) and val.__annotations__: - setattr(cls, name, validated(val)) - - # Collect all of the field names - cls._fields = tuple([v.name for v in validators]) - - # Collect type conversions. The lambda x:x is an identity - # function that's used in case no expected_type is found. - cls._types = tuple([ getattr(v, 'expected_type', lambda x: x) - for v in validators ]) - - # Create the __init__ method - if cls._fields: - cls.create_init() - - - return cls - -def typed_structure(clsname, **validators): - cls = type(clsname, (Structure,), validators) - return cls - - -",6,369 -leducholdem,./ProjectTest/Python/leducholdem.py,"''' -leducholdem/base.py -''' -''' Game-related base classes -''' -class Card: - ''' - Card stores the suit and rank of a single card - - Note: - 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] - Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] - ''' - suit = None - rank = None - valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ'] - valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - - def __init__(self, suit, rank): - ''' Initialize the suit and rank of a card - - Args: - suit: string, suit of the card, should be one of valid_suit - rank: string, rank of the card, should be one of valid_rank - ''' - self.suit = suit - self.rank = rank - - def __eq__(self, other): - if isinstance(other, Card): - return self.rank == other.rank and self.suit == other.suit - else: - # don't attempt to compare against unrelated types - return NotImplemented - - def __hash__(self): - suit_index = Card.valid_suit.index(self.suit) - rank_index = Card.valid_rank.index(self.rank) - return rank_index + 100 * suit_index - - def __str__(self): - ''' Get string representation of a card. - - Returns: - string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... - ''' - return self.rank + self.suit - - def get_index(self): - ''' Get index of a card. - - Returns: - string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ... - ''' - return self.suit+self.rank - - -''' -leducholdem/player.py -''' -from enum import Enum - - -class PlayerStatus(Enum): - ALIVE = 0 - FOLDED = 1 - ALLIN = 2 - - -class LeducholdemPlayer: - - def __init__(self, player_id, np_random): - ''' Initilize a player. - - Args: - player_id (int): The id of the player - ''' - self.np_random = np_random - self.player_id = player_id - self.status = 'alive' - self.hand = None - - # The chips that this player has put in until now - self.in_chips = 0 - - def get_state(self, public_card, all_chips, legal_actions): - ''' Encode the state for the player - - Args: - public_card (object): The public card that seen by all the players - all_chips (int): The chips that all players have put in - - Returns: - (dict): The state of the player - ''' - state = {} - state['hand'] = self.hand.get_index() - state['public_card'] = public_card.get_index() if public_card else None - state['all_chips'] = all_chips - state['my_chips'] = self.in_chips - state['legal_actions'] = legal_actions - return state - - def get_player_id(self): - ''' Return the id of the player - ''' - return self.player_id - - -''' -leducholdem/dealer.py -''' -from leducholdem.utils import init_standard_deck -from leducholdem import Card - -class LimitHoldemDealer: - def __init__(self, np_random): - self.np_random = np_random - self.deck = init_standard_deck() - self.shuffle() - self.pot = 0 - - def shuffle(self): - self.np_random.shuffle(self.deck) - - def deal_card(self): - """""" - Deal one card from the deck - - Returns: - (Card): The drawn card from the deck - """""" - return self.deck.pop() - - -class LeducholdemDealer(LimitHoldemDealer): - - def __init__(self, np_random): - ''' Initialize a leducholdem dealer class - ''' - self.np_random = np_random - self.deck = [Card('S', 'J'), Card('H', 'J'), Card('S', 'Q'), Card('H', 'Q'), Card('S', 'K'), Card('H', 'K')] - self.shuffle() - self.pot = 0 - - - -''' -leducholdem/judger.py -''' -from leducholdem.utils import rank2int - -class LeducholdemJudger: - ''' The Judger class for Leduc Hold'em - ''' - def __init__(self, np_random): - ''' Initialize a judger class - ''' - self.np_random = np_random - - @staticmethod - def judge_game(players, public_card): - ''' Judge the winner of the game. - - Args: - players (list): The list of players who play the game - public_card (object): The public card that seen by all the players - - Returns: - (list): Each entry of the list corresponds to one entry of the - ''' - # Judge who are the winners - winners = [0] * len(players) - fold_count = 0 - ranks = [] - # If every player folds except one, the alive player is the winner - for idx, player in enumerate(players): - ranks.append(rank2int(player.hand.rank)) - if player.status == 'folded': - fold_count += 1 - elif player.status == 'alive': - alive_idx = idx - if fold_count == (len(players) - 1): - winners[alive_idx] = 1 - - # If any of the players matches the public card wins - if sum(winners) < 1: - for idx, player in enumerate(players): - if player.hand.rank == public_card.rank: - winners[idx] = 1 - break - - # If non of the above conditions, the winner player is the one with the highest card rank - if sum(winners) < 1: - max_rank = max(ranks) - max_index = [i for i, j in enumerate(ranks) if j == max_rank] - for idx in max_index: - winners[idx] = 1 - - # Compute the total chips - total = 0 - for p in players: - total += p.in_chips - - each_win = float(total) / sum(winners) - - payoffs = [] - for i, _ in enumerate(players): - if winners[i] == 1: - payoffs.append(each_win - players[i].in_chips) - else: - payoffs.append(float(-players[i].in_chips)) - - return payoffs - - -''' -leducholdem/game.py -''' -import numpy as np -from copy import copy, deepcopy - -from leducholdem import Dealer -from leducholdem import Player, PlayerStatus -from leducholdem import Judger -from leducholdem import Round - - - -class LimitHoldemGame: - def __init__(self, allow_step_back=False, num_players=2): - """"""Initialize the class limit holdem game"""""" - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - - # Some configurations of the game - # These arguments can be specified for creating new games - - # Small blind and big blind - self.small_blind = 1 - self.big_blind = 2 * self.small_blind - - # Raise amount and allowed times - self.raise_amount = self.big_blind - self.allowed_raise_num = 4 - - self.num_players = num_players - - # Save betting history - self.history_raise_nums = [0 for _ in range(4)] - - self.dealer = None - self.players = None - self.judger = None - self.public_cards = None - self.game_pointer = None - self.round = None - self.round_counter = None - self.history = None - self.history_raises_nums = None - - def configure(self, game_config): - """"""Specify some game specific parameters, such as number of players"""""" - self.num_players = game_config['game_num_players'] - - def init_game(self): - """""" - Initialize the game of limit texas holdem - - This version supports two-player limit texas holdem - - Returns: - (tuple): Tuple containing: - - (dict): The first state of the game - (int): Current player's id - """""" - # Initialize a dealer that can deal cards - self.dealer = Dealer(self.np_random) - - # Initialize two players to play the game - self.players = [Player(i, self.np_random) for i in range(self.num_players)] - - # Initialize a judger class which will decide who wins in the end - self.judger = Judger(self.np_random) - - # Deal cards to each player to prepare for the first round - for i in range(2 * self.num_players): - self.players[i % self.num_players].hand.append(self.dealer.deal_card()) - - # Initialize public cards - self.public_cards = [] - - # Randomly choose a small blind and a big blind - s = self.np_random.randint(0, self.num_players) - b = (s + 1) % self.num_players - self.players[b].in_chips = self.big_blind - self.players[s].in_chips = self.small_blind - - # The player next to the big blind plays the first - self.game_pointer = (b + 1) % self.num_players - - # Initialize a bidding round, in the first round, the big blind and the small blind needs to - # be passed to the round for processing. - self.round = Round(raise_amount=self.raise_amount, - allowed_raise_num=self.allowed_raise_num, - num_players=self.num_players, - np_random=self.np_random) - - self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players]) - - # Count the round. There are 4 rounds in each game. - self.round_counter = 0 - - # Save the history for stepping back to the last state. - self.history = [] - - state = self.get_state(self.game_pointer) - - # Save betting history - self.history_raise_nums = [0 for _ in range(4)] - - return state, self.game_pointer - - def step(self, action): - """""" - Get the next state - - Args: - action (str): a specific action. (call, raise, fold, or check) - - Returns: - (tuple): Tuple containing: - - (dict): next player's state - (int): next player id - """""" - if self.allow_step_back: - # First snapshot the current state - r = deepcopy(self.round) - b = self.game_pointer - r_c = self.round_counter - d = deepcopy(self.dealer) - p = deepcopy(self.public_cards) - ps = deepcopy(self.players) - rn = copy(self.history_raise_nums) - self.history.append((r, b, r_c, d, p, ps, rn)) - - # Then we proceed to the next round - self.game_pointer = self.round.proceed_round(self.players, action) - - # Save the current raise num to history - self.history_raise_nums[self.round_counter] = self.round.have_raised - - # If a round is over, we deal more public cards - if self.round.is_over(): - # For the first round, we deal 3 cards - if self.round_counter == 0: - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - - # For the following rounds, we deal only 1 card - elif self.round_counter <= 2: - self.public_cards.append(self.dealer.deal_card()) - - # Double the raise amount for the last two rounds - if self.round_counter == 1: - self.round.raise_amount = 2 * self.raise_amount - - self.round_counter += 1 - self.round.start_new_round(self.game_pointer) - - state = self.get_state(self.game_pointer) - - return state, self.game_pointer - - def step_back(self): - """""" - Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - """""" - if len(self.history) > 0: - self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \ - self.players, self.history_raises_nums = self.history.pop() - return True - return False - - def get_num_players(self): - """""" - Return the number of players in limit texas holdem - - Returns: - (int): The number of players in the game - """""" - return self.num_players - - @staticmethod - def get_num_actions(): - """""" - Return the number of applicable actions - - Returns: - (int): The number of actions. There are 4 actions (call, raise, check and fold) - """""" - return 4 - - def get_player_id(self): - """""" - Return the current player's id - - Returns: - (int): current player's id - """""" - return self.game_pointer - - def get_state(self, player): - """""" - Return player's state - - Args: - player (int): player id - - Returns: - (dict): The state of the player - """""" - chips = [self.players[i].in_chips for i in range(self.num_players)] - legal_actions = self.get_legal_actions() - state = self.players[player].get_state(self.public_cards, chips, legal_actions) - state['raise_nums'] = self.history_raise_nums - - return state - - def is_over(self): - """""" - Check if the game is over - - Returns: - (boolean): True if the game is over - """""" - alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players] - # If only one player is alive, the game is over. - if sum(alive_players) == 1: - return True - - # If all rounds are finished - if self.round_counter >= 4: - return True - return False - - def get_payoffs(self): - """""" - Return the payoffs of the game - - Returns: - (list): Each entry corresponds to the payoff of one player - """""" - hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players] - chips_payoffs = self.judger.judge_game(self.players, hands) - payoffs = np.array(chips_payoffs) / self.big_blind - return payoffs - - def get_legal_actions(self): - """""" - Return the legal actions for current player - - Returns: - (list): A list of legal actions - """""" - return self.round.get_legal_actions() - - - -class LeducholdemGame(LimitHoldemGame): - - def __init__(self, allow_step_back=False, num_players=2): - ''' Initialize the class leducholdem Game - ''' - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - ''' No big/small blind - # Some configarations of the game - # These arguments are fixed in Leduc Hold'em Game - - # Raise amount and allowed times - self.raise_amount = 2 - self.allowed_raise_num = 2 - - self.num_players = 2 - ''' - # Some configarations of the game - # These arguments can be specified for creating new games - - # Small blind and big blind - self.small_blind = 1 - self.big_blind = 2 * self.small_blind - - # Raise amount and allowed times - self.raise_amount = self.big_blind - self.allowed_raise_num = 2 - - self.num_players = num_players - - def configure(self, game_config): - ''' Specifiy some game specific parameters, such as number of players - ''' - self.num_players = game_config['game_num_players'] - - def init_game(self): - ''' Initialilze the game of Limit Texas Hold'em - - This version supports two-player limit texas hold'em - - Returns: - (tuple): Tuple containing: - - (dict): The first state of the game - (int): Current player's id - ''' - # Initilize a dealer that can deal cards - self.dealer = Dealer(self.np_random) - - # Initilize two players to play the game - self.players = [Player(i, self.np_random) for i in range(self.num_players)] - - # Initialize a judger class which will decide who wins in the end - self.judger = Judger(self.np_random) - - # Prepare for the first round - for i in range(self.num_players): - self.players[i].hand = self.dealer.deal_card() - # Randomly choose a small blind and a big blind - s = self.np_random.randint(0, self.num_players) - b = (s + 1) % self.num_players - self.players[b].in_chips = self.big_blind - self.players[s].in_chips = self.small_blind - self.public_card = None - # The player with small blind plays the first - self.game_pointer = s - - # Initilize a bidding round, in the first round, the big blind and the small blind needs to - # be passed to the round for processing. - self.round = Round(raise_amount=self.raise_amount, - allowed_raise_num=self.allowed_raise_num, - num_players=self.num_players, - np_random=self.np_random) - - self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players]) - - # Count the round. There are 2 rounds in each game. - self.round_counter = 0 - - # Save the hisory for stepping back to the last state. - self.history = [] - - state = self.get_state(self.game_pointer) - - return state, self.game_pointer - - def step(self, action): - ''' Get the next state - - Args: - action (str): a specific action. (call, raise, fold, or check) - - Returns: - (tuple): Tuple containing: - - (dict): next player's state - (int): next plater's id - ''' - if self.allow_step_back: - # First snapshot the current state - r = copy(self.round) - r_raised = copy(self.round.raised) - gp = self.game_pointer - r_c = self.round_counter - d_deck = copy(self.dealer.deck) - p = copy(self.public_card) - ps = [copy(self.players[i]) for i in range(self.num_players)] - ps_hand = [copy(self.players[i].hand) for i in range(self.num_players)] - self.history.append((r, r_raised, gp, r_c, d_deck, p, ps, ps_hand)) - - # Then we proceed to the next round - self.game_pointer = self.round.proceed_round(self.players, action) - - # If a round is over, we deal more public cards - if self.round.is_over(): - # For the first round, we deal 1 card as public card. Double the raise amount for the second round - if self.round_counter == 0: - self.public_card = self.dealer.deal_card() - self.round.raise_amount = 2 * self.raise_amount - - self.round_counter += 1 - self.round.start_new_round(self.game_pointer) - - state = self.get_state(self.game_pointer) - - return state, self.game_pointer - - def get_state(self, player): - ''' Return player's state - - Args: - player_id (int): player id - - Returns: - (dict): The state of the player - ''' - chips = [self.players[i].in_chips for i in range(self.num_players)] - legal_actions = self.get_legal_actions() - state = self.players[player].get_state(self.public_card, chips, legal_actions) - state['current_player'] = self.game_pointer - - return state - - def is_over(self): - ''' Check if the game is over - - Returns: - (boolean): True if the game is over - ''' - alive_players = [1 if p.status=='alive' else 0 for p in self.players] - # If only one player is alive, the game is over. - if sum(alive_players) == 1: - return True - - # If all rounds are finshed - if self.round_counter >= 2: - return True - return False - - def get_payoffs(self): - ''' Return the payoffs of the game - - Returns: - (list): Each entry corresponds to the payoff of one player - ''' - chips_payoffs = self.judger.judge_game(self.players, self.public_card) - payoffs = np.array(chips_payoffs) / (self.big_blind) - return payoffs - - def step_back(self): - ''' Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - ''' - if len(self.history) > 0: - self.round, r_raised, self.game_pointer, self.round_counter, d_deck, self.public_card, self.players, ps_hand = self.history.pop() - self.round.raised = r_raised - self.dealer.deck = d_deck - for i, hand in enumerate(ps_hand): - self.players[i].hand = hand - return True - return False - - -''' -leducholdem/utils.py -''' -from leducholdem import Card - -def init_standard_deck(): - ''' Initialize a standard deck of 52 cards - - Returns: - (list): A list of Card object - ''' - suit_list = ['S', 'H', 'D', 'C'] - rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - res = [Card(suit, rank) for suit in suit_list for rank in rank_list] - return res - -def rank2int(rank): - ''' Get the coresponding number of a rank. - - Args: - rank(str): rank stored in Card object - - Returns: - (int): the number corresponding to the rank - - Note: - 1. If the input rank is an empty string, the function will return -1. - 2. If the input rank is not valid, the function will return None. - ''' - if rank == '': - return -1 - elif rank.isdigit(): - if int(rank) >= 2 and int(rank) <= 10: - return int(rank) - else: - return None - elif rank == 'A': - return 14 - elif rank == 'T': - return 10 - elif rank == 'J': - return 11 - elif rank == 'Q': - return 12 - elif rank == 'K': - return 13 - return None - - - - -''' -leducholdem/__init__.py -''' -from leducholdem.base import Card as Card -from leducholdem.dealer import LeducholdemDealer as Dealer -from leducholdem.judger import LeducholdemJudger as Judger -from leducholdem.player import LeducholdemPlayer as Player -from leducholdem.player import PlayerStatus - -from leducholdem.round import LeducholdemRound as Round -from leducholdem.game import LeducholdemGame as Game - - - -''' -leducholdem/round.py -''' -# -*- coding: utf-8 -*- -''' Implement Leduc Hold'em Round class -''' - -class LimitHoldemRound: - """"""Round can call other Classes' functions to keep the game running"""""" - - def __init__(self, raise_amount, allowed_raise_num, num_players, np_random): - """""" - Initialize the round class - - Args: - raise_amount (int): the raise amount for each raise - allowed_raise_num (int): The number of allowed raise num - num_players (int): The number of players - """""" - self.np_random = np_random - self.game_pointer = None - self.raise_amount = raise_amount - self.allowed_raise_num = allowed_raise_num - - self.num_players = num_players - - # Count the number of raise - self.have_raised = 0 - - # Count the number without raise - # If every player agree to not raise, the round is over - self.not_raise_num = 0 - - # Raised amount for each player - self.raised = [0 for _ in range(self.num_players)] - self.player_folded = None - - def start_new_round(self, game_pointer, raised=None): - """""" - Start a new bidding round - - Args: - game_pointer (int): The game_pointer that indicates the next player - raised (list): Initialize the chips for each player - - Note: For the first round of the game, we need to setup the big/small blind - """""" - self.game_pointer = game_pointer - self.have_raised = 0 - self.not_raise_num = 0 - if raised: - self.raised = raised - else: - self.raised = [0 for _ in range(self.num_players)] - - def proceed_round(self, players, action): - """""" - Call other classes functions to keep one round running - - Args: - players (list): The list of players that play the game - action (str): An legal action taken by the player - - Returns: - (int): The game_pointer that indicates the next player - """""" - if action not in self.get_legal_actions(): - raise Exception('{} is not legal action. Legal actions: {}'.format(action, self.get_legal_actions())) - - if action == 'call': - diff = max(self.raised) - self.raised[self.game_pointer] - self.raised[self.game_pointer] = max(self.raised) - players[self.game_pointer].in_chips += diff - self.not_raise_num += 1 - - elif action == 'raise': - diff = max(self.raised) - self.raised[self.game_pointer] + self.raise_amount - self.raised[self.game_pointer] = max(self.raised) + self.raise_amount - players[self.game_pointer].in_chips += diff - self.have_raised += 1 - self.not_raise_num = 1 - - elif action == 'fold': - players[self.game_pointer].status = 'folded' - self.player_folded = True - - elif action == 'check': - self.not_raise_num += 1 - - self.game_pointer = (self.game_pointer + 1) % self.num_players - - # Skip the folded players - while players[self.game_pointer].status == 'folded': - self.game_pointer = (self.game_pointer + 1) % self.num_players - - return self.game_pointer - - def get_legal_actions(self): - """""" - Obtain the legal actions for the current player - - Returns: - (list): A list of legal actions - """""" - full_actions = ['call', 'raise', 'fold', 'check'] - - # If the the number of raises already reaches the maximum number raises, we can not raise any more - if self.have_raised >= self.allowed_raise_num: - full_actions.remove('raise') - - # If the current chips are less than that of the highest one in the round, we can not check - if self.raised[self.game_pointer] < max(self.raised): - full_actions.remove('check') - - # If the current player has put in the chips that are more than others, we can not call - if self.raised[self.game_pointer] == max(self.raised): - full_actions.remove('call') - - return full_actions - - def is_over(self): - """""" - Check whether the round is over - - Returns: - (boolean): True if the current round is over - """""" - if self.not_raise_num >= self.num_players: - return True - return False - - - -class LeducholdemRound(LimitHoldemRound): - ''' Round can call other Classes' functions to keep the game running - ''' - - def __init__(self, raise_amount, allowed_raise_num, num_players, np_random): - ''' Initilize the round class - - Args: - raise_amount (int): the raise amount for each raise - allowed_raise_num (int): The number of allowed raise num - num_players (int): The number of players - ''' - super(LeducholdemRound, self).__init__(raise_amount, allowed_raise_num, num_players, np_random=np_random) - - -",8,833 -bridge,./ProjectTest/Python/bridge.py,"''' -bridge/base.py -''' -''' Game-related base classes -''' -class Card: - ''' - Card stores the suit and rank of a single card - - Note: - 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] - Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] - ''' - suit = None - rank = None - valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ'] - valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - - def __init__(self, suit, rank): - ''' Initialize the suit and rank of a card - - Args: - suit: string, suit of the card, should be one of valid_suit - rank: string, rank of the card, should be one of valid_rank - ''' - self.suit = suit - self.rank = rank - - def __eq__(self, other): - if isinstance(other, Card): - return self.rank == other.rank and self.suit == other.suit - else: - # don't attempt to compare against unrelated types - return NotImplemented - - def __hash__(self): - suit_index = Card.valid_suit.index(self.suit) - rank_index = Card.valid_rank.index(self.rank) - return rank_index + 100 * suit_index - - def __str__(self): - ''' Get string representation of a card. - - Returns: - string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... - ''' - return self.rank + self.suit - - def get_index(self): - ''' Get index of a card. - - Returns: - string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ... - ''' - return self.suit+self.rank - - -''' -bridge/player.py -''' -from typing import List - -from bridge_card import BridgeCard - - -class BridgePlayer: - - def __init__(self, player_id: int, np_random): - ''' Initialize a BridgePlayer player class - - Args: - player_id (int): id for the player - ''' - if player_id < 0 or player_id > 3: - raise Exception(f'BridgePlayer has invalid player_id: {player_id}') - self.np_random = np_random - self.player_id: int = player_id - self.hand: List[BridgeCard] = [] - - def remove_card_from_hand(self, card: BridgeCard): - self.hand.remove(card) - - def __str__(self): - return ['N', 'E', 'S', 'W'][self.player_id] - - -''' -bridge/move.py -''' -# -# These classes are used to keep a move_sheet history of the moves in a round. -# - -from action_event import ActionEvent, BidAction, PassAction, DblAction, RdblAction, PlayCardAction -from bridge_card import BridgeCard - -from bridge import Player - - -class BridgeMove(object): # Interface - pass - - -class PlayerMove(BridgeMove): # Interface - - def __init__(self, player: Player, action: ActionEvent): - super().__init__() - self.player = player - self.action = action - - -class CallMove(PlayerMove): # Interface - - def __init__(self, player: Player, action: ActionEvent): - super().__init__(player=player, action=action) - - -class DealHandMove(BridgeMove): - - def __init__(self, dealer: Player, shuffled_deck: [BridgeCard]): - super().__init__() - self.dealer = dealer - self.shuffled_deck = shuffled_deck - - def __str__(self): - shuffled_deck_text = "" "".join([str(card) for card in self.shuffled_deck]) - return f'{self.dealer} deal shuffled_deck=[{shuffled_deck_text}]' - - -class MakePassMove(CallMove): - - def __init__(self, player: Player): - super().__init__(player=player, action=PassAction()) - - def __str__(self): - return f'{self.player} {self.action}' - - -class MakeDblMove(CallMove): - - def __init__(self, player: Player): - super().__init__(player=player, action=DblAction()) - - def __str__(self): - return f'{self.player} {self.action}' - - -class MakeRdblMove(CallMove): - - def __init__(self, player: Player): - super().__init__(player=player, action=RdblAction()) - - def __str__(self): - return f'{self.player} {self.action}' - - -class MakeBidMove(CallMove): - - def __init__(self, player: Player, bid_action: BidAction): - super().__init__(player=player, action=bid_action) - self.action = bid_action # Note: keep type as BidAction rather than ActionEvent - - def __str__(self): - return f'{self.player} bids {self.action}' - - -class PlayCardMove(PlayerMove): - - def __init__(self, player: Player, action: PlayCardAction): - super().__init__(player=player, action=action) - self.action = action # Note: keep type as PlayCardAction rather than ActionEvent - - @property - def card(self): - return self.action.card - - def __str__(self): - return f'{self.player} plays {self.action}' - - -''' -bridge/dealer.py -''' -from typing import List - -from bridge import Player -from bridge_card import BridgeCard - - -class BridgeDealer: - ''' Initialize a BridgeDealer dealer class - ''' - def __init__(self, np_random): - ''' set shuffled_deck, set stock_pile - ''' - self.np_random = np_random - self.shuffled_deck: List[BridgeCard] = BridgeCard.get_deck() # keep a copy of the shuffled cards at start of new hand - self.np_random.shuffle(self.shuffled_deck) - self.stock_pile: List[BridgeCard] = self.shuffled_deck.copy() - - def deal_cards(self, player: Player, num: int): - ''' Deal some cards from stock_pile to one player - - Args: - player (BridgePlayer): The BridgePlayer object - num (int): The number of cards to be dealt - ''' - for _ in range(num): - player.hand.append(self.stock_pile.pop()) - - -''' -bridge/judger.py -''' -from typing import List - -from typing import TYPE_CHECKING - -from action_event import PlayCardAction -from action_event import ActionEvent, BidAction, PassAction, DblAction, RdblAction -from move import MakeBidMove, MakeDblMove, MakeRdblMove -from bridge_card import BridgeCard - - -class BridgeJudger: - - ''' - Judger decides legal actions for current player - ''' - - def __init__(self, game: 'BridgeGame'): - ''' Initialize the class BridgeJudger - :param game: BridgeGame - ''' - self.game: BridgeGame = game - - def get_legal_actions(self) -> List[ActionEvent]: - """""" - :return: List[ActionEvent] of legal actions - """""" - legal_actions: List[ActionEvent] = [] - if not self.game.is_over(): - current_player = self.game.round.get_current_player() - if not self.game.round.is_bidding_over(): - legal_actions.append(PassAction()) - last_make_bid_move: MakeBidMove or None = None - last_dbl_move: MakeDblMove or None = None - last_rdbl_move: MakeRdblMove or None = None - for move in reversed(self.game.round.move_sheet): - if isinstance(move, MakeBidMove): - last_make_bid_move = move - break - elif isinstance(move, MakeRdblMove): - last_rdbl_move = move - elif isinstance(move, MakeDblMove) and not last_rdbl_move: - last_dbl_move = move - first_bid_action_id = ActionEvent.first_bid_action_id - next_bid_action_id = last_make_bid_move.action.action_id + 1 if last_make_bid_move else first_bid_action_id - for bid_action_id in range(next_bid_action_id, first_bid_action_id + 35): - action = BidAction.from_action_id(action_id=bid_action_id) - legal_actions.append(action) - 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: - legal_actions.append(DblAction()) - if last_dbl_move and last_dbl_move.player.player_id % 2 != current_player.player_id % 2: - legal_actions.append(RdblAction()) - else: - trick_moves = self.game.round.get_trick_moves() - hand = self.game.round.players[current_player.player_id].hand - legal_cards = hand - if trick_moves and len(trick_moves) < 4: - led_card: BridgeCard = trick_moves[0].card - cards_of_led_suit = [card for card in hand if card.suit == led_card.suit] - if cards_of_led_suit: - legal_cards = cards_of_led_suit - for card in legal_cards: - action = PlayCardAction(card=card) - legal_actions.append(action) - return legal_actions - - -''' -bridge/action_event.py -''' -from bridge_card import BridgeCard - -# ==================================== -# Action_ids: -# 0 -> no_bid_action_id -# 1 to 35 -> bid_action_id (bid amount by suit or NT) -# 36 -> pass_action_id -# 37 -> dbl_action_id -# 38 -> rdbl_action_id -# 39 to 90 -> play_card_action_id -# ==================================== - - -class ActionEvent(object): # Interface - - no_bid_action_id = 0 - first_bid_action_id = 1 - pass_action_id = 36 - dbl_action_id = 37 - rdbl_action_id = 38 - first_play_card_action_id = 39 - - def __init__(self, action_id: int): - self.action_id = action_id - - def __eq__(self, other): - result = False - if isinstance(other, ActionEvent): - result = self.action_id == other.action_id - return result - - @staticmethod - def from_action_id(action_id: int): - if action_id == ActionEvent.pass_action_id: - return PassAction() - elif ActionEvent.first_bid_action_id <= action_id <= 35: - bid_amount = 1 + (action_id - ActionEvent.first_bid_action_id) // 5 - bid_suit_id = (action_id - ActionEvent.first_bid_action_id) % 5 - bid_suit = BridgeCard.suits[bid_suit_id] if bid_suit_id < 4 else None - return BidAction(bid_amount, bid_suit) - elif action_id == ActionEvent.dbl_action_id: - return DblAction() - elif action_id == ActionEvent.rdbl_action_id: - return RdblAction() - elif ActionEvent.first_play_card_action_id <= action_id < ActionEvent.first_play_card_action_id + 52: - card_id = action_id - ActionEvent.first_play_card_action_id - card = BridgeCard.card(card_id=card_id) - return PlayCardAction(card=card) - else: - raise Exception(f'ActionEvent from_action_id: invalid action_id={action_id}') - - @staticmethod - def get_num_actions(): - ''' Return the number of possible actions in the game - ''' - return 1 + 35 + 3 + 52 # no_bid, 35 bids, pass, dbl, rdl, 52 play_card - - -class CallActionEvent(ActionEvent): # Interface - pass - - -class PassAction(CallActionEvent): - - def __init__(self): - super().__init__(action_id=ActionEvent.pass_action_id) - - def __str__(self): - return ""pass"" - - def __repr__(self): - return ""pass"" - - -class BidAction(CallActionEvent): - - def __init__(self, bid_amount: int, bid_suit: str or None): - suits = BridgeCard.suits - if bid_suit and bid_suit not in suits: - raise Exception(f'BidAction has invalid suit: {bid_suit}') - if bid_suit in suits: - bid_suit_id = suits.index(bid_suit) - else: - bid_suit_id = 4 - bid_action_id = bid_suit_id + 5 * (bid_amount - 1) + ActionEvent.first_bid_action_id - super().__init__(action_id=bid_action_id) - self.bid_amount = bid_amount - self.bid_suit = bid_suit - - def __str__(self): - bid_suit = self.bid_suit - if not bid_suit: - bid_suit = 'NT' - return f'{self.bid_amount}{bid_suit}' - - def __repr__(self): - return self.__str__() - - -class DblAction(CallActionEvent): - - def __init__(self): - super().__init__(action_id=ActionEvent.dbl_action_id) - - def __str__(self): - return ""dbl"" - - def __repr__(self): - return ""dbl"" - - -class RdblAction(CallActionEvent): - - def __init__(self): - super().__init__(action_id=ActionEvent.rdbl_action_id) - - def __str__(self): - return ""rdbl"" - - def __repr__(self): - return ""rdbl"" - - -class PlayCardAction(ActionEvent): - - def __init__(self, card: BridgeCard): - play_card_action_id = ActionEvent.first_play_card_action_id + card.card_id - super().__init__(action_id=play_card_action_id) - self.card: BridgeCard = card - - def __str__(self): - return f""{self.card}"" - - def __repr__(self): - return f""{self.card}"" - - -''' -bridge/tray.py -''' -class Tray(object): - - def __init__(self, board_id: int): - if board_id <= 0: - raise Exception(f'Tray: invalid board_id={board_id}') - self.board_id = board_id - - @property - def dealer_id(self): - return (self.board_id - 1) % 4 - - @property - def vul(self): - vul_none = [0, 0, 0, 0] - vul_n_s = [1, 0, 1, 0] - vul_e_w = [0, 1, 0, 1] - vul_all = [1, 1, 1, 1] - basic_vuls = [vul_none, vul_n_s, vul_e_w, vul_all] - offset = (self.board_id - 1) // 4 - return basic_vuls[(self.board_id - 1 + offset) % 4] - - def __str__(self): - return f'{self.board_id}: dealer_id={self.dealer_id} vul={self.vul}' - - -''' -bridge/game.py -''' -from typing import List - -import numpy as np - -from bridge import Judger -from round import BridgeRound -from action_event import ActionEvent, CallActionEvent, PlayCardAction - - -class BridgeGame: - ''' Game class. This class will interact with outer environment. - ''' - - def __init__(self, allow_step_back=False): - '''Initialize the class BridgeGame - ''' - self.allow_step_back: bool = allow_step_back - self.np_random = np.random.RandomState() - self.judger: Judger = Judger(game=self) - self.actions: [ActionEvent] = [] # must reset in init_game - self.round: BridgeRound or None = None # must reset in init_game - self.num_players: int = 4 - - def init_game(self): - ''' Initialize all characters in the game and start round 1 - ''' - board_id = self.np_random.choice([1, 2, 3, 4]) - self.actions: List[ActionEvent] = [] - self.round = BridgeRound(num_players=self.num_players, board_id=board_id, np_random=self.np_random) - for player_id in range(4): - player = self.round.players[player_id] - self.round.dealer.deal_cards(player=player, num=13) - current_player_id = self.round.current_player_id - state = self.get_state(player_id=current_player_id) - return state, current_player_id - - def step(self, action: ActionEvent): - ''' Perform game action and return next player number, and the state for next player - ''' - if isinstance(action, CallActionEvent): - self.round.make_call(action=action) - elif isinstance(action, PlayCardAction): - self.round.play_card(action=action) - else: - raise Exception(f'Unknown step action={action}') - self.actions.append(action) - next_player_id = self.round.current_player_id - next_state = self.get_state(player_id=next_player_id) - return next_state, next_player_id - - def get_num_players(self) -> int: - ''' Return the number of players in the game - ''' - return self.num_players - - @staticmethod - def get_num_actions() -> int: - ''' Return the number of possible actions in the game - ''' - return ActionEvent.get_num_actions() - - def get_player_id(self): - ''' Return the current player that will take actions soon - ''' - return self.round.current_player_id - - def is_over(self) -> bool: - ''' Return whether the current game is over - ''' - return self.round.is_over() - - def get_state(self, player_id: int): # wch: not really used - ''' Get player's state - - Return: - state (dict): The information of the state - ''' - state = {} - if not self.is_over(): - state['player_id'] = player_id - state['current_player_id'] = self.round.current_player_id - state['hand'] = self.round.players[player_id].hand - else: - state['player_id'] = player_id - state['current_player_id'] = self.round.current_player_id - state['hand'] = self.round.players[player_id].hand - return state - - -''' -bridge/__init__.py -''' -from bridge.base import Card as Card -from bridge.player import BridgePlayer as Player -from bridge.dealer import BridgeDealer as Dealer -from bridge.judger import BridgeJudger as Judger -from bridge.game import BridgeGame as Game - - - -''' -bridge/round.py -''' -from typing import List - -from bridge import Dealer -from bridge import Player - -from action_event import CallActionEvent, PassAction, DblAction, RdblAction, BidAction, PlayCardAction -from move import BridgeMove, DealHandMove, PlayCardMove, MakeBidMove, MakePassMove, MakeDblMove, MakeRdblMove, CallMove -from tray import Tray - - -class BridgeRound: - - @property - def dealer_id(self) -> int: - return self.tray.dealer_id - - @property - def vul(self): - return self.tray.vul - - @property - def board_id(self) -> int: - return self.tray.board_id - - @property - def round_phase(self): - if self.is_over(): - result = 'game over' - elif self.is_bidding_over(): - result = 'play card' - else: - result = 'make bid' - return result - - def __init__(self, num_players: int, board_id: int, np_random): - ''' Initialize the round class - - The round class maintains the following instances: - 1) dealer: the dealer of the round; dealer has trick_pile - 2) players: the players in the round; each player has his own hand_pile - 3) current_player_id: the id of the current player who has the move - 4) doubling_cube: 2 if contract is doubled; 4 if contract is redoubled; else 1 - 5) play_card_count: count of PlayCardMoves - 5) move_sheet: history of the moves of the players (including the deal_hand_move) - - The round class maintains a list of moves made by the players in self.move_sheet. - move_sheet is similar to a chess score sheet. - I didn't want to call it a score_sheet since it is not keeping score. - I could have called move_sheet just moves, but that might conflict with the name moves used elsewhere. - I settled on the longer name ""move_sheet"" to indicate that it is the official list of moves being made. - - Args: - num_players: int - board_id: int - np_random - ''' - tray = Tray(board_id=board_id) - dealer_id = tray.dealer_id - self.tray = tray - self.np_random = np_random - self.dealer: Dealer = Dealer(self.np_random) - self.players: List[Player] = [] - for player_id in range(num_players): - self.players.append(Player(player_id=player_id, np_random=self.np_random)) - self.current_player_id: int = dealer_id - self.doubling_cube: int = 1 - self.play_card_count: int = 0 - self.contract_bid_move: MakeBidMove or None = None - self.won_trick_counts = [0, 0] # count of won tricks by side - self.move_sheet: List[BridgeMove] = [] - self.move_sheet.append(DealHandMove(dealer=self.players[dealer_id], shuffled_deck=self.dealer.shuffled_deck)) - - def is_bidding_over(self) -> bool: - ''' Return whether the current bidding is over - ''' - is_bidding_over = True - if len(self.move_sheet) < 5: - is_bidding_over = False - else: - last_make_pass_moves: List[MakePassMove] = [] - for move in reversed(self.move_sheet): - if isinstance(move, MakePassMove): - last_make_pass_moves.append(move) - if len(last_make_pass_moves) == 3: - break - elif isinstance(move, CallMove): - is_bidding_over = False - break - else: - break - return is_bidding_over - - def is_over(self) -> bool: - ''' Return whether the current game is over - ''' - is_over = True - if not self.is_bidding_over(): - is_over = False - elif self.contract_bid_move: - for player in self.players: - if player.hand: - is_over = False - break - return is_over - - def get_current_player(self) -> Player or None: - current_player_id = self.current_player_id - return None if current_player_id is None else self.players[current_player_id] - - def get_trick_moves(self) -> List[PlayCardMove]: - trick_moves: List[PlayCardMove] = [] - if self.is_bidding_over(): - if self.play_card_count > 0: - trick_pile_count = self.play_card_count % 4 - if trick_pile_count == 0: - trick_pile_count = 4 # wch: note this - for move in self.move_sheet[-trick_pile_count:]: - if isinstance(move, PlayCardMove): - trick_moves.append(move) - if len(trick_moves) != trick_pile_count: - raise Exception(f'get_trick_moves: count of trick_moves={[str(move.card) for move in trick_moves]} does not equal {trick_pile_count}') - return trick_moves - - def get_trump_suit(self) -> str or None: - trump_suit = None - if self.contract_bid_move: - trump_suit = self.contract_bid_move.action.bid_suit - return trump_suit - - def make_call(self, action: CallActionEvent): - # when current_player takes CallActionEvent step, the move is recorded and executed - current_player = self.players[self.current_player_id] - if isinstance(action, PassAction): - self.move_sheet.append(MakePassMove(current_player)) - elif isinstance(action, BidAction): - self.doubling_cube = 1 - make_bid_move = MakeBidMove(current_player, action) - self.contract_bid_move = make_bid_move - self.move_sheet.append(make_bid_move) - elif isinstance(action, DblAction): - self.doubling_cube = 2 - self.move_sheet.append(MakeDblMove(current_player)) - elif isinstance(action, RdblAction): - self.doubling_cube = 4 - self.move_sheet.append(MakeRdblMove(current_player)) - if self.is_bidding_over(): - if not self.is_over(): - self.current_player_id = self.get_left_defender().player_id - else: - self.current_player_id = (self.current_player_id + 1) % 4 - - def play_card(self, action: PlayCardAction): - # when current_player takes PlayCardAction step, the move is recorded and executed - current_player = self.players[self.current_player_id] - self.move_sheet.append(PlayCardMove(current_player, action)) - card = action.card - current_player.remove_card_from_hand(card=card) - self.play_card_count += 1 - # update current_player_id - trick_moves = self.get_trick_moves() - if len(trick_moves) == 4: - trump_suit = self.get_trump_suit() - winning_card = trick_moves[0].card - trick_winner = trick_moves[0].player - for move in trick_moves[1:]: - trick_card = move.card - trick_player = move.player - if trick_card.suit == winning_card.suit: - if trick_card.card_id > winning_card.card_id: - winning_card = trick_card - trick_winner = trick_player - elif trick_card.suit == trump_suit: - winning_card = trick_card - trick_winner = trick_player - self.current_player_id = trick_winner.player_id - self.won_trick_counts[trick_winner.player_id % 2] += 1 - else: - self.current_player_id = (self.current_player_id + 1) % 4 - - def get_declarer(self) -> Player or None: - declarer = None - if self.contract_bid_move: - trump_suit = self.contract_bid_move.action.bid_suit - side = self.contract_bid_move.player.player_id % 2 - for move in self.move_sheet: - if isinstance(move, MakeBidMove) and move.action.bid_suit == trump_suit and move.player.player_id % 2 == side: - declarer = move.player - break - return declarer - - def get_dummy(self) -> Player or None: - dummy = None - declarer = self.get_declarer() - if declarer: - dummy = self.players[(declarer.player_id + 2) % 4] - return dummy - - def get_left_defender(self) -> Player or None: - left_defender = None - declarer = self.get_declarer() - if declarer: - left_defender = self.players[(declarer.player_id + 1) % 4] - return left_defender - - def get_right_defender(self) -> Player or None: - right_defender = None - declarer = self.get_declarer() - if declarer: - right_defender = self.players[(declarer.player_id + 3) % 4] - return right_defender - - def get_perfect_information(self): - state = {} - last_call_move = None - if not self.is_bidding_over() or self.play_card_count == 0: - last_move = self.move_sheet[-1] - if isinstance(last_move, CallMove): - last_call_move = last_move - trick_moves = [None, None, None, None] - if self.is_bidding_over(): - for trick_move in self.get_trick_moves(): - trick_moves[trick_move.player.player_id] = trick_move.card - state['move_count'] = len(self.move_sheet) - state['tray'] = self.tray - state['current_player_id'] = self.current_player_id - state['round_phase'] = self.round_phase - state['last_call_move'] = last_call_move - state['doubling_cube'] = self.doubling_cube - state['contact'] = self.contract_bid_move if self.is_bidding_over() and self.contract_bid_move else None - state['hands'] = [player.hand for player in self.players] - state['trick_moves'] = trick_moves - return state - - def print_scene(self): - print(f'===== Board: {self.tray.board_id} move: {len(self.move_sheet)} player: {self.players[self.current_player_id]} phase: {self.round_phase} =====') - print(f'dealer={self.players[self.tray.dealer_id]}') - print(f'vul={self.vul}') - if not self.is_bidding_over() or self.play_card_count == 0: - last_move = self.move_sheet[-1] - last_call_text = f'{last_move}' if isinstance(last_move, CallMove) else 'None' - print(f'last call: {last_call_text}') - if self.is_bidding_over() and self.contract_bid_move: - bid_suit = self.contract_bid_move.action.bid_suit - doubling_cube = self.doubling_cube - if not bid_suit: - bid_suit = 'NT' - doubling_cube_text = """" if doubling_cube == 1 else ""dbl"" if doubling_cube == 2 else ""rdbl"" - print(f'contract: {self.contract_bid_move.player} {self.contract_bid_move.action.bid_amount}{bid_suit} {doubling_cube_text}') - for player in self.players: - print(f'{player}: {[str(card) for card in player.hand]}') - if self.is_bidding_over(): - trick_pile = ['None', 'None', 'None', 'None'] - for trick_move in self.get_trick_moves(): - trick_pile[trick_move.player.player_id] = trick_move.card - print(f'trick_pile: {[str(card) for card in trick_pile]}') - - -''' -bridge/bridge_card.py -''' -from bridge import Card - - -class BridgeCard(Card): - - suits = ['C', 'D', 'H', 'S'] - ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] - - @staticmethod - def card(card_id: int): - return _deck[card_id] - - @staticmethod - def get_deck() -> [Card]: - return _deck.copy() - - def __init__(self, suit: str, rank: str): - super().__init__(suit=suit, rank=rank) - suit_index = BridgeCard.suits.index(self.suit) - rank_index = BridgeCard.ranks.index(self.rank) - self.card_id = 13 * suit_index + rank_index - - def __str__(self): - return f'{self.rank}{self.suit}' - - def __repr__(self): - return f'{self.rank}{self.suit}' - - -# deck is always in order from 2C, ... KC, AC, 2D, ... KD, AD, 2H, ... KH, AH, 2S, ... KS, AS -_deck = [BridgeCard(suit=suit, rank=rank) for suit in BridgeCard.suits for rank in BridgeCard.ranks] # want this to be read-only - - -",11,792 -stock4,./ProjectTest/Python/stock4.py,"''' -stock4/validate.py -''' -# validate.py - -class Validator: - def __init__(self, name=None): - self.name = name - - def __set_name__(self, cls, name): - self.name = name - - @classmethod - def check(cls, value): - return value - - def __set__(self, instance, value): - instance.__dict__[self.name] = self.check(value) - - # Collect all derived classes into a dict - validators = { } - @classmethod - def __init_subclass__(cls): - cls.validators[cls.__name__] = cls - -class Typed(Validator): - expected_type = object - @classmethod - def check(cls, value): - if not isinstance(value, cls.expected_type): - raise TypeError(f'expected {cls.expected_type}') - return super().check(value) - -_typed_classes = [ - ('Integer', int), - ('Float', float), - ('String', str) ] - -globals().update((name, type(name, (Typed,), {'expected_type':ty})) - for name, ty in _typed_classes) - -class Positive(Validator): - @classmethod - def check(cls, value): - if value < 0: - raise ValueError('must be >= 0') - return super().check(value) - -class NonEmpty(Validator): - @classmethod - def check(cls, value): - if len(value) == 0: - raise ValueError('must be non-empty') - return super().check(value) - -class PositiveInteger(Integer, Positive): - pass - -class PositiveFloat(Float, Positive): - pass - -class NonEmptyString(String, NonEmpty): - pass - -from inspect import signature -from functools import wraps - -def isvalidator(item): - return isinstance(item, type) and issubclass(item, Validator) - -def validated(func): - sig = signature(func) - - # Gather the function annotations - annotations = { name:val for name, val in func.__annotations__.items() - if isvalidator(val) } - - # Get the return annotation (if any) - retcheck = annotations.pop('return', None) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - # Enforce return check (if any) - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - - return wrapper - -def enforce(**annotations): - retcheck = annotations.pop('return_', None) - - def decorate(func): - sig = signature(func) - - @wraps(func) - def wrapper(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - errors = [] - - # Enforce argument checks - for name, validator in annotations.items(): - try: - validator.check(bound.arguments[name]) - except Exception as e: - errors.append(f' {name}: {e}') - - if errors: - raise TypeError('Bad Arguments\n' + '\n'.join(errors)) - - result = func(*args, **kwargs) - - if retcheck: - try: - retcheck.check(result) - except Exception as e: - raise TypeError(f'Bad return: {e}') from None - return result - return wrapper - return decorate - - - - -''' -stock4/tableformat.py -''' -# tableformat.py -from abc import ABC, abstractmethod - -def print_table(records, fields, formatter): - if not isinstance(formatter, TableFormatter): - raise RuntimeError('Expected a TableFormatter') - - formatter.headings(fields) - for r in records: - rowdata = [getattr(r, fieldname) for fieldname in fields] - formatter.row(rowdata) - -class TableFormatter(ABC): - @abstractmethod - def headings(self, headers): - pass - - @abstractmethod - def row(self, rowdata): - pass - -class TextTableFormatter(TableFormatter): - def headings(self, headers): - print(' '.join('%10s' % h for h in headers)) - print(('-'*10 + ' ')*len(headers)) - - def row(self, rowdata): - print(' '.join('%10s' % d for d in rowdata)) - -class CSVTableFormatter(TableFormatter): - def headings(self, headers): - print(','.join(headers)) - - def row(self, rowdata): - print(','.join(str(d) for d in rowdata)) - -class HTMLTableFormatter(TableFormatter): - def headings(self, headers): - print('', end=' ') - for h in headers: - print('%s' % h, end=' ') - print('') - - def row(self, rowdata): - print('', end=' ') - for d in rowdata: - print('%s' % d, end=' ') - print('') - -class ColumnFormatMixin: - formats = [] - def row(self, rowdata): - rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)] - super().row(rowdata) - -class UpperHeadersMixin: - def headings(self, headers): - super().headings([h.upper() for h in headers]) - -def create_formatter(name, column_formats=None, upper_headers=False): - if name == 'text': - formatter_cls = TextTableFormatter - elif name == 'csv': - formatter_cls = CSVTableFormatter - elif name == 'html': - formatter_cls = HTMLTableFormatter - else: - raise RuntimeError('Unknown format %s' % name) - - if column_formats: - class formatter_cls(ColumnFormatMixin, formatter_cls): - formats = column_formats - - if upper_headers: - class formatter_cls(UpperHeadersMixin, formatter_cls): - pass - - return formatter_cls() - - - - - - -''' -stock4/ticker.py -''' -# ticker.py -from structure import Structure - -class Ticker(Structure): - name = String() - price = Float() - date = String() - time = String() - change = Float() - open = Float() - high = Float() - low = Float() - volume = Integer() - - -''' -stock4/structure.py -''' -# structure.py - -from validate import Validator, validated -from collections import ChainMap - -class StructureMeta(type): - @classmethod - def __prepare__(meta, clsname, bases): - return ChainMap({}, Validator.validators) - - @staticmethod - def __new__(meta, name, bases, methods): - methods = methods.maps[0] - return super().__new__(meta, name, bases, methods) - -class Structure(metaclass=StructureMeta): - _fields = () - _types = () - - def __setattr__(self, name, value): - if name.startswith('_') or name in self._fields: - super().__setattr__(name, value) - else: - raise AttributeError('No attribute %s' % name) - - def __repr__(self): - return '%s(%s)' % (type(self).__name__, - ', '.join(repr(getattr(self, name)) for name in self._fields)) - - def __iter__(self): - for name in self._fields: - yield getattr(self, name) - - def __eq__(self, other): - return isinstance(other, type(self)) and tuple(self) == tuple(other) - - @classmethod - def from_row(cls, row): - rowdata = [ func(val) for func, val in zip(cls._types, row) ] - return cls(*rowdata) - - @classmethod - def create_init(cls): - ''' - Create an __init__ method from _fields - ''' - args = ','.join(cls._fields) - code = f'def __init__(self, {args}):\n' - for name in cls._fields: - code += f' self.{name} = {name}\n' - locs = { } - exec(code, locs) - cls.__init__ = locs['__init__'] - - @classmethod - def __init_subclass__(cls): - # Apply the validated decorator to subclasses - validate_attributes(cls) - -def validate_attributes(cls): - ''' - Class decorator that scans a class definition for Validators - and builds a _fields variable that captures their definition order. - ''' - validators = [] - for name, val in vars(cls).items(): - if isinstance(val, Validator): - validators.append(val) - - # Apply validated decorator to any callable with annotations - elif callable(val) and val.__annotations__: - setattr(cls, name, validated(val)) - - # Collect all of the field names - cls._fields = tuple([v.name for v in validators]) - - # Collect type conversions. The lambda x:x is an identity - # function that's used in case no expected_type is found. - cls._types = tuple([ getattr(v, 'expected_type', lambda x: x) - for v in validators ]) - - # Create the __init__ method - if cls._fields: - cls.create_init() - - - return cls - -def typed_structure(clsname, **validators): - cls = type(clsname, (Structure,), validators) - return cls - - -",4,323 -doudizhu,./ProjectTest/Python/doudizhu.py,"''' -doudizhu/base.py -''' -''' Game-related base classes -''' -class Card: - ''' - Card stores the suit and rank of a single card - - Note: - 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] - Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] - ''' - suit = None - rank = None - valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ'] - valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - - def __init__(self, suit, rank): - ''' Initialize the suit and rank of a card - - Args: - suit: string, suit of the card, should be one of valid_suit - rank: string, rank of the card, should be one of valid_rank - ''' - self.suit = suit - self.rank = rank - - def __eq__(self, other): - if isinstance(other, Card): - return self.rank == other.rank and self.suit == other.suit - else: - # don't attempt to compare against unrelated types - return NotImplemented - - def __hash__(self): - suit_index = Card.valid_suit.index(self.suit) - rank_index = Card.valid_rank.index(self.rank) - return rank_index + 100 * suit_index - - def __str__(self): - ''' Get string representation of a card. - - Returns: - string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... - ''' - return self.rank + self.suit - - def get_index(self): - ''' Get index of a card. - - Returns: - string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ... - ''' - return self.suit+self.rank - - -''' -doudizhu/player.py -''' -# -*- coding: utf-8 -*- -''' Implement Doudizhu Player class -''' -import functools - -from doudizhu.utils import get_gt_cards -from doudizhu.utils import cards2str, doudizhu_sort_card - - -class DoudizhuPlayer: - ''' Player can store cards in the player's hand and the role, - determine the actions can be made according to the rules, - and can perfrom corresponding action - ''' - def __init__(self, player_id, np_random): - ''' Give the player an id in one game - - Args: - player_id (int): the player_id of a player - - Notes: - 1. role: A player's temporary role in one game(landlord or peasant) - 2. played_cards: The cards played in one round - 3. hand: Initial cards - 4. _current_hand: The rest of the cards after playing some of them - ''' - self.np_random = np_random - self.player_id = player_id - self.initial_hand = None - self._current_hand = [] - self.role = '' - self.played_cards = None - self.singles = '3456789TJQKA2BR' - - #record cards removed from self._current_hand for each play() - # and restore cards back to self._current_hand when play_back() - self._recorded_played_cards = [] - - @property - def current_hand(self): - return self._current_hand - - def set_current_hand(self, value): - self._current_hand = value - - def get_state(self, public, others_hands, num_cards_left, actions): - state = {} - state['seen_cards'] = public['seen_cards'] - state['landlord'] = public['landlord'] - state['trace'] = public['trace'].copy() - state['played_cards'] = public['played_cards'] - state['self'] = self.player_id - state['current_hand'] = cards2str(self._current_hand) - state['others_hand'] = others_hands - state['num_cards_left'] = num_cards_left - state['actions'] = actions - - return state - - def available_actions(self, greater_player=None, judger=None): - ''' Get the actions can be made based on the rules - - Args: - greater_player (DoudizhuPlayer object): player who played - current biggest cards. - judger (DoudizhuJudger object): object of DoudizhuJudger - - Returns: - list: list of string of actions. Eg: ['pass', '8', '9', 'T', 'J'] - ''' - actions = [] - if greater_player is None or greater_player.player_id == self.player_id: - actions = judger.get_playable_cards(self) - else: - actions = get_gt_cards(self, greater_player) - return actions - - def play(self, action, greater_player=None): - ''' Perfrom action - - Args: - action (string): specific action - greater_player (DoudizhuPlayer object): The player who played current biggest cards. - - Returns: - object of DoudizhuPlayer: If there is a new greater_player, return it, if not, return None - ''' - trans = {'B': 'BJ', 'R': 'RJ'} - if action == 'pass': - self._recorded_played_cards.append([]) - return greater_player - else: - removed_cards = [] - self.played_cards = action - for play_card in action: - if play_card in trans: - play_card = trans[play_card] - for _, remain_card in enumerate(self._current_hand): - if remain_card.rank != '': - remain_card = remain_card.rank - else: - remain_card = remain_card.suit - if play_card == remain_card: - removed_cards.append(self.current_hand[_]) - self._current_hand.remove(self._current_hand[_]) - break - self._recorded_played_cards.append(removed_cards) - return self - - def play_back(self): - ''' Restore recorded cards back to self._current_hand - ''' - removed_cards = self._recorded_played_cards.pop() - self._current_hand.extend(removed_cards) - self._current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card)) - - -''' -doudizhu/dealer.py -''' -# -*- coding: utf-8 -*- -''' Implement Doudizhu Dealer class -''' -import functools - -from doudizhu import Card -from doudizhu.utils import cards2str, doudizhu_sort_card - -def init_54_deck(): - ''' Initialize a standard deck of 52 cards, BJ and RJ - - Returns: - (list): Alist of Card object - ''' - suit_list = ['S', 'H', 'D', 'C'] - rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - res = [Card(suit, rank) for suit in suit_list for rank in rank_list] - res.append(Card('BJ', '')) - res.append(Card('RJ', '')) - return res - -class DoudizhuDealer: - ''' Dealer will shuffle, deal cards, and determine players' roles - ''' - def __init__(self, np_random): - '''Give dealer the deck - - Notes: - 1. deck with 54 cards including black joker and red joker - ''' - self.np_random = np_random - self.deck = init_54_deck() - self.deck.sort(key=functools.cmp_to_key(doudizhu_sort_card)) - self.landlord = None - - def shuffle(self): - ''' Randomly shuffle the deck - ''' - self.np_random.shuffle(self.deck) - - def deal_cards(self, players): - ''' Deal cards to players - - Args: - players (list): list of DoudizhuPlayer objects - ''' - hand_num = (len(self.deck) - 3) // len(players) - for index, player in enumerate(players): - current_hand = self.deck[index*hand_num:(index+1)*hand_num] - current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card)) - player.set_current_hand(current_hand) - player.initial_hand = cards2str(player.current_hand) - - def determine_role(self, players): - ''' Determine landlord and peasants according to players' hand - - Args: - players (list): list of DoudizhuPlayer objects - - Returns: - int: landlord's player_id - ''' - # deal cards - self.shuffle() - self.deal_cards(players) - players[0].role = 'landlord' - self.landlord = players[0] - players[1].role = 'peasant' - players[2].role = 'peasant' - #players[0].role = 'peasant' - #self.landlord = players[0] - - ## determine 'landlord' - #max_score = get_landlord_score( - # cards2str(self.landlord.current_hand)) - #for player in players[1:]: - # player.role = 'peasant' - # score = get_landlord_score( - # cards2str(player.current_hand)) - # if score > max_score: - # max_score = score - # self.landlord = player - #self.landlord.role = 'landlord' - - # give the 'landlord' the three cards - self.landlord.current_hand.extend(self.deck[-3:]) - self.landlord.current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card)) - self.landlord.initial_hand = cards2str(self.landlord.current_hand) - return self.landlord.player_id - - -''' -doudizhu/judger.py -''' -# -*- coding: utf-8 -*- -''' Implement Doudizhu Judger class -''' -import numpy as np -import collections -from itertools import combinations -from bisect import bisect_left - -from doudizhu.utils import CARD_RANK_STR, CARD_RANK_STR_INDEX -from doudizhu.utils import cards2str, contains_cards - - - -class DoudizhuJudger: - ''' Determine what cards a player can play - ''' - @staticmethod - def chain_indexes(indexes_list): - ''' Find chains for solos, pairs and trios by using indexes_list - - Args: - indexes_list: the indexes of cards those have the same count, the count could be 1, 2, or 3. - - Returns: - list of tuples: [(start_index1, length1), (start_index1, length1), ...] - - ''' - chains = [] - prev_index = -100 - count = 0 - start = None - for i in indexes_list: - if (i[0] >= 12): #no chains for '2BR' - break - if (i[0] == prev_index + 1): - count += 1 - else: - if (count > 1): - chains.append((start, count)) - count = 1 - start = i[0] - prev_index = i[0] - if (count > 1): - chains.append((start, count)) - return chains - - @classmethod - def solo_attachments(cls, hands, chain_start, chain_length, size): - ''' Find solo attachments for trio_chain_solo_x and four_two_solo - - Args: - hands: - chain_start: the index of start card of the trio_chain or trio or four - chain_length: the size of the sequence of the chain, 1 for trio_solo or four_two_solo - size: count of solos for the attachments - - Returns: - list of tuples: [attachment1, attachment2, ...] - Each attachment has two elemnts, - the first one contains indexes of attached cards smaller than the index of chain_start, - the first one contains indexes of attached cards larger than the index of chain_start - ''' - attachments = set() - candidates = [] - prev_card = None - same_card_count = 0 - for card in hands: - #dont count those cards in the chain - if (CARD_RANK_STR_INDEX[card] >= chain_start and CARD_RANK_STR_INDEX[card] < chain_start + chain_length): - continue - if (card == prev_card): - #attachments can not have bomb - if (same_card_count == 3): - continue - #attachments can not have 3 same cards consecutive with the trio (except 3 cards of '222') - 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'): - continue - else: - same_card_count += 1 - else: - prev_card = card - same_card_count = 1 - candidates.append(CARD_RANK_STR_INDEX[card]) - for attachment in combinations(candidates, size): - if (attachment[-1] == 14 and attachment[-2] == 13): - continue - i = bisect_left(attachment, chain_start) - attachments.add((attachment[:i], attachment[i:])) - return list(attachments) - - @classmethod - def pair_attachments(cls, cards_count, chain_start, chain_length, size): - ''' Find pair attachments for trio_chain_pair_x and four_two_pair - - Args: - cards_count: - chain_start: the index of start card of the trio_chain or trio or four - chain_length: the size of the sequence of the chain, 1 for trio_pair or four_two_pair - size: count of pairs for the attachments - - Returns: - list of tuples: [attachment1, attachment2, ...] - Each attachment has two elemnts, - the first one contains indexes of attached cards smaller than the index of chain_start, - the first one contains indexes of attached cards larger than the index of chain_start - ''' - attachments = set() - candidates = [] - for i, _ in enumerate(cards_count): - if (i >= chain_start and i < chain_start + chain_length): - continue - if (cards_count[i] == 2 or cards_count[i] == 3): - candidates.append(i) - elif (cards_count[i] == 4): - candidates.append(i) - for attachment in combinations(candidates, size): - if (attachment[-1] == 14 and attachment[-2] == 13): - continue - i = bisect_left(attachment, chain_start) - attachments.add((attachment[:i], attachment[i:])) - return list(attachments) - - @staticmethod - def playable_cards_from_hand(current_hand): - ''' Get playable cards from hand - - Returns: - set: set of string of playable cards - ''' - cards_dict = collections.defaultdict(int) - for card in current_hand: - cards_dict[card] += 1 - cards_count = np.array([cards_dict[k] for k in CARD_RANK_STR]) - playable_cards = set() - - non_zero_indexes = np.argwhere(cards_count > 0) - more_than_1_indexes = np.argwhere(cards_count > 1) - more_than_2_indexes = np.argwhere(cards_count > 2) - more_than_3_indexes = np.argwhere(cards_count > 3) - #solo - for i in non_zero_indexes: - playable_cards.add(CARD_RANK_STR[i[0]]) - #pair - for i in more_than_1_indexes: - playable_cards.add(CARD_RANK_STR[i[0]] * 2) - #bomb, four_two_solo, four_two_pair - for i in more_than_3_indexes: - cards = CARD_RANK_STR[i[0]] * 4 - playable_cards.add(cards) - for left, right in DoudizhuJudger.solo_attachments(current_hand, i[0], 1, 2): - pre_attached = '' - for j in left: - pre_attached += CARD_RANK_STR[j] - post_attached = '' - for j in right: - post_attached += CARD_RANK_STR[j] - playable_cards.add(pre_attached + cards + post_attached) - for left, right in DoudizhuJudger.pair_attachments(cards_count, i[0], 1, 2): - pre_attached = '' - for j in left: - pre_attached += CARD_RANK_STR[j] * 2 - post_attached = '' - for j in right: - post_attached += CARD_RANK_STR[j] * 2 - playable_cards.add(pre_attached + cards + post_attached) - - #solo_chain_5 -- #solo_chain_12 - solo_chain_indexes = DoudizhuJudger.chain_indexes(non_zero_indexes) - for (start_index, length) in solo_chain_indexes: - s, l = start_index, length - while(l >= 5): - cards = '' - curr_index = s - 1 - curr_length = 0 - while (curr_length < l and curr_length < 12): - curr_index += 1 - curr_length += 1 - cards += CARD_RANK_STR[curr_index] - if (curr_length >= 5): - playable_cards.add(cards) - l -= 1 - s += 1 - - #pair_chain_3 -- #pair_chain_10 - pair_chain_indexes = DoudizhuJudger.chain_indexes(more_than_1_indexes) - for (start_index, length) in pair_chain_indexes: - s, l = start_index, length - while(l >= 3): - cards = '' - curr_index = s - 1 - curr_length = 0 - while (curr_length < l and curr_length < 10): - curr_index += 1 - curr_length += 1 - cards += CARD_RANK_STR[curr_index] * 2 - if (curr_length >= 3): - playable_cards.add(cards) - l -= 1 - s += 1 - - #trio, trio_solo and trio_pair - for i in more_than_2_indexes: - playable_cards.add(CARD_RANK_STR[i[0]] * 3) - for j in non_zero_indexes: - if (j < i): - playable_cards.add(CARD_RANK_STR[j[0]] + CARD_RANK_STR[i[0]] * 3) - elif (j > i): - playable_cards.add(CARD_RANK_STR[i[0]] * 3 + CARD_RANK_STR[j[0]]) - for j in more_than_1_indexes: - if (j < i): - playable_cards.add(CARD_RANK_STR[j[0]] * 2 + CARD_RANK_STR[i[0]] * 3) - elif (j > i): - playable_cards.add(CARD_RANK_STR[i[0]] * 3 + CARD_RANK_STR[j[0]] * 2) - - #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 - trio_chain_indexes = DoudizhuJudger.chain_indexes(more_than_2_indexes) - for (start_index, length) in trio_chain_indexes: - s, l = start_index, length - while(l >= 2): - cards = '' - curr_index = s - 1 - curr_length = 0 - while (curr_length < l and curr_length < 6): - curr_index += 1 - curr_length += 1 - cards += CARD_RANK_STR[curr_index] * 3 - - #trio_chain_2 to trio_chain_6 - if (curr_length >= 2 and curr_length <= 6): - playable_cards.add(cards) - - #trio_solo_chain_2 to trio_solo_chain_5 - if (curr_length >= 2 and curr_length <= 5): - for left, right in DoudizhuJudger.solo_attachments(current_hand, s, curr_length, curr_length): - pre_attached = '' - for j in left: - pre_attached += CARD_RANK_STR[j] - post_attached = '' - for j in right: - post_attached += CARD_RANK_STR[j] - playable_cards.add(pre_attached + cards + post_attached) - - #trio_pair_chain2 -- trio_pair_chain_4 - if (curr_length >= 2 and curr_length <= 4): - for left, right in DoudizhuJudger.pair_attachments(cards_count, s, curr_length, curr_length): - pre_attached = '' - for j in left: - pre_attached += CARD_RANK_STR[j] * 2 - post_attached = '' - for j in right: - post_attached += CARD_RANK_STR[j] * 2 - playable_cards.add(pre_attached + cards + post_attached) - l -= 1 - s += 1 - #rocket - if (cards_count[13] and cards_count[14]): - playable_cards.add(CARD_RANK_STR[13] + CARD_RANK_STR[14]) - return playable_cards - - def __init__(self, players, np_random): - ''' Initilize the Judger class for Dou Dizhu - ''' - self.playable_cards = [set() for _ in range(3)] - self._recorded_removed_playable_cards = [[] for _ in range(3)] - for player in players: - player_id = player.player_id - current_hand = cards2str(player.current_hand) - self.playable_cards[player_id] = self.playable_cards_from_hand(current_hand) - - def calc_playable_cards(self, player): - ''' Recalculate all legal cards the player can play according to his - current hand. - - Args: - player (DoudizhuPlayer object): object of DoudizhuPlayer - init_flag (boolean): For the first time, set it True to accelerate - the preocess. - - Returns: - list: list of string of playable cards - ''' - removed_playable_cards = [] - - player_id = player.player_id - current_hand = cards2str(player.current_hand) - missed = None - for single in player.singles: - if single not in current_hand: - missed = single - break - - playable_cards = self.playable_cards[player_id].copy() - - if missed is not None: - position = player.singles.find(missed) - player.singles = player.singles[position+1:] - for cards in playable_cards: - if missed in cards or (not contains_cards(current_hand, cards)): - removed_playable_cards.append(cards) - self.playable_cards[player_id].remove(cards) - else: - for cards in playable_cards: - if not contains_cards(current_hand, cards): - #del self.playable_cards[player_id][cards] - removed_playable_cards.append(cards) - self.playable_cards[player_id].remove(cards) - self._recorded_removed_playable_cards[player_id].append(removed_playable_cards) - return self.playable_cards[player_id] - - def restore_playable_cards(self, player_id): - ''' restore playable_cards for judger for game.step_back(). - - Args: - player_id: The id of the player whose playable_cards need to be restored - ''' - removed_playable_cards = self._recorded_removed_playable_cards[player_id].pop() - self.playable_cards[player_id].update(removed_playable_cards) - - def get_playable_cards(self, player): - ''' Provide all legal cards the player can play according to his - current hand. - - Args: - player (DoudizhuPlayer object): object of DoudizhuPlayer - init_flag (boolean): For the first time, set it True to accelerate - the preocess. - - Returns: - list: list of string of playable cards - ''' - return self.playable_cards[player.player_id] - - - @staticmethod - def judge_game(players, player_id): - ''' Judge whether the game is over - - Args: - players (list): list of DoudizhuPlayer objects - player_id (int): integer of player's id - - Returns: - (bool): True if the game is over - ''' - player = players[player_id] - if not player.current_hand: - return True - return False - - @staticmethod - def judge_payoffs(landlord_id, winner_id): - payoffs = np.array([0, 0, 0]) - if winner_id == landlord_id: - payoffs[landlord_id] = 1 - else: - for index, _ in enumerate(payoffs): - if index != landlord_id: - payoffs[index] = 1 - return payoffs - - -''' -doudizhu/game.py -''' -# -*- coding: utf-8 -*- -''' Implement Doudizhu Game class -''' -import functools -from heapq import merge -import numpy as np - -from doudizhu.utils import cards2str, doudizhu_sort_card, CARD_RANK_STR -from doudizhu import Player -from doudizhu import Round -from doudizhu import Judger - - -class DoudizhuGame: - ''' Provide game APIs for env to run doudizhu and get corresponding state - information. - ''' - def __init__(self, allow_step_back=False): - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - self.num_players = 3 - - def init_game(self): - ''' Initialize players and state. - - Returns: - dict: first state in one game - int: current player's id - ''' - # initialize public variables - self.winner_id = None - self.history = [] - - # initialize players - self.players = [Player(num, self.np_random) - for num in range(self.num_players)] - - # initialize round to deal cards and determine landlord - self.played_cards = [np.zeros((len(CARD_RANK_STR), ), dtype=np.int32) - for _ in range(self.num_players)] - self.round = Round(self.np_random, self.played_cards) - self.round.initiate(self.players) - - # initialize judger - self.judger = Judger(self.players, self.np_random) - - # get state of first player - player_id = self.round.current_player - self.state = self.get_state(player_id) - - return self.state, player_id - - def step(self, action): - ''' Perform one draw of the game - - Args: - action (str): specific action of doudizhu. Eg: '33344' - - Returns: - dict: next player's state - int: next player's id - ''' - if self.allow_step_back: - # TODO: don't record game.round, game.players, game.judger if allow_step_back not set - pass - - # perfrom action - player = self.players[self.round.current_player] - self.round.proceed_round(player, action) - if (action != 'pass'): - self.judger.calc_playable_cards(player) - if self.judger.judge_game(self.players, self.round.current_player): - self.winner_id = self.round.current_player - next_id = (player.player_id+1) % len(self.players) - self.round.current_player = next_id - - # get next state - state = self.get_state(next_id) - self.state = state - - return state, next_id - - def step_back(self): - ''' Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - ''' - if not self.round.trace: - return False - - #winner_id will be always None no matter step_back from any case - self.winner_id = None - - #reverse round - player_id, cards = self.round.step_back(self.players) - - #reverse player - if (cards != 'pass'): - self.players[player_id].played_cards = self.round.find_last_played_cards_in_trace(player_id) - self.players[player_id].play_back() - - #reverse judger.played_cards if needed - if (cards != 'pass'): - self.judger.restore_playable_cards(player_id) - - self.state = self.get_state(self.round.current_player) - return True - - def get_state(self, player_id): - ''' Return player's state - - Args: - player_id (int): player id - - Returns: - (dict): The state of the player - ''' - player = self.players[player_id] - others_hands = self._get_others_current_hand(player) - num_cards_left = [len(self.players[i].current_hand) for i in range(self.num_players)] - if self.is_over(): - actions = [] - else: - actions = list(player.available_actions(self.round.greater_player, self.judger)) - state = player.get_state(self.round.public, others_hands, num_cards_left, actions) - - return state - - @staticmethod - def get_num_actions(): - ''' Return the total number of abstract acitons - - Returns: - int: the total number of abstract actions of doudizhu - ''' - return 27472 - - def get_player_id(self): - ''' Return current player's id - - Returns: - int: current player's id - ''' - return self.round.current_player - - def get_num_players(self): - ''' Return the number of players in doudizhu - - Returns: - int: the number of players in doudizhu - ''' - return self.num_players - - def is_over(self): - ''' Judge whether a game is over - - Returns: - Bool: True(over) / False(not over) - ''' - if self.winner_id is None: - return False - return True - - def _get_others_current_hand(self, player): - player_up = self.players[(player.player_id+1) % len(self.players)] - player_down = self.players[(player.player_id-1) % len(self.players)] - others_hand = merge(player_up.current_hand, player_down.current_hand, key=functools.cmp_to_key(doudizhu_sort_card)) - return cards2str(others_hand) - - -''' -doudizhu/utils.py -''' -''' Doudizhu utils -''' -import os -import json -from collections import OrderedDict -import threading -import collections - -# import rlcard - -# Read required docs -ROOT_PATH = '.' - -# if not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/action_space.txt')) \ -# or not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/card_type.json')) \ -# or not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/type_card.json')): -# import zipfile -# with zipfile.ZipFile(os.path.join(ROOT_PATH, 'jsondata.zip'),""r"") as zip_ref: -# zip_ref.extractall(os.path.join(ROOT_PATH, '/')) - -# Action space -action_space_path = os.path.join(ROOT_PATH, './jsondata/action_space.txt') - -with open(action_space_path, 'r') as f: - ID_2_ACTION = f.readline().strip().split() - ACTION_2_ID = {} - for i, action in enumerate(ID_2_ACTION): - ACTION_2_ID[action] = i - -# a map of card to its type. Also return both dict and list to accelerate -card_type_path = os.path.join(ROOT_PATH, './jsondata/card_type.json') -with open(card_type_path, 'r') as f: - data = json.load(f, object_pairs_hook=OrderedDict) - CARD_TYPE = (data, list(data), set(data)) - -# a map of type to its cards -type_card_path = os.path.join(ROOT_PATH, './jsondata/type_card.json') -with open(type_card_path, 'r') as f: - TYPE_CARD = json.load(f, object_pairs_hook=OrderedDict) - -# rank list of solo character of cards -CARD_RANK_STR = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', - 'A', '2', 'B', 'R'] -CARD_RANK_STR_INDEX = {'3': 0, '4': 1, '5': 2, '6': 3, '7': 4, - '8': 5, '9': 6, 'T': 7, 'J': 8, 'Q': 9, - 'K': 10, 'A': 11, '2': 12, 'B': 13, 'R': 14} -# rank list -CARD_RANK = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', - 'A', '2', 'BJ', 'RJ'] - -INDEX = {'3': 0, '4': 1, '5': 2, '6': 3, '7': 4, - '8': 5, '9': 6, 'T': 7, 'J': 8, 'Q': 9, - 'K': 10, 'A': 11, '2': 12, 'B': 13, 'R': 14} -INDEX = OrderedDict(sorted(INDEX.items(), key=lambda t: t[1])) - - -def doudizhu_sort_str(card_1, card_2): - ''' Compare the rank of two cards of str representation - - Args: - card_1 (str): str representation of solo card - card_2 (str): str representation of solo card - - Returns: - int: 1(card_1 > card_2) / 0(card_1 = card2) / -1(card_1 < card_2) - ''' - key_1 = CARD_RANK_STR.index(card_1) - key_2 = CARD_RANK_STR.index(card_2) - if key_1 > key_2: - return 1 - if key_1 < key_2: - return -1 - return 0 - - -def doudizhu_sort_card(card_1, card_2): - ''' Compare the rank of two cards of Card object - - Args: - card_1 (object): object of Card - card_2 (object): object of card - ''' - key = [] - for card in [card_1, card_2]: - if card.rank == '': - key.append(CARD_RANK.index(card.suit)) - else: - key.append(CARD_RANK.index(card.rank)) - if key[0] > key[1]: - return 1 - if key[0] < key[1]: - return -1 - return 0 - - -def get_landlord_score(current_hand): - ''' Roughly judge the quality of the hand, and provide a score as basis to - bid landlord. - - Args: - current_hand (str): string of cards. Eg: '56888TTQKKKAA222R' - - Returns: - int: score - ''' - score_map = {'A': 1, '2': 2, 'B': 3, 'R': 4} - score = 0 - # rocket - if current_hand[-2:] == 'BR': - score += 8 - current_hand = current_hand[:-2] - length = len(current_hand) - i = 0 - while i < length: - # bomb - if i <= (length - 4) and current_hand[i] == current_hand[i+3]: - score += 6 - i += 4 - continue - # 2, Black Joker, Red Joker - if current_hand[i] in score_map: - score += score_map[current_hand[i]] - i += 1 - return score - -def cards2str_with_suit(cards): - ''' Get the corresponding string representation of cards with suit - - Args: - cards (list): list of Card objects - - Returns: - string: string representation of cards - ''' - return ' '.join([card.suit+card.rank for card in cards]) - -def cards2str(cards): - ''' Get the corresponding string representation of cards - - Args: - cards (list): list of Card objects - - Returns: - string: string representation of cards - ''' - response = '' - for card in cards: - if card.rank == '': - response += card.suit[0] - else: - response += card.rank - return response - -class LocalObjs(threading.local): - def __init__(self): - self.cached_candidate_cards = None -_local_objs = LocalObjs() - -def contains_cards(candidate, target): - ''' Check if cards of candidate contains cards of target. - - Args: - candidate (string): A string representing the cards of candidate - target (string): A string representing the number of cards of target - - Returns: - boolean - ''' - # In normal cases, most continuous calls of this function - # will test different targets against the same candidate. - # So the cached counts of each card in candidate can speed up - # the comparison for following tests if candidate keeps the same. - if not _local_objs.cached_candidate_cards or _local_objs.cached_candidate_cards != candidate: - _local_objs.cached_candidate_cards = candidate - cards_dict = collections.defaultdict(int) - for card in candidate: - cards_dict[card] += 1 - _local_objs.cached_candidate_cards_dict = cards_dict - cards_dict = _local_objs.cached_candidate_cards_dict - if (target == ''): - return True - curr_card = target[0] - curr_count = 1 - for card in target[1:]: - if (card != curr_card): - if (cards_dict[curr_card] < curr_count): - return False - curr_card = card - curr_count = 1 - else: - curr_count += 1 - if (cards_dict[curr_card] < curr_count): - return False - return True - -def encode_cards(plane, cards): - ''' Encode cards and represerve it into plane. - - Args: - cards (list or str): list or str of cards, every entry is a - character of solo representation of card - ''' - if not cards: - return None - layer = 1 - if len(cards) == 1: - rank = CARD_RANK_STR.index(cards[0]) - plane[layer][rank] = 1 - plane[0][rank] = 0 - else: - for index, card in enumerate(cards): - if index == 0: - continue - if card == cards[index-1]: - layer += 1 - else: - rank = CARD_RANK_STR.index(cards[index-1]) - plane[layer][rank] = 1 - layer = 1 - plane[0][rank] = 0 - rank = CARD_RANK_STR.index(cards[-1]) - plane[layer][rank] = 1 - plane[0][rank] = 0 - - -def get_gt_cards(player, greater_player): - ''' Provide player's cards which are greater than the ones played by - previous player in one round - - Args: - player (DoudizhuPlayer object): the player waiting to play cards - greater_player (DoudizhuPlayer object): the player who played current biggest cards. - - Returns: - list: list of string of greater cards - - Note: - 1. return value contains 'pass' - ''' - # add 'pass' to legal actions - gt_cards = ['pass'] - current_hand = cards2str(player.current_hand) - target_cards = greater_player.played_cards - target_types = CARD_TYPE[0][target_cards] - type_dict = {} - for card_type, weight in target_types: - if card_type not in type_dict: - type_dict[card_type] = weight - if 'rocket' in type_dict: - return gt_cards - type_dict['rocket'] = -1 - if 'bomb' not in type_dict: - type_dict['bomb'] = -1 - for card_type, weight in type_dict.items(): - candidate = TYPE_CARD[card_type] - for can_weight, cards_list in candidate.items(): - if int(can_weight) > int(weight): - for cards in cards_list: - # TODO: improve efficiency - if cards not in gt_cards and contains_cards(current_hand, cards): - # if self.contains_cards(current_hand, cards): - gt_cards.append(cards) - return gt_cards - - -''' -doudizhu/__init__.py -''' -from doudizhu.base import Card as Card -from doudizhu.dealer import DoudizhuDealer as Dealer -from doudizhu.judger import DoudizhuJudger as Judger -from doudizhu.player import DoudizhuPlayer as Player -from doudizhu.round import DoudizhuRound as Round -from doudizhu.game import DoudizhuGame as Game - -''' -doudizhu/round.py -''' -# -*- coding: utf-8 -*- -''' Implement Doudizhu Round class -''' - -import functools -import numpy as np - -from doudizhu import Dealer -from doudizhu.utils import cards2str, doudizhu_sort_card -from doudizhu.utils import CARD_RANK_STR, CARD_RANK_STR_INDEX - - -class DoudizhuRound: - ''' Round can call other Classes' functions to keep the game running - ''' - def __init__(self, np_random, played_cards): - self.np_random = np_random - self.played_cards = played_cards - self.trace = [] - - self.greater_player = None - self.dealer = Dealer(self.np_random) - self.deck_str = cards2str(self.dealer.deck) - - def initiate(self, players): - ''' Call dealer to deal cards and bid landlord. - - Args: - players (list): list of DoudizhuPlayer objects - ''' - landlord_id = self.dealer.determine_role(players) - seen_cards = self.dealer.deck[-3:] - seen_cards.sort(key=functools.cmp_to_key(doudizhu_sort_card)) - self.seen_cards = cards2str(seen_cards) - self.landlord_id = landlord_id - self.current_player = landlord_id - self.public = {'deck': self.deck_str, 'seen_cards': self.seen_cards, - 'landlord': self.landlord_id, 'trace': self.trace, - 'played_cards': ['' for _ in range(len(players))]} - - @staticmethod - def cards_ndarray_to_str(ndarray_cards): - result = [] - for cards in ndarray_cards: - _result = [] - for i, _ in enumerate(cards): - if cards[i] != 0: - _result.extend([CARD_RANK_STR[i]] * cards[i]) - result.append(''.join(_result)) - return result - - def update_public(self, action): - ''' Update public trace and played cards - - Args: - action(str): string of legal specific action - ''' - self.trace.append((self.current_player, action)) - if action != 'pass': - for c in action: - self.played_cards[self.current_player][CARD_RANK_STR_INDEX[c]] += 1 - if self.current_player == 0 and c in self.seen_cards: - self.seen_cards = self.seen_cards.replace(c, '') - self.public['seen_cards'] = self.seen_cards - self.public['played_cards'] = self.cards_ndarray_to_str(self.played_cards) - - def proceed_round(self, player, action): - ''' Call other Classes's functions to keep one round running - - Args: - player (object): object of DoudizhuPlayer - action (str): string of legal specific action - - Returns: - object of DoudizhuPlayer: player who played current biggest cards. - ''' - self.update_public(action) - self.greater_player = player.play(action, self.greater_player) - return self.greater_player - - def step_back(self, players): - ''' Reverse the last action - - Args: - players (list): list of DoudizhuPlayer objects - Returns: - The last player id and the cards played - ''' - player_id, cards = self.trace.pop() - self.current_player = player_id - if (cards != 'pass'): - for card in cards: - # self.played_cards.remove(card) - self.played_cards[player_id][CARD_RANK_STR_INDEX[card]] -= 1 - self.public['played_cards'] = self.cards_ndarray_to_str(self.played_cards) - greater_player_id = self.find_last_greater_player_id_in_trace() - if (greater_player_id is not None): - self.greater_player = players[greater_player_id] - else: - self.greater_player = None - return player_id, cards - - def find_last_greater_player_id_in_trace(self): - ''' Find the last greater_player's id in trace - - Returns: - The last greater_player's id in trace - ''' - for i in range(len(self.trace) - 1, -1, -1): - _id, action = self.trace[i] - if (action != 'pass'): - return _id - return None - - def find_last_played_cards_in_trace(self, player_id): - ''' Find the player_id's last played_cards in trace - - Returns: - The player_id's last played_cards in trace - ''' - for i in range(len(self.trace) - 1, -1, -1): - _id, action = self.trace[i] - if (_id == player_id and action != 'pass'): - return action - return None - - -",8,1178 -limitholdem,./ProjectTest/Python/limitholdem.py,"''' -limitholdem/base.py -''' -''' Game-related base classes -''' -class Card: - ''' - Card stores the suit and rank of a single card - - Note: - 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] - Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] - ''' - suit = None - rank = None - valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ'] - valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - - def __init__(self, suit, rank): - ''' Initialize the suit and rank of a card - - Args: - suit: string, suit of the card, should be one of valid_suit - rank: string, rank of the card, should be one of valid_rank - ''' - self.suit = suit - self.rank = rank - - def __eq__(self, other): - if isinstance(other, Card): - return self.rank == other.rank and self.suit == other.suit - else: - # don't attempt to compare against unrelated types - return NotImplemented - - def __hash__(self): - suit_index = Card.valid_suit.index(self.suit) - rank_index = Card.valid_rank.index(self.rank) - return rank_index + 100 * suit_index - - def __str__(self): - ''' Get string representation of a card. - - Returns: - string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... - ''' - return self.rank + self.suit - - def get_index(self): - ''' Get index of a card. - - Returns: - string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ... - ''' - return self.suit+self.rank - - -''' -limitholdem/player.py -''' -from enum import Enum - - -class PlayerStatus(Enum): - ALIVE = 0 - FOLDED = 1 - ALLIN = 2 - - -class LimitHoldemPlayer: - - def __init__(self, player_id, np_random): - """""" - Initialize a player. - - Args: - player_id (int): The id of the player - """""" - self.np_random = np_random - self.player_id = player_id - self.hand = [] - self.status = PlayerStatus.ALIVE - - # The chips that this player has put in until now - self.in_chips = 0 - - def get_state(self, public_cards, all_chips, legal_actions): - """""" - Encode the state for the player - - Args: - public_cards (list): A list of public cards that seen by all the players - all_chips (int): The chips that all players have put in - - Returns: - (dict): The state of the player - """""" - return { - 'hand': [c.get_index() for c in self.hand], - 'public_cards': [c.get_index() for c in public_cards], - 'all_chips': all_chips, - 'my_chips': self.in_chips, - 'legal_actions': legal_actions - } - - def get_player_id(self): - return self.player_id - - -''' -limitholdem/dealer.py -''' -from limitholdem.utils import init_standard_deck - -class LimitHoldemDealer: - def __init__(self, np_random): - self.np_random = np_random - self.deck = init_standard_deck() - self.shuffle() - self.pot = 0 - - def shuffle(self): - self.np_random.shuffle(self.deck) - - def deal_card(self): - """""" - Deal one card from the deck - - Returns: - (Card): The drawn card from the deck - """""" - return self.deck.pop() - - -''' -limitholdem/judger.py -''' -from limitholdem.utils import compare_hands -import numpy as np - - -class LimitHoldemJudger: - """"""The Judger class for limit texas holdem"""""" - - def __init__(self, np_random): - self.np_random = np_random - - def judge_game(self, players, hands): - """""" - Judge the winner of the game. - - Args: - players (list): The list of players who play the game - hands (list): The list of hands that from the players - - Returns: - (list): Each entry of the list corresponds to one entry of the - """""" - # Convert the hands into card indexes - hands = [[card.get_index() for card in hand] if hand is not None else None for hand in hands] - - in_chips = [p.in_chips for p in players] - remaining = sum(in_chips) - payoffs = [0] * len(hands) - while remaining > 0: - winners = compare_hands(hands) - each_win = self.split_pots_among_players(in_chips, winners) - - for i in range(len(players)): - if winners[i]: - remaining -= each_win[i] - payoffs[i] += each_win[i] - in_chips[i] - hands[i] = None - in_chips[i] = 0 - elif in_chips[i] > 0: - payoffs[i] += each_win[i] - in_chips[i] - in_chips[i] = each_win[i] - - assert sum(payoffs) == 0 - return payoffs - - def split_pot_among_players(self, in_chips, winners): - """""" - Splits the next (side) pot among players. - Function is called in loop by distribute_pots_among_players until all chips are allocated. - - Args: - in_chips (list): List with number of chips bet not yet distributed for each player - winners (list): List with 1 if the player is among winners else 0 - - Returns: - (list): Of how much chips each player get after this pot has been split and list of chips left to distribute - """""" - nb_winners_in_pot = sum((winners[i] and in_chips[i] > 0) for i in range(len(in_chips))) - nb_players_in_pot = sum(in_chips[i] > 0 for i in range(len(in_chips))) - if nb_winners_in_pot == 0 or nb_winners_in_pot == nb_players_in_pot: - # no winner or all winners for this pot - allocated = list(in_chips) # we give back their chips to each players in this pot - in_chips_after = len(in_chips) * [0] # no more chips to distribute - else: - amount_in_pot_by_player = min(v for v in in_chips if v > 0) - how_much_one_win, remaining = divmod(amount_in_pot_by_player * nb_players_in_pot, nb_winners_in_pot) - ''' - In the event of a split pot that cannot be divided equally for every winner, the winner who is sitting - closest to the left of the dealer receives the remaining differential in chips cf - https://www.betclic.fr/poker/house-rules--play-safely--betclic-poker-cpok_rules to simplify and as this - case is very rare, we will give the remaining differential in chips to a random winner - ''' - allocated = len(in_chips) * [0] - in_chips_after = list(in_chips) - for i in range(len(in_chips)): # iterate on all players - if in_chips[i] == 0: # player not in pot - continue - if winners[i]: - allocated[i] += how_much_one_win - in_chips_after[i] -= amount_in_pot_by_player - if remaining > 0: - random_winning_player = self.np_random.choice( - [i for i in range(len(winners)) if winners[i] and in_chips[i] > 0]) - allocated[random_winning_player] += remaining - assert sum(in_chips[i] - in_chips_after[i] for i in range(len(in_chips))) == sum(allocated) - return allocated, in_chips_after - - def split_pots_among_players(self, in_chips_initial, winners): - """""" - Splits main pot and side pots among players (to handle special case of all-in players). - - Args: - in_chips_initial (list): List with number of chips bet for each player - winners (list): List with 1 if the player is among winners else 0 - - Returns: - (list): List of how much chips each player get back after all pots have been split - """""" - in_chips = list(in_chips_initial) - assert len(in_chips) == len(winners) - assert all(v == 0 or v == 1 for v in winners) - assert sum(winners) >= 1 # there must be at least one winner - allocated = np.zeros(len(in_chips), dtype=int) - while any(v > 0 for v in in_chips): # while there are still chips to allocate - allocated_current_pot, in_chips = self.split_pot_among_players(in_chips, winners) - allocated += allocated_current_pot # element-wise addition - assert all(chips >= 0 for chips in allocated) # check that all players got a non negative amount of chips - assert sum(in_chips_initial) == sum(allocated) # check that all chips bet have been allocated - return list(allocated) - - -''' -limitholdem/game.py -''' -from copy import deepcopy, copy -import numpy as np - -from limitholdem import Dealer -from limitholdem import Player, PlayerStatus -from limitholdem import Judger -from limitholdem import Round - - -class LimitHoldemGame: - def __init__(self, allow_step_back=False, num_players=2): - """"""Initialize the class limit holdem game"""""" - self.allow_step_back = allow_step_back - self.np_random = np.random.RandomState() - - # Some configurations of the game - # These arguments can be specified for creating new games - - # Small blind and big blind - self.small_blind = 1 - self.big_blind = 2 * self.small_blind - - # Raise amount and allowed times - self.raise_amount = self.big_blind - self.allowed_raise_num = 4 - - self.num_players = num_players - - # Save betting history - self.history_raise_nums = [0 for _ in range(4)] - - self.dealer = None - self.players = None - self.judger = None - self.public_cards = None - self.game_pointer = None - self.round = None - self.round_counter = None - self.history = None - self.history_raises_nums = None - - def configure(self, game_config): - """"""Specify some game specific parameters, such as number of players"""""" - self.num_players = game_config['game_num_players'] - - def init_game(self): - """""" - Initialize the game of limit texas holdem - - This version supports two-player limit texas holdem - - Returns: - (tuple): Tuple containing: - - (dict): The first state of the game - (int): Current player's id - """""" - # Initialize a dealer that can deal cards - self.dealer = Dealer(self.np_random) - - # Initialize two players to play the game - self.players = [Player(i, self.np_random) for i in range(self.num_players)] - - # Initialize a judger class which will decide who wins in the end - self.judger = Judger(self.np_random) - - # Deal cards to each player to prepare for the first round - for i in range(2 * self.num_players): - self.players[i % self.num_players].hand.append(self.dealer.deal_card()) - - # Initialize public cards - self.public_cards = [] - - # Randomly choose a small blind and a big blind - s = self.np_random.randint(0, self.num_players) - b = (s + 1) % self.num_players - self.players[b].in_chips = self.big_blind - self.players[s].in_chips = self.small_blind - - # The player next to the big blind plays the first - self.game_pointer = (b + 1) % self.num_players - - # Initialize a bidding round, in the first round, the big blind and the small blind needs to - # be passed to the round for processing. - self.round = Round(raise_amount=self.raise_amount, - allowed_raise_num=self.allowed_raise_num, - num_players=self.num_players, - np_random=self.np_random) - - self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players]) - - # Count the round. There are 4 rounds in each game. - self.round_counter = 0 - - # Save the history for stepping back to the last state. - self.history = [] - - state = self.get_state(self.game_pointer) - - # Save betting history - self.history_raise_nums = [0 for _ in range(4)] - - return state, self.game_pointer - - def step(self, action): - """""" - Get the next state - - Args: - action (str): a specific action. (call, raise, fold, or check) - - Returns: - (tuple): Tuple containing: - - (dict): next player's state - (int): next player id - """""" - if self.allow_step_back: - # First snapshot the current state - r = deepcopy(self.round) - b = self.game_pointer - r_c = self.round_counter - d = deepcopy(self.dealer) - p = deepcopy(self.public_cards) - ps = deepcopy(self.players) - rn = copy(self.history_raise_nums) - self.history.append((r, b, r_c, d, p, ps, rn)) - - # Then we proceed to the next round - self.game_pointer = self.round.proceed_round(self.players, action) - - # Save the current raise num to history - self.history_raise_nums[self.round_counter] = self.round.have_raised - - # If a round is over, we deal more public cards - if self.round.is_over(): - # For the first round, we deal 3 cards - if self.round_counter == 0: - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - self.public_cards.append(self.dealer.deal_card()) - - # For the following rounds, we deal only 1 card - elif self.round_counter <= 2: - self.public_cards.append(self.dealer.deal_card()) - - # Double the raise amount for the last two rounds - if self.round_counter == 1: - self.round.raise_amount = 2 * self.raise_amount - - self.round_counter += 1 - self.round.start_new_round(self.game_pointer) - - state = self.get_state(self.game_pointer) - - return state, self.game_pointer - - def step_back(self): - """""" - Return to the previous state of the game - - Returns: - (bool): True if the game steps back successfully - """""" - if len(self.history) > 0: - self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \ - self.players, self.history_raises_nums = self.history.pop() - return True - return False - - def get_num_players(self): - """""" - Return the number of players in limit texas holdem - - Returns: - (int): The number of players in the game - """""" - return self.num_players - - @staticmethod - def get_num_actions(): - """""" - Return the number of applicable actions - - Returns: - (int): The number of actions. There are 4 actions (call, raise, check and fold) - """""" - return 4 - - def get_player_id(self): - """""" - Return the current player's id - - Returns: - (int): current player's id - """""" - return self.game_pointer - - def get_state(self, player): - """""" - Return player's state - - Args: - player (int): player id - - Returns: - (dict): The state of the player - """""" - chips = [self.players[i].in_chips for i in range(self.num_players)] - legal_actions = self.get_legal_actions() - state = self.players[player].get_state(self.public_cards, chips, legal_actions) - state['raise_nums'] = self.history_raise_nums - - return state - - def is_over(self): - """""" - Check if the game is over - - Returns: - (boolean): True if the game is over - """""" - alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players] - # If only one player is alive, the game is over. - if sum(alive_players) == 1: - return True - - # If all rounds are finished - if self.round_counter >= 4: - return True - return False - - def get_payoffs(self): - """""" - Return the payoffs of the game - - Returns: - (list): Each entry corresponds to the payoff of one player - """""" - hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players] - chips_payoffs = self.judger.judge_game(self.players, hands) - payoffs = np.array(chips_payoffs) / self.big_blind - return payoffs - - def get_legal_actions(self): - """""" - Return the legal actions for current player - - Returns: - (list): A list of legal actions - """""" - return self.round.get_legal_actions() - - -''' -limitholdem/utils.py -''' -import numpy as np -from limitholdem import Card - - -def init_standard_deck(): - ''' Initialize a standard deck of 52 cards - - Returns: - (list): A list of Card object - ''' - suit_list = ['S', 'H', 'D', 'C'] - rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] - res = [Card(suit, rank) for suit in suit_list for rank in rank_list] - return res - - -class Hand: - def __init__(self, all_cards): - self.all_cards = all_cards # two hand cards + five public cards - self.category = 0 - #type of a players' best five cards, greater combination has higher number eg: 0:""Not_Yet_Evaluated"" 1: ""High_Card"" , 9:""Straight_Flush"" - self.best_five = [] - #the largest combination of five cards in all the seven cards - self.flush_cards = [] - #cards with same suit - self.cards_by_rank = [] - #cards after sort - self.product = 1 - #cards’ type indicator - self.RANK_TO_STRING = {2: ""2"", 3: ""3"", 4: ""4"", 5: ""5"", 6: ""6"", - 7: ""7"", 8: ""8"", 9: ""9"", 10: ""T"", 11: ""J"", 12: ""Q"", 13: ""K"", 14: ""A""} - self.STRING_TO_RANK = {v:k for k, v in self.RANK_TO_STRING.items()} - self.RANK_LOOKUP = ""23456789TJQKA"" - self.SUIT_LOOKUP = ""SCDH"" - - def get_hand_five_cards(self): - ''' - Get the best five cards of a player - Returns: - (list): the best five cards among the seven cards of a player - ''' - return self.best_five - - def _sort_cards(self): - ''' - Sort all the seven cards ascendingly according to RANK_LOOKUP - ''' - self.all_cards = sorted( - self.all_cards, key=lambda card: self.RANK_LOOKUP.index(card[1])) - - def evaluateHand(self): - """""" - Evaluate all the seven cards, get the best combination catagory - And pick the best five cards (for comparing in case 2 hands have the same Category) . - """""" - if len(self.all_cards) != 7: - raise Exception( - ""There are not enough 7 cards in this hand, quit evaluation now ! "") - - self._sort_cards() - self.cards_by_rank, self.product = self._getcards_by_rank( - self.all_cards) - - if self._has_straight_flush(): - self.category = 9 - #Straight Flush - elif self._has_four(): - self.category = 8 - #Four of a Kind - self.best_five = self._get_Four_of_a_kind_cards() - elif self._has_fullhouse(): - self.category = 7 - #Full house - self.best_five = self._get_Fullhouse_cards() - elif self._has_flush(): - self.category = 6 - #Flush - i = len(self.flush_cards) - self.best_five = [card for card in self.flush_cards[i-5:i]] - elif self._has_straight(self.all_cards): - self.category = 5 - #Straight - elif self._has_three(): - self.category = 4 - #Three of a Kind - self.best_five = self._get_Three_of_a_kind_cards() - elif self._has_two_pairs(): - self.category = 3 - #Two Pairs - self.best_five = self._get_Two_Pair_cards() - elif self._has_pair(): - self.category = 2 - #One Pair - self.best_five = self._get_One_Pair_cards() - elif self._has_high_card(): - self.category = 1 - #High Card - self.best_five = self._get_High_cards() - - def _has_straight_flush(self): - ''' - Check the existence of straight_flush cards - Returns: - True: exist - False: not exist - ''' - self.flush_cards = self._getflush_cards() - if len(self.flush_cards) > 0: - straightflush_cards = self._get_straightflush_cards() - if len(straightflush_cards) > 0: - self.best_five = straightflush_cards - return True - return False - - def _get_straightflush_cards(self): - ''' - Pick straight_flush cards - Returns: - (list): the straightflush cards - ''' - straightflush_cards = self._get_straight_cards(self.flush_cards) - return straightflush_cards - - def _getflush_cards(self): - ''' - Pick flush cards - Returns: - (list): the flush cards - ''' - card_string = ''.join(self.all_cards) - for suit in self.SUIT_LOOKUP: - suit_count = card_string.count(suit) - if suit_count >= 5: - flush_cards = [ - card for card in self.all_cards if card[0] == suit] - return flush_cards - return [] - - def _has_flush(self): - ''' - Check the existence of flush cards - Returns: - True: exist - False: not exist - ''' - if len(self.flush_cards) > 0: - return True - else: - return False - - def _has_straight(self, all_cards): - ''' - Check the existence of straight cards - Returns: - True: exist - False: not exist - ''' - diff_rank_cards = self._get_different_rank_list(all_cards) - self.best_five = self._get_straight_cards(diff_rank_cards) - if len(self.best_five) != 0: - return True - else: - return False - @classmethod - def _get_different_rank_list(self, all_cards): - ''' - Get cards with different ranks, that is to say, remove duplicate-ranking cards, for picking straight cards' use - Args: - (list): two hand cards + five public cards - Returns: - (list): a list of cards with duplicate-ranking cards removed - ''' - different_rank_list = [] - different_rank_list.append(all_cards[0]) - for card in all_cards: - if(card[1] != different_rank_list[-1][1]): - different_rank_list.append(card) - return different_rank_list - - def _get_straight_cards(self, Cards): - ''' - Pick straight cards - Returns: - (list): the straight cards - ''' - ranks = [self.STRING_TO_RANK[c[1]] for c in Cards] - - highest_card = Cards[-1] - if highest_card[1] == 'A': - Cards.insert(0, highest_card) - ranks.insert(0, 1) - - for i_last in range(len(ranks) - 1, 3, -1): - if ranks[i_last-4] + 4 == ranks[i_last]: # works because ranks are unique and sorted in ascending order - return Cards[i_last-4:i_last+1] - return [] - - def _getcards_by_rank(self, all_cards): - ''' - Get cards by rank - Args: - (list): # two hand cards + five public cards - Return: - card_group(list): cards after sort - product(int):cards‘ type indicator - ''' - card_group = [] - card_group_element = [] - product = 1 - prime_lookup = {0: 1, 1: 1, 2: 2, 3: 3, 4: 5} - count = 0 - current_rank = 0 - - for card in all_cards: - rank = self.RANK_LOOKUP.index(card[1]) - if rank == current_rank: - count += 1 - card_group_element.append(card) - elif rank != current_rank: - product *= prime_lookup[count] - # Explanation : - # if count == 2, then product *= 2 - # if count == 3, then product *= 3 - # if count == 4, then product *= 5 - # if there is a Quad, then product = 5 ( 4, 1, 1, 1) or product = 10 ( 4, 2, 1) or product= 15 (4,3) - # if there is a Fullhouse, then product = 12 ( 3, 2, 2) or product = 9 (3, 3, 1) or product = 6 ( 3, 2, 1, 1) - # if there is a Trip, then product = 3 ( 3, 1, 1, 1, 1) - # if there is two Pair, then product = 4 ( 2, 1, 2, 1, 1) or product = 8 ( 2, 2, 2, 1) - # if there is one Pair, then product = 2 (2, 1, 1, 1, 1, 1) - # if there is HighCard, then product = 1 (1, 1, 1, 1, 1, 1, 1) - card_group_element.insert(0, count) - card_group.append(card_group_element) - # reset counting - count = 1 - card_group_element = [] - card_group_element.append(card) - current_rank = rank - # the For Loop misses operation for the last card - # These 3 lines below to compensate that - product *= prime_lookup[count] - # insert the number of same rank card to the beginning of the - card_group_element.insert(0, count) - # after the loop, there is still one last card to add - card_group.append(card_group_element) - return card_group, product - - def _has_four(self): - ''' - Check the existence of four cards - Returns: - True: exist - False: not exist - ''' - if self.product == 5 or self.product == 10 or self.product == 15: - return True - else: - return False - - def _has_fullhouse(self): - ''' - Check the existence of fullhouse cards - Returns: - True: exist - False: not exist - ''' - if self.product == 6 or self.product == 9 or self.product == 12: - return True - else: - return False - - def _has_three(self): - ''' - Check the existence of three cards - Returns: - True: exist - False: not exist - ''' - if self.product == 3: - return True - else: - return False - - def _has_two_pairs(self): - ''' - Check the existence of 2 pair cards - Returns: - True: exist - False: not exist - ''' - if self.product == 4 or self.product == 8: - return True - else: - return False - - def _has_pair(self): - ''' - Check the existence of 1 pair cards - Returns: - True: exist - False: not exist - ''' - if self.product == 2: - return True - else: - return False - - def _has_high_card(self): - ''' - Check the existence of high cards - Returns: - True: exist - False: not exist - ''' - if self.product == 1: - return True - else: - return False - - def _get_Four_of_a_kind_cards(self): - ''' - Get the four of a kind cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Four_of_a_Kind = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 4: - Four_of_a_Kind = cards_by_rank.pop(i) - break - # The Last cards_by_rank[The Second element] - kicker = cards_by_rank[-1][1] - Four_of_a_Kind[0] = kicker - - return Four_of_a_Kind - - def _get_Fullhouse_cards(self): - ''' - Get the fullhouse cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Fullhouse = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 3: - Trips = cards_by_rank.pop(i)[1:4] - break - for i in reversed(range(cards_len - 1)): - if cards_by_rank[i][0] >= 2: - TwoPair = cards_by_rank.pop(i)[1:3] - break - Fullhouse = TwoPair + Trips - return Fullhouse - - def _get_Three_of_a_kind_cards(self): - ''' - Get the three of a kind cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Trip_cards = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 3: - Trip_cards += cards_by_rank.pop(i)[1:4] - break - - Trip_cards += cards_by_rank.pop(-1)[1:2] - Trip_cards += cards_by_rank.pop(-1)[1:2] - Trip_cards.reverse() - return Trip_cards - - def _get_Two_Pair_cards(self): - ''' - Get the two pair cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - Two_Pair_cards = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 2 and len(Two_Pair_cards) < 3: - Two_Pair_cards += cards_by_rank.pop(i)[1:3] - - Two_Pair_cards += cards_by_rank.pop(-1)[1:2] - Two_Pair_cards.reverse() - return Two_Pair_cards - - def _get_One_Pair_cards(self): - ''' - Get the one pair cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - One_Pair_cards = [] - cards_by_rank = self.cards_by_rank - cards_len = len(cards_by_rank) - for i in reversed(range(cards_len)): - if cards_by_rank[i][0] == 2: - One_Pair_cards += cards_by_rank.pop(i)[1:3] - break - - One_Pair_cards += cards_by_rank.pop(-1)[1:2] - One_Pair_cards += cards_by_rank.pop(-1)[1:2] - One_Pair_cards += cards_by_rank.pop(-1)[1:2] - One_Pair_cards.reverse() - return One_Pair_cards - - def _get_High_cards(self): - ''' - Get the high cards among a player's cards - Returns: - (list): best five hand cards after sort - ''' - High_cards = self.all_cards[2:7] - return High_cards - -def compare_ranks(position, hands, winner): - ''' - Compare cards in same position of plays' five handcards - Args: - position(int): the position of a card in a sorted handcard - hands(list): cards of those players. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - winner: array of same length than hands with 1 if the hand is among winners and 0 among losers - Returns: - new updated winner array - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - ''' - assert len(hands) == len(winner) - RANKS = '23456789TJQKA' - cards_figure_all_players = [None]*len(hands) #cards without suit - for i, hand in enumerate(hands): - if winner[i]: - cards = hands[i].get_hand_five_cards() - if len(cards[0]) != 1:# remove suit - for p in range(5): - cards[p] = cards[p][1:] - cards_figure_all_players[i] = cards - - rival_ranks = [] # ranks of rival_figures - for i, cards_figure in enumerate(cards_figure_all_players): - if winner[i]: - rank = cards_figure_all_players[i][position] - rival_ranks.append(RANKS.index(rank)) - else: - rival_ranks.append(-1) # player has already lost - new_winner = list(winner) - for i, rival_rank in enumerate(rival_ranks): - if rival_rank != max(rival_ranks): - new_winner[i] = 0 - return new_winner - -def determine_winner(key_index, hands, all_players, potential_winner_index): - ''' - Find out who wins in the situation of having players with same highest hand_catagory - Args: - key_index(int): the position of a card in a sorted handcard - hands(list): cards of those players with same highest hand_catagory. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - all_players(list): all the players in this round, 0 for losing and 1 for winning or draw - potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - ''' - winner = [1]*len(hands) - i_index = 0 - while i_index < len(key_index) and sum(winner) > 1: - index_break_tie = key_index[i_index] - winner = compare_ranks(index_break_tie, hands, winner) - i_index += 1 - for i in range(len(potential_winner_index)): - if winner[i]: - all_players[potential_winner_index[i]] = 1 - return all_players - -def determine_winner_straight(hands, all_players, potential_winner_index): - ''' - Find out who wins in the situation of having players all having a straight or straight flush - Args: - key_index(int): the position of a card in a sorted handcard - hands(list): cards of those players which all have a straight or straight flush - all_players(list): all the players in this round, 0 for losing and 1 for winning or draw - potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - ''' - highest_ranks = [] - for hand in hands: - highest_rank = hand.STRING_TO_RANK[hand.best_five[-1][1]] # cards are sorted in ascending order - highest_ranks.append(highest_rank) - max_highest_rank = max(highest_ranks) - for i_player in range(len(highest_ranks)): - if highest_ranks[i_player] == max_highest_rank: - all_players[potential_winner_index[i_player]] = 1 - return all_players - -def determine_winner_four_of_a_kind(hands, all_players, potential_winner_index): - ''' - Find out who wins in the situation of having players which all have a four of a kind - Args: - key_index(int): the position of a card in a sorted handcard - hands(list): cards of those players with a four of a kind - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - all_players(list): all the players in this round, 0 for losing and 1 for winning or draw - potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - ''' - ranks = [] - for hand in hands: - rank_1 = hand.STRING_TO_RANK[hand.best_five[-1][1]] # rank of the four of a kind - rank_2 = hand.STRING_TO_RANK[hand.best_five[0][1]] # rank of the kicker - ranks.append((rank_1, rank_2)) - max_rank = max(ranks) - for i, rank in enumerate(ranks): - if rank == max_rank: - all_players[potential_winner_index[i]] = 1 - return all_players - -def compare_hands(hands): - ''' - Compare all palyer's all seven cards - Args: - hands(list): cards of those players with same highest hand_catagory. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - if hands[0] == None: - return [0, 1] - elif hands[1] == None: - return [1, 0] - ''' - hand_category = [] #such as high_card, straight_flush, etc - all_players = [0]*len(hands) #all the players in this round, 0 for losing and 1 for winning or draw - if None in hands: - fold_players = [i for i, j in enumerate(hands) if j is None] - if len(fold_players) == len(all_players) - 1: - for _ in enumerate(hands): - if _[0] in fold_players: - all_players[_[0]] = 0 - else: - all_players[_[0]] = 1 - return all_players - else: - for _ in enumerate(hands): - if hands[_[0]] is not None: - hand = Hand(hands[_[0]]) - hand.evaluateHand() - hand_category.append(hand.category) - elif hands[_[0]] is None: - hand_category.append(0) - else: - for i in enumerate(hands): - hand = Hand(hands[i[0]]) - hand.evaluateHand() - hand_category.append(hand.category) - 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 - - return final_compare(hands, potential_winner_index, all_players) - -def final_compare(hands, potential_winner_index, all_players): - ''' - Find out the winners from those who didn't fold - Args: - hands(list): cards of those players with same highest hand_catagory. - e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] - potential_winner_index(list): index of those with same max card_catagory in all_players - all_players(list): a list of all the player's win/lose situation, 0 for lose and 1 for win - Returns: - [0, 1, 0]: player1 wins - [1, 0, 0]: player0 wins - [1, 1, 1]: draw - [1, 1, 0]: player1 and player0 draws - - if hands[0] == None: - return [0, 1] - elif hands[1] == None: - return [1, 0] - ''' - if len(potential_winner_index) == 1: - all_players[potential_winner_index[0]] = 1 - return all_players - elif len(potential_winner_index) > 1: - # compare when having equal max categories - equal_hands = [] - for _ in potential_winner_index: - hand = Hand(hands[_]) - hand.evaluateHand() - equal_hands.append(hand) - hand = equal_hands[0] - if hand.category == 8: - return determine_winner_four_of_a_kind(equal_hands, all_players, potential_winner_index) - if hand.category == 7: - return determine_winner([2, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 4: - return determine_winner([2, 1, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 3: - return determine_winner([4, 2, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 2: - return determine_winner([4, 2, 1, 0], equal_hands, all_players, potential_winner_index) - if hand.category == 1 or hand.category == 6: - return determine_winner([4, 3, 2, 1, 0], equal_hands, all_players, potential_winner_index) - if hand.category in [5, 9]: - return determine_winner_straight(equal_hands, all_players, potential_winner_index) - - -''' -limitholdem/__init__.py -''' -from limitholdem.base import Card as Card - -from limitholdem.dealer import LimitHoldemDealer as Dealer -from limitholdem.judger import LimitHoldemJudger as Judger -from limitholdem.player import LimitHoldemPlayer as Player -from limitholdem.player import PlayerStatus -from limitholdem.round import LimitHoldemRound as Round -from limitholdem.game import LimitHoldemGame as Game - - - -''' -limitholdem/round.py -''' -# -*- coding: utf-8 -*- -""""""Limit texas holdem round class implementation"""""" - - -class LimitHoldemRound: - """"""Round can call other Classes' functions to keep the game running"""""" - - def __init__(self, raise_amount, allowed_raise_num, num_players, np_random): - """""" - Initialize the round class - - Args: - raise_amount (int): the raise amount for each raise - allowed_raise_num (int): The number of allowed raise num - num_players (int): The number of players - """""" - self.np_random = np_random - self.game_pointer = None - self.raise_amount = raise_amount - self.allowed_raise_num = allowed_raise_num - - self.num_players = num_players - - # Count the number of raise - self.have_raised = 0 - - # Count the number without raise - # If every player agree to not raise, the round is over - self.not_raise_num = 0 - - # Raised amount for each player - self.raised = [0 for _ in range(self.num_players)] - self.player_folded = None - - def start_new_round(self, game_pointer, raised=None): - """""" - Start a new bidding round - - Args: - game_pointer (int): The game_pointer that indicates the next player - raised (list): Initialize the chips for each player - - Note: For the first round of the game, we need to setup the big/small blind - """""" - self.game_pointer = game_pointer - self.have_raised = 0 - self.not_raise_num = 0 - if raised: - self.raised = raised - else: - self.raised = [0 for _ in range(self.num_players)] - - def proceed_round(self, players, action): - """""" - Call other classes functions to keep one round running - - Args: - players (list): The list of players that play the game - action (str): An legal action taken by the player - - Returns: - (int): The game_pointer that indicates the next player - """""" - if action not in self.get_legal_actions(): - raise Exception('{} is not legal action. Legal actions: {}'.format(action, self.get_legal_actions())) - - if action == 'call': - diff = max(self.raised) - self.raised[self.game_pointer] - self.raised[self.game_pointer] = max(self.raised) - players[self.game_pointer].in_chips += diff - self.not_raise_num += 1 - - elif action == 'raise': - diff = max(self.raised) - self.raised[self.game_pointer] + self.raise_amount - self.raised[self.game_pointer] = max(self.raised) + self.raise_amount - players[self.game_pointer].in_chips += diff - self.have_raised += 1 - self.not_raise_num = 1 - - elif action == 'fold': - players[self.game_pointer].status = 'folded' - self.player_folded = True - - elif action == 'check': - self.not_raise_num += 1 - - self.game_pointer = (self.game_pointer + 1) % self.num_players - - # Skip the folded players - while players[self.game_pointer].status == 'folded': - self.game_pointer = (self.game_pointer + 1) % self.num_players - - return self.game_pointer - - def get_legal_actions(self): - """""" - Obtain the legal actions for the current player - - Returns: - (list): A list of legal actions - """""" - full_actions = ['call', 'raise', 'fold', 'check'] - - # If the the number of raises already reaches the maximum number raises, we can not raise any more - if self.have_raised >= self.allowed_raise_num: - full_actions.remove('raise') - - # If the current chips are less than that of the highest one in the round, we can not check - if self.raised[self.game_pointer] < max(self.raised): - full_actions.remove('check') - - # If the current player has put in the chips that are more than others, we can not call - if self.raised[self.game_pointer] == max(self.raised): - full_actions.remove('call') - - return full_actions - - def is_over(self): - """""" - Check whether the round is over - - Returns: - (boolean): True if the current round is over - """""" - if self.not_raise_num >= self.num_players: - return True - return False - - -",8,1243 -svm,./ProjectTest/Python/svm.py,"''' -svm/base.py -''' -# coding:utf-8 -import numpy as np - - -class BaseEstimator: - y_required = True - fit_required = True - - def _setup_input(self, X, y=None): - """"""Ensure inputs to an estimator are in the expected format. - - Ensures X and y are stored as numpy ndarrays by converting from an - array-like object if necessary. Enables estimators to define whether - they require a set of y target values or not with y_required, e.g. - kmeans clustering requires no target labels and is fit against only X. - - Parameters - ---------- - X : array-like - Feature dataset. - y : array-like - Target values. By default is required, but if y_required = false - then may be omitted. - """""" - if not isinstance(X, np.ndarray): - X = np.array(X) - - if X.size == 0: - raise ValueError(""Got an empty matrix."") - - if X.ndim == 1: - self.n_samples, self.n_features = 1, X.shape - else: - self.n_samples, self.n_features = X.shape[0], np.prod(X.shape[1:]) - - self.X = X - - if self.y_required: - if y is None: - raise ValueError(""Missed required argument y"") - - if not isinstance(y, np.ndarray): - y = np.array(y) - - if y.size == 0: - raise ValueError(""The targets array must be no-empty."") - - self.y = y - - def fit(self, X, y=None): - self._setup_input(X, y) - - def predict(self, X=None): - if not isinstance(X, np.ndarray): - X = np.array(X) - - if self.X is not None or not self.fit_required: - return self._predict(X) - else: - raise ValueError(""You must call `fit` before `predict`"") - - def _predict(self, X=None): - raise NotImplementedError() - - -''' -svm/kernerls.py -''' -# coding:utf-8 -import numpy as np -import scipy.spatial.distance as dist - - -class Linear(object): - def __call__(self, x, y): - return np.dot(x, y.T) - - def __repr__(self): - return ""Linear kernel"" - - -class Poly(object): - def __init__(self, degree=2): - self.degree = degree - - def __call__(self, x, y): - return np.dot(x, y.T) ** self.degree - - def __repr__(self): - return ""Poly kernel"" - - -class RBF(object): - def __init__(self, gamma=0.1): - self.gamma = gamma - - def __call__(self, x, y): - x = np.atleast_2d(x) - y = np.atleast_2d(y) - return np.exp(-self.gamma * dist.cdist(x, y) ** 2).flatten() - - def __repr__(self): - return ""RBF kernel"" - - -''' -svm/__init__.py -''' -# coding:utf-8 - - -''' -svm/svm.py -''' -# coding:utf-8 -import logging - -import numpy as np - -from base import BaseEstimator -from kernerls import Linear - -np.random.seed(9999) - -"""""" -References: -The Simplified SMO Algorithm http://cs229.stanford.edu/materials/smo.pdf -"""""" - - -class SVM(BaseEstimator): - def __init__(self, C=1.0, kernel=None, tol=1e-3, max_iter=100): - """"""Support vector machines implementation using simplified SMO optimization. - - Parameters - ---------- - C : float, default 1.0 - kernel : Kernel object - tol : float , default 1e-3 - max_iter : int, default 100 - """""" - self.C = C - self.tol = tol - self.max_iter = max_iter - if kernel is None: - self.kernel = Linear() - else: - self.kernel = kernel - - self.b = 0 - self.alpha = None - self.K = None - - def fit(self, X, y=None): - self._setup_input(X, y) - self.K = np.zeros((self.n_samples, self.n_samples)) - for i in range(self.n_samples): - self.K[:, i] = self.kernel(self.X, self.X[i, :]) - self.alpha = np.zeros(self.n_samples) - self.sv_idx = np.arange(0, self.n_samples) - return self._train() - - def _train(self): - iters = 0 - while iters < self.max_iter: - iters += 1 - alpha_prev = np.copy(self.alpha) - - for j in range(self.n_samples): - # Pick random i - i = self.random_index(j) - - eta = 2.0 * self.K[i, j] - self.K[i, i] - self.K[j, j] - if eta >= 0: - continue - L, H = self._find_bounds(i, j) - - # Error for current examples - e_i, e_j = self._error(i), self._error(j) - - # Save old alphas - alpha_io, alpha_jo = self.alpha[i], self.alpha[j] - - # Update alpha - self.alpha[j] -= (self.y[j] * (e_i - e_j)) / eta - self.alpha[j] = self.clip(self.alpha[j], H, L) - - self.alpha[i] = self.alpha[i] + self.y[i] * self.y[j] * (alpha_jo - self.alpha[j]) - - # Find intercept - b1 = ( - self.b - e_i - self.y[i] * (self.alpha[i] - alpha_io) * self.K[i, i] - - self.y[j] * (self.alpha[j] - alpha_jo) * self.K[i, j] - ) - b2 = ( - self.b - e_j - self.y[j] * (self.alpha[j] - alpha_jo) * self.K[j, j] - - self.y[i] * (self.alpha[i] - alpha_io) * self.K[i, j] - ) - if 0 < self.alpha[i] < self.C: - self.b = b1 - elif 0 < self.alpha[j] < self.C: - self.b = b2 - else: - self.b = 0.5 * (b1 + b2) - - # Check convergence - diff = np.linalg.norm(self.alpha - alpha_prev) - if diff < self.tol: - break - logging.info(""Convergence has reached after %s."" % iters) - - # Save support vectors index - self.sv_idx = np.where(self.alpha > 0)[0] - - def _predict(self, X=None): - n = X.shape[0] - result = np.zeros(n) - for i in range(n): - result[i] = np.sign(self._predict_row(X[i, :])) - return result - - def _predict_row(self, X): - k_v = self.kernel(self.X[self.sv_idx], X) - return np.dot((self.alpha[self.sv_idx] * self.y[self.sv_idx]).T, k_v.T) + self.b - - def clip(self, alpha, H, L): - if alpha > H: - alpha = H - if alpha < L: - alpha = L - return alpha - - def _error(self, i): - """"""Error for single example."""""" - return self._predict_row(self.X[i]) - self.y[i] - - def _find_bounds(self, i, j): - """"""Find L and H such that L <= alpha <= H. - Also, alpha must satisfy the constraint 0 <= αlpha <= C. - """""" - if self.y[i] != self.y[j]: - L = max(0, self.alpha[j] - self.alpha[i]) - H = min(self.C, self.C - self.alpha[i] + self.alpha[j]) - else: - L = max(0, self.alpha[i] + self.alpha[j] - self.C) - H = min(self.C, self.alpha[i] + self.alpha[j]) - return L, H - - def random_index(self, z): - i = z - while i == z: - i = np.random.randint(0, self.n_samples) - return i - - -",4,238