id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
22,825
from rlcard.games.uno.card import UnoCard def _print_action(action): ''' Print out an action in a nice form Args: action (str): A string a action ''' UnoCard.print_cards(action, wild_color=True) 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 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='') The provided code snippet includes necessary dependencies for implementing the `_print_state` function. Write a Python function `def _print_state(state, action_record)` to solve the following problem: Print out the state of a given player Args: player (int): Player id Here is the function: def _print_state(state, action_record): ''' Print out the state of a given player Args: player (int): Player id ''' _action_list = [] for i in range(1, len(action_record)+1): if action_record[-i][0] == state['current_player']: break _action_list.insert(0, action_record[-i]) for pair in _action_list: print('>> Player', pair[0], 'chooses ', end='') _print_action(pair[1]) print('') print('\n=============== Your Hand ===============') UnoCard.print_cards(state['hand']) print('') print('=============== Last Card ===============') UnoCard.print_cards(state['target'], wild_color=True) print('') print('========== Players Card Number ===========') for i in range(state['num_players']): if i != state['current_player']: print('Player {} has {} cards.'.format(i, state['num_cards'][i])) print('======== Actions You Can Choose =========') for i, action in enumerate(state['legal_actions']): print(str(i)+': ', end='') UnoCard.print_cards(action, wild_color=True) if i < len(state['legal_actions']) - 1: print(', ', end='') print('\n')
Print out the state of a given player Args: player (int): Player id
22,826
import os from PIL import Image, ImageTk, ImageDraw def reporthook(count, block_size, total_size): global start_time if count == 0: start_time = time.time() return duration = time.time() - start_time progress_size = int(count * block_size) speed = int(progress_size / (1024 * duration)) percent = int(count * block_size * 100 / total_size) sys.stdout.write("\r...%d%%, %d KB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024), speed, duration)) sys.stdout.flush()
null
22,827
import os from PIL import Image, ImageTk, ImageDraw image_dir = os.path.abspath(os.path.dirname(__file__)) def long_rank_name_for(rank: str) -> str: rank_exceptions = {'A': 'ace', 'T': '10', 'J': 'jack', 'Q': 'queen', 'K': 'king'} result = rank if rank not in rank_exceptions.keys() else rank_exceptions[rank] return result def long_suit_name_for(suit: str) -> str: known_suit_name_by_suit = {'C': 'clubs', 'D': 'diamonds', 'H': 'hearts', 'S': 'spades'} result = suit if suit not in known_suit_name_by_suit else known_suit_name_by_suit[suit] return result def get_card_filename(rank: str, suit: str) -> str: long_rank_name = long_rank_name_for(rank) long_suit_name = long_suit_name_for(suit) card_file_name = "{}/cards_png/{}_of_{}@2x.png".format(image_dir, long_rank_name, long_suit_name) return card_file_name
null
22,828
import os from PIL import Image, ImageTk, ImageDraw image_dir = os.path.abspath(os.path.dirname(__file__)) def get_card_back_image(scale_factor: float): card_filename = "{}/cards_png/back.jpg".format(image_dir) image = Image.open(card_filename) image_width, image_height = image.size card_scale_factor = 0.25 * scale_factor * 0.666 card_image_width = int(image_width * card_scale_factor) card_image_height = int(image_height * card_scale_factor) image = image.resize((card_image_width, card_image_height), Image.ANTIALIAS) return image
null
22,829
from typing import TYPE_CHECKING from typing import List import tkinter as tk import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError from .canvas_item import CardItem, CanvasItem from .player_type import PlayerType from .configurations import SCORE_PLAYER_0_ACTION_ID, SCORE_PLAYER_1_ACTION_ID from .configurations import DRAW_CARD_ACTION_ID, PICK_UP_DISCARD_ACTION_ID from .configurations import DECLARE_DEAD_HAND_ACTION_ID from .configurations import DISCARD_ACTION_ID, KNOCK_ACTION_ID from . import configurations class GinRummyProgramError(GinRummyError): pass def translated_by(dx: float, dy: float, location): if not len(location) == 2: raise GinRummyProgramError("location={} must have length of 2.".format(location)) return [location[0] + dx, location[1] + dy]
null
22,830
from typing import TYPE_CHECKING from typing import List import tkinter as tk import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError from .canvas_item import CardItem, CanvasItem from .player_type import PlayerType from .configurations import SCORE_PLAYER_0_ACTION_ID, SCORE_PLAYER_1_ACTION_ID from .configurations import DRAW_CARD_ACTION_ID, PICK_UP_DISCARD_ACTION_ID from .configurations import DECLARE_DEAD_HAND_ACTION_ID from .configurations import DISCARD_ACTION_ID, KNOCK_ACTION_ID from . import configurations def player_short_name(player_id: int) -> str: return "N" if player_id == 0 else "S" if player_id == 1 else "X"
null
22,831
from typing import TYPE_CHECKING from typing import List import tkinter as tk import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError from .canvas_item import CardItem, CanvasItem from .player_type import PlayerType from .configurations import SCORE_PLAYER_0_ACTION_ID, SCORE_PLAYER_1_ACTION_ID from .configurations import DRAW_CARD_ACTION_ID, PICK_UP_DISCARD_ACTION_ID from .configurations import DECLARE_DEAD_HAND_ACTION_ID from .configurations import DISCARD_ACTION_ID, KNOCK_ACTION_ID from . import configurations def get_action_type(action: int) -> int: if action == DRAW_CARD_ACTION_ID: result = action elif action == PICK_UP_DISCARD_ACTION_ID: result = action elif action == DECLARE_DEAD_HAND_ACTION_ID: result = action elif DISCARD_ACTION_ID <= action < DISCARD_ACTION_ID + 52: result = DISCARD_ACTION_ID elif KNOCK_ACTION_ID <= action < KNOCK_ACTION_ID + 52: result = KNOCK_ACTION_ID elif action == SCORE_PLAYER_0_ACTION_ID: result = action elif action == SCORE_PLAYER_1_ACTION_ID: result = action else: raise GinRummyProgramError("No action type for {}.".format(action)) return result DISCARD_ACTION_ID = 6 KNOCK_ACTION_ID = DISCARD_ACTION_ID + 52 def get_action_card_id(action: int) -> int or None: result = None action_type = get_action_type(action) if action_type == DISCARD_ACTION_ID: result = action - DISCARD_ACTION_ID elif action_type == KNOCK_ACTION_ID: result = action - KNOCK_ACTION_ID return result
null
22,832
from typing import TYPE_CHECKING from typing import List import tkinter as tk import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError from .canvas_item import CardItem, CanvasItem from .player_type import PlayerType from .configurations import SCORE_PLAYER_0_ACTION_ID, SCORE_PLAYER_1_ACTION_ID from .configurations import DRAW_CARD_ACTION_ID, PICK_UP_DISCARD_ACTION_ID from .configurations import DECLARE_DEAD_HAND_ACTION_ID from .configurations import DISCARD_ACTION_ID, KNOCK_ACTION_ID from . import configurations class GinRummyProgramError(GinRummyError): pass def held_pile_insert(card_item_id: int, above_hit_item_id: int or None, player_id: int, game_canvas: 'GameCanvas'): held_pile_item_ids = game_canvas.getter.get_held_pile_item_ids(player_id=player_id) held_pile_item_ids_count = len(held_pile_item_ids) if above_hit_item_id is None or above_hit_item_id == game_canvas.held_pile_ghost_card_items[player_id]: insertion_index = 0 else: insertion_index = held_pile_item_ids.index(above_hit_item_id) + 1 held_pile_tab = game_canvas.held_pile_tab if not card_item_id == held_pile_item_ids[-1]: # Note: card_item_id is last and already positioned and raised raise GinRummyProgramError("card_item_id={} must be last card of hand.".format(card_item_id)) for i in range(insertion_index, held_pile_item_ids_count - 1): held_pile_item_id = held_pile_item_ids[i] game_canvas.move(held_pile_item_id, held_pile_tab, 0) game_canvas.tag_raise(held_pile_item_id)
null
22,833
from typing import TYPE_CHECKING from typing import List import tkinter as tk import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError from .canvas_item import CardItem, CanvasItem from .player_type import PlayerType from .configurations import SCORE_PLAYER_0_ACTION_ID, SCORE_PLAYER_1_ACTION_ID from .configurations import DRAW_CARD_ACTION_ID, PICK_UP_DISCARD_ACTION_ID from .configurations import DECLARE_DEAD_HAND_ACTION_ID from .configurations import DISCARD_ACTION_ID, KNOCK_ACTION_ID from . import configurations def set_card_id_face_up(card_id: int, face_up: bool, game_canvas: 'GameCanvas'): def set_card_item_id_face_up(card_item_id: int, face_up: bool, game_canvas: 'GameCanvas'): card_id = game_canvas.card_item_ids.index(card_item_id) set_card_id_face_up(card_id=card_id, face_up=face_up, game_canvas=game_canvas)
null
22,834
from typing import TYPE_CHECKING import tkinter as tk from ..gin_rummy_human_agent import HumanAgent from . import configurations from . import info_messaging from . import utils from .env_thread import EnvThread import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError class GinRummyProgramError(GinRummyError): pass def show_new_game(game_canvas: 'GameCanvas'): game = game_canvas.game_canvas_updater.env_thread.gin_rummy_env.game game_canvas.dealer_id = game.round.dealer_id dealer = game.round.dealer shuffled_deck = dealer.shuffled_deck # Deal cards to players if utils.is_debug(): for card_id in range(52): card_item_id = game_canvas.card_item_ids[card_id] tags = game_canvas.gettags(card_item_id) if tags: raise GinRummyProgramError("tags must be None.") for i in range(2): player_id = (game_canvas.dealer_id + 1 + i) % 2 anchor_x, anchor_y = game_canvas.player_held_pile_anchors[player_id] face_up = True # Note: cannot use card_ids = [gin_rummy_utils.get_card_id(card) for card in game.round.players[player_id].hand] if not game_canvas.is_treating_as_human(player_id=player_id): face_up = False if i == 0: dealt_cards = list(shuffled_deck[-11:]) else: dealt_cards = list(shuffled_deck[-21:-11]) card_ids = [gin_rummy_utils.get_card_id(card=card) for card in dealt_cards] card_ids = sorted(card_ids, reverse=True, key=utils.gin_rummy_sort_order_id) for card_id in card_ids: card_item_id = game_canvas.card_item_ids[card_id] if utils.is_debug() or True: tags = game_canvas.gettags(card_item_id) if tags: raise GinRummyProgramError("tags must be None.") game_canvas.tag_raise(card_item_id) # note this game_canvas.itemconfig(card_item_id, tag=game_canvas.held_pile_tags[player_id]) utils.set_card_id_face_up(card_id=card_id, face_up=face_up, game_canvas=game_canvas) utils.move_to(card_item_id, anchor_x, anchor_y, parent=game_canvas) game_canvas.itemconfigure(card_item_id, state=tk.NORMAL) anchor_x += game_canvas.held_pile_tab # Deal stockpile cards stock_pile_x, stock_pile_y = game_canvas.stock_pile_anchor # Note: cannot use stock_pile = [gin_rummy_utils.get_card_id(card) for card in game.round.dealer.stock_pile] stock_pile = list(shuffled_deck[:31]) stock_pile_card_ids = [gin_rummy_utils.get_card_id(card) for card in stock_pile] for card_id in stock_pile_card_ids: card_item_id = game_canvas.card_item_ids[card_id] if utils.is_debug(): tags = game_canvas.gettags(card_item_id) if tags: raise GinRummyProgramError("tags must be None.") game_canvas.tag_raise(card_item_id) # note this game_canvas.itemconfig(card_item_id, tag=configurations.STOCK_PILE_TAG) utils.set_card_id_face_up(card_id=card_id, face_up=False, game_canvas=game_canvas) utils.move_to(card_item_id, stock_pile_x, stock_pile_y, parent=game_canvas) game_canvas.itemconfigure(card_item_id, state=tk.NORMAL) stock_pile_x += game_canvas.stock_pile_tab # update canvas game_canvas.update() # seems to be needed: scores not cleared if 'new game' chosen from menu with no mouse move if utils.is_debug(): settings = game.settings settings.print_settings()
null
22,835
from typing import TYPE_CHECKING from .canvas_item import CanvasItem from .player_type import PlayerType from . import handling_tap from . import utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError def handle_tap_to_arrange_held_pile(hit_item: CanvasItem, game_canvas: 'GameCanvas'): # game is not over. # tapper_id must be human_player. if not game_canvas.query.is_game_over(): hit_item_tags = hit_item.get_tags() arranger_id = None for player_id in range(2): held_pile_tag = game_canvas.held_pile_tags[player_id] if held_pile_tag in hit_item_tags: arranger_id = player_id if arranger_id is not None and game_canvas.player_types[arranger_id] is PlayerType.human_player: held_pile_item_ids = game_canvas.getter.get_held_pile_item_ids(player_id=arranger_id) selected_item_ids = [x for x in held_pile_item_ids if game_canvas.query.is_item_id_selected(item_id=x)] if selected_item_ids: utils.drop_item_ids(item_ids=selected_item_ids, on_item_id=hit_item.item_id, player_id=arranger_id, game_canvas=game_canvas) class PlayerType(int, enum.Enum): computer_player = 1 human_player = 2 demo_player = 3 class GinRummyProgramError(GinRummyError): pass def on_tap_to_arrange_held_pile(event): widget = event.widget if widget.query.is_game_over(): return # game must not be over hit_items_ids = widget.find_withtag("current") if not hit_items_ids: return if not len(hit_items_ids) == 1: raise GinRummyProgramError("len(hit_items_ids)={} must be 1.".format(len(hit_items_ids))) hit_item_id = hit_items_ids[0] hit_item = None for canvas_item in widget.canvas_items: if canvas_item.item_id == hit_item_id: hit_item = canvas_item if hit_item: hit_item_tags = hit_item.get_tags() hit_held_pile_tag = None for held_pile_tag in widget.held_pile_tags: if held_pile_tag in hit_item_tags: hit_held_pile_tag = held_pile_tag break if not hit_held_pile_tag: return # must hit a held_pile hitter_id = widget.held_pile_tags.index(hit_held_pile_tag) if widget.player_types[hitter_id] is not PlayerType.human_player: return # held_pile hit must belong to human player must_do_on_tap = False if hitter_id == widget.current_player_id: is_top_discard_pile_item_drawn = widget.query.is_top_discard_pile_item_drawn() is_top_stock_pile_item_drawn = widget.query.is_top_stock_pile_item_drawn() must_do_on_tap = is_top_discard_pile_item_drawn or is_top_stock_pile_item_drawn if must_do_on_tap: # Minor kludge to handle the following situation. # The current_player should just tap to combine drawn card with the selected cards. # However, I suspect the player will get in the habit of treating this situation as an arrangement. handling_tap.on_game_canvas_tap(event) # kludge else: handle_tap_to_arrange_held_pile(hit_item=hit_item, game_canvas=widget)
null
22,836
from PIL import Image, ImageDraw, ImageFilter def rounded_rectangle(self: ImageDraw, xy, corner_radius, fill=None, outline=None): # FIXME: not used upper_left_point = xy[0] bottom_right_point = xy[1] self.rectangle( [ (upper_left_point[0], upper_left_point[1] + corner_radius), (bottom_right_point[0], bottom_right_point[1] - corner_radius) ], fill=fill, outline=outline ) self.rectangle( [ (upper_left_point[0] + corner_radius, upper_left_point[1]), (bottom_right_point[0] - corner_radius, bottom_right_point[1]) ], fill=fill, outline=outline ) self.pieslice( [upper_left_point, (upper_left_point[0] + corner_radius * 2, upper_left_point[1] + corner_radius * 2)], 180, 270, fill=fill, outline=outline ) self.pieslice( [(bottom_right_point[0] - corner_radius * 2, bottom_right_point[1] - corner_radius * 2), bottom_right_point], 0, 90, fill=fill, outline=outline ) self.pieslice([(upper_left_point[0], bottom_right_point[1] - corner_radius * 2), (upper_left_point[0] + corner_radius * 2, bottom_right_point[1])], 90, 180, fill=fill, outline=outline ) self.pieslice([(bottom_right_point[0] - corner_radius * 2, upper_left_point[1]), (bottom_right_point[0], upper_left_point[1] + corner_radius * 2)], 270, 360, fill=fill, outline=outline ) ImageDraw.rounded_rectangle = rounded_rectangle def mask_rounded_rectangle_transparent(pil_img, corner_radius=8): # FIXME: not used blur_radius = 0 # FIXME: what is this for ??? wch mask = Image.new("L", pil_img.size, 0) draw = ImageDraw.Draw(mask) rounded_rectangle(draw, xy=((0, 0), (pil_img.size[0], pil_img.size[1])), corner_radius=corner_radius, fill=255) mask = mask.filter(ImageFilter.GaussianBlur(blur_radius)) result = pil_img.copy() result.putalpha(mask) return result
null
22,837
from typing import TYPE_CHECKING from . import configurations from . import info_messaging from . import utils from .configurations import DECLARE_DEAD_HAND_ACTION_ID from rlcard.games.gin_rummy.game import GinRummyGame def show_put_card_message(player_id: int, game_canvas: 'GameCanvas'): is_human_player = game_canvas.query.is_human(player_id=player_id) player_name = utils.player_name(player_id=player_id) if game_canvas.query.is_dead_hand_button_visible(): game_canvas.dead_hand_button.place_forget() # hide button can_gin = game_canvas.query.can_gin(player_id=player_id) can_knock = game_canvas.query.can_knock(player_id=player_id) _show_going_out_button(can_gin=can_gin, can_knock=can_knock, player_id=player_id, game_canvas=game_canvas) info_messaging.show_arrange_cards_message(player_id=player_id, game_canvas=game_canvas) show_status_messages = configurations.SHOW_STATUS_MESSAGES if not show_status_messages == "none": is_verbose = show_status_messages == "verbose" if not is_human_player: message = "{} is discarding.".format(player_name) else: if is_verbose: if can_gin: message = "Put card: tap the gin button to go out." elif can_knock: prefix_message = "Put card: tap a card in your hand" suffix_message = "tap the discard pile to discard it or tap the knock button to go out." message = "{}; then {}".format(prefix_message, suffix_message) else: prefix_message = "Put card: tap a card in your hand" suffix_message = "tap the discard pile to discard it." message = "{}; then {}".format(prefix_message, suffix_message) else: message = "Put card." game_canvas.info_label.configure(text=message) def _show_get_card_message(player_id: int, game_canvas: 'GameCanvas'): is_human_player = game_canvas.query.is_human(player_id=player_id) player_name = utils.player_name(player_id=player_id) can_declare_dead_hand = game_canvas.query.can_declare_dead_hand(player_id=player_id) if player_id == 1 and can_declare_dead_hand: game_canvas.dead_hand_button.place(game_canvas.dead_hand_button_place) # show button show_status_messages = configurations.SHOW_STATUS_MESSAGES if not show_status_messages == "none": is_verbose = show_status_messages == "verbose" if can_declare_dead_hand: if game_canvas.current_player_id == 0: message = "Your opponent can declare the hand is dead." elif not is_human_player: message = "You can declare the hand is dead." else: if is_verbose: message = ("Tap the dead hand button to declare hand is dead. " "Or tap the discard pile to pickup a discard; " "then tap a card in your hand to place it.") else: message = "You can declare the hand is dead." else: if not is_human_player: message = "{} is drawing a card.".format(player_name) else: if is_verbose: message = ("Get card: tap the stockpile to draw a card " "or tap the discard pile to pickup a discard; " "then tap a card in your hand to place it.") else: message = "Get card." game_canvas.info_label.configure(text=message) def _show_scoring_message(game_canvas: 'GameCanvas'): game_canvas.info_label.configure(text="") def show_prolog_message(player_id: int, legal_actions, game_canvas: 'GameCanvas'): game_canvas_moves = game_canvas.getter.get_game_canvas_moves() game_canvas_moves_count = len(game_canvas_moves) if 0 < game_canvas_moves_count < 3 and player_id == 1: info_messaging.show_activate_menus_message(game_canvas=game_canvas) if game_canvas.query.can_declare_dead_hand(player_id=player_id): _show_get_card_message(player_id=player_id, game_canvas=game_canvas) elif game_canvas.query.can_draw_from_stock_pile(player_id=player_id): info_messaging.show_pick_up_discard_message(player_id=player_id, game_canvas=game_canvas) _show_get_card_message(player_id=player_id, game_canvas=game_canvas) elif game_canvas.query.can_gin(player_id=player_id): show_put_card_message(player_id=player_id, game_canvas=game_canvas) elif game_canvas.query.can_discard_card(player_id=player_id): show_put_card_message(player_id=player_id, game_canvas=game_canvas) elif game_canvas.query.is_scoring(legal_actions=legal_actions): _show_scoring_message(game_canvas=game_canvas)
null
22,838
from typing import TYPE_CHECKING from . import configurations from . import info_messaging from . import utils from .configurations import DECLARE_DEAD_HAND_ACTION_ID from rlcard.games.gin_rummy.game import GinRummyGame def show_epilog_message_on_declare_dead_hand(game_canvas: 'GameCanvas'): game_canvas.info_label.configure(text="")
null
22,839
from typing import TYPE_CHECKING from . import configurations from . import info_messaging from . import utils from .configurations import DECLARE_DEAD_HAND_ACTION_ID from rlcard.games.gin_rummy.game import GinRummyGame DECLARE_DEAD_HAND_ACTION_ID = 4 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 = GinRummyJudge(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) -> GinRummyPlayer 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 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) def show_game_over_message(game: GinRummyGame, game_canvas: 'GameCanvas'): move = game.round.move_sheet[-3] if move.action.action_id == DECLARE_DEAD_HAND_ACTION_ID: dead_hand_declarer = move.player if dead_hand_declarer.player_id == 1: prefix_message = "You declared the hand dead." else: prefix_message = "Your opponent declared the hand dead." else: prefix_message = "The game is over." message = "{} Tap the top card of the discard pile to start a new game.".format(prefix_message) game_canvas.info_label.configure(text=message) info_messaging.show_hide_tips_message(game_canvas=game_canvas)
null
22,840
from rlcard.utils.utils import print_card def print_card(cards): ''' Nicely print a card or list of cards Args: card (string or list): The card(s) to be printed ''' if cards is None: cards = [None] if isinstance(cards, str): cards = [cards] lines = [[] for _ in range(9)] for card in cards: if card is None: lines[0].append('┌─────────┐') lines[1].append('│░░░░░░░░░│') lines[2].append('│░░░░░░░░░│') lines[3].append('│░░░░░░░░░│') lines[4].append('│░░░░░░░░░│') lines[5].append('│░░░░░░░░░│') lines[6].append('│░░░░░░░░░│') lines[7].append('│░░░░░░░░░│') lines[8].append('└─────────┘') else: if isinstance(card, Card): elegent_card = elegent_form(card.suit + card.rank) else: elegent_card = elegent_form(card) suit = elegent_card[0] rank = elegent_card[1] if len(elegent_card) == 3: space = elegent_card[2] else: space = ' ' lines[0].append('┌─────────┐') lines[1].append('│{}{} │'.format(rank, space)) lines[2].append('│ │') lines[3].append('│ │') lines[4].append('│ {} │'.format(suit)) lines[5].append('│ │') lines[6].append('│ │') lines[7].append('│ {}{}│'.format(space, rank)) lines[8].append('└─────────┘') for line in lines: print (' '.join(line)) The provided code snippet includes necessary dependencies for implementing the `_print_state` function. Write a Python function `def _print_state(state, raw_legal_actions, action_record)` to solve the following problem: Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions Here is the function: def _print_state(state, raw_legal_actions, action_record): ''' Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions ''' _action_list = [] for i in range(1, len(action_record)+1): _action_list.insert(0, action_record[-i]) for pair in _action_list: print('>> Player', pair[0], 'chooses', pair[1]) print('\n============= Dealer Hand ===============') print_card(state['dealer hand']) num_players = len(state) - 3 for i in range(num_players): print('=============== Player {} Hand ==============='.format(i)) print_card(state['player' + str(i) + ' hand']) print('\n=========== Actions You Can Choose ===========') print(', '.join([str(index) + ': ' + action for index, action in enumerate(raw_legal_actions)])) print('')
Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions
22,841
from rlcard.utils.utils import print_card def print_card(cards): ''' Nicely print a card or list of cards Args: card (string or list): The card(s) to be printed ''' if cards is None: cards = [None] if isinstance(cards, str): cards = [cards] lines = [[] for _ in range(9)] for card in cards: if card is None: lines[0].append('┌─────────┐') lines[1].append('│░░░░░░░░░│') lines[2].append('│░░░░░░░░░│') lines[3].append('│░░░░░░░░░│') lines[4].append('│░░░░░░░░░│') lines[5].append('│░░░░░░░░░│') lines[6].append('│░░░░░░░░░│') lines[7].append('│░░░░░░░░░│') lines[8].append('└─────────┘') else: if isinstance(card, Card): elegent_card = elegent_form(card.suit + card.rank) else: elegent_card = elegent_form(card) suit = elegent_card[0] rank = elegent_card[1] if len(elegent_card) == 3: space = elegent_card[2] else: space = ' ' lines[0].append('┌─────────┐') lines[1].append('│{}{} │'.format(rank, space)) lines[2].append('│ │') lines[3].append('│ │') lines[4].append('│ {} │'.format(suit)) lines[5].append('│ │') lines[6].append('│ │') lines[7].append('│ {}{}│'.format(space, rank)) lines[8].append('└─────────┘') for line in lines: print (' '.join(line)) The provided code snippet includes necessary dependencies for implementing the `_print_state` function. Write a Python function `def _print_state(state, action_record)` to solve the following problem: Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions Here is the function: def _print_state(state, action_record): ''' Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions ''' _action_list = [] for i in range(1, len(action_record)+1): _action_list.insert(0, action_record[-i]) for pair in _action_list: print('>> Player', pair[0], 'chooses', pair[1]) print('\n=============== Community Card ===============') print_card(state['public_cards']) print('=============== Your Hand ===============') print_card(state['hand']) print('=============== Chips ===============') print('Yours: ', end='') for _ in range(state['my_chips']): print('+', end='') print('') for i in range(len(state['all_chips'])): for _ in range(state['all_chips'][i]): print('+', end='') print('\n=========== Actions You Can Choose ===========') print(', '.join([str(index) + ': ' + action for index, action in enumerate(state['legal_actions'])])) print('')
Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions
22,842
from rlcard.utils.utils import print_card def print_card(cards): ''' Nicely print a card or list of cards Args: card (string or list): The card(s) to be printed ''' if cards is None: cards = [None] if isinstance(cards, str): cards = [cards] lines = [[] for _ in range(9)] for card in cards: if card is None: lines[0].append('┌─────────┐') lines[1].append('│░░░░░░░░░│') lines[2].append('│░░░░░░░░░│') lines[3].append('│░░░░░░░░░│') lines[4].append('│░░░░░░░░░│') lines[5].append('│░░░░░░░░░│') lines[6].append('│░░░░░░░░░│') lines[7].append('│░░░░░░░░░│') lines[8].append('└─────────┘') else: if isinstance(card, Card): elegent_card = elegent_form(card.suit + card.rank) else: elegent_card = elegent_form(card) suit = elegent_card[0] rank = elegent_card[1] if len(elegent_card) == 3: space = elegent_card[2] else: space = ' ' lines[0].append('┌─────────┐') lines[1].append('│{}{} │'.format(rank, space)) lines[2].append('│ │') lines[3].append('│ │') lines[4].append('│ {} │'.format(suit)) lines[5].append('│ │') lines[6].append('│ │') lines[7].append('│ {}{}│'.format(space, rank)) lines[8].append('└─────────┘') for line in lines: print (' '.join(line)) The provided code snippet includes necessary dependencies for implementing the `_print_state` function. Write a Python function `def _print_state(state, action_record)` to solve the following problem: Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the historical actions Here is the function: def _print_state(state, action_record): ''' Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the historical actions ''' _action_list = [] for i in range(1, len(action_record)+1): if action_record[-i][0] == state['current_player']: break _action_list.insert(0, action_record[-i]) for pair in _action_list: print('>> Player', pair[0], 'chooses', pair[1]) print('\n=============== Community Card ===============') print_card(state['public_cards']) print('============= Player',state["current_player"],'- Hand =============') print_card(state['hand']) print('=============== Chips ===============') print('In Pot:',state["pot"]) print('Remaining:',state["stakes"]) print('\n=========== Actions You Can Choose ===========') print(', '.join([str(index) + ': ' + str(action) for index, action in enumerate(state['legal_actions'])])) print('') print(state)
Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the historical actions
22,843
import logging import traceback import numpy as np import torch def get_batch( free_queue, full_queue, buffers, batch_size, lock ): with lock: indices = [full_queue.get() for _ in range(batch_size)] batch = { key: torch.stack([buffers[key][m] for m in indices], dim=1) for key in buffers } for m in indices: free_queue.put(m) return batch
null
22,844
import logging import traceback import numpy as np import torch def create_buffers( T, num_buffers, state_shape, action_shape, device_iterator, ): buffers = {} for device in device_iterator: buffers[device] = [] for player_id in range(len(state_shape)): specs = dict( done=dict(size=(T,), dtype=torch.bool), episode_return=dict(size=(T,), dtype=torch.float32), target=dict(size=(T,), dtype=torch.float32), state=dict(size=(T,)+tuple(state_shape[player_id]), dtype=torch.int8), action=dict(size=(T,)+tuple(action_shape[player_id]), dtype=torch.int8), ) _buffers = {key: [] for key in specs} for _ in range(num_buffers): for key in _buffers: if device == "cpu": _buffer = torch.empty(**specs[key]).to('cpu').share_memory_() else: _buffer = torch.empty(**specs[key]).to('cuda:'+str(device)).share_memory_() _buffers[key].append(_buffer) buffers[device].append(_buffers) return buffers
null
22,845
import logging import traceback import numpy as np import torch def create_optimizers( num_players, learning_rate, momentum, epsilon, alpha, learner_model ): optimizers = [] for player_id in range(num_players): optimizer = torch.optim.RMSprop( learner_model.parameters(player_id), lr=learning_rate, momentum=momentum, eps=epsilon, alpha=alpha) optimizers.append(optimizer) return optimizers
null
22,846
import logging import traceback import numpy as np import torch log = logging.getLogger('doudzero') log.propagate = False log.addHandler(shandle) log.setLevel(logging.INFO) def act( i, device, T, free_queue, full_queue, model, buffers, env ): try: log.info('Device %s Actor %i started.', str(device), i) # Configure environment env.seed(i) env.set_agents(model.get_agents()) done_buf = [[] for _ in range(env.num_players)] episode_return_buf = [[] for _ in range(env.num_players)] target_buf = [[] for _ in range(env.num_players)] state_buf = [[] for _ in range(env.num_players)] action_buf = [[] for _ in range(env.num_players)] size = [0 for _ in range(env.num_players)] while True: trajectories, payoffs = env.run(is_training=True) for p in range(env.num_players): size[p] += len(trajectories[p][:-1]) // 2 diff = size[p] - len(target_buf[p]) if diff > 0: done_buf[p].extend([False for _ in range(diff-1)]) done_buf[p].append(True) episode_return_buf[p].extend([0.0 for _ in range(diff-1)]) episode_return_buf[p].append(float(payoffs[p])) target_buf[p].extend([float(payoffs[p]) for _ in range(diff)]) # State and action for i in range(0, len(trajectories[p])-2, 2): state = trajectories[p][i]['obs'] action = env.get_action_feature(trajectories[p][i+1]) state_buf[p].append(torch.from_numpy(state)) action_buf[p].append(torch.from_numpy(action)) while size[p] > T: index = free_queue[p].get() if index is None: break for t in range(T): buffers[p]['done'][index][t, ...] = done_buf[p][t] buffers[p]['episode_return'][index][t, ...] = episode_return_buf[p][t] buffers[p]['target'][index][t, ...] = target_buf[p][t] buffers[p]['state'][index][t, ...] = state_buf[p][t] buffers[p]['action'][index][t, ...] = action_buf[p][t] full_queue[p].put(index) done_buf[p] = done_buf[p][T:] episode_return_buf[p] = episode_return_buf[p][T:] target_buf[p] = target_buf[p][T:] state_buf[p] = state_buf[p][T:] action_buf[p] = action_buf[p][T:] size[p] -= T except KeyboardInterrupt: pass except Exception as e: log.error('Exception in worker process %i', i) traceback.print_exc() print() raise e
null
22,847
import os import threading import time import timeit import pprint from collections import deque import torch from torch import multiprocessing as mp from torch import nn from .file_writer import FileWriter from .model import DMCModel from .pettingzoo_model import DMCModelPettingZoo from .utils import ( get_batch, create_buffers, create_optimizers, act, log, ) from .pettingzoo_utils import ( create_buffers_pettingzoo, act_pettingzoo, ) def compute_loss(logits, targets): loss = ((logits - targets)**2).mean() return loss The provided code snippet includes necessary dependencies for implementing the `learn` function. Write a Python function `def learn( position, actor_models, agent, batch, optimizer, training_device, max_grad_norm, mean_episode_return_buf, lock )` to solve the following problem: Performs a learning (optimization) step. Here is the function: def learn( position, actor_models, agent, batch, optimizer, training_device, max_grad_norm, mean_episode_return_buf, lock ): """Performs a learning (optimization) step.""" device = "cuda:"+str(training_device) if training_device != "cpu" else "cpu" state = torch.flatten(batch['state'].to(device), 0, 1).float() action = torch.flatten(batch['action'].to(device), 0, 1).float() target = torch.flatten(batch['target'].to(device), 0, 1) episode_returns = batch['episode_return'][batch['done']] mean_episode_return_buf[position].append(torch.mean(episode_returns).to(device)) with lock: values = agent.forward(state, action) loss = compute_loss(values, target) stats = { 'mean_episode_return_'+str(position): torch.mean(torch.stack([_r for _r in mean_episode_return_buf[position]])).item(), 'loss_'+str(position): loss.item(), } optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(agent.parameters(), max_grad_norm) optimizer.step() for actor_model in actor_models.values(): actor_model.get_agent(position).load_state_dict(agent.state_dict()) return stats
Performs a learning (optimization) step.
22,849
import traceback import numpy as np import torch from .utils import log from rlcard.utils import run_game_pettingzoo def create_buffers_pettingzoo( T, num_buffers, env, device_iterator, ): buffers = {} for device in device_iterator: buffers[device] = [] for agent_name in env.agents: state_shape = env.observation_space(agent_name)["observation"].shape specs = dict( done=dict(size=(T,), dtype=torch.bool), episode_return=dict(size=(T,), dtype=torch.float32), target=dict(size=(T,), dtype=torch.float32), state=dict(size=(T,)+tuple(state_shape), dtype=torch.int8), action=dict(size=(T,)+(env.action_space(agent_name).n,), dtype=torch.int8), ) _buffers = {key: [] for key in specs} for _ in range(num_buffers): for key in _buffers: if device == "cpu": _buffer = torch.empty(**specs[key]).to('cpu').share_memory_() else: _buffer = torch.empty(**specs[key]).to('cuda:'+str(device)).share_memory_() _buffers[key].append(_buffer) buffers[device].append(_buffers) return buffers
null
22,850
import traceback import numpy as np import torch from .utils import log from rlcard.utils import run_game_pettingzoo def _get_action_feature(action, action_space): out = np.zeros(action_space) out[action] = 1 return out log = logging.getLogger('doudzero') log.propagate = False log.addHandler(shandle) log.setLevel(logging.INFO) def act_pettingzoo( i, device, T, free_queue, full_queue, model, buffers, env ): log.info('Device %s Actor %i started.', str(device), i) try: done_buf = [[] for _ in range(env.num_agents)] episode_return_buf = [[] for _ in range(env.num_agents)] target_buf = [[] for _ in range(env.num_agents)] state_buf = [[] for _ in range(env.num_agents)] action_buf = [[] for _ in range(env.num_agents)] size = [0 for _ in range(env.num_agents)] while True: trajectories = run_game_pettingzoo(env, model.agents, is_training=True) for agent_id, agent_name in enumerate(env.possible_agents): traj_size = len(trajectories[agent_name]) // 2 if traj_size > 0: size[agent_id] += traj_size target_return = trajectories[agent_name][-2][1] target_buf[agent_id].extend([target_return for _ in range(traj_size)]) for i in range(0, len(trajectories[agent_name]), 2): state = trajectories[agent_name][i][0]['observation'] action = _get_action_feature( trajectories[agent_name][i+1], model.agents[agent_name].action_shape ) episode_return = trajectories[agent_name][i][1] done = trajectories[agent_name][i][2] state_buf[agent_id].append(torch.from_numpy(state)) action_buf[agent_id].append(torch.from_numpy(action)) episode_return_buf[agent_id].append(episode_return) done_buf[agent_id].append(done) while size[agent_id] > T: index = free_queue[agent_id].get() if index is None: print("index is None") break for t in range(T): temp_done = done_buf[agent_id][t] buffers[agent_id]['done'][index][t, ...] = temp_done buffers[agent_id]['episode_return'][index][t, ...] = episode_return_buf[agent_id][t] buffers[agent_id]['target'][index][t, ...] = target_buf[agent_id][t] buffers[agent_id]['state'][index][t, ...] = state_buf[agent_id][t] buffers[agent_id]['action'][index][t, ...] = action_buf[agent_id][t] full_queue[agent_id].put(index) done_buf[agent_id] = done_buf[agent_id][T:] episode_return_buf[agent_id] = episode_return_buf[agent_id][T:] target_buf[agent_id] = target_buf[agent_id][T:] state_buf[agent_id] = state_buf[agent_id][T:] action_buf[agent_id] = action_buf[agent_id][T:] size[agent_id] -= T except KeyboardInterrupt: pass except Exception as e: log.error('Exception in worker process %i', i) traceback.print_exc() raise e
null
22,851
import numpy as np from rlcard.games.mahjong.card import MahjongCard as Card 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 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
null
22,852
import numpy as np from rlcard.games.mahjong.card import MahjongCard as Card def pile2list(pile): cards_list = [] for each in pile: cards_list.extend(each) return cards_list
null
22,853
import numpy as np from rlcard.games.mahjong.card import MahjongCard as Card card_encoding_dict = {} num = 0 card_encoding_dict['pong'] = num card_encoding_dict['chow'] = num + 1 card_encoding_dict['gong'] = num + 2 card_encoding_dict['stand'] = num + 3 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
null
22,854
from typing import List import numpy as np from .bridge_card import BridgeCard class BridgeCard(Card): def card(card_id: int): def get_deck() -> [Card]: def __init__(self, suit: str, rank: str): def __str__(self): def __repr__(self): def encode_cards(cards: List[BridgeCard]) -> np.ndarray: # Note: not used ?? plane = np.zeros(52, dtype=int) for card in cards: plane[card.card_id] = 1 return plane
null
22,855
import os import json import numpy as np from collections import OrderedDict import rlcard from rlcard.games.uno.card import UnoCard as Card The provided code snippet includes necessary dependencies for implementing the `init_deck` function. Write a Python function `def init_deck()` to solve the following problem: Generate uno deck of 108 cards Here is the function: 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
Generate uno deck of 108 cards
22,856
import os import json import numpy as np from collections import OrderedDict import rlcard from rlcard.games.uno.card import UnoCard as Card The provided code snippet includes necessary dependencies for implementing the `cards2list` function. Write a Python function `def cards2list(cards)` to solve the following problem: Get the corresponding string representation of cards Args: cards (list): list of UnoCards objects Returns: (string): string representation of cards Here is the function: 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
Get the corresponding string representation of cards Args: cards (list): list of UnoCards objects Returns: (string): string representation of cards
22,857
import os import json import numpy as np from collections import OrderedDict import rlcard from rlcard.games.uno.card import UnoCard as Card COLOR_MAP = {'r': 0, 'g': 1, 'b': 2, 'y': 3} 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} 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 The provided code snippet includes necessary dependencies for implementing the `encode_hand` function. Write a Python function `def encode_hand(plane, hand)` to solve the following problem: 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 Here is the function: 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
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
22,858
import os import json import numpy as np from collections import OrderedDict import rlcard from rlcard.games.uno.card import UnoCard as Card COLOR_MAP = {'r': 0, 'g': 1, 'b': 2, 'y': 3} 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} The provided code snippet includes necessary dependencies for implementing the `encode_target` function. Write a Python function `def encode_target(plane, target)` to solve the following problem: 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 Here is the function: 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
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
22,859
from typing import TYPE_CHECKING from typing import List, Tuple from .utils.action_event import * from .utils.scorers import GinRummyScorer from .utils import melding from .utils.gin_rummy_error import GinRummyProgramError from rlcard.games.gin_rummy.utils import utils 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) class GinRummyProgramError(GinRummyError): pass The provided code snippet includes necessary dependencies for implementing the `get_going_out_cards` function. Write a Python function `def get_going_out_cards(hand: List[Card], going_out_deadwood_count: int) -> Tuple[List[Card], List[Card]]` to solve the following problem: :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 Here is the function: 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)
: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
22,860
from typing import List from rlcard.games.base import Card from rlcard.games.gin_rummy.utils import utils from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError 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 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
null
22,861
from typing import List, Iterable import numpy as np from rlcard.games.base import Card from .gin_rummy_error import GinRummyProgramError 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 class GinRummyProgramError(GinRummyError): pass 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])
null
22,862
from typing import List, Iterable import numpy as np from rlcard.games.base import Card from .gin_rummy_error import GinRummyProgramError _deck = [card_from_card_id(card_id) for card_id in range(52)] 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 def get_deck() -> List[Card]: return _deck.copy()
null
22,863
from typing import List, Iterable import numpy as np from rlcard.games.base import Card from .gin_rummy_error import GinRummyProgramError _deck = [card_from_card_id(card_id) for card_id in range(52)] 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 class GinRummyProgramError(GinRummyError): pass 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
null
22,864
from typing import List, Iterable import numpy as np from rlcard.games.base import Card from .gin_rummy_error import GinRummyProgramError def get_card_id(card: Card) -> int: class Card: def __init__(self, suit, rank): def __eq__(self, other): def __hash__(self): def __str__(self): def get_index(self): 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
null
22,865
from typing import TYPE_CHECKING from typing import Callable from .action_event import * from ..player import GinRummyPlayer from .move import ScoreNorthMove, ScoreSouthMove from .gin_rummy_error import GinRummyProgramError from rlcard.games.gin_rummy.utils import melding from rlcard.games.gin_rummy.utils import utils from . import utils as utils class GinAction(ActionEvent): def __init__(self): super().__init__(action_id=gin_action_id) def __str__(self): return "gin" 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)) 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" def short_name_of(player_id: int) -> str: return "N" if player_id == 0 else "S" 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] The provided code snippet includes necessary dependencies for implementing the `get_payoff_gin_rummy_v1` function. Write a Python function `def get_payoff_gin_rummy_v1(player: GinRummyPlayer, game: 'GinRummyGame') -> float` to solve the following problem: 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) Here is the function: def get_payoff_gin_rummy_v1(player: GinRummyPlayer, 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
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)
22,866
import os import json from collections import OrderedDict import threading import collections import rlcard CARD_RANK_STR = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A', '2', 'B', 'R'] The provided code snippet includes necessary dependencies for implementing the `doudizhu_sort_str` function. Write a Python function `def doudizhu_sort_str(card_1, card_2)` to solve the following problem: 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) Here is the function: 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
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)
22,867
import os import json from collections import OrderedDict import threading import collections import rlcard CARD_RANK = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A', '2', 'BJ', 'RJ'] The provided code snippet includes necessary dependencies for implementing the `doudizhu_sort_card` function. Write a Python function `def doudizhu_sort_card(card_1, card_2)` to solve the following problem: Compare the rank of two cards of Card object Args: card_1 (object): object of Card card_2 (object): object of card Here is the function: 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
Compare the rank of two cards of Card object Args: card_1 (object): object of Card card_2 (object): object of card
22,868
import os import json from collections import OrderedDict import threading import collections import rlcard The provided code snippet includes necessary dependencies for implementing the `get_landlord_score` function. Write a Python function `def get_landlord_score(current_hand)` to solve the following problem: 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 Here is the function: 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
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
22,869
import os import json from collections import OrderedDict import threading import collections import rlcard The provided code snippet includes necessary dependencies for implementing the `cards2str_with_suit` function. Write a Python function `def cards2str_with_suit(cards)` to solve the following problem: Get the corresponding string representation of cards with suit Args: cards (list): list of Card objects Returns: string: string representation of cards Here is the function: 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])
Get the corresponding string representation of cards with suit Args: cards (list): list of Card objects Returns: string: string representation of cards
22,870
import os import json from collections import OrderedDict import threading import collections import rlcard CARD_RANK_STR = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A', '2', 'B', 'R'] The provided code snippet includes necessary dependencies for implementing the `encode_cards` function. Write a Python function `def encode_cards(plane, cards)` to solve the following problem: 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 Here is the function: 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
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
22,871
import os import json from collections import OrderedDict import threading import collections import rlcard 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 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 The provided code snippet includes necessary dependencies for implementing the `get_gt_cards` function. Write a Python function `def get_gt_cards(player, greater_player)` to solve the following problem: 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' Here is the function: 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
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'
22,872
import numpy as np 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 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 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) The provided code snippet includes necessary dependencies for implementing the `compare_hands` function. Write a Python function `def compare_hands(hands)` to solve the following problem: 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] Here is the function: 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)
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]
22,873
import importlib registry = EnvRegistry() The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(env_id, entry_point)` to solve the following problem: Register an environment Args: env_id (string): The name of the environent entry_point (string): A string the indicates the location of the envronment class Here is the function: def register(env_id, entry_point): ''' Register an environment Args: env_id (string): The name of the environent entry_point (string): A string the indicates the location of the envronment class ''' return registry.register(env_id, entry_point)
Register an environment Args: env_id (string): The name of the environent entry_point (string): A string the indicates the location of the envronment class
22,874
import importlib DEFAULT_CONFIG = { 'allow_step_back': False, 'seed': None, } registry = EnvRegistry() The provided code snippet includes necessary dependencies for implementing the `make` function. Write a Python function `def make(env_id, config={})` to solve the following problem: Create and environment instance Args: env_id (string): The name of the environment config (dict): A dictionary of the environment settings env_num (int): The number of environments Here is the function: def make(env_id, config={}): ''' Create and environment instance Args: env_id (string): The name of the environment config (dict): A dictionary of the environment settings env_num (int): The number of environments ''' _config = DEFAULT_CONFIG.copy() for key in config: _config[key] = config[key] return registry.make(env_id, _config)
Create and environment instance Args: env_id (string): The name of the environment config (dict): A dictionary of the environment settings env_num (int): The number of environments
22,875
import numpy as np from collections import OrderedDict from rlcard.envs import Env from rlcard.games.blackjack import Game 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 get_score(hand): score = 0 count_a = 0 for card in hand: score += rank2score[card[1:]] if card[1] == 'A': count_a += 1 while score > 21 and count_a > 0: count_a -= 1 score -= 10 return score
null
22,876
from collections import Counter, OrderedDict import numpy as np from rlcard.envs import Env def _get_one_hot_array(num_left_cards, max_num_cards): one_hot = np.zeros(max_num_cards, dtype=np.int8) one_hot[num_left_cards - 1] = 1 return one_hot
null
22,877
from collections import Counter, OrderedDict import numpy as np from rlcard.envs import Env def _cards2array(cards): if cards == 'pass': return np.zeros(54, dtype=np.int8) matrix = np.zeros([4, 13], dtype=np.int8) jokers = np.zeros(2, dtype=np.int8) counter = Counter(cards) for card, num_times in counter.items(): if card == 'B': jokers[0] = 1 elif card == 'R': jokers[1] = 1 else: matrix[:, Card2Column[card]] = NumOnes2Array[num_times] return np.concatenate((matrix.flatten('F'), jokers)) def _action_seq2array(action_seq_list): action_seq_array = np.zeros((len(action_seq_list), 54), np.int8) for row, cards in enumerate(action_seq_list): action_seq_array[row, :] = _cards2array(cards) action_seq_array = action_seq_array.flatten() return action_seq_array
null
22,878
from collections import Counter, OrderedDict import numpy as np from rlcard.envs import Env def _process_action_seq(sequence, length=9): sequence = [action[1] for action in sequence[-length:]] if len(sequence) < length: empty_sequence = ['' for _ in range(length - len(sequence))] empty_sequence.extend(sequence) sequence = empty_sequence return sequence
null
22,879
import importlib model_registry = ModelRegistry() The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(model_id, entry_point)` to solve the following problem: Register a model Args: model_id (string): the name of the model entry_point (string): a string the indicates the location of the model class Here is the function: def register(model_id, entry_point): ''' Register a model Args: model_id (string): the name of the model entry_point (string): a string the indicates the location of the model class ''' return model_registry.register(model_id, entry_point)
Register a model Args: model_id (string): the name of the model entry_point (string): a string the indicates the location of the model class
22,880
import importlib model_registry = ModelRegistry() The provided code snippet includes necessary dependencies for implementing the `load` function. Write a Python function `def load(model_id)` to solve the following problem: Create and model instance Args: model_id (string): the name of the model Here is the function: def load(model_id): ''' Create and model instance Args: model_id (string): the name of the model ''' return model_registry.load(model_id)
Create and model instance Args: model_id (string): the name of the model
22,881
import numpy as np from rlcard.games.base import Card def set_seed(seed): if seed is not None: import subprocess import sys reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']) installed_packages = [r.decode().split('==')[0] for r in reqs.split()] if 'torch' in installed_packages: import torch torch.backends.cudnn.deterministic = True torch.manual_seed(seed) np.random.seed(seed) import random random.seed(seed)
null
22,882
import numpy as np from rlcard.games.base import Card def get_device(): import torch if torch.backends.mps.is_available(): device = torch.device("mps:0") print("--> Running on the GPU") elif torch.cuda.is_available(): device = torch.device("cuda:0") print("--> Running on the GPU") else: device = torch.device("cpu") print("--> Running on the CPU") return device
null
22,883
import numpy as np from rlcard.games.base import Card 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 The provided code snippet includes necessary dependencies for implementing the `init_standard_deck` function. Write a Python function `def init_standard_deck()` to solve the following problem: Initialize a standard deck of 52 cards Returns: (list): A list of Card object Here is the function: 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
Initialize a standard deck of 52 cards Returns: (list): A list of Card object
22,884
import numpy as np from rlcard.games.base import Card 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 The provided code snippet includes necessary dependencies for implementing the `init_54_deck` function. Write a Python function `def init_54_deck()` to solve the following problem: Initialize a standard deck of 52 cards, BJ and RJ Returns: (list): Alist of Card object Here is the function: 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
Initialize a standard deck of 52 cards, BJ and RJ Returns: (list): Alist of Card object
22,885
import numpy as np from rlcard.games.base import Card The provided code snippet includes necessary dependencies for implementing the `rank2int` function. Write a Python function `def rank2int(rank)` to solve the following problem: 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. Here is the function: 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
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.
22,886
import numpy as np from rlcard.games.base import Card The provided code snippet includes necessary dependencies for implementing the `reorganize` function. Write a Python function `def reorganize(trajectories, payoffs)` to solve the following problem: Reorganize the trajectory to make it RL friendly Args: trajectory (list): A list of trajectories payoffs (list): A list of payoffs for the players. Each entry corresponds to one player Returns: (list): A new trajectories that can be fed into RL algorithms. Here is the function: def reorganize(trajectories, payoffs): ''' Reorganize the trajectory to make it RL friendly Args: trajectory (list): A list of trajectories payoffs (list): A list of payoffs for the players. Each entry corresponds to one player Returns: (list): A new trajectories that can be fed into RL algorithms. ''' num_players = len(trajectories) new_trajectories = [[] for _ in range(num_players)] for player in range(num_players): for i in range(0, len(trajectories[player])-2, 2): if i ==len(trajectories[player])-3: reward = payoffs[player] done =True else: reward, done = 0, False transition = trajectories[player][i:i+3].copy() transition.insert(2, reward) transition.append(done) new_trajectories[player].append(transition) return new_trajectories
Reorganize the trajectory to make it RL friendly Args: trajectory (list): A list of trajectories payoffs (list): A list of payoffs for the players. Each entry corresponds to one player Returns: (list): A new trajectories that can be fed into RL algorithms.
22,887
import numpy as np from rlcard.games.base import Card The provided code snippet includes necessary dependencies for implementing the `remove_illegal` function. Write a Python function `def remove_illegal(action_probs, legal_actions)` to solve the following problem: Remove illegal actions and normalize the probability vector Args: action_probs (numpy.array): A 1 dimention numpy array. legal_actions (list): A list of indices of legal actions. Returns: probd (numpy.array): A normalized vector without legal actions. Here is the function: def remove_illegal(action_probs, legal_actions): ''' Remove illegal actions and normalize the probability vector Args: action_probs (numpy.array): A 1 dimention numpy array. legal_actions (list): A list of indices of legal actions. Returns: probd (numpy.array): A normalized vector without legal actions. ''' probs = np.zeros(action_probs.shape[0]) probs[legal_actions] = action_probs[legal_actions] if np.sum(probs) == 0: probs[legal_actions] = 1 / len(legal_actions) else: probs /= sum(probs) return probs
Remove illegal actions and normalize the probability vector Args: action_probs (numpy.array): A 1 dimention numpy array. legal_actions (list): A list of indices of legal actions. Returns: probd (numpy.array): A normalized vector without legal actions.
22,888
import numpy as np from rlcard.games.base import Card The provided code snippet includes necessary dependencies for implementing the `tournament` function. Write a Python function `def tournament(env, num)` to solve the following problem: Evaluate he performance of the agents in the environment Args: env (Env class): The environment to be evaluated. num (int): The number of games to play. Returns: A list of avrage payoffs for each player Here is the function: def tournament(env, num): ''' Evaluate he performance of the agents in the environment Args: env (Env class): The environment to be evaluated. num (int): The number of games to play. Returns: A list of avrage payoffs for each player ''' payoffs = [0 for _ in range(env.num_players)] counter = 0 while counter < num: _, _payoffs = env.run(is_training=False) if isinstance(_payoffs, list): for _p in _payoffs: for i, _ in enumerate(payoffs): payoffs[i] += _p[i] counter += 1 else: for i, _ in enumerate(payoffs): payoffs[i] += _payoffs[i] counter += 1 for i, _ in enumerate(payoffs): payoffs[i] /= counter return payoffs
Evaluate he performance of the agents in the environment Args: env (Env class): The environment to be evaluated. num (int): The number of games to play. Returns: A list of avrage payoffs for each player
22,889
import numpy as np from rlcard.games.base import Card import os if not os.path.isfile(os.path.join(ROOT_PATH, 'games/doudizhu/jsondata/action_space.txt')) \ or not os.path.isfile(os.path.join(ROOT_PATH, 'games/doudizhu/jsondata/card_type.json')) \ or not os.path.isfile(os.path.join(ROOT_PATH, 'games/doudizhu/jsondata/type_card.json')): import zipfile with zipfile.ZipFile(os.path.join(ROOT_PATH, 'games/doudizhu/jsondata.zip'),"r") as zip_ref: zip_ref.extractall(os.path.join(ROOT_PATH, 'games/doudizhu/')) The provided code snippet includes necessary dependencies for implementing the `plot_curve` function. Write a Python function `def plot_curve(csv_path, save_path, algorithm)` to solve the following problem: Read data from csv file and plot the results Here is the function: def plot_curve(csv_path, save_path, algorithm): ''' Read data from csv file and plot the results ''' import os import csv import matplotlib.pyplot as plt with open(csv_path) as csvfile: reader = csv.DictReader(csvfile) xs = [] ys = [] for row in reader: xs.append(int(row['episode'])) ys.append(float(row['reward'])) fig, ax = plt.subplots() ax.plot(xs, ys, label=algorithm) ax.set(xlabel='episode', ylabel='reward') ax.legend() ax.grid() save_dir = os.path.dirname(save_path) if not os.path.exists(save_dir): os.makedirs(save_dir) fig.savefig(save_path)
Read data from csv file and plot the results
22,890
import hashlib import numpy as np import os import struct def error(msg, *args): print(colorize('%s: %s'%('ERROR', msg % args), 'red')) def hash_seed(seed=None, max_bytes=8): """Any given evaluation is likely to have many PRNG's active at once. (Most commonly, because the environment is running in multiple processes.) There's literature indicating that having linear correlations between seeds of multiple PRNG's can correlate the outputs: http://blogs.unity3d.com/2015/01/07/a-primer-on-repeatable-random-numbers/ http://stackoverflow.com/questions/1554958/how-different-do-random-seeds-need-to-be http://dl.acm.org/citation.cfm?id=1276928 Thus, for sanity we hash the seeds before using them. (This scheme is likely not crypto-strength, but it should be good enough to get rid of simple correlations.) Args: seed (Optional[int]): None seeds from an operating system specific randomness source. max_bytes: Maximum number of bytes to use in the hashed seed. """ if seed is None: seed = create_seed(max_bytes=max_bytes) _hash = hashlib.sha512(str(seed).encode('utf8')).digest() return _bigint_from_bytes(_hash[:max_bytes]) def create_seed(a=None, max_bytes=8): """Create a strong random seed. Otherwise, Python 2 would seed using the system time, which might be non-robust especially in the presence of concurrency. Args: a (Optional[int, str]): None seeds from an operating system specific randomness source. max_bytes: Maximum number of bytes to use in the seed. """ # Adapted from https://svn.python.org/projects/python/tags/r32/Lib/random.py if a is None: a = _bigint_from_bytes(os.urandom(max_bytes)) elif isinstance(a, str): a = a.encode('utf8') a += hashlib.sha512(a).digest() a = _bigint_from_bytes(a[:max_bytes]) elif isinstance(a, int): a = a % 2**(8 * max_bytes) else: raise error.Error('Invalid type for seed: {} ({})'.format(type(a), a)) return a def _int_list_from_bigint(bigint): # Special case 0 if bigint < 0: raise error.Error('Seed must be non-negative, not {}'.format(bigint)) elif bigint == 0: return [0] ints = [] while bigint > 0: bigint, mod = divmod(bigint, 2 ** 32) ints.append(mod) return ints def np_random(seed=None): if seed is not None and not (isinstance(seed, int) and 0 <= seed): raise error.Error('Seed must be a non-negative integer or omitted, not {}'.format(seed)) seed = create_seed(seed) rng = np.random.RandomState() rng.seed(_int_list_from_bigint(hash_seed(seed))) return rng, seed
null
22,891
from collections import defaultdict import numpy as np def wrap_state(state): # check if obs is already wrapped if "obs" in state and "legal_actions" in state and "raw_legal_actions" in state: return state wrapped_state = {} wrapped_state["obs"] = state["observation"] legal_actions = np.flatnonzero(state["action_mask"]) # the values of legal_actions isn't available so setting them to None wrapped_state["legal_actions"] = {l: None for l in legal_actions} # raw_legal_actions isn't available so setting it to legal actions wrapped_state["raw_legal_actions"] = list(wrapped_state["legal_actions"].keys()) return wrapped_state
null
22,892
from collections import defaultdict import numpy as np def run_game_pettingzoo(env, agents, is_training=False): env.reset() trajectories = defaultdict(list) for agent_name in env.agent_iter(): obs, reward, done, _, _ = env.last() trajectories[agent_name].append((obs, reward, done)) if done: action = None else: if is_training: action = agents[agent_name].step(obs) else: action, _ = agents[agent_name].eval_step(obs) trajectories[agent_name].append(action) env.step(action) return trajectories def reorganize_pettingzoo(trajectories): ''' Reorganize the trajectory to make it RL friendly Args: trajectory (list): A list of trajectories Returns: (list): A new trajectories that can be fed into RL algorithms. ''' new_trajectories = defaultdict(list) for agent_name, trajectory in trajectories.items(): for i in range(0, len(trajectory)-2, 2): transition = [ trajectory[i][0], # obs, trajectory[i+1], # action trajectory[i+2][1], # reward trajectory[i+2][0], # next_obs trajectory[i+2][2], # done ] new_trajectories[agent_name].append(transition) return new_trajectories def tournament_pettingzoo(env, agents, num_episodes): total_rewards = defaultdict(float) for _ in range(num_episodes): trajectories = run_game_pettingzoo(env, agents) trajectories = reorganize_pettingzoo(trajectories) for agent_name, trajectory in trajectories.items(): reward = sum([t[2] for t in trajectory]) total_rewards[agent_name] += reward return {k: v / num_episodes for (k, v) in total_rewards.items()}
null
22,893
import os import sys import asyncio from multiprocessing import Process, Manager from platform import system import websockets from config import ServerConfig as Config from util.server_cosmic import Cosmic, console from util.server_check_model import check_model from util.server_ws_recv import ws_recv from util.server_ws_send import ws_send from util.server_init_recognizer import init_recognizer from util.empty_working_set import empty_current_working_set console.line(2) console.rule('[bold #d55252]CapsWriter Offline Server' console.line() console.print(f'项目地址:[cyan underline]https://github.com/HaujetZhao/CapsWriter-Offline', end='\n\n') console.print(f'当前基文件夹:[cyan underline]{BASE_DIR}', end='\n\n') console.print(f'绑定的服务地址:[cyan underline]{Config.addr}:{Config.port}', end='\n\n') Cosmic.queue_out.get() console.rule('[green3]开始服务') console.line() await asyncio.gather(recv, send) console = Console(highlight=False) class Cosmic: sockets: Dict[str, websockets.WebSocketClientProtocol] = {} sockets_id: List queue_in = Queue() queue_out = Queue() def init(): try: asyncio.run(main()) except KeyboardInterrupt: # Ctrl-C 停止 console.print('\n再见!') except OSError as e: # 端口占用 console.print(f'出错了:{e}', style='bright_red'); console.input('...') except Exception as e: print(e) finally: Cosmic.queue_out.put(None) sys.exit(0) # os._exit(0)
null
22,894
import os import sys import asyncio import signal from pathlib import Path from platform import system from typing import List import typer import colorama import keyboard from config import ClientConfig as Config from util.client_cosmic import console, Cosmic from util.client_stream import stream_open, stream_close from util.client_shortcut_handler import bond_shortcut from util.client_recv_result import recv_result from util.client_show_tips import show_mic_tips, show_file_tips from util.client_hot_update import update_hot_all, observe_hot from util.client_transcribe import transcribe_check, transcribe_send, transcribe_recv from util.client_adjust_srt import adjust_srt from util.empty_working_set import empty_current_working_set def main_mic(): Cosmic.loop = asyncio.get_event_loop() Cosmic.queue_in = asyncio.Queue() Cosmic.queue_out = asyncio.Queue() show_mic_tips() # 更新热词 update_hot_all() # 实时更新热词 observer = observe_hot() # 打开音频流 Cosmic.stream = stream_open() # Ctrl-C 关闭音频流,触发自动重启 signal.signal(signal.SIGINT, stream_close) # 绑定按键 bond_shortcut() # 清空物理内存工作集 if system() == 'Windows': empty_current_working_set() # 接收结果 while True: await recv_result() console = Console(highlight=False, soft_wrap=False, theme=my_theme) def init_mic(): try: asyncio.run(main_mic()) except KeyboardInterrupt: console.print(f'再见!') finally: print('...')
null
22,895
import os import sys import asyncio import signal from pathlib import Path from platform import system from typing import List import typer import colorama import keyboard from config import ClientConfig as Config from util.client_cosmic import console, Cosmic from util.client_stream import stream_open, stream_close from util.client_shortcut_handler import bond_shortcut from util.client_recv_result import recv_result from util.client_show_tips import show_mic_tips, show_file_tips from util.client_hot_update import update_hot_all, observe_hot from util.client_transcribe import transcribe_check, transcribe_send, transcribe_recv from util.client_adjust_srt import adjust_srt from util.empty_working_set import empty_current_working_set () == 'Darwin' and not sys.argv[1: async def main_file(files: List[Path]): show_file_tips() for file in files: if file.suffix in ['.txt', '.json', 'srt']: adjust_srt(file) else: await transcribe_check(file) await asyncio.gather( transcribe_send(file), transcribe_recv(file) ) if Cosmic.websocket: await Cosmic.websocket.close() input('\n按回车退出\n') console = Console(highlight=False, soft_wrap=False, theme=my_theme) The provided code snippet includes necessary dependencies for implementing the `init_file` function. Write a Python function `def init_file(files: List[Path])` to solve the following problem: 用 CapsWriter Server 转录音视频文件,生成 srt 字幕 Here is the function: def init_file(files: List[Path]): """ 用 CapsWriter Server 转录音视频文件,生成 srt 字幕 """ try: asyncio.run(main_file(files)) except KeyboardInterrupt: console.print(f'再见!') sys.exit()
用 CapsWriter Server 转录音视频文件,生成 srt 字幕
22,896
import argparse import asyncio import logging import wave import subprocess from typing import List, Tuple import shlex import json import time import numpy as np def get_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "--server-addr", type=str, default="localhost", help="Address of the server", ) parser.add_argument( "--server-port", type=int, default=6007, help="Port of the server", ) parser.add_argument( "sound_files", type=str, nargs="+", help="The input sound file(s) to decode. Each file must be of WAVE" "format with a single channel, and each sample has 16-bit, " "i.e., int16_t. " "The sample rate of the file can be arbitrary and does not need to " "be 16 kHz", ) return parser.parse_args()
null
22,897
import argparse import asyncio import logging import wave import subprocess from typing import List, Tuple import shlex import json import time try: import websockets except ImportError: print("please run:") print("") print(" pip install websockets") print("") print("before you run this script") print("") import numpy as np def read_wave(wave_filename: str) -> Tuple[np.ndarray, int]: """ Args: wave_filename: Path to a wave file. It should be single channel and each sample should be 16-bit. Its sample rate does not need to be 16kHz. Returns: Return a tuple containing: - A 1-D array of dtype np.float32 containing the samples, which are normalized to the range [-1, 1]. - sample rate of the wave file """ with wave.open(wave_filename) as f: assert f.getnchannels() == 1, f.getnchannels() assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes num_samples = f.getnframes() samples = f.readframes(num_samples) samples_int16 = np.frombuffer(samples, dtype=np.int16) samples_float32 = samples_int16.astype(np.float32) samples_float32 = samples_float32 / 32768 return samples_float32, f.getframerate() async def run( server_addr: str, server_port: int, sound_files: List[str], ): async with websockets.connect( f"ws://{server_addr}:{server_port}" ) as websocket: # noqa for wave_filename in sound_files: # 先统一用 ffmpeg 转换 command = f'ffmpeg -y -i "{wave_filename}" -ac 1 -ar 16000 temp.wav' subprocess.run(shlex.split(command), stderr=subprocess.PIPE) logging.info(f"Sending {wave_filename}") samples, sample_rate = read_wave('temp.wav') assert isinstance(sample_rate, int) assert samples.dtype == np.float32, samples.dtype assert samples.ndim == 1, samples.dim buf = sample_rate.to_bytes(4, byteorder="little") # 4 bytes buf += (samples.size * 4).to_bytes(4, byteorder="little") buf += samples.tobytes() payload_len = 10240 while len(buf) > payload_len: await websocket.send(buf[:payload_len]) buf = buf[payload_len:] if buf: await websocket.send(buf) t1 = time.time() decoding_results = await websocket.recv() wav_duration = len(samples) / 16000 dec_duration = time.time() - t1 print(decoding_results) print(f'文件:{wave_filename}\n时长:{wav_duration:.1f}s\n用时:{dec_duration:.1f}s\nRTF:{dec_duration/wav_duration:.4f}') # 将结果写入 txt with open(wave_filename[:-4]+'.txt', 'w', encoding='utf-8') as f: f.write(json.loads(decoding_results)['text']) # to signal that the client has sent all the data await websocket.send("Done")
null
22,898
import sys from pathlib import Path from typing import Dict import yaml def write_tokens(tokens: Dict[int, str]): with open("tokens.txt", "w", encoding="utf-8") as f: for idx, s in enumerate(tokens): f.write(f"{s} {idx}\n")
null
22,899
import json from datetime import timedelta from pathlib import Path import typer import srt from rich import print def lines_match_words(text_lines: list[str], words: list[dict[str, str | float]]) -> list[srt.Subtitle]: def get_words(json_file: Path) -> list[dict[str, str | float]]: def get_lines(txt_file: Path) -> list[str]: e__ == '__main__': typer.run(main) def one_task(media_file: Path): # 配置要打开的文件 txt_file = media_file.with_suffix('.txt') json_file = media_file.with_suffix('.json') srt_file = media_file.with_suffix('.srt') if (not txt_file.exists()) or (not json_file.exists()): print(f'无法找到 {media_file}对应的txt、json文件,跳过') return None # 获取带有时间戳的分词列表,获取分行稿件,匹配得到 srt words = get_words(json_file) text_lines = get_lines(txt_file) subtitle_list = lines_match_words(text_lines, words) # 写入 srt with open(srt_file, 'w', encoding='utf-8') as f: f.write(srt.compose(subtitle_list))
null
22,900
from pathlib import Path from typing import Dict import numpy as np import onnx import yaml def load_cmvn(): neg_mean = None inv_stddev = None with open("am.mvn", encoding="utf-8") as f: for line in f: if not line.startswith("<LearnRateCoef>"): continue t = line.split()[3:-1] if neg_mean is None: neg_mean = ",".join(t) else: inv_stddev = ",".join(t) return neg_mean, inv_stddev
null
22,901
from pathlib import Path from typing import Dict import numpy as np import onnx import yaml def load_lfr_params(config): with open("config.yaml", encoding="utf-8") as f: for line in f: if "lfr_m" in line: lfr_m = int(line.split()[-1]) elif "lfr_n" in line: lfr_n = int(line.split()[-1]) break lfr_window_size = config["frontend_conf"]["lfr_m"] lfr_window_shift = config["frontend_conf"]["lfr_n"] return lfr_window_size, lfr_window_shift
null
22,902
from pathlib import Path from typing import Dict import numpy as np import onnx import yaml The provided code snippet includes necessary dependencies for implementing the `add_meta_data` function. Write a Python function `def add_meta_data(filename: str, meta_data: Dict[str, str])` to solve the following problem: Add meta data to an ONNX model. It is changed in-place. Args: filename: Filename of the ONNX model to be changed. meta_data: Key-value pairs. Here is the function: def add_meta_data(filename: str, meta_data: Dict[str, str]): """Add meta data to an ONNX model. It is changed in-place. Args: filename: Filename of the ONNX model to be changed. meta_data: Key-value pairs. """ model = onnx.load(filename) for key, value in meta_data.items(): meta = model.metadata_props.add() meta.key = key meta.value = value onnx.save(model, filename) print(f"Updated {filename}")
Add meta data to an ONNX model. It is changed in-place. Args: filename: Filename of the ONNX model to be changed. meta_data: Key-value pairs.
22,903
import argparse import shutil import subprocess import sys import json import time import re from dataclasses import dataclass from datetime import timedelta from pathlib import Path from copy import copy import numpy as np import sherpa_onnx def get_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "--tokens", type=str, help="Path to tokens.txt", ) parser.add_argument( "--encoder", default="", type=str, help="Path to the transducer encoder model", ) parser.add_argument( "--decoder", default="", type=str, help="Path to the transducer decoder model", ) parser.add_argument( "--joiner", default="", type=str, help="Path to the transducer joiner model", ) parser.add_argument( "--paraformer", default="", type=str, help="Path to the model.onnx from Paraformer", ) parser.add_argument( "--wenet-ctc", default="", type=str, help="Path to the CTC model.onnx from WeNet", ) parser.add_argument( "--num-threads", type=int, default=1, help="Number of threads for neural network computation", ) parser.add_argument( "--whisper-encoder", default="", type=str, help="Path to whisper encoder model", ) parser.add_argument( "--whisper-decoder", default="", type=str, help="Path to whisper decoder model", ) parser.add_argument( "--whisper-language", default="", type=str, help="""It specifies the spoken language in the input file. Example values: en, fr, de, zh, jp. Available languages for multilingual models can be found at https://github.com/openai/whisper/blob/main/whisper/tokenizer.py#L10 If not specified, we infer the language from the input audio file. """, ) parser.add_argument( "--whisper-task", default="transcribe", choices=["transcribe", "translate"], type=str, help="""For multilingual models, if you specify translate, the output will be in English. """, ) parser.add_argument( "--decoding-method", type=str, default="greedy_search", help="""Valid values are greedy_search and modified_beam_search. modified_beam_search is valid only for transducer models. """, ) parser.add_argument( "--debug", type=bool, default=False, help="True to show debug messages when loading modes.", ) parser.add_argument( "--sample-rate", type=int, default=16000, help="""Sample rate of the feature extractor. Must match the one expected by the model. Note: The input sound files can have a different sample rate from this argument.""", ) parser.add_argument( "--feature-dim", type=int, default=80, help="Feature dimension. Must match the one expected by the model", ) parser.add_argument( "sound_file", type=str, help="The input sound file to generate subtitles ", ) return parser.parse_args()
null
22,904
import argparse import shutil import subprocess import sys import json import time import re from dataclasses import dataclass from datetime import timedelta from pathlib import Path from copy import copy import numpy as np import sherpa_onnx def assert_file_exists(filename: str): assert Path(filename).is_file(), ( f"{filename} does not exist!\n" "Please refer to " "https://k2-fsa.github.io/sherpa/onnx/pretrained_models/index.html to download it" ) def create_recognizer(args) -> sherpa_onnx.OfflineRecognizer: if args.encoder: assert len(args.paraformer) == 0, args.paraformer assert len(args.wenet_ctc) == 0, args.wenet_ctc assert len(args.whisper_encoder) == 0, args.whisper_encoder assert len(args.whisper_decoder) == 0, args.whisper_decoder assert_file_exists(args.encoder) assert_file_exists(args.decoder) assert_file_exists(args.joiner) recognizer = sherpa_onnx.OfflineRecognizer.from_transducer( encoder=args.encoder, decoder=args.decoder, joiner=args.joiner, tokens=args.tokens, num_threads=args.num_threads, sample_rate=args.sample_rate, feature_dim=args.feature_dim, decoding_method=args.decoding_method, debug=args.debug, ) elif args.paraformer: assert len(args.wenet_ctc) == 0, args.wenet_ctc assert len(args.whisper_encoder) == 0, args.whisper_encoder assert len(args.whisper_decoder) == 0, args.whisper_decoder assert_file_exists(args.paraformer) recognizer = sherpa_onnx.OfflineRecognizer.from_paraformer( paraformer=args.paraformer, tokens=args.tokens, num_threads=args.num_threads, sample_rate=args.sample_rate, feature_dim=args.feature_dim, decoding_method=args.decoding_method, debug=args.debug, ) elif args.wenet_ctc: assert len(args.whisper_encoder) == 0, args.whisper_encoder assert len(args.whisper_decoder) == 0, args.whisper_decoder assert_file_exists(args.wenet_ctc) recognizer = sherpa_onnx.OfflineRecognizer.from_wenet_ctc( model=args.wenet_ctc, tokens=args.tokens, num_threads=args.num_threads, sample_rate=args.sample_rate, feature_dim=args.feature_dim, decoding_method=args.decoding_method, debug=args.debug, ) elif args.whisper_encoder: assert_file_exists(args.whisper_encoder) assert_file_exists(args.whisper_decoder) recognizer = sherpa_onnx.OfflineRecognizer.from_whisper( encoder=args.whisper_encoder, decoder=args.whisper_decoder, tokens=args.tokens, num_threads=args.num_threads, decoding_method=args.decoding_method, debug=args.debug, language=args.whisper_language, task=args.whisper_task, ) else: raise ValueError("Please specify at least one model") return recognizer
null
22,905
import json import base64 import asyncio from multiprocessing import Queue from util.server_cosmic import console, Cosmic from util.server_classes import Result from util.asyncio_to_thread import to_thread from rich import inspect console = Console(highlight=False) class Cosmic: class Result: def __init__(self, task_id, socket_id, source) -> None: async def to_thread(func, /, *args, **kwargs): async def ws_send(): queue_out = Cosmic.queue_out sockets = Cosmic.sockets while True: try: # 获取识别结果(从多进程队列) result: Result = await to_thread(queue_out.get) # 得到退出的通知 if result is None: return # 构建消息 message = { 'task_id': result.task_id, 'duration': result.duration, 'time_start': result.time_start, 'time_submit': result.time_submit, 'time_complete': result.time_complete, 'tokens': result.tokens, 'timestamps': result.timestamps, 'text': result.text, 'is_final': result.is_final, } # 获得 socket websocket = next( (ws for ws in sockets.values() if str(ws.id) == result.socket_id), None, ) if not websocket: continue # 发送消息 await websocket.send(json.dumps(message)) if result.source == 'mic': console.print(f'识别结果:\n [green]{result.text}') elif result.source == 'file': console.print(f' 转录进度:{result.duration:.2f}s', end='\r') if result.is_final: console.print('\n [green]转录完成') except Exception as e: print(e)
null
22,906
from importlib.util import find_spece import os import sys from os import remove from pathlib import Path from typing import List from pprint import pprint from urllib.parse import unquote from markdown_it import MarkdownIt from markdown_it.token import Token from rich.console import Console markdown_ext = ['md', 'markdown'] def get_md_files(path): # 从输入目录递归搜索所有的 Markdown 文件 p = Path(path) if not p.exists(): return [] if not p.is_dir(): return [] md_files = [] for ext in markdown_ext: md_files.extend(list(p.glob("**/*." + ext))) return md_files
null
22,907
from importlib.util import find_spece import os import sys from os import remove from pathlib import Path from typing import List from pprint import pprint from urllib.parse import unquote from markdown_it import MarkdownIt from markdown_it.token import Token from rich.console import Console def get_links(text: str): # 查找文本内的所有链接 links = [] def add_link(token: Token): if 'src' in token.attrs: links.append(unquote(token.attrs['src'])) if 'href' in token.attrs: links.append(unquote(token.attrs['href'])) if token.type == 'html_inline': m = re.match(r'.*src="(.+?)".*', token.content) if m: links.append(unquote(m.group(1))) elif token.type == 'text': for m in re.finditer(r'.*?\[\[(.+?)\]\]', token.content): links.append(unquote(m.group(1))) if token.children is None: return for t in token.children: add_link(t) md = (MarkdownIt('commonmark' ,{'breaks':True,'html':True})) # pprint(md.parse(text)) for t in md.parse(text): add_link(t) return links
null
22,908
from importlib.util import find_spece import os import sys from os import remove from pathlib import Path from typing import List from pprint import pprint from urllib.parse import unquote from markdown_it import MarkdownIt from markdown_it.token import Token from rich.console import Console def absolutify_links(file, links: List[str]): # 验证链接是本地文件 if type(file) is not Path: file = Path(file) temp_links = links.copy(); links.clear() for link in temp_links: if (file.parent / link).exists(): links.append(file.parent / link) continue elif Path(link).exists(): links.append(link)
null
22,909
import sys from pathlib import Path from config import ModelPaths from util.server_cosmic import console # 输出时是否将中文数字转为阿拉伯数字 # 输出时是否启用标点符号引擎 # 输出时是否调整中英之间的空格 # Server 地址 # Server 端口 # 控制录音的快捷键,默认是 CapsLock # 长按模式,按下录音,松开停止,像对讲机一样用。 # 改为 False,则关闭长按模式,也就是单击模式 # 即:单击录音,再次单击停止 # 且:长按会执行原本的单击功能 # 是否阻塞按键事件(让其它程序收不到这个按键消息) # 录音完成,松开按键后,是否自动再按一遍,以恢复 CapsLock 或 Shift 等按键之前的状态 # 按下快捷键后,触发语音识别的时间阈值 # 是否以写入剪切板然后模拟 Ctrl-V 粘贴的方式输出结果 # 模拟粘贴后是否恢复剪贴板 # 是否保存录音文件 # 将录音识别结果的前多少个字存储到录音文件名中,建议不要超过200 # 识别结果要消除的末尾标点 # 是否启用中文热词替换,中文热词存储在 hot_zh.txt 文件里 # True 表示多音字匹配 # False 表示忽略声调区别,这样「黄章」就能匹配「慌张」 # 是否启用英文热词替换,英文热词存储在 hot_en.txt 文件里 # 是否启用自定义规则替换,自定义规则存储在 hot_rule.txt 文件里 # 是否启用关键词日记功能,自定义关键词存储在 keyword.txt 文件里 # 麦克风听写时分段长度:15秒 # 麦克风听写时分段重叠:2秒 # 转录文件时分段长度 # 转录文件时分段重叠 class ModelPaths: model_dir = Path() / 'models' paraformer_path = Path() / 'models' / 'paraformer-offline-zh' / 'model.int8.onnx' tokens_path = Path() / 'models' / 'paraformer-offline-zh' / 'tokens.txt' punc_model_dir = Path() / 'models' / 'punc_ct-transformer_cn-en' console = Console(highlight=False) def check_model(): for key, path in ModelPaths.__dict__.items() : if key.startswith('_'): continue if path.exists(): continue console.print(f''' 未能找到模型文件 未找到:{path} 本服务端需要 paraformer-offline-zh 模型和 punc_ct-transformer_zh-cn 模型, 请下载模型并放置到: {ModelPaths.model_dir} 下载地址在: https://github.com/HaujetZhao/CapsWriter-Offline/releases/tag/v0.3 ''', style='bright_red') input('按回车退出') sys.exit()
null
22,910
import json import time import base64 import asyncio import websockets from base64 import b64decode from util.server_cosmic import console, Cosmic from util.server_classes import Task, Result from util.my_status import Status status_mic = Status('正在接收音频', spinner='point') class Cache: # 定义一个可变对象,用于保存音频数据、偏移时间 def __init__(self): self.chunks = b'' self.offset = 0 self.frame_num = 0 async def message_handler(websocket, message, cache: Cache): """处理得到的音频流数据""" queue_in = Cosmic.queue_in global status_mic source = message['source'] is_final = message['is_final'] is_start = not bool(cache.chunks) # 获取 id task_id = message['task_id'] socket_id = str(websocket.id) # 获取分段长度(以多长的音频进行识别) seg_duration = message['seg_duration'] seg_overlap = message['seg_overlap'] seg_threshold = seg_duration + seg_overlap * 2 # base64 解码音频数据,再 # 音频数据是 float32、单声道、16000采样率 data = b64decode(message['data']) cache.chunks += data cache.frame_num += len(data) if not is_final: # 打印消息 if source == 'mic': status_mic.start() if source == 'file' and is_start: console.print('正在接收音频文件...') # 若缓冲已达到分段长度,将片段作为任务提交 while len(cache.chunks) / 4 / 16000 >= seg_threshold: data = cache.chunks[:4 * 16000 * (seg_duration + seg_overlap)] cache.chunks = cache.chunks[4 * 16000 * seg_duration:] task = Task(source=message['source'], data=data, offset=cache.offset, task_id=task_id, socket_id=socket_id, overlap=seg_overlap, is_final=False, time_start=message['time_start'], time_submit=time.time()) cache.offset += seg_duration queue_in.put(task) elif is_final: # 打印消息 if source == 'mic': status_mic.stop() elif source == 'file': print(f'音频文件接收完毕,时长 {cache.frame_num / 16000 / 4:.2f}s') # 客户端说片段结束,将缓冲区音频识别 task = Task(source=message['source'], data=cache.chunks[0:], offset=cache.offset, task_id=task_id, socket_id=socket_id, overlap=seg_overlap, is_final=True, time_start=message['time_start'], time_submit=time.time()) queue_in.put(task) # 还原缓冲区、偏移时长 cache.chunks = b'' cache.offset = 0 cache.frame_num = 0 console = Console(highlight=False) class Cosmic: sockets: Dict[str, websockets.WebSocketClientProtocol] = {} sockets_id: List queue_in = Queue() queue_out = Queue() async def ws_recv(websocket): global status_mic # 登记 socket 到字典,以 socket id 字符串为索引 sockets = Cosmic.sockets sockets_id = Cosmic.sockets_id sockets[str(websocket.id)] = websocket sockets_id.append(str(websocket.id)) console.print(f'接客了:{websocket}\n', style='yellow') # 设定分段长度 seg_duration = 15 seg_overlap = 2 seg_threshold = seg_duration + seg_overlap * 2 # 片段缓冲区、偏移时长 cache = Cache() # 接收数据 try: async for message in websocket: # json 解码字符串 message = json.loads(message) # 处理数据 await message_handler(websocket, message, cache) console.print("ConnectionClosed...", ) except websockets.ConnectionClosed: console.print("ConnectionClosed...", ) except websockets.InvalidState: console.print("InvalidState...") except Exception as e: console.print("Exception:", e) finally: status_mic.stop() status_mic.on = False sockets.pop(str(websocket.id)) sockets_id.remove(str(websocket.id))
null
22,911
import time import sherpa_onnx from multiprocessing import Queue import signal from platform import system from config import ServerConfig as Config from config import ParaformerArgs, ModelPaths from util.server_cosmic import console from util.server_recognize import recognize from util.empty_working_set import empty_current_working_set def disable_jieba_debug(): # 关闭 jieba 的 debug import jieba import logging jieba.setLogLevel(logging.INFO) # 输出时是否将中文数字转为阿拉伯数字 # 输出时是否启用标点符号引擎 # 输出时是否调整中英之间的空格 # Server 地址 # Server 端口 # 控制录音的快捷键,默认是 CapsLock # 长按模式,按下录音,松开停止,像对讲机一样用。 # 改为 False,则关闭长按模式,也就是单击模式 # 即:单击录音,再次单击停止 # 且:长按会执行原本的单击功能 # 是否阻塞按键事件(让其它程序收不到这个按键消息) # 录音完成,松开按键后,是否自动再按一遍,以恢复 CapsLock 或 Shift 等按键之前的状态 # 按下快捷键后,触发语音识别的时间阈值 # 是否以写入剪切板然后模拟 Ctrl-V 粘贴的方式输出结果 # 模拟粘贴后是否恢复剪贴板 # 是否保存录音文件 # 将录音识别结果的前多少个字存储到录音文件名中,建议不要超过200 # 识别结果要消除的末尾标点 # 是否启用中文热词替换,中文热词存储在 hot_zh.txt 文件里 # True 表示多音字匹配 # False 表示忽略声调区别,这样「黄章」就能匹配「慌张」 # 是否启用英文热词替换,英文热词存储在 hot_en.txt 文件里 # 是否启用自定义规则替换,自定义规则存储在 hot_rule.txt 文件里 # 是否启用关键词日记功能,自定义关键词存储在 keyword.txt 文件里 # 麦克风听写时分段长度:15秒 # 麦克风听写时分段重叠:2秒 # 转录文件时分段长度 # 转录文件时分段重叠 class ModelPaths: model_dir = Path() / 'models' paraformer_path = Path() / 'models' / 'paraformer-offline-zh' / 'model.int8.onnx' tokens_path = Path() / 'models' / 'paraformer-offline-zh' / 'tokens.txt' punc_model_dir = Path() / 'models' / 'punc_ct-transformer_cn-en' class ParaformerArgs: paraformer = f'{ModelPaths.paraformer_path}' tokens = f'{ModelPaths.tokens_path}' num_threads = 6 sample_rate = 16000 feature_dim = 80 decoding_method = 'greedy_search' debug = False console = Console(highlight=False) def recognize(recognizer, punc_model, task: Task): # inspect({key:value for key, value in task.__dict__.items() if not key.startswith('_') and key != 'data'}) # todo 清空遗存的任务结果 # 确保结果容器存在 if task.task_id not in results: results[task.task_id] = Result(task.task_id, task.socket_id, task.source) # 取出结果容器 result = results[task.task_id] # 片段预处理 samples = np.frombuffer(task.data, dtype=np.float32) duration = len(samples) / task.samplerate result.duration += duration - task.overlap if task.is_final: result.duration += task.overlap # 识别片段 stream = recognizer.create_stream() stream.accept_waveform(task.samplerate, samples) recognizer.decode_stream(stream) # 记录识别时间 result.time_start = task.time_start result.time_submit = task.time_submit result.time_complete = time.time() # 先粗去重,依据:字级时间戳 m = n = len(stream.result.timestamps) for i, timestamp in enumerate(stream.result.timestamps, start=0): if timestamp > task.overlap / 2: m = i break for i, timestamp in enumerate(stream.result.timestamps, start=1): n = i if timestamp > duration - task.overlap / 2: break if not result.timestamps: m = 0 if task.is_final: n = len(stream.result.timestamps) # 再细去重,依据:在端点是否有重复的字 if result.tokens and result.tokens[-2:] == stream.result.tokens[m:n][:2]: m += 2 elif result.tokens and result.tokens[-1:] == stream.result.tokens[m:n][:1]: m += 1 # 最后与先前的结果合并 result.timestamps += [t + task.offset for t in stream.result.timestamps[m:n]] result.tokens += [token for token in stream.result.tokens[m:n]] # token 合并为文本 text = ' '.join(result.tokens).replace('@@ ', '') text = re.sub('([^a-zA-Z0-9]) (?![a-zA-Z0-9])', r'\1', text) result.text = text if not task.is_final: return result # 调整文本格式 result.text = format_text(text, punc_model) # 若最后一个片段完成识别,从字典摘取任务 result = results.pop(task.task_id) result.is_final = True return result def empty_current_working_set(): # 获取当前进程ID pid = ctypes.windll.kernel32.GetCurrentProcessId() empty_working_set(pid) def init_recognizer(queue_in: Queue, queue_out: Queue, sockets_id): # Ctrl-C 退出 signal.signal(signal.SIGINT, lambda signum, frame: exit()) # 导入模块 with console.status("载入模块中…", spinner="bouncingBall", spinner_style="yellow"): import sherpa_onnx from funasr_onnx import CT_Transformer disable_jieba_debug() console.print('[green4]模块加载完成', end='\n\n') # 载入语音模型 console.print('[yellow]语音模型载入中', end='\r'); t1 = time.time() recognizer = sherpa_onnx.OfflineRecognizer.from_paraformer( **{key: value for key, value in ParaformerArgs.__dict__.items() if not key.startswith('_')} ) console.print(f'[green4]语音模型载入完成', end='\n\n') # 载入标点模型 punc_model = None if Config.format_punc: console.print('[yellow]标点模型载入中', end='\r') punc_model = CT_Transformer(ModelPaths.punc_model_dir, quantize=True) console.print(f'[green4]标点模型载入完成', end='\n\n') console.print(f'模型加载耗时 {time.time() - t1 :.2f}s', end='\n\n') # 清空物理内存工作集 if system() == 'Windows': empty_current_working_set() queue_out.put(True) # 通知主进程加载完了 while True: # 从队列中获取任务消息 # 阻塞最多1秒,便于中断退出 try: task = queue_in.get(timeout=1) except: continue if task.socket_id not in sockets_id: # 检查任务所属的连接是否存活 continue result = recognize(recognizer, punc_model, task) # 执行识别 queue_out.put(result) # 返回结果
null
22,912
import os import sys import glob import platform import shutil from setuptools import find_packages from setuptools import setup, Extension from setuptools.command.build_ext import build_ext The provided code snippet includes necessary dependencies for implementing the `copy_compiled_libs` function. Write a Python function `def copy_compiled_libs(libs, dest_dir)` to solve the following problem: Copy compiled libraries to the destination directory. Here is the function: def copy_compiled_libs(libs, dest_dir): """Copy compiled libraries to the destination directory.""" for lib in libs: try: shutil.copy2(lib, dest_dir) except shutil.SameFileError: # In case the file is the same do nothing pass
Copy compiled libraries to the destination directory.
22,913
import os import sys import glob import platform import shutil from setuptools import find_packages from setuptools import setup, Extension from setuptools.command.build_ext import build_ext The provided code snippet includes necessary dependencies for implementing the `copy_fonts` function. Write a Python function `def copy_fonts(dest_dir)` to solve the following problem: Copy fonts to the destination directory. Here is the function: def copy_fonts(dest_dir): """Copy fonts to the destination directory.""" dst_fonts = os.path.join(dest_dir, "fonts") if not os.path.exists(dst_fonts): shutil.copytree("third_party/fonts", dst_fonts)
Copy fonts to the destination directory.
22,914
import os import sys import glob import platform import shutil from setuptools import find_packages from setuptools import setup, Extension from setuptools.command.build_ext import build_ext The provided code snippet includes necessary dependencies for implementing the `process_develop_setup` function. Write a Python function `def process_develop_setup()` to solve the following problem: Clean up (if necessary) some directories before or after running setup in development (a.k.a. editable) mode (`pip install -e .`). Here is the function: def process_develop_setup(): """ Clean up (if necessary) some directories before or after running setup in development (a.k.a. editable) mode (`pip install -e .`). """ if 'develop' in sys.argv and os.path.exists('build'): # Remove `build` directory created by a regular installation shutil.rmtree('build') elif 'develop' not in sys.argv and os.path.exists('gfootball_engine'): # If `pip install .` is called after development mode, # remove the 'fonts' directory copied by a `develop` setup copied_fonts = 'third_party/gfootball_engine/fonts' if os.path.exists(copied_fonts): shutil.rmtree(copied_fonts) # Remove .so files (.pyd on Windows) for empty_lib in glob.glob("brainball_cpp_engine*"): os.remove(empty_lib) # Finally, remove symlink to the gfootball_engine directory if not os.path.exists('gfootball_engine'): return if os.path.islink('gfootball_engine'): if platform.system() == 'Windows': os.remove('gfootball_engine') else: os.unlink('gfootball_engine') else: shutil.rmtree('gfootball_engine')
Clean up (if necessary) some directories before or after running setup in development (a.k.a. editable) mode (`pip install -e .`).
22,915
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = True builder.SetBallPosition(0.77, 0.0) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.75, 0.0, e_PlayerRole_CB) builder.SetTeam(Team.e_Right) builder.AddPlayer(1.0, 0.0, e_PlayerRole_GK)
null
22,916
from . import * def build_scenario(builder): builder.config().game_duration = 3000 builder.config().second_half = 1500 builder.config().right_team_difficulty = 1.0 builder.config().left_team_difficulty = 1.0 builder.config().deterministic = False if builder.EpisodeNumber() % 2 == 0: first_team = Team.e_Left second_team = Team.e_Right else: first_team = Team.e_Right second_team = Team.e_Left builder.SetTeam(first_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK) builder.AddPlayer(-0.422000, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.500000, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.500000, 0.063559, e_PlayerRole_CB) builder.AddPlayer(-0.422000, 0.195760, e_PlayerRole_RB) builder.AddPlayer(-0.184212, -0.105680, e_PlayerRole_CM) builder.AddPlayer(-0.267574, 0.000000, e_PlayerRole_CM) builder.AddPlayer(-0.184212, 0.10568, e_PlayerRole_CM) builder.AddPlayer(-0.010000, -0.21610, e_PlayerRole_LM) builder.AddPlayer(0.000000, 0.020000, e_PlayerRole_CF) builder.AddPlayer(0.000000, -0.020000, e_PlayerRole_RM) builder.SetTeam(second_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK) builder.AddPlayer(-0.422000, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.500000, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.500000, 0.063559, e_PlayerRole_CB) builder.AddPlayer(-0.422000, 0.195760, e_PlayerRole_RB) builder.AddPlayer(-0.184212, -0.105680, e_PlayerRole_CM) builder.AddPlayer(-0.267574, 0.000000, e_PlayerRole_CM) builder.AddPlayer(-0.184212, 0.10568, e_PlayerRole_CM) builder.AddPlayer(-0.010000, -0.21610, e_PlayerRole_LM) builder.AddPlayer(-0.050000, 0.000000, e_PlayerRole_CF) builder.AddPlayer(-0.010000, 0.216102, e_PlayerRole_RM)
null
22,917
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = True builder.SetBallPosition(0.7, -0.28) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.7, 0.0, e_PlayerRole_CB) builder.AddPlayer(0.7, -0.3, e_PlayerRole_CB) builder.SetTeam(Team.e_Right) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(-0.75, 0.3, e_PlayerRole_CB)
null
22,918
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = True builder.SetBallPosition(0.02, 0.0) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.0, 0.0, e_PlayerRole_CB) builder.SetTeam(Team.e_Right) builder.AddPlayer(1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.12, 0.2, e_PlayerRole_LB) builder.AddPlayer(0.12, 0.1, e_PlayerRole_CB) builder.AddPlayer(0.12, 0.0, e_PlayerRole_CM) builder.AddPlayer(0.12, -0.1, e_PlayerRole_CB) builder.AddPlayer(0.12, -0.2, e_PlayerRole_RB)
null
22,919
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = True builder.SetBallPosition(0.62, 0.0) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.6, 0.0, e_PlayerRole_CM) builder.AddPlayer(0.7, 0.2, e_PlayerRole_CM) builder.AddPlayer(0.7, -0.2, e_PlayerRole_CM) builder.SetTeam(Team.e_Right) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(-0.75, 0.0, e_PlayerRole_CB)
null
22,920
from . import * def build_scenario(builder): builder.config().game_duration = 500 builder.config().right_team_difficulty = 0.0 builder.config().left_team_difficulty = 0.0 builder.config().deterministic = False if builder.EpisodeNumber() % 2 == 0: first_team = Team.e_Left second_team = Team.e_Right else: first_team = Team.e_Right second_team = Team.e_Left builder.SetTeam(first_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK) builder.SetTeam(second_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK)
null
22,921
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = True builder.SetBallPosition(0.26, -0.11) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(-0.672, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.75, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.75, 0.063559, e_PlayerRole_CB) builder.AddPlayer(-0.672, 0.19576, e_PlayerRole_RB) builder.AddPlayer(-0.434, -0.10568, e_PlayerRole_CM) builder.AddPlayer(-0.434, 0.10568, e_PlayerRole_CM) builder.AddPlayer(0.5, -0.3161, e_PlayerRole_CM) builder.AddPlayer(0.25, -0.1, e_PlayerRole_LM) builder.AddPlayer(0.25, 0.1, e_PlayerRole_RM) builder.AddPlayer(0.35, 0.316102, e_PlayerRole_CF) builder.SetTeam(Team.e_Right) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.128, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.4, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.4, 0.063559, e_PlayerRole_CB) builder.AddPlayer(0.128, -0.19576, e_PlayerRole_RB) builder.AddPlayer(0.365, -0.10568, e_PlayerRole_CM) builder.AddPlayer(0.282, 0.0, e_PlayerRole_CM) builder.AddPlayer(0.365, 0.10568, e_PlayerRole_CM) builder.AddPlayer(0.54, -0.3161, e_PlayerRole_LM) builder.AddPlayer(0.51, 0.0, e_PlayerRole_RM) builder.AddPlayer(0.54, 0.316102, e_PlayerRole_CF)
null
22,922
from . import * def build_scenario(builder): builder.config().game_duration = 3000 builder.config().right_team_difficulty = 0.05 builder.config().deterministic = False if builder.EpisodeNumber() % 2 == 0: first_team = Team.e_Left second_team = Team.e_Right else: first_team = Team.e_Right second_team = Team.e_Left builder.SetTeam(first_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK) builder.AddPlayer(0.000000, 0.020000, e_PlayerRole_RM) builder.AddPlayer(0.000000, -0.020000, e_PlayerRole_CF) builder.AddPlayer(-0.422000, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.500000, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.500000, 0.063559, e_PlayerRole_CB) builder.AddPlayer(-0.422000, 0.195760, e_PlayerRole_RB) builder.AddPlayer(-0.184212, -0.10568, e_PlayerRole_CM) builder.AddPlayer(-0.267574, 0.000000, e_PlayerRole_CM) builder.AddPlayer(-0.184212, 0.105680, e_PlayerRole_CM) builder.AddPlayer(-0.010000, -0.21610, e_PlayerRole_LM) builder.SetTeam(second_team) builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK) builder.AddPlayer(-0.050000, 0.000000, e_PlayerRole_RM) builder.AddPlayer(-0.010000, 0.216102, e_PlayerRole_CF) builder.AddPlayer(-0.422000, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.500000, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.500000, 0.063559, e_PlayerRole_CB) builder.AddPlayer(-0.422000, 0.195760, e_PlayerRole_RB) builder.AddPlayer(-0.184212, -0.10568, e_PlayerRole_CM) builder.AddPlayer(-0.267574, 0.000000, e_PlayerRole_CM) builder.AddPlayer(-0.184212, 0.105680, e_PlayerRole_CM) builder.AddPlayer(-0.010000, -0.21610, e_PlayerRole_LM)
null
22,923
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = True builder.SetBallPosition(0.26, -0.11) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(-0.672, -0.19576, e_PlayerRole_LB) builder.AddPlayer(-0.75, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.75, 0.063559, e_PlayerRole_CB) builder.AddPlayer(-0.672, 0.19576, e_PlayerRole_RB) builder.AddPlayer(-0.434, -0.10568, e_PlayerRole_CM) builder.AddPlayer(-0.434, 0.10568, e_PlayerRole_CM) builder.AddPlayer(0.5, -0.3161, e_PlayerRole_CM) builder.AddPlayer(0.25, -0.1, e_PlayerRole_LM) builder.AddPlayer(0.25, 0.1, e_PlayerRole_RM) builder.AddPlayer(0.35, 0.316102, e_PlayerRole_CF) builder.SetTeam(Team.e_Right) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.128, -0.19576, e_PlayerRole_LB) builder.AddPlayer(0.4, -0.06356, e_PlayerRole_CB) builder.AddPlayer(-0.4, 0.063559, e_PlayerRole_CB) builder.AddPlayer(0.128, -0.19576, e_PlayerRole_RB) builder.AddPlayer(0.365, -0.10568, e_PlayerRole_CM) builder.AddPlayer(0.282, 0.0, e_PlayerRole_CM) builder.AddPlayer(0.365, 0.10568, e_PlayerRole_CM) builder.AddPlayer(0.54, -0.3161, e_PlayerRole_LM) builder.AddPlayer(0.51, 0.0, e_PlayerRole_RM) builder.AddPlayer(0.54, 0.316102, e_PlayerRole_CF)
null
22,924
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = False builder.SetBallPosition(0.99, 0.41) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(1.0, 0.42, e_PlayerRole_LB) builder.AddPlayer(0.7, 0.15, e_PlayerRole_CB) builder.AddPlayer(0.7, 0.05, e_PlayerRole_CB) builder.AddPlayer(0.7, -0.05, e_PlayerRole_RB) builder.AddPlayer(0.0, 0.0, e_PlayerRole_CM) builder.AddPlayer(0.6, 0.35, e_PlayerRole_CM) builder.AddPlayer(0.8, 0.07, e_PlayerRole_CM) builder.AddPlayer(0.8, -0.03, e_PlayerRole_LM) builder.AddPlayer(0.8, -0.13, e_PlayerRole_RM) builder.AddPlayer(0.7, -0.3, e_PlayerRole_CF) builder.SetTeam(Team.e_Right) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(-0.75, -0.18, e_PlayerRole_LB) builder.AddPlayer(-0.75, -0.08, e_PlayerRole_CB) builder.AddPlayer(-0.75, 0.02, e_PlayerRole_CB) builder.AddPlayer(-1.0, -0.1, e_PlayerRole_RB) builder.AddPlayer(-0.8, -0.25, e_PlayerRole_CM) builder.AddPlayer(-0.88, -0.07, e_PlayerRole_CM) builder.AddPlayer(-0.88, 0.03, e_PlayerRole_CM) builder.AddPlayer(-0.88, 0.13, e_PlayerRole_LM) builder.AddPlayer(-0.75, 0.25, e_PlayerRole_RM) builder.AddPlayer(-0.2, 0.0, e_PlayerRole_CF)
null
22,925
from . import * def build_scenario(builder): builder.config().game_duration = 400 builder.config().deterministic = False builder.config().offsides = False builder.config().end_episode_on_score = True builder.config().end_episode_on_out_of_play = True builder.config().end_episode_on_possession_change = True builder.SetBallPosition(0.02, 0.0) builder.SetTeam(Team.e_Left) builder.AddPlayer(-1.0, 0.0, e_PlayerRole_GK) builder.AddPlayer(0.0, 0.0, e_PlayerRole_CB) builder.SetTeam(Team.e_Right) builder.AddPlayer(1.0, 0.0, e_PlayerRole_GK)
null