def start_game(self): with open("./GameData/Text/story.json", encoding="utf-8") as infile: data = json.load(infile) self.intro = data['intro'] print(self.intro) directory = "./GameData/RoomTypes" # Iterate through room JSON files in directory and # initialize with Room class constructor using file name for fileName in os.listdir(directory): if fileName.endswith(".json"): room_path = directory + "/" + fileName cur_room = Room.from_file_name(room_path) # Set starting location if cur_room.name == "Serene Forest - South": cur_room.get_desc() cur_room.toggle_visit() self.location = cur_room self.rooms.append(cur_room) else: continue self.player = Player(None) self.play_game()
def _get_player_state(self, player: Player): """ Determines the state of the given player in the game. :return: the state of the player :rtype: PlayerState """ # short-circuit if the player hasn't made their first move, yet if player.tile is None: return PlayerState.ALIVE adjacent = self.board.get_tile_at(*get_coordinates_in_direction( player.tile.x, player.tile.y, player.port.direction)) if adjacent is not None and adjacent is not OutOfBounds: # advance the player onto the adjacent tile and recur player.tile = adjacent player.port = adjacent.get_exit_port(player.port.neighbor) return self._get_player_state(player) elif adjacent is OutOfBounds: death_tile = (player.tile, player.port) if death_tile in self.start_positions: # a player has collided if they end at another's start position return PlayerState.COLLIDED return PlayerState.DEAD elif adjacent is None: return PlayerState.ALIVE
def load_game(self): save_file = Path("./Saves/gameSave.json") if save_file.is_file(): with open("./Saves/gameSave.json") as infile: data = json.load(infile) # Receive JSON lists of data player_data = json.loads(data["player"]) location_data = json.loads(data["location"]) room_data = json.loads(data["rooms"]) # Call constructors for initializing using JSON data self.location = Room( location_data['name'], location_data['long_desc'], location_data['short_desc'], location_data['prior_visit'], location_data['connections'], location_data['inventory'], location_data['feature_list'], True) self.player = Player(player_data['inventory']) # Call constructors for each object in room list from JSON # and append to rooms list in Game for room in room_data: cur_room = Room(room['name'], room['long_desc'], room['short_desc'], room['prior_visit'], room['connections'], room['inventory'], room['feature_list'], True) self.rooms.append(cur_room) self.play_game() else: print("No save file found. Creating a new game...") self.start_game()
def test_player_failed_strategy() -> None: bs = BoardState() p = Player(Strategy()) r = p.generate_move([], bs) assert r.error() == "Strategy does not implement method generate_move!" r2 = p.generate_first_move([], bs) assert r2.error( ) == "Strategy does not implement method generate_first_move!"
def createNewPlayer(self, name): """ Create a New Player """ trainer = TrainerFactory.createNewTrainer("Pokemon Trainer", name) player = Player(trainer, "Player Bedroom - Pallet Town", 5, 5) self.setLastPlayer() playerElement = SubElement(self.rootElement, Tags.playerTag) trainerElement = SubElement(playerElement, Tags.trainerTag) nameElement = SubElement(trainerElement, Tags.nameTag) nameElement.text = trainer.name titleElement = SubElement(trainerElement, Tags.titleTag) titleElement.text = trainer.title zoneElement = SubElement(playerElement, Tags.zoneTag) zoneNameElement = SubElement(zoneElement, Tags.nameTag) zoneNameElement.text = player.zone rowElement = SubElement(zoneElement, Tags.rowTag) rowElement.text = str(player.row) columnElement = SubElement(zoneElement, Tags.columnTag) columnElement.text = str(player.column) lastPlayerElement = SubElement(playerElement, Tags.lastTag) lastPlayerElement.text = "true" self.saveXMLTree() return player
async def _dispatcher(self, websocket, path): player = Player(websocket) try: async for message in player.socket: data = json.loads(message) logging.info(self.MSG_RECEIVED + message) if player.state == PlayerState.USERNAME_SELECTION: if 'username' in data: name = data['username'] if self._is_valid_name(name): player.name = name self.register_player(player) await self.send_valid_username(player) else: await self.send_invalid_username(player) elif player.state == PlayerState.IN_LOBBY: if 'challengePlayer' in data: opponent_name = data['challengePlayer'] if self.name_in_use( opponent_name ) and opponent_name.lower() != player.lower_name: await self.send_challenge_by_name( player, opponent_name) else: pass elif 'joinQueue' in data: do_join = data['joinQueue'] if do_join: await self.join_queue(player) elif 'leaveQueue' in data: self.leave_queue(player) elif player.state == PlayerState.IN_GAME: if 'move' in data: move = data['move'] await self.handle_turn(player, move) finally: await self.disconnect_player(player)
def render_results(inputs): """ Performs placements and returns their results. """ placements = [PlacementFactory.create(x) for x in inputs] players = [] for i, placement in enumerate(placements): p = Player(name=str(i)) p.color = placement.color players.append(p) ref = Referee(players) ref.add_placements(placements) return observer.render_board(ref.board, ref.players)
def createPlayer(): #create a new player money = 0 new_player = Player( "P" + str(len(players) + 1)) #create a player with a new label while money <= 0: #set the money on the player try: money = int( input("How much money does %s have " % new_player.label)) #get input from the user if new_player.setMoney(money): break #try to put the money in the Player Objecet if it meets parameters except ValueError: print("Not a Number!") #money value must be some integer players.append(new_player)
def render_intermediate(inputs, requested): placements = [PlacementFactory.create(x) for x in inputs + [requested[0]]] players = [] for i, placement in enumerate(placements): p = Player(name=str(i)) p.color = placement.color players.append(p) ref = Referee(players) ref.add_placements(placements[:-1]) next_move = placements[-1] ref.players_by_color[next_move.color].tile_hand = [ Tile.Builder.build(i).readonly() for i in requested[1:] ] ref.players_by_color[next_move.color].strategy = Predetermined(next_move) ref.turn_index = ref.turn_order.index( ref.players_by_color[next_move.color]) return observer.render_board(ref.board, ref.players, ref.turn)
def getLastPlayer(self): """ Return the last Player played as """ playerElement = self.getLastPlayerElement() if playerElement is None: return None trainer = self.loadTrainerFromPlayerElement(playerElement) zoneElement = playerElement.find(Tags.zoneTag) zoneName = zoneElement.findtext(Tags.nameTag) row = int(zoneElement.findtext(Tags.rowTag)) column = int(zoneElement.findtext(Tags.columnTag)) return Player(trainer, zoneName, row, column)
def test_admin_by_function() -> None: tobs = TournamentObserver() admin = Administrator(SimpleBracketStrategy()) admin.add_observer(tobs) pid_to_idx = {} for idx in range(20): pid_r = admin.add_player(Player(SecondS())) assert pid_r.is_ok() pid_to_idx[pid_r.value()] = idx time.sleep(0.1) admin.run_tournament()
def create_players(player_info: JSON) -> List[Tuple]: all_players = [] for spec in player_info: if not any(spec["name"] == player[0] for player in all_players): Strat = None try: Strat = get_strategy_component(spec["strategy"]) except Exception: continue if Strat != None: all_players.append((spec["name"], Player(Strat()))) return all_players
def test_admin_10_second_s() -> None: # Assert that it runs in a reasonable amount of time with timeout(seconds=10): admin = Administrator(SimpleBracketStrategy()) pid_to_idx = {} for idx in range(10): pid_r = admin.add_player(Player(SecondS())) assert pid_r.is_ok() pid_to_idx[pid_r.value()] = idx winners_r = admin.run_tournament() assert winners_r.is_ok() real_winners = winners_r.value()[0][0] assert len(real_winners) assert set([pid_to_idx[pid] for pid in real_winners]) == {1, 5}
def test_referee_crashing_player() -> None: cp_exception_init = CrashingPlayer(True, True) cp_error_init = CrashingPlayer(False, True) cp_exception_inter = CrashingPlayer(True, False) cp_error_inter = CrashingPlayer(False, False) p = Player(FirstS()) ref = make_ref() assert ref.set_players([ cp_error_init, cp_exception_init, cp_error_inter, cp_exception_inter, p ]).assert_value() == ["white", "black", "red", "green", "blue"] ref.set_tile_iterator(deterministic_tile_iterator()) r = ref.run_game() assert r.is_ok() assert r.value() == ([{"blue"}], {"green", "red", "black", "white"})
def test_set_players_error() -> None: ref = make_ref() r = ref.set_players([]) assert r.is_error() assert r.error() == "there must be between 3 and 5 players, not 0." r = ref.set_players([Player(FirstS())] * 6) assert r.is_error() assert r.error() == "there must be between 3 and 5 players, not 6." r = ref.set_players([Player(FirstS())] * 4) assert r.is_error() assert ( r.error() == "the given set of players contains duplicates (or players that do not implement __hash__, __eq__)" ) r = ref.set_players([Player(FirstS()), Player(FirstS()), Player(FirstS())]) assert r.is_ok() assert r.value() == ["white", "black", "red"] r = ref.set_players([Player(FirstS()), Player(FirstS()), Player(FirstS())]) assert r.is_error() assert r.error() == "players have already been set for this game."
def test_admin_5_second_s() -> None: admin = Administrator(SimpleBracketStrategy()) pid_to_idx = {} players = [] for idx in range(5): player = Mock(wraps=Player(SecondS())) players.append(player) pid_r = admin.add_player(player) assert pid_r.is_ok() pid_to_idx[pid_r.value()] = idx winners_r = admin.run_tournament() assert winners_r.is_ok() real_winners = winners_r.value()[0][0] assert set([pid_to_idx[pid] for pid in real_winners]) == {0, 2} assert players[0].notify_won_tournament.call_args_list == [call(True)] assert players[1].notify_won_tournament.call_args_list == [call(False)] assert players[2].notify_won_tournament.call_args_list == [call(True)] assert players[3].notify_won_tournament.call_args_list == [call(False)] assert players[4].notify_won_tournament.call_args_list == [call(False)]
def test_admin_crashing_player() -> None: admin = Administrator(SimpleBracketStrategy()) cp_exception_init = CrashingPlayer(True, True) assert admin.add_player(cp_exception_init).is_ok() cp_error_init = CrashingPlayer(False, True) assert admin.add_player(cp_error_init).is_ok() cp_exception_inter = CrashingPlayer(True, False) assert admin.add_player(cp_exception_inter).is_ok() cp_error_inter = CrashingPlayer(False, False) assert admin.add_player(cp_error_inter).is_ok() p = Player(FirstS()) r = admin.add_player(p) assert r.is_ok() real_player_pid = r.value() winners_r = admin.run_tournament() assert winners_r.is_ok() real_winners = winners_r.value()[0][0] assert real_winners == {real_player_pid}
def game_setup(): player_name = '' player_balance = 0 while True: try: player_name = input("Please enter your name: ") player_balance = int(input("Please enter your balance: ")) break except ValueError: print("Enter your balance in number!") continue p1 = Player(player_name.capitalize(), player_balance) print("Thank you for the details.\nYour dealer for the game will be: {}. \n" "The balance for {} is USD {}. " "Let us begin!".format(d1.get_dealer_name(), p1.player_name, p1.money_balance)) start_game(p1)
def run_game(names): players = [Player(name=name, age=i) for i, name in enumerate(names)] ref = Referee(players=players) while ref.run_turn(): pass overall_losers, overall_winners = [], [] for round_number in reversed(sorted(ref.dead.keys())): results = ref.dead[round_number] winners = [] for player, reason in results: (overall_losers if reason is PlayerState.EJECTED else winners).append(player.name) if winners: overall_winners.append(winners) return {"losers": overall_losers, "winners": overall_winners}
def make_players(num_players: int) -> List[PlayerInterface]: return [Player(FirstS()) for _ in range(num_players)]
def run_game(self): log.info("started run game") soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: soc.connect((self.host, self.port)) log.info("connected") except: log.error("Connection error") sys.exit() is_active = True strategy = None if self.strategy_name.lower() == "dumb": strategy = Dumb() elif self.strategy_name.lower() == "second": strategy = Second() player = Player(self.player_name, strategy) while is_active: data = soc.recv(5120).decode("utf8") if not data: exit(code=0) server_message = json.loads(data) try: msg_type = ServerMessage(server_message["type"]) except ValueError: log.error( f"{server_message['type']} is not a valid message type") continue if msg_type is ServerMessage.ASK_FOR_PLAYER_INFO: # server should ask for join then send join request # fmt: off soc.sendall( json.dumps({ "type": ClientMessage.JOIN.value, "name": self.player_name, "strategy": self.strategy_name, }).encode("utf8")) # fmt: on if msg_type is ServerMessage.ASK_FOR_MOVE: # convert the json board into a Board # convert the json tiles into Tiles board = server_message["board"] real_board = ReadOnlyBoard.json_to_board(board) # player.receive_gamestate(real_board) # a list of tiles, call json to tile on each real_tiles = [ ReadOnlyTile.json_to_tile(tile) for tile in server_message["tiles"] ] player.receive_tiles(real_tiles) move = player.next_move() # fmt: off soc.sendall( json.dumps({ "type": ClientMessage.MOVE_REQUEST.value, **move.to_json() }).encode("utf8")) # fmt: on if msg_type is ServerMessage.RECEIVE_COLOR: player.receive_color(Color(server_message["color"])) if msg_type is ServerMessage.MOVE_ACCEPTED: player.receive_move_success() if msg_type is ServerMessage.EJECTED: player.receive_move_failure(server_message["reason"]) if msg_type is ServerMessage.RECEIVE_GAME_STATE: # their own message type and the interface for player should # support receiving them player.tile = (ReadOnlyTile.json_to_tile( server_message["tile"]) if server_message["tile"] is not None else None) player.port = (Port[server_message["port"]] if server_message["port"] is not None else None) player.receive_gamestate( ReadOnlyBoard.json_to_board(server_message["board"]), PlayerState[server_message["state"]], server_message["players"], )
def test_player_calls_observers() -> None: bs = BoardState() lo = LoggingPlayerObserver() p = Player(FirstS()) p.add_observer(lo) p.set_color("red") assert lo.set_colors == ["red"] p.set_color("green") assert lo.set_colors == ["red", "green"] assert p.generate_first_move( [index_to_tile(3), index_to_tile(4), index_to_tile(5)], bs).is_ok() assert lo.initial_move_offereds == [ ([index_to_tile(3), index_to_tile(4), index_to_tile(5)], bs) ] assert lo.initial_move_playeds == [( [index_to_tile(3), index_to_tile(4), index_to_tile(5)], bs, InitialMove(BoardPosition(1, 0), index_to_tile(5), Port.RightTop, "green"), )] assert p.generate_move([index_to_tile(10), index_to_tile(11)], bs).is_ok() assert lo.intermediate_move_offereds == [ ([index_to_tile(10), index_to_tile(11)], bs) ] assert lo.intermediate_move_playeds == [( [index_to_tile(10), index_to_tile(11)], bs, IntermediateMove(index_to_tile(10), "green"), )] gr = ([{"red"}, {"black", "green"}], {"white"}) p.game_result(gr) # type: ignore assert lo.game_results == [gr]
import numpy as np # pegartempo import time pygame.init() window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) icon = pygame.image.load("./Img/icon.png") pygame.display.set_caption("Carros autonĂ¢mos") clock = pygame.time.Clock() pygame.display.set_icon(icon) # init players players = [] for i in range(N_PLAYERS): pose = Pose(PIX2M * round(907 + i * 65 / N_PLAYERS), PIX2M * 435, -pi / 2) players.append(Player(pose, 3 * FORWARD_SPEED, 3 * ANGULAR_SPEED, i)) player = np.array(players) simulation = Simulation(player) # cars cars = [] for i in range(N_PLAYERS): cars.append(pygame.image.load("./Img/carro" + str(i % 7) + ".png")) # collision array scale = 1 position = (0, 0) mapParameters = [scale, position] carsParameters = [] simulation.initScenario(window, mapParameters, cars)
def setUp(self): self.board = Board() self.board.add_tile(get_tile(0), x=5, y=5, rotation=0) self.player = Player() self.rule = FirstMoveCheckNeighbors()
def setUp(self): self.board = Board() self.player = Player() self.rule = FirstMoveOutsidePort()
def setUp(self): self.board = Board() self.player = Player() self.rule = FirstMoveOnBorder()
def test_invalid(self): placement = dummy_placement(x=0, y=0) is_valid, msg = self.rule.is_valid(placement, self.board, Player()) self.assertFalse(is_valid) self.assertEqual(msg, UnoccupiedSpace.ERROR_MSG)
def test_valid(self): placement = dummy_placement(x=1, y=1) is_valid, msg = self.rule.is_valid(placement, self.board, Player()) self.assertTrue(is_valid)
def setUp(self): self.board = Board() self.board.add_tile(get_tile(0), x=0, y=0, rotation=0) self.player = Player() self.rule = UnoccupiedSpace()
def __init__(self, ip: str, port: int, strategy: str): Strat = get_strategy_component(strategy) if Strat != None: self._remote_admin = RemoteAdmin(Player(Strat())) self._remote_admin.connect_to_admin(ip, port)