def test_get_transitions(self): """ Make sure that we can get public and private transitions """ game1 = game_runner.get_game(self.game_id) game1.max_players = 2 player1 = Player() player2 = Player() action_name = "private_public_action" game1.register((player1, player2)) self.assertTrue( game_runner.make_action(self.game_id, action_name=action_name, player=player1.game_id)) # Now we expect a list of public transitions self.assertListEqual([("public", "foobar")], game_runner.get_public_transitions(self.game_id)) # We also expect player1 to have a private list transitions = game_runner.get_player_transitions( self.game_id, player1.game_id) self.assertListEqual([("private", "foobaz")], transitions) transitions = game_runner.get_player_transitions( self.game_id, player2.game_id) self.assertListEqual([], transitions)
def test_player_calls__when_players_allin_with_stack_that_is_too_small__side_pot_is_formed(self): player1 = Player("Player1", 1000) player2 = Player("Player2", 90) player3 = Player("Player3", 80) pot = Pot() pot.player_calls(player1, 100) pot.player_calls(player2, 90) pot.player_calls(player3, 80) pots = pot.get_all_pots() self.assertEqual(3, len(pots)) main_pot = pots[0] self.assertEqual(240, main_pot.pot_size()) self.assertTrue(player1 in main_pot.chips_per_player) self.assertTrue(player2 in main_pot.chips_per_player) self.assertTrue(player3 in main_pot.chips_per_player) side_pot = pots[1] self.assertEqual(20, side_pot.pot_size()) self.assertTrue(player1 in side_pot.chips_per_player) self.assertTrue(player2 in side_pot.chips_per_player) self.assertTrue(player3 not in side_pot.chips_per_player) side_pot = pots[2] self.assertEqual(10, side_pot.pot_size()) self.assertTrue(player1 in side_pot.chips_per_player) self.assertTrue(player2 not in side_pot.chips_per_player) self.assertTrue(player3 not in side_pot.chips_per_player)
def test_player_calls__when_players_allin_after_placing_blinds(self): player1 = Player("Player1", 1000) player2 = Player("Player2", 600) player3 = Player("Player3", 200) pot = Pot() pot.player_calls(player2, 5) pot.player_calls(player3, 200) pot.player_calls(player1, 1000) pot.player_calls(player2, 600) pots = pot.get_all_pots() self.assertEqual(3, len(pots)) main_pot = pots[0] self.assertEqual(600, main_pot.pot_size()) self.assertTrue(player1 in main_pot.chips_per_player) self.assertTrue(player2 in main_pot.chips_per_player) self.assertTrue(player3 in main_pot.chips_per_player) side_pot = pots[1] self.assertEqual(800, side_pot.pot_size()) self.assertTrue(player1 in side_pot.chips_per_player) self.assertTrue(player2 in side_pot.chips_per_player) self.assertTrue(player3 not in side_pot.chips_per_player) side_pot = pots[2] self.assertEqual(400, side_pot.pot_size()) self.assertTrue(player1 in side_pot.chips_per_player) self.assertTrue(player2 not in side_pot.chips_per_player) self.assertTrue(player3 not in side_pot.chips_per_player)
def train(self, player): # create new a new bot shares the same strategy player2 = Player(player.name + "COPY") player2.bot = EasyBot(player.bot.name + "_COPY") player2.bot.strategy = player.bot.strategy for _ in range(self._TRAIN_ITER): self.headsup_simulate(player, player2)
def add_player(self): """ Adds a player if possible and returns the player id """ if len(self.players) >= self.max_players: raise ValueError("Too many players.") if self.is_set_up: raise ValueError("Unable to join a game in progress") player = Player() player.add_zones(self.player_zones) self.players.append(player) # Register both the player and it's zones with the game. self.register([player]) self.register(player.zones.values()) # Add the per-player zones to our dictionary and add the owner to # each zone. for name, zone in player.zones.items(): zone.owner = player zone_name = name + '_' + str(player.game_id) self.zones[zone_name] = zone setattr(self, zone_name, zone) return player.game_id
def __init__(self, renderer_name, config, game): self.__config = config self.__game = game pygame.init() self.__clock = pygame.time.Clock() self.__screen = ScreenProvider.create(config) self.__renderer = RendererProvider.create(config, renderer_name) self.__done = False self.__joysticks = [] self.__connect_joysticks() self.__players = [ Player( InputState([ KeyboardInputHandler(ei.KEY_MAP_1), JoystickInputHandler(0) ])), Player( InputState([ KeyboardInputHandler(ei.KEY_MAP_2), JoystickInputHandler(1) ])) ]
def initialize_game(prev_game): player_pos_dict = { 1: Player('player1', 1), 2: Player('player2', 2), 3: Player('player3', 3), 4: Player('player4', 4) } return Game28(player_pos_dict, prev_game)
def create_game_for_testing(): player_dict = { 1: Player('player1', 1), 2: Player('player2', 2), 3: Player('player3', 3), 4: Player('player4', 4), } game = GameFactory.get_game_implementation(GameType.TWENTY_EIGHT, player_dict, None) game.player_action('player1', PlayerAction.DEALING_ACTION, None) return game
def __init__(self,agent1,agent2): self.spawn_cost = 500 self.convert_cost = 500 self.halite_init = 100000 self.halite_collect = 0.75 self.init_halite() self.players = [Player(0,agent1,self),Player(1,agent2,self)] self.nb_step = 0 self.length = 10
def create_game_for_testing(): player_dict = { 1: Player('player1', 1), 2: Player('player2', 2), 3: Player('player3', 3), 4: Player('player4', 4), } game = GameFactory.get_game_implementation(GameType.TWENTY_EIGHT, player_dict, None) game.state = Game28State.ROUND_ONE_BIDDING_DONE return game
def test_big_blind_player__correctly_determines_big_blind_position(self): button_positions = [(0, "Player2"), (1, "Player3"), (2, "Player0"), (3, "Player1")] for button_position, big_blind_name in button_positions: with self.subTest(): player0 = Player("Player0") player1 = Player("Player1") player2 = Player("Player2") player3 = Player("Player3") seating = Seating([player0, player1, player2, player3]) seating.button_position = button_position result = seating.big_blind_player().name self.assertEqual(big_blind_name, result)
def test_deal(self): player1 = Player("player1", 1000) player2 = Player("player2", 1000) seating = Seating([player1, player2]) deck = Deck() deck.initialize() dealer = Dealer(deck, seating) dealer.deal_cards_to_players() hand_size = 2 cards_dealt = len(seating.players) * hand_size self.assertEqual(cards_dealt, len(set(player1.cards + player2.cards))) expected_remaining_card_count = TestDeck.deck_size - cards_dealt self.assertEqual(expected_remaining_card_count, len(deck.cards))
class TestPlayer(unittest.TestCase): def setUp(self): self.player = Player('player') def test_constructor(self): self.assertEqual('player', self.player.name) self.assertEqual(0, self.player.score) self.assert_(not self.player.rack) def test_valid_play(self): self.player.rack = list('DEADBEEF') l = self.player.valid_play('DEAD') for letter in 'DEAD': self.assertIn(letter, l) l = self.player.valid_play('DEADBEEF') for letter in 'DEADBEEF': self.assertIn(letter, l) l = self.player.valid_play('BLAH') self.assert_(not l) # With blanks now self.player.rack = list('HELLO WORLD') l = self.player.valid_play('HELLOS') for letter in 'HELLOs': self.assertIn(letter, l) # Make sure the blank isn't used unless absolutely necessary l = self.player.valid_play('HELLO') for letter in 'HELLO': self.assertIn(letter, l) # What if the blank is a second instance of an existing letter? l = self.player.valid_play('LLLL') self.assertEqual(1, l.count('l')) def test_use_letters(self): self.player.rack = list('DEADBEEF') self.player.use_letters('DEAD') self.assertEqual(list('BEEF'), self.player.rack) self.player.rack = list('HELLO WORLD') self.player.use_letters('JELLO') self.assertEqual(list('HWORLD'), self.player.rack)
def add_player_to_session(self, player_id): for pos in range(1, self.number_of_players + 1): if pos not in self.player_pos_dict: player = Player(player_id, pos) self.player_pos_dict[pos] = player return self.player_pos_dict raise GameEngineException("No free position available for allocation")
def __init__(self,width=800,height=600): """ Game loop Class Accepts game window height and width """ # game display vars self.game = pygame self.game.init() self.width = width self.height = height self.screen = self.game.display.set_mode((self.width,self.height)) self.clock = pygame.time.Clock() self.game.display.set_caption('Bunbunmaru Gamejam 2013 | TOPGUN') self.clock.tick(60) # images self.f14 = self._load_png("f14.png") self.cloud = self._load_png("alpha_cloud.png") self.bullet = self._load_png("bullet.png") self.enemy = self._load_png("mig.png") # level management self.level = Level1( self.enemy ) self.bulletMan = BulletManager() # entities self.enemies = self.level.getCurrentEnemies() self.sky = clouds(self.cloud) self.player = Player( 3, 0, self.bulletMan, 1, self.f14, self.f14.get_rect(), self.bullet, self.bullet.get_rect() )
def setUp(self): # Here we will construct a Test World we can use to verify our systems # work well together. self.player = Player() self.g = Graphics() self.sim = Simulation() self.sun = SunMoon() # Build Test World self.worldmap = WorldMap(0, 0, 2, 2) self.worldmap.SetMapTile(0, 0, MapTile('00', 'ohoh', [MapTileTag.FOREST])) self.worldmap.SetMapTile(0, 1, MapTile('01', 'oh one', [MapTileTag.FOREST])) self.worldmap.SetMapTile(1, 0, MapTile('10', 'ten', [MapTileTag.FOREST])) self.worldmap.SetMapTile(1, 1, MapTile('11', 'eleven', [MapTileTag.FOREST])) self.worldmap.AddItemAt(0, 1, 'Test Item') # Create Test NPC self.worldmap.AddNPCAt(1, 0, 'roger') self.worldmap.AddNPCAt(1, 0, 'bob') self.game = MyGame(worldmap=self.worldmap, sim=self.sim, player1=self.player, graphics=self.g, sun=self.sun)
def test_player_values(self): """ Make sure that we can set values for a specific player. """ player = Player() self.game.register([player]) # Make sure that we can't get any values from a default player object self.assertIsNone( self.stateful_game_object.get_value("visible", player)) expected_state_changes = [ ("set", "foo", self.stateful_game_object.game_id, "visible", True) ] # Add per player transition self.stateful_game_object.set_value("visible", True, player) self.assertIsNone(self.stateful_game_object.get_value("visible")) self.assertEqual( self.stateful_game_object.get_value("visible", player), True) # Make sure the game got the right transitions self.assertEqual(expected_state_changes, self.game.get_player_transitions(player.game_id)) # Make sure we can get the proper dictionary representation self.assertDictEqual(self.stateful_game_object.to_dict(), {'game_id': self.stateful_game_object.game_id}) self.assertDictEqual(self.stateful_game_object.to_dict(player), { 'game_id': self.stateful_game_object.game_id, 'visible': True })
def __allocate_seats(self, player_ids): for pos in range (1,self.number_of_players + 1): if pos < len(player_ids) + 1: player = Player(player_ids[pos -1], pos) self.player_pos_dict[pos] = player else: break return self.player_pos_dict
def __init__(self, mapText, timeSpeed=1): self.timeSpeed = timeSpeed self.time = 0 self.player = Player.DEFAULT(self) self.entityList = set((self.player, )) self._map = MapClass(self, mapText) self.loadedSheets = {}
def load_player(instance): tmp_items = [] data = None with open("characters/player.json", "r") as rf: data = json.load(rf) for loc_item in data["items"]: tmp_items.append(instance.get_item(loc_item)) data["items"] = tmp_items p = Player(*data.values()) return p
def __init__(self): self.player1 = Player('1', player_config['types'][0]) self.player2 = Player('2', player_config['types'][1]) self.game_board = GameWindow(window_config['resolution'], window_config['size'], window_config['hexes']) self.game_board.draw_display(True) self.game_engine = GameEngine(self.game_board, self.player1) self.turns_played = 0 # Four functions for four different types of game. self._games = { 'human_human': self._run_p1_p2_human, 'human_ai': self._run_p1_human_p2_ai, 'ai_human': self._run_p1_ai_p2_human, 'ai_ai': self._run_p1_ai_p2_ai, } # Select game type based on players self._run_func = self._games['{}_{}'.format(self.player1.type, self.player2.type)] self.game_ended = False self.start_time = time.time()
def test_player_calls__when_three_players_allin_with_stacks_that_are_too_small__three_side_pots_are_formed(self): player1 = Player("Player1", 1000) player2 = Player("Player2", 600) player3 = Player("Player3", 200) player4 = Player("Player4", 50) pot = Pot() pot.player_calls(player1, 999) pot.player_calls(player2, 600) pot.player_calls(player3, 200) pot.player_calls(player4, 50) pots = pot.get_all_pots() self.assertEqual(4, len(pots)) main_pot = pots[0] self.assertEqual(200, main_pot.pot_size()) self.assertTrue(player1 in main_pot.chips_per_player) self.assertTrue(player2 in main_pot.chips_per_player) self.assertTrue(player3 in main_pot.chips_per_player) self.assertTrue(player4 in main_pot.chips_per_player) side_pot = pots[1] self.assertEqual(450, side_pot.pot_size()) self.assertTrue(player1 in side_pot.chips_per_player) self.assertTrue(player2 in side_pot.chips_per_player) self.assertTrue(player3 in side_pot.chips_per_player) self.assertTrue(player4 not in side_pot.chips_per_player) side_pot = pots[2] self.assertEqual(800, side_pot.pot_size()) self.assertTrue(player1 in side_pot.chips_per_player) self.assertTrue(player2 in side_pot.chips_per_player) self.assertTrue(player3 not in side_pot.chips_per_player) self.assertTrue(player4 not in side_pot.chips_per_player) side_pot = pots[3] self.assertEqual(399, side_pot.pot_size()) self.assertTrue(player1 in side_pot.chips_per_player) self.assertTrue(player2 not in side_pot.chips_per_player) self.assertTrue(player3 not in side_pot.chips_per_player) self.assertTrue(player4 not in side_pot.chips_per_player)
def create_game_for_testing(): player_dict = { 1: Player('player1', 1), 2: Player('player2', 2), 3: Player('player3', 3), 4: Player('player4', 4), } game = GameFactory.get_game_implementation(GameType.TWENTY_EIGHT, player_dict, None) game.player_action('player1', PlayerAction.DEALING_ACTION, None) game.player_action( 'player2', PlayerAction.BIDDING_ACTION, { constants.BID_VALUE: game.settings.get_setting_value(constants.MIN_BID_VALUE), constants.TRUMP_CARD_ABBREVIATION: TestRoundOneBidding.get_random_card_abbreviation(game) }) game.player_action( 'player3', PlayerAction.BIDDING_ACTION, { constants.BID_VALUE: game.settings.get_setting_value(constants.MIN_BID_VALUE) + 1, constants.TRUMP_CARD_ABBREVIATION: TestRoundOneBidding.get_random_card_abbreviation(game) }) game.player_action( 'player4', PlayerAction.BIDDING_ACTION, { constants.BID_VALUE: game.settings.get_setting_value(constants.MIN_BID_VALUE) + 2, constants.TRUMP_CARD_ABBREVIATION: TestRoundOneBidding.get_random_card_abbreviation(game) }) game.player_action( 'player1', PlayerAction.BIDDING_ACTION, { constants.BID_VALUE: game.settings.get_setting_value(constants.MIN_BID_VALUE) + 3, constants.TRUMP_CARD_ABBREVIATION: TestRoundOneBidding.get_random_card_abbreviation(game) }) game.player_action('player1', PlayerAction.DEALING_ACTION, None) return game
def test_deregister(self): """ Make sure that we can properly deregister objects. """ player = Player() card = Card() zone = Zone() other = GameObject() unregistered = GameObject() self.game.register([player, card, zone, other]) self.game.deregister([player, card, zone, other, unregistered]) print self.game.registered_objects self.assertEqual(self.game.registered_objects["Player"][0], 2) self.assertEqual(self.game.registered_objects["Card"][0], 1) self.assertEqual(self.game.registered_objects["Zone"][0], 1) self.assertEqual(self.game.registered_objects["GameObject"][0], 1)
def __init__(self, worldmap=initialize.GENERATE_PHEZYGG_WORLD(), sim=Simulation(), player1=Player(), graphics=Graphics(), sun=SunMoon()): self.info_commands = ['help', 'info'] self.player_move_commands = [ 'north', 'south', 'east', 'west', 'n', 's', 'e', 'w' ] self.fart_commands = ['fart'] self.look_commands = ['look', 'search', 'investigate'] self.npc_commands = ['greet'] self.quit_commands = ['quit'] self.nothing_commands = ['wait', 'nothing'] self.item_commands = ['pickup', 'get', 'take'] self.inventory_commands = ['inventory'] self.use_commands = ['use'] self.all_commands = (self.info_commands + self.player_move_commands + self.fart_commands + self.quit_commands + self.look_commands + self.npc_commands + self.nothing_commands + self.item_commands + self.inventory_commands + self.use_commands) self.worldmap = worldmap self.sim = sim print("Beginning game...") self.player1 = player1 self.sim.AddUpdateable(self.player1) self.sun = sun self.sim.AddUpdateable(self.sun) # Every game loop, add things to be rendered/printed to this list. self.render_list = [] # Every game loop, update our input queue to process player input. # In normal operation, there will only be one entry in the queue. However, this # enables us to insert commands in the queue for testing purposes. self.input_queue = deque() self.graphics = graphics
def processInput(): userText = input("Enter command [Add player] [Team player] [Spot] [Web spot] [Flee jail] [Print] [teamChat]: \n") if 'f' in userText: jailCode = input("enter jail code: ") Action.fleePlayerWithCode(jailCode) Stats.printPlayersDetailed() elif 's' in userText: mobile = input("enter mobile: ") code = input("enter code: ") Action.handleSms(mobile, code) Stats.printPlayersDetailed() elif 'a' in userText: name = input("enter name: ") mobile = input("enter mobile: ") #email = input("enter email: ") Action.addPlayer(name, mobile, "") Stats.printPlayersDetailed() elif 'w' in userText: hash = input("enter player hash: ") code = input("enter code: ") Action.handleWeb(hash, code) Stats.printPlayersDetailed() elif 't' in userText: name = input("enter player name: ") team = input("enter team name: ") Action.addPlayerToTeam(name, team) Stats.printPlayersDetailed() elif 'p' in userText: Stats.printStats() elif 'c' in userText: name = input("enter name: ") message = input("enter text: ") playerId = Player._getIdByName(name) Action.sayToMyTeam(playerId, message) elif 'q' in userText: id = input("enter id: ") Action.browserRequestsMessages(id) elif 'b' in userText: msg = Action.base_msg_get() print("BASE:", msg)
def test_make_action(self): """ Make sure that we can make actions through the GameRunner. """ game1 = game_runner.get_game(self.game_id) game1.phase = "restricted" player = Player() game1.register([player]) action = "restricted_action" valid, message = game_runner.make_action(self.game_id, action_name=action, player_id=player.game_id) self.assertFalse(valid) self.assertEqual(message, "Illegal Action") game1.phase = "unrestricted" self.assertEqual((True, None), game_runner.make_action(self.game_id, action_name=action, player_id=player.game_id))
def setUp(self): self.player = Player('player')
def __init__(self,index,name,screen,invert=False): Player.__init__(self,index,name) self.screen = screen self.board = Board(screen.get_size()) self.points_visible = False self.invert = invert
def setUp(self): """Create a Player for use in testing.""" self.player1 = Player() self.testitem = Detritus("A ROCK")
class PlayerTestCase(unittest.TestCase): """Tests Player class and functions.""" def setUp(self): """Create a Player for use in testing.""" self.player1 = Player() self.testitem = Detritus("A ROCK") def test_move(self): """Test player position and movement.""" # Check default x position self.assertEqual(self.player1.position.x, 0) # Check default y position self.assertEqual(self.player1.position.y, 0) # Check the different move directions and the resulting position change self.player1.move('n') self.assertEqual(self.player1.position.y, 1) self.player1.move('s') self.assertEqual(self.player1.position.y, 0) self.player1.move('e') self.assertEqual(self.player1.position.x, 1) self.player1.move('w') self.assertEqual(self.player1.position.x, 0) def test_status(self): """Test player hunger level and update.""" # Check initial hunger self.assertEqual(self.player1.PlayerStatus(), 'You feel content.') self.assertEqual(self.player1.hunger, 0) for _ in range(0, 4): self.player1.Update(4) self.assertEqual(self.player1.hunger, 4) self.assertEqual(self.player1.PlayerStatus(), 'You are hungry.') def test_inventory(self): """Test inventory.""" self.player1.add_item_to_inv(self.testitem) self.assertIn(self.testitem, self.player1.inventory) self.assertEqual(self.player1.display_inv(), ["A ROCK"])
class GameLoop: def __init__(self,width=800,height=600): """ Game loop Class Accepts game window height and width """ # game display vars self.game = pygame self.game.init() self.width = width self.height = height self.screen = self.game.display.set_mode((self.width,self.height)) self.clock = pygame.time.Clock() self.game.display.set_caption('Bunbunmaru Gamejam 2013 | TOPGUN') self.clock.tick(60) # images self.f14 = self._load_png("f14.png") self.cloud = self._load_png("alpha_cloud.png") self.bullet = self._load_png("bullet.png") self.enemy = self._load_png("mig.png") # level management self.level = Level1( self.enemy ) self.bulletMan = BulletManager() # entities self.enemies = self.level.getCurrentEnemies() self.sky = clouds(self.cloud) self.player = Player( 3, 0, self.bulletMan, 1, self.f14, self.f14.get_rect(), self.bullet, self.bullet.get_rect() ) def _actall( self ): self.sky.act() self.player.act() if self.enemies != None: self.bulletMan.update( self.enemies ) else: # game is done, do that shit here pass for enemy in self.enemies.enemyList: enemy.act( self.player ) def _drawall( self ): """ Draws the player, bullets, and enemies (in that order) to the screen """ self.screen.fill((135,206,250)) self.sky.draw(self.screen) self.player.draw(self.screen) for enemy in self.enemies.enemyList: enemy.draw( self.screen) self.bulletMan.drawall( self.screen) pygame.display.flip() def _load_png( self, name): """ Private Load_png method accept: name - file name return: pygame image obj """ fullname = os.path.join('resources',name) try: image = pygame.image.load(fullname) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() except pygame.error: print "Cannot load image: ",fullname return image def start(self): """ Entry point of the game """ while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # check if current wave is done, if it is, get new enemies if self.level.isComplete(): self.enemies = self.level.getCurrentEnemies() if self.enemies == None: break self._actall() self._drawall()
class GameLevel: """ Level of the game """ def __init__(self, objects, player_pos, limgpar=[], name='', parallax=True, gravity=2100, music=None): #Gravity is set experimentally for jumps to 2100 """ The player spawn in (0,0) """ assert objects != [] #Empty GameLevel self.camera = Camera() #Camera self.camera.set_position(Vector(-12, -12)) self.camera.set_dimension(Vector(25, 25)) self.objects = objects self.player_pos = player_pos self.compute_size_level() self.name = name self.music = music #Creation of the gravity self.gravity = Gravity( gravity ) #NOTE POUR LES RAGEUX : On a testé et ca marche bien avec cette valeur -> ca permet d'avoir un saut élegant self.begin_time = 0 self.time = 0 #Time Referential of the level #Death animation self.lost = False self.countdown = 1 #Creation of the player self.player = Player() self.player.set_position(0, -16) #Init pos of the player self.objects.append(self.player) self.player.link_world(self) #Camera Y scrolling self.camera_y_pos = self.player.get_position().y #To optimise physics self.sorted_objects = None self.dynamic_objects = set([self.player]) self.opti_step = 10 self.optimise_data() self.progression = 0 #Get end platform locations to compute score self.end_platform_location = None self.compute_end_platform_location() #Load Background self.parallax = parallax self.load_bg(limgpar) #Link worlds for o in objects: o.link_world(self) #End the initialisatio self.end_init() def load_bg(self, limgpar): if not self.parallax: if len(limgpar) >= 6: limgpar = [limgpar[0]] elif len(limgpar) >= 2: limgpar = [limgpar[1]] lpar = [] #List of Parallax for (name, index) in limgpar: p = Parallax(name, index) #Create parallax with given speed lpar.append(p) self.background = Background(lpar) def end_init(self): """ Call all end_init of objects in the world """ for o in self.objects: o.end_init() def get_camera(self): """ Returns the camera """ return self.camera def get_objects(self): """ Returns objects of the level """ return self.objects def load_inventory(self, inv): """ Load the inventory of campaign mode in the GameLevel """ self.player.load_inventory(inv) def add_node(self, n): """ Adds a new node to the world """ self.objects.append(n) self.dynamic_objects.add(n) n.link_world(self) def compute_end_platform_location(self): """ Compute the list of platform location """ self.end_platform_location = [] for o in self.get_objects(): if isinstance(o, SolidPlatform): self.end_platform_location.append( o.get_hit_box().get_world_rect().get_max_x()) self.end_platform_location.sort() def get_objects_opti(self): """ Optimise the data structure """ while self.progression < len(self.sorted_objects): o = self.sorted_objects[self.progression] orect = o.get_hit_box().get_world_rect() crect = self.get_camera().rect if orect.collidex(crect): self.dynamic_objects.add(o) self.progression += 1 else: break return self.dynamic_objects def optimise_data(self): """ Optimise collisions checks and aff """ #Call it before launching the game of making modification in camera (be carefull it may take a while to execute def order(o1): return o1.get_hit_box().get_world_rect().get_min_x() sorted_objects = self.objects[:] sorted_objects.sort(key=order) self.sorted_objects = sorted_objects def compute_size_level(self): """ Computes the size of the level """ maxi_x = None maxi_y = None mini_x = None mini_y = None #Get the rect in which the level is for o in self.objects: hit_box = o.get_hit_box() val_max_x = hit_box.get_world_rect().get_max_x() val_max_y = hit_box.get_world_rect().get_max_y() val_min_x = hit_box.get_world_rect().get_min_x() val_min_y = hit_box.get_world_rect().get_min_y() if maxi_x is None or val_max_x > maxi_x: maxi_x = val_max_x if mini_x is None or val_min_x < mini_x: mini_x = val_min_x if maxi_y is None or val_max_y > maxi_y: maxi_y = val_max_y if mini_y is None or val_min_y < mini_y: mini_y = val_min_y self.size_level = (mini_x, maxi_x, mini_y, maxi_y) def get_size_level(self): """ Returns the size of the level as a tuple (minx,maxx,miny,maxy) """ return self.size_level def play(self, fps): """ Launches the gameLevel , returns +score if win, -score if lose """ #Starts the music if self.music != None: pygame.mixer.music.load(self.music) pygame.mixer.music.play(-1) t0 = get_current_time() tn = t0 try: while True: #Get time now = get_current_time() #Compute dt from previous iteration dt = now - tn #Updates time from the begining self.time = tn - t0 #Launch the loop self.main_loop(dt) #Updates tn for the next iteration tn = now except EndGame as e: #print("--",time.clock()-t0,self.time) return (e.issue, e.score) def main_loop(self, dt): #to = time.clock() """ Main loop of the game (controllers, physics, ...) """ #Animation of lose self.animation_end_game(dt) #Computes opti objects obj_opti = set(self.get_objects_opti()) #Call controllers self.compute_controller(obj_opti, dt) #Computation of physics self.physics_step(dt, obj_opti) #Camera set position (3/4) self.compute_camera_position(obj_opti) #Show all sprites self.aff(dt, obj_opti) #print("aff",time.clock()-t) #Score self.compute_score() #Win / Lose conditions self.compute_win_lose() def animation_end_game(self, dt): """ Waits a bit after the player dies before ending the game """ if self.lost: if self.countdown > 0: self.countdown -= dt else: raise EndGame(False, self.player.score) def compute_camera_position(self, obj_opti): """ Compute the camera position by trying to fix it on the platform below the player and smooth movements """ prect = self.player.get_hit_box().get_world_rect() #Search for the platform right below the player mini = None for o in obj_opti: if isinstance(o, SolidPlatform): rect = o.get_hit_box().get_world_rect() if rect.collidex(prect): y = rect.get_min_y() if ( mini is None and prect.get_min_y() < y or prect.get_min_y() < y < mini ) and abs( prect.get_min_y() - y ) < 100: #If it's too far it will forget it and fix on the player instead mini = y if mini is None: #No platform -> fix on the player y = self.player.get_position().y else: #Fix on a platform y = mini #Smooth moving of the camera old_percent = 95 #The percentage of the old value of self.camera_y_pos that will be kept self.camera_y_pos = self.camera_y_pos * old_percent / 100 + y * ( 100 - old_percent ) / 100 #Computation of the new continous Y position of the camera self.camera.threeforth_on( Vector(self.player.get_position().x, self.camera_y_pos) ) #Position of the camera (pos X of the player et pos Y previously computed) def compute_win_lose(self): """ Compute win / lose conditions (only lose since the commit adding flags)""" (minx, maxx, miny, maxy) = self.get_size_level() if self.player.get_position().y > maxy or not ( self.player.alive): #C'est inversé :) self.lose() def compute_score(self): """ Compute score """ while len(self.end_platform_location) > 0 and self.player.get_position( ).x >= self.end_platform_location[0]: del self.end_platform_location[0] self.player.add_score(1000) def compute_controller(self, objects, dt): """ Compute controllers """ pressed = pygame.key.get_pressed() #Controller loop for event in pygame.event.get() + [None]: for o in set(objects): if o.get_controller() is not None: o.get_controller().execute(event, pressed, dt) #Physics def win(self): """ Win the game """ self.player.flush_score() raise EndGame(True, self.player.score) def lose(self): """ Lose the game """ self.player.flush_score() self.lost = True def physics_step(self, dt, obj_opti): """ Compute collisions """ for i, o in enumerate(obj_opti): if True: #not(isinstance(o,SolidPlatform)): #On peut se permettre d'integrer les plateformes au calcul suite a de nombreux gains de performance o.compute_speed(dt) o.move(dt) if o == self.player and self.player.alive: #Reposition the player pos = o.get_position() new_pos = Vector(self.player_pos(self.time), pos.y) o.translate(new_pos - pos) #Cut X speed (for MAXSPEED) speed = self.player.get_speed() self.player.set_speed(Vector( 1, speed.y)) #Player needs to have a str pos speed for j, o2 in enumerate(obj_opti): if o.get_collide() and o2.get_collide(): coll = o.get_hit_box().collide_sides(o2.get_hit_box()) #print("--",o,o2,coll) if o != o2 and coll: o.collide(o2, coll, (coll + 2) % 4) o2.collide(o, (coll + 2) % 4, coll) while o.get_rigid_body() and o2.get_rigid_body( ) and o.get_rigid_hit_box().collide( o2.get_rigid_hit_box( )) and o.get_speed() != Vector(0, 0): #print("rigid") o.apply_solid_reaction(o2) def load_camera(self, fen): """ Loads the actual camera of the Level """ self.background.load(fen) #Loads the background too self.camera.set_fen(fen) self.camera.link_world(self) def get_background(self): """ Returns the background """ return self.background def set_background(self, v): """ Set the background """ self.background = v def aff(self, dt, objects): """ Aff all objects that are in the camera of this """ self.camera.aff(objects, self.get_background(), self.player.get_score(), dt) pygame.display.flip()
def __init__(self, objects, player_pos, limgpar=[], name='', parallax=True, gravity=2100, music=None): #Gravity is set experimentally for jumps to 2100 """ The player spawn in (0,0) """ assert objects != [] #Empty GameLevel self.camera = Camera() #Camera self.camera.set_position(Vector(-12, -12)) self.camera.set_dimension(Vector(25, 25)) self.objects = objects self.player_pos = player_pos self.compute_size_level() self.name = name self.music = music #Creation of the gravity self.gravity = Gravity( gravity ) #NOTE POUR LES RAGEUX : On a testé et ca marche bien avec cette valeur -> ca permet d'avoir un saut élegant self.begin_time = 0 self.time = 0 #Time Referential of the level #Death animation self.lost = False self.countdown = 1 #Creation of the player self.player = Player() self.player.set_position(0, -16) #Init pos of the player self.objects.append(self.player) self.player.link_world(self) #Camera Y scrolling self.camera_y_pos = self.player.get_position().y #To optimise physics self.sorted_objects = None self.dynamic_objects = set([self.player]) self.opti_step = 10 self.optimise_data() self.progression = 0 #Get end platform locations to compute score self.end_platform_location = None self.compute_end_platform_location() #Load Background self.parallax = parallax self.load_bg(limgpar) #Link worlds for o in objects: o.link_world(self) #End the initialisatio self.end_init()
#imports from bots.pseudo_bot import PseudoBot from bots.easy_bot import EasyBot from bots.trainer import Trainer from engine.dealer import Dealer from engine.player import Player #constants #n/a #functions #n/a # valerie = Dealer() #print("valerie will be our dealer.") matt_damon = Player("Matt") ed_norton = Player("Ed") trainer = Trainer() matt_damon.bot = EasyBot("MattBot") ed_norton.bot = PseudoBot("EdBot") # each iteration took about 1 min, default is 100 iters # trainer = Trainer() # trainer.train(matt_damon) valerie.start_game(matt_damon, ed_norton) #c = "To play a hand, run ``valerie.play_hand()``\n" valerie.play_hand();