def test_load_tiles(self, w=3, h=4, offset=2, tiles='x#x###x##'): gmap = GameMap() print( f"TESTING 'load_tiles(w,h,offset,tiles)' WITH THESE VALUES: w={w} h={h} offset={offset} tiles={tiles}" ) gmap.load_tiles(w, h, offset, tiles) print(" SUCCESS! Loaded map:") self.print_map(gmap, indent=' ')
def init(self): self._game_map = GameMap(Vector2D(*DEFAULT_RESOLUTION), [], []) self._creating_basic_platform = None self.grid(row=0, column=0) self._init_slave_widgets() self._init_mouse_bindings()
def test_dimensions(self, w=4, h=4, offset=4, tiles='#####@@# ##'): print( f"TESTING 'dimensions' property WITH THESE VALUES: w={w} h={h} offset={offset} tiles={tiles}" ) gmap = GameMap() gmap.load_tiles(w, h, offset, tiles) dim = gmap.dimensions print(f" ORIGINAL: w={w} h={h}") print(f" LOADED: w={dim.x} h={dim.y}") if w == dim.x and h == dim.y: print(" SUCCESS!") else: print(" FAILURE...") print()
class StateUpdaterTests(TestCase): _state_updater: GameEngine._StateUpdater = GameEngine._StateUpdater( GameEngine(GameMap(Vector2D(100, 100), [], []))) def test_velocity_to_the_left(self): self.assertEqual( -self._state_updater._PLAYER_MOVE_SPEED, self._state_updater._get_horizontal_velocity( {self._state_updater._KEY_CODE_A})) def test_velocity_to_the_right(self): self.assertEqual( self._state_updater._PLAYER_MOVE_SPEED, self._state_updater._get_horizontal_velocity( {self._state_updater._KEY_CODE_D})) def test_no_horizontal_velocity_with_both_keys_pressed(self): assert (self._state_updater._get_horizontal_velocity( {self._state_updater._KEY_CODE_A, self._state_updater._KEY_CODE_D}) == 0) def test_no_horizontal_velocity_with_no_keys_pressed(self): assert self._state_updater._get_horizontal_velocity(set()) == 0 def test_initial_jump_velocity(self): self._state_updater._player_is_on_the_ground = True assert self._state_updater._get_vertical_velocity( {self._state_updater._KEY_CODE_SPACE}) == ( self._state_updater._INITIAL_JUMP_VELOCITY) def test_gravity_acceleration(self): assert self._state_updater._get_vertical_velocity(set()) == ( self._state_updater._GRAVITY_ACCELERATION.y) def test_max_vertical_velocity(self): self._state_updater._vertical_velocity = 100 assert self._state_updater._get_vertical_velocity(set()) == 12 def test_buffs_processing(self): # noinspection PyTypeChecker player: Player = self._state_updater._game_map.movable_objects[0] JumpHeightUpBuff(Vector2D(0, 0)).capture_this_buff( 0, player) SpeedUpBuff(Vector2D(0, 0)).capture_this_buff( 0, player) self._state_updater._check_player_buffs(player) self.assertEqual(2, self._state_updater._PMS_gb_multiplier) self.assertEqual(1.5, self._state_updater._IJV_gb_multiplier) player.current_buffs = [] self._state_updater._PMS_gb_multiplier = 1 self._state_updater._IJV_gb_multiplier = 1
def test_get_tile(self, x=4, y=0, w=4, h=4, offset=2, tiles='abcdefgh'): print( f"TESTING 'get_tile(x,y)' WITH THESE VALUES: w={w} h={h} offset={offset} tiles={tiles}" ) gmap = GameMap() gmap.load_tiles(w, h, offset, tiles) print(f" GETTING TILE @: ({x},{y})") self.print_map(gmap, indent=' ') tile = gmap.get_tile(x, y) if tile == '': print(f" coordinates out of range: ({x},{y})") print(" SUCCESS!") else: print(f" TILE: '{tile}'") print(" SUCCESS!") print()
def test_dump_tiles(self, w=4, h=4, offset=4, tiles='#####@@# ##'): print( f"TESTING 'dump_tiles()' WITH THESE VALUES: w={w} h={h} offset={offset} tiles={tiles}" ) gmap = GameMap() gmap.load_tiles(w, h, offset, tiles) print(" LOADED MAP:") self.print_map(gmap, indent=' ') offset, result = gmap.dump_tiles() print(f" DUMPED MAP: '{result}' offset='{offset}") if result == tiles: print(f" SUCCESS!\n ORIGINAL: '{tiles}'") else: print(f" FAILURE...\n ORIGINAL: '{tiles}'") print()
def test_deserialize(self, w=4, h=4, offset=2, tiles=' abcdefgh'): print(f"TESTING 'deserialize()'") gmap = GameMap() gmap.load_tiles(w, h, offset, tiles) print(" ORIGINAL:") self.print_map(gmap, indent=' ') serial = gmap.serialize() print(f" SERIAL VERSION: {str(serial)}") new_gmap = GameMap() new_gmap.deserialize(serial) self.print_map(new_gmap, indent=' ') if gmap.tiles == new_gmap.tiles: print(" SUCCESS! Maps match.") else: print(" FAILURE... Maps do not match.")
class GameObjectsSpawnerTests(TestCase): _game_objects_spawner: GameEngine._GameObjectsSpawner = ( GameEngine._GameObjectsSpawner( GameEngine(GameMap(Vector2D(100, 100), [], [])))) def test_player_hand_cursor_unit_vector_getter(self): cursor_location: Vector2D = Vector2D(100, 100) # Player hand location = [Vector2D(30, 22)] # abs_player_hand_location: Vector2D = Vector2D(30, 22) non_unit_vector: Vector2D = Vector2D(70, 78) non_unit_vector_length: float = sqrt(70**2 + 78**2) self.assertEqual( Vector2D( non_unit_vector.x / non_unit_vector_length, non_unit_vector.y / non_unit_vector_length), self._game_objects_spawner._get_player_hand_cursor_unit_vector( cursor_location)) def test_spawn_player_projectiles(self): self.assertEqual(True, self._game_objects_spawner._handgun_can_fire) class ButtonStateEnum(Enum): ButtonRelease = object() ButtonPress = object() class MouseEvent: type = object() x = 0 y = 0 self._game_objects_spawner._lmb_event = MouseEvent() self._game_objects_spawner._lmb_event.type = ( ButtonStateEnum.ButtonPress) self._game_objects_spawner.spawn_player_projectiles() self.assertEqual(False, self._game_objects_spawner._handgun_can_fire) self.assertEqual( 2, len(self._game_objects_spawner._game_map.movable_objects)) self._game_objects_spawner._lmb_event.type = ( ButtonStateEnum.ButtonRelease) self._game_objects_spawner.spawn_player_projectiles() self.assertEqual(True, self._game_objects_spawner._handgun_can_fire)
from os.path import (join as os_path_join, dirname as os_path_dirname, abspath as os_path_abspath) from os import pardir as os_pardir from sys import path as sys_path sys_path.append( os_path_join(os_path_dirname(os_path_abspath(__file__)), os_pardir)) from engine.collisions_processor import (CollisionsProcessor, Collision, GameEvent, CollisionsProcessorException) from maps import GameMap from engine.game_objects import (Vector2D, Player, MovableObject, SpeedUpBuff, BasicPlatform) test_map_1: GameMap = GameMap(Vector2D(100, 100), [], [Player(Vector2D(0, 0))]) test_map_2: GameMap = GameMap(Vector2D(100, 100), [SpeedUpBuff(Vector2D(50, 50))], [Player(Vector2D(0, 0))]) test_map_3: GameMap = GameMap(Vector2D(100, 100), [BasicPlatform(10, 10, Vector2D(30, 30))], [Player(Vector2D(0, 0))]) class ExceptionsTests(TestCase): def test_unknown_moving_object_exception(self): with self.assertRaises(CollisionsProcessorException) as occurred_exc: CollisionsProcessor(test_map_1).get_collisions( MovableObject(Vector2D(0, 0)), Vector2D(0, 0))
class MapEditor(tk_Frame): _game_map: GameMap _game_gui: GameGUI # Check what button is sunken to find out creation state. Always one and # only one creation button should be in pressed state # # Button name MUST be legit game object class. 'globals()[button_name]' # is used in mouse bindings methods _creation_button: Dict[str, tk_Button] _creation_game_objects: List[str] _save_filename_entry: tk_Entry _save_button: tk_Button _load_filename_entry: tk_Entry _load_button: tk_Button # [BasicPlatform] instance that is currently creating via sunken mouse # left button (button 1) in motion. In any other mouse state this var is # [None] _creating_basic_platform: Optional[BasicPlatform] def init(self): self._game_map = GameMap(Vector2D(*DEFAULT_RESOLUTION), [], []) self._creating_basic_platform = None self.grid(row=0, column=0) self._init_slave_widgets() self._init_mouse_bindings() def _init_slave_widgets(self): self._game_gui = GameGUI(input_widgets_root=self.master, master=self) self._game_gui.init(self._game_map, [EventListener()]) self._game_gui.grid(row=0, column=0, rowspan=8) self._init_creation_buttons() self._init_saving_widgets() self._init_loading_widgets() def _init_creation_buttons(self): self._creation_button = dict() self._creation_game_objects = [ 'Player', 'BasicPlatform', 'SpeedUpBuff', 'JumpHeightUpBuff' ] for i in range(len(self._creation_game_objects)): self._creation_button[self._creation_game_objects[i]] = tk_Button( master=self, text=self._creation_game_objects[i]) self._creation_button[self._creation_game_objects[i]].grid( row=i, column=1) self._creation_button[self._creation_game_objects[i]].configure( command=self._get_creation_button_command( self._creation_game_objects[i])) self._creation_button['Player'].configure(relief='sunken') def _get_creation_button_command( self, sinking_button_name: str) -> (Callable[[], None]): def result_func(): for button_name in self._creation_button: self._creation_button[button_name].configure(relief='raised') self._creation_button[sinking_button_name].configure( relief='sunken') return result_func def _init_saving_widgets(self): self._save_filename_entry = tk_Entry(master=self) self._save_filename_entry.grid(row=4, column=1) self._save_button = tk_Button(master=self, text='Save') self._save_button.grid(row=5, column=1) self._save_button.configure(command=self._save_button_command) def _save_button_command(self): if self._save_filename_entry.get() != '': with open(self._save_filename_entry.get(), 'wb') as file_handle: pickle_dump(self._game_map, file_handle) self._game_map.remove_all_game_objects() self._game_gui.render() def _init_loading_widgets(self): self._load_filename_entry = tk_Entry(master=self) self._load_filename_entry.grid(row=6, column=1) self._load_button = tk_Button(master=self, text='Load') self._load_button.grid(row=7, column=1) self._load_button.configure(command=self._load_button_command) def _load_button_command(self): if self._load_filename_entry.get() != '': with open(self._load_filename_entry.get(), 'rb') as file_handle: self._game_map.set(pickle_load(file_handle)) self._game_gui.render() def _init_mouse_bindings(self): self.master.bind('<Button-1>', self._create_game_object) self.master.bind('<B1-Motion>', self._change_basic_platform_size) self.master.bind('<ButtonRelease-1>', self._finish_basic_platform_creation) def _create_game_object(self, event): """Adds new game object to current game map Invokes on left mouse button click """ for button_name in self._creation_button: if (self._creation_button[button_name]['relief'] == 'sunken' and event.widget.__class__.__name__ == 'GameGUI'): if button_name == 'Player': if len(self._game_map.movable_objects) == 0: self._game_map.movable_objects.append( Player(Vector2D(event.x, event.y))) else: # If one [Player] instance already exists on map then # it is forbidden to create another [Player] # instance on the same map (game will crush # otherwise). So here firstly created [Player] # instance is moved to new location self._game_map.movable_objects[0].location = (Vector2D( event.x, event.y)) elif button_name == 'BasicPlatform': self._creating_basic_platform = (BasicPlatform( 0, 0, Vector2D(event.x, event.y))) self._game_map.immovable_objects.append( self._creating_basic_platform) else: self._game_map.immovable_objects.append( globals()[button_name](Vector2D(event.x, event.y))) self._game_gui.render() def _change_basic_platform_size(self, event): """Imitates basic platform stretching on its creation Invokes when left mouse button is held down and moved """ if self._creating_basic_platform is not None: self._creating_basic_platform.width = ( event.x - self._creating_basic_platform.location.x) self._creating_basic_platform.height = ( event.y - self._creating_basic_platform.location.y) self._game_gui.render() def _finish_basic_platform_creation(self, _): if self._creating_basic_platform is not None: if self._creating_basic_platform.width < 0: self._creating_basic_platform.location.x += ( self._creating_basic_platform.width) self._creating_basic_platform.width *= -1 if self._creating_basic_platform.height < 0: self._creating_basic_platform.location.y += ( self._creating_basic_platform.height) self._creating_basic_platform.height *= -1 self._creating_basic_platform = None # Improvement: [_move_game_object] method def _move_game_object(self, event): """Draw chosen game object on cursor position Invokes every 10 millis """ pass
def test_serialize(self, w=4, h=4, offset=2, tiles=' abcdefgh'): print(f"TESTING 'serialize()'") gmap = GameMap() gmap.load_tiles(w, h, offset, tiles) print(' ', gmap.serialize()) print()