示例#1
0
    def obstPlacement(self):
    #Basic Obstacle Placement Method

    #There are three types of Obstacles: Obstacles, Slow, and Cars
    #Parameteres are imported from obst_type.py
    #Obstacle placement becomes more frequent as level progresses

        self.obsTick += 1
        if self.obsTick >= self.obsNext:
           self.obsTick = 0
           self.obsNext = self.obsNext * random.randint((100 - self.placefreq), 100) / 100
           ot = random.choice(obslist)
           self.obstacle = Obstacle(ot[0], ot[1], ot[2], ot[3], ot[4])
           self.ObstGr.add(self.obstacle)
        self.sloTick += 1

        if self.sloTick >= self.sloNext:
           self.sloTick = 0
           self.sloNext = self.sloNext * random.randint((100 - self.placefreq), 100) / 100
           ot = random.choice(self.slolist)
           self.obstacle = Obstacle(ot[0], ot[1], ot[2], ot[3], ot[4])
           self.ObstGr.add(self.obstacle)
        self.carTick += 1

        if self.carTick >= self.carNext:
           self.carTick = 0
           self.carNext = self.carNext * random.randint((100 - self.placefreq), 100) / 100
           ot = random.choice(self.carlist)
           self.obstacle = Obstacle(ot[0], ot[1], ot[2], ot[3], ot[4])
           self.ObstGr.add(self.obstacle)
示例#2
0
def create_obstacles(screen, obstacles):
    """Create obstacle walls"""
    ob1 = Obstacle(screen, 'horizontal', 393, 140)
    ob2 = Obstacle(screen, 'horizontal', 393, 616)
    ob3 = Obstacle(screen, 'vertical', 240, 293)
    ob4 = Obstacle(screen, 'vertical', 716, 293)
    obstacles.add(ob1, ob2, ob3, ob4)
示例#3
0
def get_sector_1():
    objects = []

    enemy_set = [[150, 22, 0], [210, 18, 1], [210, 28, 2], [240, 10, 3],
                 [240, 15, 3], [240, 30, 4], [240, 35, 4], [240, 40, 4]]
    enemies = [enemy.StrongEnemy(Vector2D(345, 22), 5)]
    for i in range(0, 7):
        enemies.append(
            enemy.TinyEnemy(Vector2D(enemy_set[i][0], enemy_set[i][1]),
                            enemy_set[i][2]))

    objects.append(enemies)
    obstacles = [
        Obstacle(Vector2D(150, 3), 5),
        Obstacle(Vector2D(150, 48), 6),
        Obstacle(Vector2D(230, 3), 2),
        Obstacle(Vector2D(230, 39), 1)
    ]
    objects.append(obstacles)
    powerups = [
        PowerUp(Vector2D(50, 22), 2),
        PowerUp(Vector2D(180, 22), 3),
        PowerUp(Vector2D(250, 22), 1)
    ]
    objects.append(powerups)
    return objects
示例#4
0
 def dummyData(self):
     self.waypoints.append(WayPoint(100, 23, "Rim"))
     self.waypoints.append(WayPoint(150, -23, "Crater"))
     self.waypoints.append(WayPoint(250, 2, "Target"))
     self.obstacles.append(Obstacle(230, 122))
     self.obstacles.append(Obstacle(280, 243))
     self.obstacles.append(Obstacle(350, 23))
示例#5
0
def create_obstacles(number_obstacle):
    for obstacle in range(number_obstacle):
        obstacle_one = Obstacle(random.randint(300, 340),
                                random.randint(100, 150))
        obstacle_two = Obstacle(random.randint(200, 240),
                                random.randint(200, 250))
        list_obstacles.append(obstacle_one)
        list_obstacles.append(obstacle_two)
示例#6
0
    def reset_algorithm(self):
        self.costmap[:] = 0.0
        Obstacle(3, 3, 3, 3).draw(self.costmap)
        Obstacle(9, 5, 3, 3).draw(self.costmap)
        Obstacle(16, 4, 3, 3).draw(self.costmap)

        self.pf = PotentialField(self.costmap)
        self.costmap_widget.canvas.on_map_update()
示例#7
0
    def update(self):
        #Game Loop - Update
        #update all_sprite group
        self.all_sprites.update()
        #update the obstacles
        for obs in self.obstacles:
            obs.update()

        #check if player hits a ground - only if falling
        if self.player.velocity.y > 0:
            hits = pygame.sprite.collide_rect(self.player, self.ground)
            #if player hits a Ground, put him on the ground
            if hits:
                self.player.pos.y = self.ground.rect.y
                self.player.velocity.y = 0

        #ckeck if player hits a obstacle
        for obs in self.obstacles:
            if obs.rect.left < PLAYER_X + 30:
                hits = pygame.sprite.collide_rect(self.player, obs)
                if hits:
                    self.playing = False

        #kill old obstacles and count up score
        for i, obs in enumerate(self.obstacles):
            if obs.rect.left < -60:
                self.score += 10
                self.obstacles.pop(i)

        #only spawn new obstacles if the last one is far enough away
        if not self.soon_boss_Obstacle and self.obstacles[-1].rect.x < 830:
            self.obstacles.append(Obstacle())

        #boss is comming
        if (self.score + 10) % 90 == 0:
            self.soon_boss_Obstacle = True
            self.t0 = time.perf_counter()
            self.once = False

        #timer for boss spawntime
        self.t1 = time.perf_counter()

        #check if t0 existist
        try:
            self.t0
        except AttributeError:
            var_exists = False
        else:
            var_exists = True
        #spawns the boss
        if var_exists:
            if self.t1 - self.t0 > 3 and not self.once:
                self.soon_boss_Obstacle = False
                self.once = True
                bossObs = Obstacle()
                bossObs.speed = 30
                bossObs.setcolor(RED)
                self.obstacles.append(bossObs)
示例#8
0
 def add_obstacles(self, count: int = 1, obstacle_position: List[int] = None):
     for index in range(count):
         if not obstacle_position:
             position = [np.random.randint(0, self.size[0]), np.random.randint(0, self.size[1])]
             if self.is_empty(position):
                 self.obstacles.append(Obstacle(position))
             else:
                 index -= 1
         else:
             self.obstacles.append(Obstacle(obstacle_position))
示例#9
0
    def reset_algorithm(self):
        """Resets the algorithm"""
        self.costmap_widget.canvas.freeze = True
        self.costmap[:] = 0.0
        Obstacle(3, 3, 3, 3).draw(self.costmap)
        Obstacle(9, 5, 3, 3).draw(self.costmap)
        Obstacle(16, 4, 3, 3).draw(self.costmap)

        self.vo = VoronoiExpansion(self.costmap)
        self.costmap_widget.canvas.freeze = False
        self.costmap_widget.canvas.on_map_update()
示例#10
0
    def reset_algorithm(self):
        """Resets the algorithm"""
        self.costmap_widget.canvas.freeze = True
        self.costmap[:] = 0.0
        Obstacle(3, 3, 3, 3).draw(self.costmap)
        Obstacle(9, 5, 3, 3).draw(self.costmap)
        Obstacle(16, 4, 3, 3).draw(self.costmap)

        self.be = BrushfireExpansion(self.costmap)
        temp = self.costmap_widget.canvas.start_coord
        self.start_coord = (floor(temp[0] + 0.5), floor(temp[1] + 0.5))
        self.be.set_ignition_cells([self.start_coord])
        self.costmap_widget.canvas.freeze = False
        self.costmap_widget.canvas.on_map_update()
示例#11
0
 def set_scenario(self, scenario):
     number_of_spots = np.random.choice(scenario.spawn_count)
     self.spawn_x(number_of_spots, scenario.lowest_spot)
     car_x_offset = 20
     car_y_offset = 20
     car_x_limit = scenario.random_car_x
     car_y_limit = scenario.random_car_y
     self.scene.set_car(
         Car((car_x_offset + int(car_x_limit * np.random.random_sample()),
              car_y_offset + int(car_y_limit * np.random.random_sample()))))
     self.scene.add_obstacle(Obstacle(Point(-2, 0), 'obstacle_width.png'))
     self.scene.add_obstacle(Obstacle(Point(720, 0), 'obstacle_width.png'))
     self.scene.add_obstacle(Obstacle(Point(0, -2), 'obstacle_length.png'))
     self.scene.add_obstacle(Obstacle(Point(0, 420), 'obstacle_length.png'))
示例#12
0
    def setup_algorithm(self):
        """Override this"""
        print '(setup_algorithm) Implement me!'
        from costmap import Costmap2D
        from obstacle import Obstacle
        from costmapwidget import Costmap2DWidget
        self.costmap = Costmap2D(DEFAULT_WIDTH,
                                 DEFAULT_HEIGHT,
                                 resolution=DEFAULT_RESOLUTION)
        Obstacle(3, 3, 3, 3).draw(self.costmap)
        Obstacle(5, 9, 3, 3).draw(self.costmap)
        Obstacle(4, 16, 3, 3).draw(self.costmap)

        self.costmap_widget = Costmap2DWidget(self.costmap, parent=self)
 def __init__(self, canvas, obj, window_size):
     self.canvas = canvas
     self.obstacles = [
         Obstacle('rectangle', 50, 50, 100, 100),
         Obstacle('rectangle', 150, 150, 200, 200),
         Obstacle('rectangle', 50, 150, 100, 200),
         Obstacle('rectangle', 150, 50, 200, 100)
     ]
     self.target = [175, 175, 175, 175]
     self.obj = obj
     self.init_obj = obj.save_obj()
     self.window_width = window_size[0]
     self.window_height = window_size[1]
     self.time = 1.
示例#14
0
    def spawn_single_obstacle(self, delta_time):
        """
        Will be called once every second to spawn obstacle in the game. Will consist of a stalagmite or a stalagtite.
        :param delta_time:
        :return:
        """
        if self.game_state == GameState.PAUSE or self.game_state == GameState.PLAYER_EXPLOSION:
            return

        obstacle_type = randint(1, 2)
        if obstacle_type == game_constants.OBSTACLE_DOWNWARD:
            self.obstacle_list.append(Obstacle(True))
        elif obstacle_type == game_constants.OBSTACLE_UPWARD:
            self.obstacle_list.append(Obstacle(False))
示例#15
0
    def setup_algorithm(self):
        """Sets up the algorithm"""
        self.costmap = Costmap2D(DEFAULT_WIDTH,
                                 DEFAULT_HEIGHT,
                                 resolution=DEFAULT_RESOLUTION)
        Obstacle(3, 3, 3, 3).draw(self.costmap)
        Obstacle(9, 5, 3, 3).draw(self.costmap)
        Obstacle(16, 4, 3, 3).draw(self.costmap)

        self.costmap_widget = Costmap2DWidget(self.costmap,
                                              parent=self,
                                              show_goal=False,
                                              show_start=False,
                                              show_colorbar=self.colorbar)
        self.pf = PotentialField(self.costmap)
示例#16
0
def on_key_press(symbol, modifiers):
    if symbol == KEY.P:
        world.paused = not world.paused
    elif symbol == KEY.A:
        world.agents.append(Agent(world))
    elif symbol == KEY.I:
        for agent in world.agents:
            agent.show_info = not agent.show_info
    elif symbol == KEY.O:
        world.obstacles.append(Obstacle(world))
    elif symbol == KEY.C:
        world.obstacles = []
        for agent in world.agents:
            agent.hiding_spots = []
        world.obstacles.append(Obstacle(world))
示例#17
0
    def generate_obstacles_preset_map(self, map_):
        map_file = open(f"./maps/{map_.lower().replace(' ', '_')}.pickle",
                        "rb")
        map_info = pickle.load(map_file)
        tiles_file = open("./maps/texture_id_map.pickle", "rb")
        tiles_info = pickle.load(tiles_file)

        nontiles_file = open("./maps/nontile_id_map.pickle", "rb")
        nontiles_info = pickle.load(nontiles_file)

        #print(tiles_info)
        items = map_info["ammo"]
        tiles = map_info["groundTiles"]
        nontiles = map_info["tiles"]
        self.spawn_points = map_info["spawningPoints"]
        self.items = list()
        self.obstacles = list()

        for item in items:
            self.items.append(
                Item(self.SIZE,
                     x=item["x"],
                     y=item["y"],
                     weapon=item["weapon"]))

        for tile in tiles:
            if tiles_info[tile["id"]].lower().find("water") != -1:

                if tile["x"] >= 0 and tile["x"] < self.SIZE and tile[
                        "y"] >= 0 and tile["y"] < self.SIZE:
                    self.obstacles.append(
                        Obstacle(self.SIZE, x=tile["x"], y=tile["y"]))

        for tile in nontiles:
            if nontiles_info[tile["id"]].lower().find("torch") == -1:
                if nontiles_info[tile["id"]].lower().find("2x2") != -1:
                    for i in range(2):
                        for j in range(2):
                            temp_x = tile["x"] + i
                            temp_y = tile["y"] + j
                            if temp_x >= 0 and temp_x < self.SIZE and temp_y >= 0 and temp_y < self.SIZE:
                                self.obstacles.append(
                                    Obstacle(self.SIZE, x=temp_x, y=temp_y))
                else:
                    if tile["x"] >= 0 and tile["x"] < self.SIZE and tile[
                            "y"] >= 0 and tile["y"] < self.SIZE:
                        self.obstacles.append(
                            Obstacle(self.SIZE, x=tile["x"], y=tile["y"]))
示例#18
0
    def create_obstacle(self):
        """ Create obstacle if stage is more than 1 """

        rotation_speed = self.target.TARGET_ROTATION_SPEED
        rotation_radius = (self.target_collider.height / 2) + 30
        rotation_center = self.target.TARGET_POSITION

        if self.stage > 1:
            # Max obstacle count are inversely proportional to stage knife count
            max_obstacle_count = (self.MAX_KNIFE_COUNT -
                                  self.initial_knife_count) + 2
            obstacle_count = random.randrange(0, max_obstacle_count)

            current_rotation = []
            for i in range(obstacle_count):
                while True:
                    # Randomize the obstacle position
                    initial_rotation_position = random.randrange(0, 359)
                    if not current_rotation:
                        break

                    # Make sure the obstacle are not too close with each other
                    closest_rotation = min(
                        current_rotation,
                        key=lambda x: abs(x - initial_rotation_position))
                    if abs(closest_rotation - initial_rotation_position) > 10:
                        break

                # Create the obstacle
                current_rotation.append(initial_rotation_position)
                self.obstacle = Obstacle(self.GAME_CONFIG, self.target,
                                         initial_rotation_position)
                self.obstacle_list.append(self.obstacle)
示例#19
0
async def fly_garbage(canvas, column, garbage_frame, obs_id, speed=0.5):
    """ Animate garbage, flying from top to bottom. 
    Сolumn position will stay same, as specified on start."""

    frame_row, frame_column = get_frame_size(garbage_frame)

    rows_number, columns_number = canvas.getmaxyx()
    column = max(column, 0)
    column = min(column, columns_number - frame_column - 1)

    row = 1

    obs = Obstacle(row, column, frame_row, frame_column)
    obstacles[obs_id] = obs

    try:
        while row < rows_number:
            draw_frame(canvas, obs.row, obs.column, garbage_frame)
            await asyncio.sleep(0)
            draw_frame(canvas,
                       obs.row,
                       obs.column,
                       garbage_frame,
                       negative=True)
            obs.row += speed
        else:
            obstacles.pop(obs_id)
    except asyncio.CancelledError:
        draw_frame(canvas, obs.row, obs.column, garbage_frame, negative=True)
        coroutines.append(
            explode(canvas, obs.row + round(frame_row / 2),
                    obs.column + round(frame_column / 2)))
        obstacles.pop(obs_id)
        obstacles_to_stop.remove(obs_id)
        return
示例#20
0
def load_obstacles_config(environment):
    """
    :param environment: name of the yaml config file
    :return: all obstacles, area of the environment
    """
    with open('config/' + environment + '.yaml') as file:
        yaml_data = yaml.load(file, Loader=yaml.FullLoader)

        # load environment area parameters
        area = yaml_data['area']
        area = (area['x_min'], area['x_max'], area['y_min'], area['y_max'])

        # load static and dynamic obstacles
        obs = yaml_data['obstacles']
        all_obstacles = []
        for i in range(len(obs)):
            obs_i = Obstacle(
                centroid=[obs[i]['centroid_x'], obs[i]['centroid_y']],
                dx=obs[i]['dx'],
                dy=obs[i]['dy'],
                angle=obs[i]['orientation'] * np.pi / 180,
                vel=[obs[i]['velocity_x'], obs[i]['velocity_y']],
                acc=[obs[i]['acc_x'], obs[i]['acc_y']])
            all_obstacles.append(obs_i)
    return all_obstacles, area
示例#21
0
    def mapWorld(self, maxCount = 10000):

        self.cars = [MappingAgent(0.45 * self.displayWidth, 0.8 * self.displayWidth, self, 0)]
        self.cars[0].prm = self.prm

        count = 0
        while count < maxCount:
            for event in pygame.event.get():
                pass
            count += 1
            self.screen.fill((255, 255, 255))
            for car in self.cars:
                if car.i >= len(car.currentPath) - 1:
                    if car.endPoints:
                        car.setPath(car.endPoints[1], car.prm.sample(self), self)
                    else:
                        car.setPath(car.prm.sample(self), car.prm.sample(self), self)
                car.update(self)
            # redraw all the obstacles
            for obstacle in self.obstacles:
                obstacle.update(self)
            # update the screen
            pygame.display.update()
            self.clock.tick(self.frameRate)
        self.cars[0].buildMap()
        self.cars[0].thresh(0.2)
        self.cars[0].drawMap(self)
        self.obstacleCorners = self.cars[0].getObstacles(self)
        self.obstacleBeliefs = self.obstacles[:4]
        for i in range(0, len(self.obstacleCorners), 2):
            x = self.obstacleCorners[i][0]
            y = self.obstacleCorners[i][1]
            width = abs(self.obstacleCorners[i + 1][0] - x)
            height = abs(self.obstacleCorners[i + 1][1] - y)
            self.obstacleBeliefs.append(Obstacle(x, y, width, height, (0, 0, 0)))
示例#22
0
def addObstacle(gameDisplay, clock):
    cactus = Obstacle(gameDisplay)
    cactus.addToDisplay(obstacle_init_position_X, obstacle_init_position_Y)
    global obstacles
    obstacles.append(cactus)
    global nCycles
    nCycles = 0
示例#23
0
    def reset_algorithm(self):
        """Resets the algorithm"""
        self.costmap_widget.canvas.freeze = True
        self.costmap[:] = 0.0
        Obstacle(3, 3, 3, 3).draw(self.costmap)
        Obstacle(9, 5, 3, 3).draw(self.costmap)
        Obstacle(16, 4, 3, 3).draw(self.costmap)

        temp = self.costmap_widget.canvas.start_coord
        self.start_coord = (floor(temp[0] + 0.5), floor(temp[1] + 0.5))
        temp = self.costmap_widget.canvas.goal_coord
        self.goal_coord = (floor(temp[0] + 0.5), floor(temp[1] + 0.5))
        self.a_star = AStar(self.costmap, self.start_coord, self.goal_coord,
                            self.heuristic)
        self.costmap_widget.canvas.freeze = False
        self.costmap_widget.canvas.on_map_update()
示例#24
0
    def apply_command_welcome(self, cmd):
        phase = cmd[1]
        scores = cmd[2]
        coord = cmd[3]
        obs_coords = cmd[4]

        if (phase == "attente"):
            self.logger.add_message("Waiting to start session")
            self.logger.add_message("Type /race to start a race next")
            self.session_state = "attente"
        elif (phase == "jeu" or phase == "ingame_race"):
            self.logger.add_message("Joining a game")
            self.session_state = "jeu"
            goals_coord = coord.split("|")
            goalx, goaly = parse_coord(goals_coord[0])
            if (len(goals_coord) == 2):
                nextgoalx, nextgoaly = parse_coord(goals_coord[1])
                self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)
            else:
                self.arena.next_goal = None
            self.arena.goal = Goal(goalx, goaly)
            self.main_player.to_display = False  # Wait to get coord before displaying
            for s in scores.split("|"):
                [name, score] = s.split(":")
                if (name in self.arena.players):
                    self.arena.players[name].score = int(score)
                else:
                    new_player = Player("enemy.png", name)
                    new_player.score = int(score)
                    self.arena.players[name] = new_player

            if (len(obs_coords) > 0):
                for o in obs_coords.split("|"):
                    pos = parse_coord(o)
                    self.arena.obstacles.append(Obstacle(pos[0], pos[1]))
示例#25
0
    def apply_command_session(self, cmd):
        coords = cmd[1]
        coord = cmd[2]
        obs_coords = cmd[3]

        self.logger.add_message("Session starting !")
        players_coords = coords.split("|")
        for p in players_coords:
            [name, pos] = p.split(":")
            pos = parse_coord(pos)
            if (name in self.arena.players):
                self.arena.players[name].reset()
                self.arena.players[name].moveTo(pos[0], pos[1])
                self.arena.players[name].to_display = True
            else:
                self.arena.players[name] = Player("enemy.png", name, pos, True)
        goals_coord = coord.split("|")
        goalx, goaly = parse_coord(goals_coord[0])
        if (len(goals_coord) == 2):
            nextgoalx, nextgoaly = parse_coord(goals_coord[1])
            self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)

        self.arena.goal = Goal(goalx, goaly)

        if (len(obs_coords) > 0):
            for o in obs_coords.split("|"):
                pos = parse_coord(o)
                self.arena.obstacles.append(Obstacle(pos[0], pos[1]))

        self.session_state = "jeu"
示例#26
0
 def generate_next_obstacle(self):
     if self.next_obstacle_generate_time - time.time() < 0:
         self.next_obstacle_generate_time = time.time() + random.randint(
             1, 5)
         self.array_obstacles.append(
             Obstacle(self, self.cols_max - 1, self.ground_level,
                      random.randint(2, 4)))
示例#27
0
    def setup_algorithm(self):
        """Sets up the algorithm"""
        self.costmap = Costmap2D(DEFAULT_WIDTH,
                                 DEFAULT_HEIGHT,
                                 resolution=DEFAULT_RESOLUTION)
        Obstacle(3, 3, 3, 3).draw(self.costmap)
        Obstacle(9, 5, 3, 3).draw(self.costmap)
        Obstacle(16, 4, 3, 3).draw(self.costmap)

        self.costmap_widget = Costmap2DWidget(self.costmap,
                                              parent=self,
                                              show_goal=False,
                                              show_colorbar=self.colorbar)
        self.costmap_widget.canvas.show_start = False
        self.costmap_widget.canvas.show_goal = False
        self.vo = VoronoiExpansion(self.costmap)
示例#28
0
    def gameLoop(self):
        while self.gameRunning:
            for event in pygame.event.get():

                if event.type == QUIT:
                    self.gameRunning = False

                elif event.type == E_ADDOBSTACLE:
                    self.graphicsEngine.addObstacle(Obstacle())

                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        self.gameRunning = False
            
            pressed_keys = pygame.key.get_pressed()
            
            if pressed_keys[K_UP] or pressed_keys[K_w]:
                self.graphicsEngine.updatePlayer(DIR_UP)
            
            elif pressed_keys[K_DOWN] or pressed_keys[K_s]:
                self.graphicsEngine.updatePlayer(DIR_DOWN)

            elif pressed_keys[K_LEFT] or pressed_keys[K_a]:
                self.graphicsEngine.updatePlayer(DIR_LEFT)

            elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
                self.graphicsEngine.updatePlayer(DIR_RIGHT)

            self.graphicsEngine.renderGame()
            pygame.display.update()
            self.clock.tick(60)

                
示例#29
0
def collision(player, level):
    for o in levels[level].obstacles:
        if rect_collision(
                Obstacle(player.x, player.y, player.side, player.side), o):
            return True
    return not (0 <= player.x and player.x + player.side < C.WIDTH
                and 0 <= player.y and player.y + player.side < C.HEIGHT)
示例#30
0
def on_mouse_press(x, y, button, modifiers):
    if button == 1:  # left
        world.target = Vector2D(x, y)
    elif window.mouse.RIGHT:
        world.obstacle.append((Obstacle(world, Vector2D(x, y))))
        if modifiers & KEY.MOD_ALT:
            world.obstacle.clear()