Exemple #1
0
    def keyPressEvent(self, event):
        """
        Метод обработки ввода с клав.
        :param event: Параметр сигнала с квал.
        :return: None
        """
        if event.key() == Qt.Key_Left:
            self.player.move('left')
            self.player.anim_left = True
        elif event.key() == Qt.Key_Right:
            self.player.move('right')
            self.player.anim_right = True
        elif event.key() == Qt.Key_Up:
            self.player.move('up')
            self.player.anim_up = True
        elif event.key() == Qt.Key_Down:
            self.player.move('down')
            self.player.anim_down = True

        elif event.key() == Qt.Key_Shift:
            self.player.roll_bomb()
        elif event.key() == Qt.Key_Space:
            self.player.drop_bomb()

        elif event.key() == Qt.Key_S:
            map.save_map()

        elif event.key() == Qt.Key_L:
            map.load_map()
        elif event.key() == Qt.Key_I:
            get_info_game(self)
        elif event.key() == Qt.Key_N:
            map.scroll_map()

        self.update()
Exemple #2
0
    def timerEvent(self, event):
        """
        Метод Апдейтов(?) и вывод тулбара для игрока.
        :param event: Параметр события.
        :return: None
        """
        update_bomb()
        update_explosion()
        update_bonus()
        self.player = constants.LIST_PLAYERS[
            0]  # КОСТЫЛЬ НА СОХРАНЕНИЯ ПОЗИЦИИ ИГРОКА ПРИ ЗАГРУЗКЕ
        if self.step2 / 10 > self.player.coef_speed_enemy:  # temp
            update_enemy()
            self.step2 = 0  # temp

        self.statusBar().showMessage(
            'Время: {} | Жизни: {} | Бомбы: {} | Тип: {} | Монстров на карте: {} | {}'
            .format(self.step / 10,
                    self.player.hit_point, self.player.count_bomb, 'Обычные',
                    len(LIST_ENEMY), self.player.type_bomb))

        if update_player(self.player):
            reply = QMessageBox.question(
                self, 'Repeat?',
                "\tGAME OVER \nЗагрузить последнее сохранение?",
                QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.Yes:
                map.load_map()
            else:
                print('КОНЕЦ ИГРЫ')
                self.close()

        self.step += 1
        self.step2 += 1
Exemple #3
0
    def init_mode(self, **kwargs):

        session_data.player_hp = 100.0
        # session_data.player_mana = 1000
        session_data.enemies_in_level = 0

        tower.towers = []
        enemy.enemies = []
        session_data.spells_researched = [False] * len(spell.spells_definitions)

        self.build_mode_active = True

        map.create_map()
        self.current_map = kwargs.get("file_name")
        map.load_map(self.current_map)

        self.init_gui()

        enemies_spawner_gameobject = GameObject((0, 0), (0, 0), 0)
        enemies_spawner_gameobject.add_component(EnemiesSpawner).init_component(
            game_mode=self
        )
        self.enemies_spawner = enemies_spawner_gameobject.get_components(EnemiesSpawner)[0]

        game_gui_updater_go = GameObject((0, 0), (1, 1), 0)
        game_gui_updater_go.add_component(GameGUIUpdater).init_component(
            fall_label=self.fall_label,
            fall_reward_label=self.fall_reward_label,
            gold_label=self.gold_label,
            tower_build_buttons=self.tower_build_buttons,
            spell_research_buttons=self.spell_research_buttons,
            spell_use_buttons=self.spell_use_buttons,
            enemies_spawner=self.enemies_spawner,
            player_hp_bar=self.player_hp_bar,
            enemies_fall_bar=self.enemy_fall_bar,
            game_mode=self
        )
        self.game_gui_updater = game_gui_updater_go.get_components(GameGUIUpdater)[0]
        self.game_gui_updater.update_stats_gui()

        self.dragging_tower = None
        self.casting_spell = None

        # test effect
        """
        effect_go = GameObject((100, 100), (1, 1), 0)
        effect_go.add_component(DynamicSprite).init_component(
            pos=(0, 0),
            size=(256, 256),
            angle=0,
            images_paths=file_utils.get_all_files_in_path("sources\images\effects\explosion"),
            alpha=True,
            speed=0.3
        )
        """

        self.switch_right_panel(True)

        self.game_over = False
Exemple #4
0
def init():
    particle.init()

    render.add_screen_sprites(cursor, cursor.hover_text)

    map.load_map("2")

    camera.init(map.width(), map.height())
Exemple #5
0
def init():
    particle.init()

    render.add_screen_sprites(cursor, cursor.hover_text)

    map.load_map("2")

    camera.init(map.width(), map.height())
Exemple #6
0
 def load_game(self):
     try:
         map.load_map()
         self.run_game()
     except FileNotFoundError:
         button_reply = QMessageBox.question(self, 'Yps..',
                                             MESSAGE_ERROR_LOAD_GAME,
                                             QMessageBox.Yes,
                                             QMessageBox.No)
         if button_reply == QMessageBox.Yes:
             self.run_game()
         else:
             pass
Exemple #7
0
    def __init__(self, fname="maps/default.dat", random_map=True,\
                 keep_map=False, test=False,\
                 switch_interval=10, object_reward=1,\
                 node_ranges=[8,8], cost_range=[10,500],
                 objects_range=[4,4], occurrences_range=[1,4]):

        self.fname = fname
        self.random_map = random_map
        self.switch_interval = switch_interval
        self.object_reward = object_reward
        self.test = test
        self.keep_map = keep_map
        self.node_ranges = node_ranges
        self.cost_range = cost_range
        self.objects_range = objects_range
        self.occurrences_range = occurrences_range
        self.max_step = 10 * node_ranges[-1]

        if not path.exists(fname):
            self.reset_map()
        self.map = load_map(fname)
        self.map.reset()

        self.N = self.map.get_node_num()
        self.ep_count = self.switch_interval + 1

        self.action_space = Discrete(self.N)
        self.observation_space = Box(low=0,
                                     high=1,
                                     shape=(self.N, ),
                                     dtype=float)
Exemple #8
0
    def __init__(self,):
        super(TestScene1, self).__init__()

        self.render_sys = RenderSystem()
        self.player_move_sys = PlayerMovementSystem()
        self.player_animation_sys = PlayerAnimationSystem()
        self.fps_text_sys = FpsTextSystem("Terminus.ttf", self.fps)
        self.collision_sys = CollisionDetectionSystem()
        self.event_sys = EventSystem()
        self.camera_sys = CameraSystem()

        # Test Map
        tiles_list = load_map("tallmap.tmx", "mg")
        for tile in tiles_list:
            self.render_sys.register(tile)

            if tile.is_collidable:
                self.collision_sys.register(tile)

            self.camera_sys.register(tile)

        # Test Player
        self.player = SewerMan((40, 40))
        self.render_sys.register(self.player)
        self.player_animation_sys.register(self.player)
        self.player_move_sys.register(self.player)
        self.collision_sys.register(self.player)
        self.event_sys.register(
            self.player,
            [
                "up_pressed",
                "down_pressed",
                "left_pressed",
                "right_pressed",
                "up_released",
                "down_released",
                "left_released",
                "right_released",
            ],
        )
        self.camera_sys.register(self.player)

        # multiple entities
        for i in range(6, 6 * 2 + 1, 6):
            player = SewerMan((i * 10, 40))
            self.render_sys.register(player)
            self.player_animation_sys.register(player)
            self.player_move_sys.register(player)
            self.collision_sys.register(player)
            self.camera_sys.register(player)

        # Test Fps Text
        self.fps_text = Text((5, 5), (0, 0, 255))
        self.render_sys.register(self.fps_text)
        self.fps_text_sys.register(self.fps_text)

        self.cam = Camera(WIN_WIDTH, WIN_HEIGHT, WIN_WIDTH / 2, WIN_HEIGHT / 2, 7.5, 7.5)
        self.camera_sys.register_camera(self.cam)
        self.render_sys.register_camera(self.cam)
        self.cam.follow(self.player)
Exemple #9
0
def main():
    load_map()
    drop_gold()
    update()
    while True:
        pressedkey = getch().lower()
        if pressedkey == 'q':
            clear()
            sys.exit(0)
        elif pressedkey == 'w':
            go(MOVE['UP'])
        elif pressedkey == 'a':
            go(MOVE['LEFT'])
        elif pressedkey == 's':
            go(MOVE['DOWN'])
        elif pressedkey == 'd':
            go(MOVE['RIGHT'])
Exemple #10
0
 def reset_map(self):
     if not self.keep_map:
         generate(self.fname, self.node_ranges, self.cost_range,
                  self.objects_range, self.occurrences_range)
         self.map = load_map(self.fname)
     else:
         self.map = reset_distribution(self.fname, self.node_ranges,
                                       self.cost_range, self.objects_range,
                                       self.occurrences_range)
Exemple #11
0
def create_game(cfg):
    """
    Creates a game from a ConfNode containing the following childs:
      - player-X: with X \in [0, 5], contains the properties for
        player number X. See create_player.
      - map: Contains the path to the map file.
    """

    players = []
    for i in range(0, 6):
        pcfg = cfg.child('player-' + str(i))
        if pcfg.child('enabled').value:
            players.append(create_player(pcfg))

    map_ = load_map(cfg.child('map').value)

    world = World(map_, players)
    world.use_on_attack = cfg.child('use-on-attack').value
    world.use_on_move = cfg.child('use-on-move').value
    world.name = cfg.name

    return world
Exemple #12
0
def create_game (cfg):
    """
    Creates a game from a ConfNode containing the following childs:
      - player-X: with X \in [0, 5], contains the properties for
        player number X. See create_player.
      - map: Contains the path to the map file.
    """
    
    players = []
    for i in range (0, 6):
        pcfg = cfg.child ('player-' + str (i))
        if pcfg.child ('enabled').value:
            players.append (create_player (pcfg))

    map_ = load_map (cfg.child ('map').value)
    
    world = World (map_, players)
    world.use_on_attack = cfg.child ('use-on-attack').value
    world.use_on_move   = cfg.child ('use-on-move').value
    world.name          = cfg.name
    
    return world
Exemple #13
0
(player_img, main_menu_pict, skelet_anim_up, skelet_anim_down,
 skelet_anim_left, skelet_anim_right, player_anim_up, player_anim_down,
 player_anim_left, player_anim_right, player_udar_up, player_udar_down,
 player_udar_left, player_udar_right, death_screen) = create_pictures(img_dir)

# Создание групп спрайтов
(active_sprites, player_sprite, player, mobs) = create_characters(player_img)

# Создание объектов
(objects, health_bar, dialog_box, npc, stamina_bar, stamina_bar0,
 svitok) = sozdanie_objectov(active_sprites, img_dir)

# Создание карт и фона
(map1, map2, map3) = sozdanie_maps()
current_map = redactor_map(map1, player)
(background, background_rect) = load_map(current_map.img_dir, img_dir)

# Загрузка музыки
pygame.mixer.music.load(path.join(img_dir, 'TownTheme.mp3'))
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(loops=-1)
clock = pygame.time.Clock()
while not g.finished:
    player.next_x = player.rect.x + int(player.speedx)
    player.next_y = player.rect.y + int(player.speedy)
    if current_map.trigger(player.next_x, player.next_y) > 1:
        id = current_map.trigger(player.next_x, player.next_y)
        if current_map == map1:
            if id == 2:
                sozdanie_vragov(mobs, active_sprites)
                current_map = redactor_map(map2, player)
Exemple #14
0
import sys
from os.path import join, abspath, dirname
sys.path.append(dirname(dirname(join(abspath(__file__)))))
import map
from map import load_map, parse_world

if __name__ == "__main__":
    m = load_map("maps/default.dat")
    m.reset()
    print(m.get_cost(0,1))
    print(m.get_cost_map())
    print(m.get_prob_distrs())
    print(m.get_distrs())
    print(m.get_node_num())
    print(m.get_current_loc())
    print(m.get_find_at_least_one_prob())
    print(m.obj_loc)

    print("\n")
    print(m.move(1))
    print(m.get_cost(0,1))
    print(m.get_cost_map())
    print(m.get_prob_distrs())
    print(m.get_distrs())
    print(m.get_node_num())
    print(m.get_current_loc())
    print(m.get_find_at_least_one_prob())


    print("\n")
    print(m.move(2))
    def __init__(
        self,
        map,
        robot_controller,
        init_position=None,
        steering_noise=0.01,
        color_noise=10,
        sonar_noise=0.1,
        distance_noise=0.001,
        forward_steering_drift=0,
        measurement_noise=0.2,
        speed=5.0,
        turning_speed=0.4 * pi,
        execution_cpu_time_limit=10.0,
        simulation_time_limit=10.0,
        simulation_dt=0.0,
        frame_dt=0.1,
        gps_delay=2.0,
        collision_threshold=50,
        iteration_write_frequency=1000,
        command_line=True,
        print_robot=True,
        seed=777,
        print_logger=False,
        accepted_commands=[TURN, MOVE, BEEP, FINISH, SENSE_COLOR],
    ):
        """
            Construct KrakrobotSimulator instancew

            :param steering_noise - variance of steering in move
            :param distance_noise - variance of distance in move
            :param measurement_noise - variance of measurement (GPS??)
            :param map - map for the robot simulator representing the maze or file to map
            :param init_position - starting position of the Robot (can be moved to map class) [x,y,heading]
            :param speed - distance travelled by one move action (cannot be bigger than 0.5, or he could traverse the walls)
            :param simulation_time_limit - limit in ms for whole robot execution (also with init)
            :param collision_threshold - maximum number of collisions after which robot is destroyed
            :param simulation_dt -  controlls simulation calculation intensivity
            :param frame_dt - save frame every dt
            :param robot - RobotController class that will be simulated in run procedure
        """

        if type(map) is str:
            self.map = load_map(map)
            for row in self.map["board"]:
                logger.info(row)
        else:
            self.map = map

        self.iteration_write_frequency = iteration_write_frequency

        self.collision_threshold = collision_threshold

        if init_position is not None:
            self.init_position = tuple(init_position)
        else:
            for i in xrange(self.map["N"]):
                for j in xrange(self.map["M"]):
                    if self.map["board"][i][j] == MAP_START_POSITION:
                        self.init_position = (i + 0.5, j + 0.5, 0)

        self.speed = speed
        self.seed = seed
        self.turning_speed = turning_speed
        self.simulation_dt = simulation_dt
        self.frame_dt = frame_dt
        self.robot_controller = robot_controller
        self.print_robot = print_robot
        self.print_logger = print_logger
        self.accepted_commands = accepted_commands

        self.command_line = command_line

        self.sonar_time = SONAR_TIME
        self.gps_delay = gps_delay
        self.light_sensor_time = LIGHT_SENSOR_TIME

        self.simulation_time_limit = simulation_time_limit
        self.execution_cpu_time_limit = execution_cpu_time_limit

        self.goal_threshold = 0.5  # When to declare goal reach

        self.color_noise = color_noise
        self.sonar_noise = sonar_noise
        self.distance_noise = distance_noise
        self.forward_steering_drift = forward_steering_drift
        self.measurement_noise = measurement_noise
        self.steering_noise = steering_noise
        self.reset()

        # TODO: Disable logger printing when needed
        if self.print_logger:
            logger.propagate = True
        else:
            logger.propagate = False

        for i in xrange(self.map["N"]):
            for j in xrange(self.map["M"]):
                if self.map["board"][i][j] == MAP_GOAL:
                    self.goal = (i, j)
Exemple #16
0
from map import Map, load_map
from pathfinder import Pathfinder

map_40 = load_map()
start = 8
goal = 27
pathfinder = Pathfinder(map_40, start, goal)
path = pathfinder.path

map_40.draw(path)
    def __init__(self,
                 map,
                 robot_controller,
                 init_position=None,
                 steering_noise=0.01,
                 color_noise=10,
                 sonar_noise=0.1,
                 distance_noise=0.001,
                 forward_steering_drift=0,
                 measurement_noise=0.2,
                 speed=5.0,
                 turning_speed=0.4 * pi,
                 execution_cpu_time_limit=10.0,
                 simulation_time_limit=10.0,
                 simulation_dt=0.0,
                 frame_dt=0.1,
                 gps_delay=2.0,
                 collision_threshold=50,
                 iteration_write_frequency=1000,
                 command_line=True,
                 print_robot=True,
                 seed=777,
                 print_logger=False,
                 accepted_commands=[TURN, MOVE, BEEP, FINISH, SENSE_COLOR]):
        """
            Construct KrakrobotSimulator instancew

            :param steering_noise - variance of steering in move
            :param distance_noise - variance of distance in move
            :param measurement_noise - variance of measurement (GPS??)
            :param map - map for the robot simulator representing the maze or file to map
            :param init_position - starting position of the Robot (can be moved to map class) [x,y,heading]
            :param speed - distance travelled by one move action (cannot be bigger than 0.5, or he could traverse the walls)
            :param simulation_time_limit - limit in ms for whole robot execution (also with init)
            :param collision_threshold - maximum number of collisions after which robot is destroyed
            :param simulation_dt -  controlls simulation calculation intensivity
            :param frame_dt - save frame every dt
            :param robot - RobotController class that will be simulated in run procedure
        """

        if type(map) is str:
            self.map = load_map(map)
            for row in self.map['board']:
                logger.info(row)
        else:
            self.map = map

        self.iteration_write_frequency = iteration_write_frequency

        self.collision_threshold = collision_threshold

        if init_position is not None:
            self.init_position = tuple(init_position)
        else:
            for i in xrange(self.map['N']):
                for j in xrange(self.map['M']):
                    if self.map['board'][i][j] == MAP_START_POSITION:
                        self.init_position = (i + 0.5, j + 0.5, 0)

        self.speed = speed
        self.seed = seed
        self.turning_speed = turning_speed
        self.simulation_dt = simulation_dt
        self.frame_dt = frame_dt
        self.robot_controller = robot_controller
        self.print_robot = print_robot
        self.print_logger = print_logger
        self.accepted_commands = accepted_commands

        self.command_line = command_line

        self.sonar_time = SONAR_TIME
        self.gps_delay = gps_delay
        self.light_sensor_time = LIGHT_SENSOR_TIME

        self.simulation_time_limit = simulation_time_limit
        self.execution_cpu_time_limit = execution_cpu_time_limit

        self.goal_threshold = 0.5  # When to declare goal reach

        self.color_noise = color_noise
        self.sonar_noise = sonar_noise
        self.distance_noise = distance_noise
        self.forward_steering_drift = forward_steering_drift
        self.measurement_noise = measurement_noise
        self.steering_noise = steering_noise
        self.reset()

        # TODO: Disable logger printing when needed
        if self.print_logger:
            logger.propagate = True
        else:
            logger.propagate = False

        for i in xrange(self.map['N']):
            for j in xrange(self.map['M']):
                if self.map['board'][i][j] == MAP_GOAL:
                    self.goal = (i, j)