def charge_rent(player_id): """Entry point for a player to be charged rent and property owner gains rent amount """ games = get_games() game_id = None # Access the game the player is playing in # and the position the player is on the board with Player(player_id) as player: position = player.board_position for game in games: if player.username in games[game]: game_id = game break # Accesses owner and rent of property; if the games's # current turn's player doesn't own it, charge the player # and increase the property owner's balance with Property(position, game_id) as property_: owner_id = property_.owner rent = property_.rent with Player(owner_id) as owner: if owner.uid != player_id: player.balance -= rent owner.balance += rent
def main(): library_manager = LibraryManager() player = Player(library_manager) listener = WebListener(player, library_manager) player.play()
def add_house(source=sys.stdin, output=sys.stdout): """Adds a house to a property. """ output.write('Content-Type: application/json\n\n') request = json.load(source) player_id = request["player_id"] property_name = request["property_name"] property_position = get_position_by_name(player_id, property_name) position = property_position["property_position"] games = get_games() houses = None with Player(player_id) as player: for game in games: if player.username in games[game]: game_id = game break with Property(position, game_id) as prop: if prop.houses < 4 and prop.hotels == 0: prop.houses += 1 houses = prop.houses player.balance -= prop.house_price else: prop.houses = 0 prop.hotels = 1 houses = 5 player.balance -= prop.house_price json.dump({"house_number": houses, "property_position": position}, output)
def increment_turn(source=sys.stdin, output=sys.stdout): """Entry point for the client ending their turn """ output.write('Content-Type: application/json\n\n') request = json.load(source) player_id = request["player_id"] games = get_games() with Player(player_id) as player: for game in games: if player.username in games[game]: game_id = game break with Game(game_id) as game: turn = game.current_turn if turn == len(game.players) - 1: turn = 0 else: turn += 1 game.current_turn = turn is_bankrupt(player_id) json.dump({"turn": "turn_over"}, output)
def check_new_turn(output_stream, old_turn, new_turn, turn_order): """Checks if the turn has changed to a different player and sends an SSE event if it has. Arguments: old_turn: An int representing the current position in the playing queue. new_turn: An int representing the latest (aka. "new") position in the playing queue. turn_order: A dictionary representing mapping player ids to the player's position in the playing queue. Returns: An int representing the current position of the playing queue. """ if new_turn != old_turn: for uid, turn_pos in turn_order.items(): if turn_pos == new_turn: player = Player(uid) output_event(output_stream, 'playerTurn', { 'name': player.username, 'id': player.uid }) return new_turn
def check_property_ownership(output_stream, game_id, old_properties): """Issue events if the ownership of any properties has changed. Arguments: game_id: The id of the game the events are being issued for. Returns: The current property ownership data, as a dictionary where the keys are property positions, and the values are owner player ids. """ owners = owned_property_positions(game_id) new_properties = {} for positions in owners.values(): for position in positions: with Property(position, game_id) as prop: with Player(prop.owner) as player: new_properties[position] = { 'name': prop.name, 'owner': { 'id': player.uid, 'name': player.username, }, } if old_properties != new_properties: generate_ownership_events(output_stream, old_properties, new_properties) return new_properties
def register_player(self, name) -> Player: if self.get_player_by_name(name) is not None: raise CoupException(f"{name} is already in the game") player = Player(name) self.players[player.id] = player return player
def return_card_to_deck(self, player: Player, card_id): card = player.pop_card(card_id) if not card: raise CoupException(f"Player {player.name} does not have card id {card_id}") card.visible = False self.deck.append(card) self.shuffle_deck()
async def get_rooms(body: RoomBody) -> RoomResponse: # TODO: load user_id from session player = Player(body.nickname) users[str(player.id)] = player room = None for _room in rooms.values(): if _room.type == "public" and not _room.is_full: _room.register_player(player) room = _room break if not room: room = Room(body.type) room.register_player(player) rooms[str(room.id)] = room return {"room_id": room.id, "player": player.to_schema()}
def jail_player(player_id): """Function that sends a player to jail Args: player_id(int) the player's unique id. """ with Player(player_id) as player: player.board_position = -1 player.jail_state = 'in_jail'
def leave_jail(player_id): """Function that removes a player from jail Args: player_id(int) the player's unique id. """ with Player(player_id) as player: player.jail_state = 'not_in_jail' player.board_position = 10
def pay_tax(player_id, tax_payable): """Deduct tax payable from player's balance. Arguments: player_id: An int representing the player_id. tax_payable: An int representing the money to deduct from player. """ with Player(player_id) as player: player.balance -= tax_payable
def add_player(player_id, game_id): """Adds a player to a game.""" with Player(player_id) as player: with Game(game_id) as game: players = game.players players.append(player_id) game.players = players if str(game.state) == 'waiting': player.turn_position = len(game.players) - 1 else: pass
def pay_to_leave_jail(source=sys.stdin, output=sys.stdout): """Function that removes a player from jail for a fee """ output.write("Content-Type: text/plain\n") output.write("\n") request = json.load(source) player_id = request["player_id"] with Player(player_id) as player: player.balance -= 50 player.jail_state = 'not_in_jail' player.board_position = 10 json.dump({player_id: 'not_in_jail'}, output)
def generate_game_end_event(output_stream, game): """Generates a gameEnd event. Arguments: output_stream: The stream to which the event should be written. game: The Game object to check. """ winner = Player(game.players[0]) output_event(output_stream, 'gameEnd', { 'winner': { 'name': winner.username, 'id': winner.uid, }, })
def buy_property_db(game, user, position): """Changes a property's state to 'owned' in the database. Arguments: game: The id of the game the property should be bought in. user: The id of the user to buy the property for. position: The position of the property to buy. """ with Property(position, game) as prop: prop.property_state = 'owned' prop.owner = user with Player(user) as player: player.balance -= prop.price
def start_game(self): self.board = Board() self.board.initialize_board() self.cures = [False] * 4 self.lost = False self.infection_deck = InfectionDeck() self.infection_deck.init_infection() self.infection_deck.shuffle() for i in range(3): for j in range(3): card = self.infection_deck.draw_card() self.board.locations[card.city.id_].infect(amount=(3 - i)) print(str(self.board.locations[card.city.id_].infections)) infections = [location.infections for location in self.board.locations] infections_zip = list(zip(*infections)) self.infection_sum = list(map(sum, infections_zip)) self.player_deck = PlayerDeck(self.difficulty + 2) self.player_deck.init_player_deck() self.player_deck.shuffle() self.outbreaks = 0 roles = list(Player.ROLES.keys()) shuffle(roles) self.players = list() for j in range(self.num_players): role = roles.pop() player = Player(j, role, self.board) for j in range(2): player.add_card(self.player_deck.draw_card()) self.players.append(player) self.player_deck.add_epidemics() self.turn_of = 0 self.remaining_actions = 4 max_pop = 0 for player in self.players: for card in player.cards: if card.city.population > max_pop: self.turn_of = player.id_ max_pop = card.city.population
def player_roll_dice(source=sys.stdin, output=sys.stdout): """Rolls two dice for a player, appends there rolls to the database, updates their position and the current game turn. Checks if the user is in jail and does not increment their position if so. Also has a check for the board position 30(go to jail) and sends the player to the jail position if so. """ output.write('Content-Type: application/json\n\n') request = json.load(source) player_id = request["user_id"] number_of_squares = 40 pass_go_amount = 200 games = get_games() rolls = [] player_board_position = 0 with Player(player_id) as player: for game in games: if player.username in games[game]: game_id = game in_jail = player.jail_state break with Game(game_id) as game: if game.current_turn == player.turn_position: rolls = roll_two_dice() player.rolls.append(rolls) if in_jail == 'not_in_jail': player.board_position += sum(rolls) if player.board_position == 30: player.board_position = -1 player.jail_state = 'in_jail' else: if rolls[0] == rolls[1]: player.jail_state = 'not_in_jail' player.board_position = 10 if player.board_position >= number_of_squares: player.balance += pass_go_amount player.board_position -= number_of_squares player_board_position = player.board_position card_details = check_position(player_id, player_board_position) json.dump({"your_rolls": rolls, "card_details": card_details}, output)
def start_game_push(output_stream, turn_order): """Generates an event for to update the details table at game start. Compares two dictionaries and outputs a playerBalance server-sent event if the two dicts differ. Along with the event is JSON containing the difference between the two dicts. """ for uid, turn_pos in turn_order.items(): if turn_pos == 0: player = Player(uid) output_event(output_stream, 'playerTurn', { 'name': player.username, 'id': player.uid }) generate_player_balance_event(output_stream, {}, { 1: 1500, 2: 1500, 3: 1500, 4: 1500 })
def __init__(self, screen, faction="Dark", actions=None, players=None, artworks=None, spells=None, rooms=None): self.screen = screen self.faction = faction self.actions = actions self.players = players or { 'Dark': Player('Dark'), 'Light': Player('Light'), } self.game_over = False self.check_game_over = True # IDEA: what if each Room inits it's spells and each a_spell inits its # artworks and neither are stored directly on board self.artworks = artworks or [ Artwork('Priestess'), Artwork('Imposter'), Artwork('Opportunist'), Artwork('Usurper'), Artwork('Stonemason'), Artwork('Locksmith'), Artwork('Yeoman'), ] self.spells = spells or [ Priestess(self.artworks[0]), Purify(), Imposter(self.artworks[1]), Imprint(), Opportunist(self.artworks[2]), Overwork(), Usurper(self.artworks[3]), Upset(), Stonemason(self.artworks[4]), Shovel(), Locksmith(self.artworks[5]), Leap(), Yeoman(self.artworks[6]), Yoke(), ] self.rooms = rooms or [ Room('Pink', np.matrix([3,-4,1]), [ np.matrix([-1,0,1]), np.matrix([-1,1,0]), np.matrix([1,0,-1]) ], self.spells[0], self.spells[1] ), Room('Indigo', np.matrix([3,-3,0]), [ np.matrix([1,0,-1]), np.matrix([2,0,-2]), np.matrix([3,0,-3]) ], self.spells[2], self.spells[3] ), Room('Orange', np.matrix([2,-2,0]), [ np.matrix([0,1,-1]), np.matrix([1,0,-1]), np.matrix([1,1,-2]) ], self.spells[4], self.spells[5] ), Room('Umber', np.matrix([4,-2,-2]), [ np.matrix([0,1,-1]), np.matrix([-1,2,-1]), np.matrix([-2,2,0]) ], self.spells[6],self.spells[7] ), Room('Sapphire', np.matrix([0,0,0]), [ np.matrix([1,0,-1]), np.matrix([1,1,-2]), np.matrix([2,1,-3]) ], self.spells[8], self.spells[9] ), Room('Lime', np.matrix([1,2,-3]), [ np.matrix([1,0,-1]), np.matrix([2,0,-2]), np.matrix([2,1,-3]) ], self.spells[10], self.spells[11] ), Room('Yellow', np.matrix([0,3,-3]), [ np.matrix([0,-1,1]), np.matrix([-1,1,0]), np.matrix([1,0,-1]) ], self.spells[12], self.spells[13] ) ]
def activate_card(player_id, game_id, card_landed_on): # pylint: disable=too-many-locals # pylint: disable=too-many-branches """Read a chance or community chest card that the player landed on. Arguments: player_id: An int representing the current player id. game_id: An int representing the current game id. card_landed_on: An int representing the type of card the player has activated """ # Check if card is chance or community chest if card_landed_on == "chest": card_table_id = randint(0, LAST_CHEST_INDEX_IN_TABLE) else: card_table_id = randint(LAST_CHEST_INDEX_IN_TABLE + 1, LAST_CHANCE_INDEX_IN_TABLE) # Dive into database to get the card details card_details = get_card_details(card_table_id) # Check what type of chance card it is card_type = card_details["operation"] # Get the card description, this is what's sent to the client card_description = card_details["description"] # Get value # This card_value is unique in that it represents different things # depending on the card_type. See below comments for more information card_value = card_details["operation_value"] # If it's a "move_specific" type of chance card if card_type == "move_specific": # Update the player position in players table with "chance" value with Player(player_id) as player: # Check if the card wants the player to move back some spaces # or simply *jump* to a specific space on the board if card_value < 0: # The card value here indicates how many spaces to move back player.board_position += card_value else: # The card value here indicates the board position to move to player.board_position = card_value # If it's a "pay_per_house" type of chance card elif card_type == "pay_per_house": # Variable to store total houses owned (hotels are worth four houses) total_houses = 0 # Get a *list* of all properties owned by the current player this_player_properties = get_properties(player_id) # Go through each property for property_position in this_player_properties: with Property(game_id, property_position) as property_: total_houses += property_.houses total_houses += (property_.hotels * 4) # The card_value here indicates how much to pay for a single house to_pay = total_houses * card_value with Player(player_id) as player: player.balance -= to_pay # If it's a "get_money" type of chance card elif card_type == "get_money": with Player(player_id) as player: # The card_value here indicates how much money to add to balance player.balance += card_value # If it's a "pay_bank" type of chance card elif card_type == "pay_bank": with Player(player_id) as player: # The card_value here indicates how much to deduct from balance player.balance -= card_value elif card_type == "collect_from_opponents": # Get a list of players in this game players_in_game = [] with Game(game_id) as game: players_in_game = game.players # Iterate through each player and deduct from their balance if they # are not the current (aka. this) player for id_ in players_in_game: with Player(id_) as player: if int(player_id) != id_: # card_value here indicates the amount to deduct from # opponent's balance player.balance -= card_value else: # Add to this player's balance the total amount deducted # from the opponents. # Note that the amount to add to this player's balance can # be found by simply multiplying the amount to deduct per # opponent (i.e. card_value) by the *number* of opponents player.balance += (card_value * (len(players_in_game) - 1)) return card_description
def open_card(player: Player, card_id: int): card = player.get_card(card_id) if not card: raise CoupException(f"Player {player.name} does not have card id {card_id}") card.visible = True
def take_card_from_deck(self, player: Player): if len(self.deck) <= 0: raise CoupException("Deck is empty") card = self.deck.pop() player.add_card(card)
def is_bankrupt(player_id): """Player is checked if they are bankrupt or not""" player = Player(player_id) if player.balance < 0: player_remove(player)
def test_deserialize(self, board, player, serialized): card = Card(id_=0, city=board.locations[0]) player.add_card(card) assert Player.deserialize(data=serialized, board=board) == player
def player(self, board): player = Player(id_=1, role=1, board=board) return player
import random as rd from backend.player import Player if __name__ == "__main__": print("Welcome to the Bellagio !") # Constante choice = ["c", "n", "color", "number"] color = ["red", "black"] exit = ["y", "n", "yes", "no"] # Création du joueur player = Player("", 1000) player.generate_player() player_name = player.player_name print("Bonjourno", player_name, "!") play = True while play: # Choix du joueur. player_choice = 0 while player_choice not in choice: player_choice = input( "What's your choice ? [Color/Number] ").lower() # Le joueur choisit une couleur. if player_choice == "c" or player_choice == "color": while player_choice not in color: player_choice = input("Which color ? [Black/Red] ").lower() if player_choice == "r": player_choice = "red"
def add_player(self, name, is_host=False): if name in self.players: raise PlayerAlreadyExistsException self.players[name] = Player(name, is_host) self.check_ready_to_start()