def on_road(self, car, screen):
        Ox = 32
        Oy = 16
        center_world_x = int(self.screen_width / 2)
        center_world_y = int(self.screen_height / 2)

        bot_right_x = center_world_x + int(Ox * cos(radians(-car.angle))) - int(Oy * sin(radians(-car.angle)))
        bot_right_y = center_world_y + int(Ox * sin(radians(-car.angle))) + int(Oy * cos(radians(-car.angle)))

        bot_left_x = center_world_x - int(Ox * cos(radians(-car.angle))) - int(Oy * sin(radians(-car.angle)))
        bot_left_y = center_world_y - int(Ox * sin(radians(-car.angle))) + int(Oy * cos(radians(-car.angle)))

        top_left_x = center_world_x - int(Ox * cos(radians(-car.angle))) + int(Oy * sin(radians(-car.angle)))
        top_left_y = center_world_y - int(Ox * sin(radians(-car.angle))) - int(Oy * cos(radians(-car.angle)))

        top_right_x = center_world_x + int(Ox * cos(radians(-car.angle))) + int(Oy * sin(radians(-car.angle)))
        top_right_y = center_world_y + int(Ox * sin(radians(-car.angle))) - int(Oy * cos(radians(-car.angle)))

        if (np.array_equal(screen.get_at((bot_right_x, bot_right_y)), self.bkd_color) or np.array_equal
            (screen.get_at((bot_left_x, bot_left_y)), self.bkd_color) or
                np.array_equal(screen.get_at((top_left_x, top_left_y)), self.bkd_color) or
                np.array_equal(screen.get_at((top_right_x, top_right_y)), self.bkd_color)):
            Collision.offroad(car)
            return False
        else:
            return True
Esempio n. 2
0
def test_performance():
    # warmup run for mem allocation
    lengthscale = 0.03
    n = 300000
    points = np.random.rand(n, 3).astype(np.float32)
    spec = spatial.Spec3d(points, lengthscale)

    start = time.clock()
    grid = spatial.Grid3d(spec, points)
    warmup = time.clock() - start

    # run on unsorted data
    points = np.random.rand(n, 3).astype(np.float32)
    start = time.clock()
    grid = spatial.Grid3d(spec, points)
    unsorted = time.clock() - start

    # update from existing
    start = time.clock()
    grid = grid.update(points)
    update = time.clock() - start

    # sort data
    points = points[grid.permutation]

    # run on sorted data
    start = time.clock()
    grid = spatial.Grid3d(spec, points)
    sorted = time.clock() - start

    print(warmup, unsorted, update, sorted)
    def optimized_front_sensor(self):
        # act_mask is a separate image where you can only see what the sensor sees
        center_rect = Collision.center_rect(self.screen_width,
                                            self.screen_height)
        mid_of_front_axle = Collision.point_rotation(self.car, -1, 16,
                                                     center_rect)

        arc_points = get_arc_points(mid_of_front_axle, 150,
                                    radians(90 + self.car.angle),
                                    radians(270 + self.car.angle), 80)

        offroad_edge_points = []

        for end_point in arc_points:
            points_to_be_checked = list(
                get_equidistant_points(mid_of_front_axle, end_point, 25))

            check = False

            for line_point in points_to_be_checked:
                if np.array_equal(
                        self.screen.get_at(
                            (int(line_point[0]), int(line_point[1]))),
                        self.obstacle_color):
                    check = True
                    break

            if check is False:
                offroad_edge_points.append(end_point)
            else:
                offroad_edge_points.append(line_point)

        return mid_of_front_axle, arc_points, offroad_edge_points
Esempio n. 4
0
    def __init__(self):
        self.d0 = 0
        self.v0 = 0

        self.d = 0
        self.v = 0
        self.a = 0
        self.F = 0

        self.t = 0
        self.dt = 0.001

        self.m = 0.1
        self.B = 0.1

        self.d_array = []
        self.v_array = []
        self.a_array = []
        self.f_array = []
        self.t_array = []
        self.fext_array = []

        self._m_store_trajectory = False
        self._f_array_set = False
        self._compute_collision = False
        self.Col_obj = Collision()
        self._sim_finished = False
Esempio n. 5
0
 def collision_prepare(self):
     # self.spatial_grid = self.spatial_grid.update(self.position)
     # bounds = np.array([[-10]*3, [10]*3]).astype(np.float32)
     self.spec = spatial.Spec3d(self.position, self.scale)
     self.offsets = self.spec.stencil(self.stencil).astype(np.int32)
     self.spatial_grid = spatial.Grid3d(self.spec, self.position,
                                        self.offsets)
Esempio n. 6
0
    def _detect_collisions(self):
        """
        Collision detector:
            - detects future collisions between self and other cars
            - creates new Collision objects and sends them to the main queue
        """

        while not self._kill:
            if len(self.frames) == 0:
                continue
            curr_frame = self.frames[-1]
            my_vals = curr_frame[self.name]

            # don't waste time on old frames
            if self._last_frame_number >= my_vals[-1]:
                continue

            self._last_frame_number = my_vals[-1]

            # +1 makes loop inclusive
            for dt in xrange(utils.FRAME_STEP, utils.FRAME_LOOKAHEAD + 1,
                             utils.FRAME_STEP):
                my_future_pos = (my_vals[0] + my_vals[3] * dt,
                                 my_vals[1] + my_vals[4] * dt)

                for car_name, vals in curr_frame.iteritems():
                    if car_name == self.name:
                        continue

                    dx = vals[3] * dt
                    dy = vals[4] * dt
                    future_pos = (vals[0] + dx, vals[1] + dy)

                    if not utils.SAFE_DISTANCE(my_future_pos, future_pos):

                        if car_name not in self._collisions:
                            print "NEW COLLISION"
                            if dt > utils.COLLISION_CRITICAL:
                                self._collisions[car_name] = Collision(
                                    car_name, self._last_frame_number + dt,
                                    utils.CENTER_POINT(my_future_pos,
                                                       future_pos))
                            else:
                                self._collisions[car_name] = Collision(
                                    car_name,
                                    self._last_frame_number + dt,
                                    utils.CENTER_POINT(my_future_pos,
                                                       future_pos),
                                    critical=True)
                        else:
                            # print "REPEAT"
                            if dt <= utils.COLLISION_CRITICAL:
                                # print "START CRITICAL"
                                self._collisions[car_name].lock.acquire()
                                self._collisions[car_name].critical = True
                                self._collisions[car_name].lock.release()
                                print "DETECTED CRITICAL COLLISION", car_name

            time.sleep(utils.THREAD_SLEEP)
    def optimized_rear_sensor(self, car, act_mask, display_obstacle_on_sensor=False):
        """
        rear visual sensor
        :param car:
        :param object_mask:
        :param act_mask:
        :param display_obstacle_on_sensor:
        :return:
        """
        # act_mask is a separate image where you can only see what the sensor sees
        position = self.global_cars_positions[car.car_tag]
        center = Collision.calculate_center_for_car(car, position)
        if car.car_tag == self.current_car:
            center = Collision.center_rect(self.screen_width, self.screen_height)
        mid_of_rear_axle = Collision.point_rotation(car, 65, 16, center)

        arc_points = get_arc_points(mid_of_rear_axle, 150, radians(-90 + car.angle), radians(90 + car.angle),
                                    self.sensor_size)

        draw_center = Collision.center_rect(self.screen_width, self.screen_height)
        draw_mid_rear_axle = Collision.point_rotation(car, 65, 16, draw_center)
        draw_arc_points = get_arc_points(draw_mid_rear_axle, 150, radians(-90 + car.angle), radians(90 + car.angle),
                                         self.sensor_size)

        offroad_edge_points = []
        draw_offroad_edge_points = []

        for end_point, draw_end_point in zip(arc_points, draw_arc_points):
            points_to_be_checked = list(get_equidistant_points(mid_of_rear_axle, end_point, 25))
            draw_points_to_be_checked = list(get_equidistant_points(draw_mid_rear_axle, draw_end_point, 25))

            check = False

            for line_point, draw_line_point in zip(points_to_be_checked, draw_points_to_be_checked):
                try:
                    if np.array_equal(self.object_mask.get_at((int(line_point[0]), int(line_point[1]))), self.bkd_color):
                        check = True
                        break
                except:
                    check = True
                    break

            if check is False:
                offroad_edge_points.append(end_point)
                draw_offroad_edge_points.append(draw_end_point)
            else:
                offroad_edge_points.append(line_point)
                draw_offroad_edge_points.append(draw_line_point)

        for index in range(0, len(arc_points)):
            if offroad_edge_points[index] == arc_points[index]:
                pygame.draw.line(self.screen, (0, 255, 0), mid_of_rear_axle, arc_points[index], True)
                pygame.draw.line(act_mask, (0, 255, 0), draw_mid_rear_axle, draw_arc_points[index], True)
            else:
                pygame.draw.line(self.screen, (0, 255, 0), mid_of_rear_axle, offroad_edge_points[index], True)
                pygame.draw.line(act_mask, (0, 255, 0), draw_mid_rear_axle, draw_offroad_edge_points[index], True)
                if display_obstacle_on_sensor is True:
                    pygame.draw.line(self.screen, (255, 0, 0), offroad_edge_points[index], arc_points[index], True)
                    pygame.draw.line(act_mask, (255, 0, 0), draw_offroad_edge_points[index], draw_arc_points[index], True)
class Player(pygame.sprite.Sprite):

    def __init__(self, manager, sprite, frame_data, player_initial_position, ball, sfx):
        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)
        self.change_x = 0
        self.change_y = 0
        self.frames = []
        self.manager = manager
        player_frames = SpriteFactory.generate_frames(sprite, frame_data)
        image = player_frames[0]
        self.frames.append(image)
        self.manager.add(self)
        # Set the image the player starts with
        self.image = self.frames[0]
        # Set a reference to the image rect
        self.rect = self.image.get_rect()
        # self.center = self.rect.width / 2, self.rect.height / 2
        self.rect.x = player_initial_position[0]
        self.rect.y = player_initial_position[1]
        self.radius = 37
        self.m = 50
        self.collision = Collision()
        self.ball = ball
        self.player_list = []
        self.sfx = sfx
        self.player_vs_ball_observable = PlayerVsBallObservable()
        self.player_vs_ball_observer = PlayerVsBallObserver(sfx)
        self.player_vs_ball_observable.register(self.player_vs_ball_observer)
        self.direction = [0, 0]

    def update(self):
        # Move left/right/up/down
        self.collision.collisionPlayer2Wall(self)
        self.rect.x += self.change_x
        self.rect.y += self.change_y
        self.collision.collisionPlayer2Ball(self, self.ball, self.player_vs_ball_observable)

    def go_left(self):
        self.change_x = -6
        self.change_y = 0

    def go_right(self):
        self.change_x = 6
        self.change_y = 0

    def go_up(self):
        self.change_y = -6
        self.change_x = 0

    def go_down(self):
        self.change_y = 6
        self.change_x = 0

    def stop(self):
        self.change_x = 0
        self.change_y = 0
    def getPlayerList(self, player_list):
        self.player_list = player_list
Esempio n. 9
0
    def optimized_front_sensor(self,
                               act_mask,
                               display_obstacle_on_sensor=False):
        """
        front visual sensor
        :param act_mask:
        :param display_obstacle_on_sensor:
        :return:
        """
        # act_mask is a separate image where you can only see what the sensor sees
        center_rect = Collision.center_rect(self.screen_width,
                                            self.screen_height)
        mid_of_front_axle = Collision.point_rotation(self.car, -1, 16,
                                                     center_rect)

        arc_points = get_arc_points(mid_of_front_axle, 150,
                                    radians(90 + self.car.angle),
                                    radians(270 + self.car.angle),
                                    self.sensor_size)

        offroad_edge_points = []

        for end_point in arc_points:
            points_to_be_checked = list(
                get_equidistant_points(mid_of_front_axle, end_point, 25))

            check = False

            for line_point in points_to_be_checked:
                if np.array_equal(
                        self.object_mask.get_at(
                            (int(line_point[0]), int(line_point[1]))),
                        self.bkd_color):
                    check = True
                    break

            if check is False:
                offroad_edge_points.append(end_point)
            else:
                offroad_edge_points.append(line_point)

        for index in range(0, len(arc_points)):
            if offroad_edge_points[index] == arc_points[index]:
                pygame.draw.line(self.screen, (0, 255, 0), mid_of_front_axle,
                                 arc_points[index], True)
                pygame.draw.line(act_mask, (0, 255, 0), mid_of_front_axle,
                                 arc_points[index], True)
            else:
                pygame.draw.line(self.screen, (0, 255, 0), mid_of_front_axle,
                                 offroad_edge_points[index], True)
                pygame.draw.line(act_mask, (0, 255, 0), mid_of_front_axle,
                                 offroad_edge_points[index], True)
                if display_obstacle_on_sensor is True:
                    pygame.draw.line(self.screen, (255, 0, 0),
                                     offroad_edge_points[index],
                                     arc_points[index], True)
                    pygame.draw.line(act_mask, (255, 0, 0),
                                     offroad_edge_points[index],
                                     arc_points[index], True)
Esempio n. 10
0
    def debug_draw(self, screen):
        if DEBUG:
            self.wall_container.debug_draw(screen)
            for robot in self.robots:
                robot.debug_draw(screen)
            Collision.debug_draw(screen)

            self.line_of_sight.debug_draw(screen, (255, 255, 255))
Esempio n. 11
0
 def testRedundancyMultipleOccurence(self):
     tiles = ['s', 'a', 'f', 'e', None, None, 's', 'a', 'f', None]
     nodes = self.create_horizontal_nodes(tiles)
     placements = Placement.placements('safe', nodes[0])
     placement = placements[0]
     self.assertFalse(Collision.safe(placement))
     placements = Placement.placements('safe', nodes[6])
     placement = placements[0]
     self.assertTrue(Collision.safe(placement))
Esempio n. 12
0
    def reset(self,
              scored=False,
              puck_was_hit=False,
              puck_is_at_the_bottom=False,
              distance_decreased=False,
              hit_the_border=False):

        draw_puck = self.use_object['puck']
        draw_top_mallet = self.use_object['top_mallet']

        # 重置冰球、两个击球器的位置
        if draw_puck:
            # self.puck.reset(self.dim, self.dim.rink_top, self.dim.center[1])
            # self.puck.reset(self.dim, self.dim.center[1], self.dim.rink_bottom-self.dim.mallet_radius-10) # 将冰球置于中线以下
            self.puck.reset(self.dim,
                            self.dim.rink_top + self.dim.mallet_radius + 10,
                            self.dim.center[1])
            # self.puck.reset(self.dim, self.dim.rink_top - self.dim.mallet_radius , self.dim.rink_top - self.dim.mallet_radius+1)
            self.bottom_mallet.reset(self.dim, self.dim.center[1],
                                     self.dim.rink_bottom)

        if draw_top_mallet:
            self.top_mallet.reset(self.dim, self.dim.rink_top,
                                  self.dim.center[1])

        self.motions.clear_all_motions()

        # Resolve possible interpenetration
        Collision.circle_circle([self.puck, self.top_mallet])
        Collision.circle_circle([self.top_mallet, self.bottom_mallet])
        # 计算小球是否在bottom_target这个圆圈里
        in_the_target = Collision.circle_circle(
            [self.bottom_mallet, self.bottom_target], resolve=False)

        # 读取贴图
        # self.sprites, self.dominant_arm = load_sprites()
        # 画图
        self.render()

        puck_position = self.puck.get_position()
        puck_velocity = V.address_data(self.puck.get_velocity())
        bottom_mallet_position = self.bottom_mallet.get_position()
        bottom_mallet_velocity = V.address_data(
            self.bottom_mallet.get_velocity())
        top_mallet_position = self.top_mallet.get_position()
        top_mallet_velocity = V.address_data(self.top_mallet.get_velocity())

        puck_position_mode = bool(
            self.dim.center[1] <= puck_position[1] <= self.dim.rink_bottom)
        game_info = GameInfo([], puck_position, puck_velocity,
                             bottom_mallet_position, bottom_mallet_velocity,
                             top_mallet_position, top_mallet_velocity,
                             puck_was_hit, puck_is_at_the_bottom,
                             distance_decreased, hit_the_border, in_the_target,
                             puck_position_mode)

        return game_info
Esempio n. 13
0
 def collision_lines_with_trail(self, lines, location, cycle_number):
     if Collision.intersect_lines_to_lines(lines, self._trail):
         return True
     if not self._trail_on:
         return False
     if self._cycle_number == cycle_number:
         return False
     if Collision.intersect_lines_to_lines(
             lines, ((self._trail_start_location, location), )):
         return True
     return False
Esempio n. 14
0
 def collision(self, lines, cycle_trail, location):
     if Collision.intersect_lines_to_lines(lines, cycle_trail._trail):
         return True
     if not cycle_trail._trail_on:
         return False
     if self == cycle_trail:
         return False
     if Collision.intersect_lines_to_lines(
             lines, ((cycle_trail._trail_start_location, location), )):
         return True
     return False
Esempio n. 15
0
 def testRedundancy(self):
     # Run the test again, but without any empty space.
     tiles = ['s', 'a', 'f', 'e', None, None]
     nodes = self.create_horizontal_nodes(tiles)
     placements = Placement.placements('safe', nodes[0])
     placement = placements[0]
     self.assertFalse(Collision.safe(placement))
     tiles = ['a', 'b', 's', 'a', 'f', 'e', 't', 'b', 'z', 'x', 'h']
     nodes = self.create_horizontal_nodes(tiles)
     placements = Placement.placements('safe', nodes[2])
     placement = placements[0]
     self.assertEqual(placement.node(0), nodes[2])
     self.assertEqual(placement.node(0).letter, 's')
     self.assertFalse(Collision.safe(placement))
Esempio n. 16
0
 def testPreexistingLetters(self):
     tiles = [None, None, None, 'x', 'z', 's', None, 'f', None]
     nodes = self.create_vertical_nodes(tiles)
     placements = Placement.placements('safe', nodes[5])
     self.assertEqual(len(placements), 2)
     placement = placements[1]
     self.assertTrue(placement, Collision.safe(placement))
     # The preexisting letters should contain the lettera 's' and 'f' because
     # when placing the word 'safe' across from the letter 's' the letter 'f'
     # would be used as well.
     letters = Collision.preexisting_letters(placement)
     self.assertEqual(len(letters), 2)
     self.assertEqual(letters[0], 's')
     self.assertEqual(letters[1], 'f')
Esempio n. 17
0
 def __init__(self, lan):
     pygame.init()
     self.gravity = 0
     self.rotated = 0
     self.next_figure = self.get_random_figure()
     self.figure = self.get_random_figure()
     self.stage = Stage()
     self.menu = Menu(self.stage, self.next_figure)
     self.collision = Collision(self.stage)
     self.move_x = 0
     self.move_y = 0
     if lan is None:
         self.second_player = NoPlayer()
     else:
         self.second_player = LanSecondPlayer(self.menu, lan)
Esempio n. 18
0
    def testHorizontalSafe(self):
        tiles = [None, 's', None, 'f', None]
        nodes = self.create_horizontal_nodes(tiles)
        placements = Placement.placements('safe', nodes[1])
        self.assertEqual(len(placements), 2)

        placement = placements[0]
        # Test that we have the right start node.
        self.assertEqual(placement.node(0), nodes[1])

        # Make sure that there is no collision.
        self.assertTrue(Collision.safe(placement))

        vertical_placement = placements[1]
        self.assertEqual(vertical_placement.node(0), nodes[1])
        self.assertFalse(Collision.safe(vertical_placement))
Esempio n. 19
0
    def __init__(self, level, speed, tileset, **kwargs):
        super().__init__(dirRule=lambda: {
            -1: Direction.Left,
            0: None,
            1: Direction.Right
        }[self.move.getDir(x=True)],
                         **kwargs)
        self.collision = Collision(self, level)
        self.move = Move(self, speed, collision=self.collision)
        self._gravity = GravityLine(self, 2, h=level.map.h // 2)
        self.jumping = Jumping(self.move, self._gravity, 2)
        self._input = Input(inputStream=self.getInputStream())
        self.applyInputSettings()
        self._damageTimer = MinTimeEventStream(duration=2)
        self._damageTimer.subscribe("self", self._takeDmg, autoInit=False)

        def _isMoving():
            return self.move.getSpeed(x=True) != 0

        def _hDir():
            return self.move.getDir(x=True)

        def _vDir():
            return {False: -1, True: 1}[self._gravity.positiveDir()]

        image = Files.loadImage(tileset)
        self._display = Display(image, self,
                                Animation(image, 11, _isMoving, _hDir, _vDir),
                                True)
        self._weapon = Weapon(level,
                              anchor=self,
                              offsetFunc=lambda: ((5 * self.getIntDir()), 0),
                              inputStream=self.getInputStream())
Esempio n. 20
0
    def collide(self):
        for a in self.actors:
            a.collision_prepare()

        for i, ai in enumerate(self.actors):
            if isinstance(ai, ParticleActor):
                ai.collision_self()

            for j, aj in enumerate(self.actors):
                if isinstance(aj, ParticleActor):
                    continue
                if i == j: continue
                info = spatial.Info(ai.spatial_grid, aj.spatial_mesh, i == j)
                mask = info.triangle != -1
                active = np.flatnonzero(mask)  # active vertex idx
                if np.any(mask):  # and not isinstance(ai, StaticActor):
                    triangle = info.triangle[active]
                    bary = info.bary[active]

                    velocity = aj.velocity[aj.mesh.faces[triangle]]
                    velocity = np.einsum('vtc,vt->vc', velocity, bary)
                    relative_velocity = ai.velocity[active] - velocity

                    friction = 1e-2
                    stiffness = 1e1
                    force = info.depth[active][:, None] * info.normal[
                        active] * stiffness - relative_velocity * friction
                    assert not np.any(np.isnan(force))

                    np.add.at(ai.force, active, force)
                    corners = aj.mesh.faces[triangle]
                    for i in range(3):
                        np.add.at(aj.force, corners[:, i],
                                  -bary[:, [i]] * force)
 def __init__(self, manager, sprite, frame_data, player_initial_position, ball, sfx):
     # Call the parent's constructor
     pygame.sprite.Sprite.__init__(self)
     self.change_x = 0
     self.change_y = 0
     self.frames = []
     self.manager = manager
     player_frames = SpriteFactory.generate_frames(sprite, frame_data)
     image = player_frames[0]
     self.frames.append(image)
     self.manager.add(self)
     # Set the image the player starts with
     self.image = self.frames[0]
     # Set a reference to the image rect
     self.rect = self.image.get_rect()
     # self.center = self.rect.width / 2, self.rect.height / 2
     self.rect.x = player_initial_position[0]
     self.rect.y = player_initial_position[1]
     self.radius = 37
     self.m = 50
     self.collision = Collision()
     self.ball = ball
     self.player_list = []
     self.sfx = sfx
     self.player_vs_ball_observable = PlayerVsBallObservable()
     self.player_vs_ball_observer = PlayerVsBallObserver(sfx)
     self.player_vs_ball_observable.register(self.player_vs_ball_observer)
     self.direction = [0, 0]
Esempio n. 22
0
    def __init__(self, rect, speed, tileset, level, maxHealth, **kwargs):
        super().__init__(rect=rect,
                         dirRule=lambda: {
                             -1: Direction.Left,
                             0: None,
                             1: Direction.Right,
                         }[self.move.getDir(x=True)],
                         idName="enemy",
                         baseHealth=maxHealth,
                         **kwargs)

        self.collision = Collision(self, level, "enemy")
        self.move = Move(self, speed, self.collision)
        self.gravity = GravityLine(self, 2, h=level.map.h // 2)
        self._ai = AI(self)

        def _isMoving():
            return self.move.getSpeed(x=True) != 0

        def _hDir():
            return self.move.getDir(x=True)

        def _vDir():
            return {False: -1, True: 1}[self.gravity.positiveDir()]

        image = Files.loadImage(tileset)
        self._display = Display(image, self,
                                Animation(image, 11, _isMoving, _hDir, _vDir),
                                True)
Esempio n. 23
0
def test_basic():
    lengthscale = 0.5
    points = np.random.rand(30, 2).astype(np.float32)
    grid = spatial.Grid2d(points, lengthscale)
    print(grid.permutation)
    print(grid.pivots)  #[:grid.n_buckets+1])
    print(grid.n_buckets)
    print(grid.cells[grid.permutation])
Esempio n. 24
0
File: main.py Progetto: iPazu/Slimy
 def loadEntities(self):
     startingPoint = (100, 0, 10)
     self.AIworld = AIWorld(render)
     self.collision = Collision(Monster.monster)
     #terrain, initialPos, slimeModelPath, floorPos, scale, lifePoint, volumicMass, movingSpeed, dt
     self.slime = Slime(self.terrain, startingPoint, "assets/models/slime.egg", 10, 10, 100, 0.01, 5, self.dt, "slime", self.collision) 
     self.spawn = Spawn([self.slime]+Monster.monster, self.terrain, self.AIworld, self.collision)
     self.spawn.spawn()
Esempio n. 25
0
    def __init__(self, window_x, window_y):
        self.window_x = window_x
        self.window_y = window_y
        self.WINDOW_WIDTH = 800
        self.WINDOW_HEIGHT = 600
        self.backgroundColor = (255, 255, 255)
        self.textColor = (0, 0, 0)

        self.is_running = True
        pygame.init()
        self.fps_controller = fps_limiter(
        )  # IMPORTANT - FPS Controller must be started AFTER the call to
        # pygame.init(). The timer in pygame gets the time in milliseconds
        self.up_pressed = False  # from the call to pygame.init().
        self.down_pressed = False
        self.left_pressed = False
        self.right_pressed = False

        self.pressed = None  # Empty object to store output from pygame.key.get_pressed()

        self.up = pygame.K_UP  # Key constants redefined for easier typing
        self.down = pygame.K_DOWN
        self.left = pygame.K_LEFT
        self.right = pygame.K_RIGHT
        self.space = pygame.K_SPACE

        # Setup for the screen, background, and player objects
        self.screen = pygame.display.set_mode(
            (self.WINDOW_WIDTH, self.WINDOW_HEIGHT))
        self.background = pygame.Surface(
            (self.WINDOW_WIDTH, self.WINDOW_HEIGHT))
        self.background.fill(self.backgroundColor, None)
        self.player = Player("Gjiorgisborgen")
        self.player.setup_entity(400, 400, 30, 30)

        # Font initialization
        pygame.font.init()
        self.text_font = pygame.font.SysFont(pygame.font.get_default_font(),
                                             20)

        # Text Surface initial render
        self.player_info = self.text_font.render(self.player.__str__(), True,
                                                 (0, 0, 0))

        # Collision detection object
        self.collision_checker = Collision(self.player)
Esempio n. 26
0
 def testHorizontalCollision(self):
     tiles = [None, 's', 'a', 'e', None]
     nodes = self.create_horizontal_nodes(tiles)
     placements = Placement.placements('safe', nodes[1])
     # We expect the vertical and horizontal placements.
     placement = placements[0]
     self.assertEqual(placement.node(0), nodes[1])
     self.assertFalse(Collision.safe(placement))
Esempio n. 27
0
    def checkForCollision(self):
        self.__collisionPoints.clear()
        self.__collisions.clear()

        # for enemy in self.__enemies:
        #    if enemy.getRect().colliderect(self.__tank.getRect()):
        #        print(f"Enemy {enemy.getEnemyId()} brought your tank down")
        #        enemy.setActive(False)
        #        self.__scoreCard.loseLife()

        for missile in self.__missiles:
            if missile.getRect().top <= 5:
                missile.setActive(False)
                print(f"Missile {missile.getMissileId()} missed")

        for enemy in self.__enemies:
            if enemy.getRect().bottom >= (self.__graphics.getFieldSize()[1] -
                                          5):
                enemy.setActive(False)
                print(f"Enemy {enemy.getEnemyId()} attached your fort")
                self.__scoreCard.loseLife()

        for missile in self.__missiles:
            if missile.isActive():
                for enemy in self.__enemies:
                    if enemy.isActive():
                        if missile.getRect().colliderect(enemy.getRect()):
                            # print(f"Missile {missile.getMissileId()} at {missile.getRect()} collides with Enemy "
                            #      f"{enemy.getEnemyId()} at {enemy.getRect()}")
                            # print(missile.getRect())
                            # print(enemy.getRect())
                            missile.setActive(False)
                            enemy.setActive(False)
                            # print("Collision")
                            # collisionPosition = (missile.getRect()[0], missile.getRect()[1])
                            collisionPoint = ((int(enemy.getRect().left +
                                                   missile.getRect().left) /
                                               2),
                                              (int(enemy.getRect().bottom +
                                                   missile.getRect().top) / 2))
                            self.__missiles.remove(missile)
                            self.__enemies.remove(enemy)
                            collision = Collision()
                            collision.setCollisionPoint(collisionPoint)
                            self.__collisionPoints.append(collisionPoint)
                            self.__collisions.append(collision)
Esempio n. 28
0
def test_mesh():
    mesh = icosphere(0.5, refinement=3)
    edge_length = float(mesh.edge_lengths().mean())
    normals = mesh.vertex_normals()
    cmesh = spatial.Mesh(mesh.vertices, mesh.vertex_normals(), mesh.faces,
                         edge_length, edge_length)
    boxes = cmesh.boxes.reshape(-1, 3, 2).transpose(0, 2, 1)
    for box in boxes[:10]:
        print(box)
Esempio n. 29
0
 def testVerticalSafe(self):
     tiles = [None, 's', None, 'f', None]
     nodes = self.create_vertical_nodes(tiles)
     placements = Placement.placements('safe', nodes[1])
     # There should be two placement objects returned from the previous static
     # method.
     # One would attempt to place it to the right, and the other downward. Of
     # course the downward placement would fall right off the board, and should
     # not pass the collision safety test.
     self.assertEqual(len(placements), 2)
     placement = placements[1]
     # Test that we have the right start node.
     self.assertEqual(placement.node(0), nodes[1])
     # Make sure that there is no collision.
     self.assertTrue(Collision.safe(placement))
     horizontal_placement = placements[0]
     self.assertEqual(horizontal_placement.node(0), nodes[1])
     self.assertFalse(Collision.safe(horizontal_placement))
Esempio n. 30
0
def test_collision():
    meshes = [
        icosphere(0.5, refinement=3),
        icosphere(0.5, [0.95, 0, 0], refinement=3)
    ]
    lengthscale = 0.2
    grids = [spatial.Grid3d(m.vertices, lengthscale) for m in meshes]
    ctmeshes = [
        spatial.Mesh(m.vertices, m.vertex_normals(), m.faces, 0.1, 0)
        for m in meshes
    ]

    for i, mi in enumerate(meshes):
        for j, mj in enumerate(meshes):
            print(i, j)
            info = spatial.Info(grids[i], ctmeshes[j], i == j)
            mask = info.triangle != -1
            print(info.triangle[mask])
            print(info.depth[mask])
Esempio n. 31
0
 def enable_sensor(self, car, draw_screen, rays_nr):
     """
     distance sensor
     :param car:
     :param data_screen:
     :param draw_screen:
     :param rays_nr:
     :return:
     """
     center_rect = Collision.center_rect(self.screen_width,
                                         self.screen_height)
     mid_of_front_axle = Collision.point_rotation(car, 0, 16, center_rect)
     distance = np.array([])
     for angle_index in range(120, 240, int(round(120 / rays_nr))):
         distance = np.append(
             distance,
             self.compute_sensor_distance(car, mid_of_front_axle, 200,
                                          angle_index, self.object_mask,
                                          draw_screen))
     return distance
Esempio n. 32
0
 def testNodesMatchingLetter(self):
     tiles = [['', '', '', 'x', 'z', 's', '', 'f', '']]
     board = Board(tiles)
     first_row = board.nodes[0]
     placements = Placement.placements('safe', first_row[5])
     placement = placements[0]
     nodes = Collision.nodes_matching_letter(placement, 'f')
     self.assertEqual(len(nodes), 1)
     f_node = nodes[0]
     self.assertEqual(f_node.letter, 'f')
     self.assertTrue(f_node.placed)
 def __init__(self, manager, position, frame, sfx, speed=1000):
     Animation.__init__(self, manager, frame, speed)
     self.collision = Collision()
     self.set_position_center(position[0], position[1])
     self.change_x = 0
     self.change_y = 0
     self.radius = 15.5
     self.is_ball_going_in = False
     self.is_ball_hit_wall = False
     self.goal = False
     self.m = 0.45
     self.prevent = 1.01
     self.ball_vs_wall_observable = BallVsWallObservable()
     self.ball_vs_wall_observer = BallVsWallObserver(sfx)
     self.ball_vs_wall_observable.register(self.ball_vs_wall_observer)
 def __init__(self):
     self.number_of_user = 0
     self.userList = []
     self.player_list = []
     self.screen = None
     self.sfx = SoundEffects()
     self.display_init()
     self.sprite_group = pygame.sprite.Group()
     self.focus_effect_group = pygame.sprite.Group()
     self.goal_effect_group = pygame.sprite.Group()
     self.ball = self.ball_init(self.sfx)
     self.user_init(self.ball, self.sfx)
     self.platform = None
     self.platform_init()
     self.done = False
     self.focus_effect_blue = None
     self.focus_effect_red = None
     self.focus_effect_list = []
     self.focus_effect_init()
     self.collision = Collision()
     self.scoreboard = Scoreboard(self.screen)
     self.ball_reset_delay = 2000
     self.goal_effect_init()
     self.max_score = 3
Esempio n. 35
0
    def get_matrix_contribution(self,
                                grid_points,
                                frequency_step=1.0,
                                sigmas=[0.1],
                                is_adaptive_sigma=False,
                                filename=None):
        mc = Collision(self._interaction,
                            sigmas=sigmas,
                            is_adaptive_sigma=is_adaptive_sigma,
                            frequencies = self._frequencies,
                            degeneracy=self._degeneracy,
                            write=write_scr,
                            read=read_scr,
                            cutoff_frequency=self._cutfr,
                            cutoff_lifetime=self._cutlt)
        is_sum = False
        if grid_points == None:
            is_sum = True
            if self._is_nosym: # All grid points
                grid_points = np.arange(np.product(self._mesh))
            else: # Automatic sampling
                (grid_points,
                 grid_weights,
                 grid_address) = get_ir_grid_points(
                    self._mesh,
                    self._primitive)
        matrix_contributions = []
        for gp in grid_points:
            print "# grid %d" %gp
            mc.set_grid_point(gp)
            mc.run_interaction()
            matrix_contributions_temp = []
            for sigma in sigmas:
                mc.set_sigma(sigma)
                max_freq = (np.amax(self._interaction.get_phonons()[0]) * 2
                            + sigma * 4)
                fpoints = np.arange(0, max_freq + frequency_step / 2,
                                    frequency_step)
                mc.set_fpoints(fpoints)
                mc.run()
                matrix_contribution = mc.get_imag_self_energy()
                matrix_contributions_temp.append(matrix_contribution)
                if not is_sum:
                    write_matrix_contribution(
                                gp,
                                self._mesh,
                                fpoints,
                                matrix_contribution,
                                sigma=sigma,
                                filename=filename)
            matrix_contributions.append(matrix_contributions_temp)
        matrix_contributions = np.array(matrix_contributions)

        if is_sum:
            for i, sigma in enumerate(sigmas):
                write_matrix_contribution(
                                    None,
                                    self._mesh,
                                    fpoints,
                                    np.sum(matrix_contributions[:,i], axis=0),
                                    sigma=sigma,
                                    filename=filename)
class Ball(Animation):
    BALL_STOP_BOUND = 1.3
    MAX_VELOCITY = 10

    def __init__(self, manager, position, frame, sfx, speed=1000):
        Animation.__init__(self, manager, frame, speed)
        self.collision = Collision()
        self.set_position_center(position[0], position[1])
        self.change_x = 0
        self.change_y = 0
        self.radius = 15.5
        self.is_ball_going_in = False
        self.is_ball_hit_wall = False
        self.goal = False
        self.m = 0.45
        self.prevent = 1.01
        self.ball_vs_wall_observable = BallVsWallObservable()
        self.ball_vs_wall_observer = BallVsWallObserver(sfx)
        self.ball_vs_wall_observable.register(self.ball_vs_wall_observer)

    def calc_frame_step(self):
        cx = math.fabs(self.change_x)
        cy = math.fabs(self.change_y)
        if max(cx, cy) == 0:
            return 1
        # elif 2 >= cx > 0.6 or 2 >= cy > 0.6:
        #     return 1
        elif 4 > cx > 2 or 4 > cy > 2:
            self.speed = 1000
            return 2
        elif 5 > cx >= 4 or 5 > cy >= 4:
            self.speed = 1000
            return 3
        elif cx >= 5 or cy >= 5:
            self.speed = 1000
            return 4
        else:
            self.speed = int(1000 * 0.5 / (self.change_x + self.change_y))
            # self.speed = 1000 - 80 / (self.change_x + self.change_y)
            return 1

    def update(self):
        if self.change_x + self.change_y == 0:
            self.is_static = True
        else:
            self.is_static = False
        Animation.update(self)
        if (
            self.rect.center[1] + self.change_y < constants.PLAY_SPACE_RECT[1]
            or self.rect.center[1] + self.change_y > constants.PLAY_SPACE_RECT[1] + constants.PLAY_SPACE_RECT[3]
        ):
            self.change_y = 0
        # if ((self.rect.center[0] + self.change_x < constants.PLAY_SPACE_RECT[0] or self.rect.center[0] + self.change_x >
        #         constants.PLAY_SPACE_RECT[0] + constants.PLAY_SPACE_RECT[2]) \
        #             and (self.rect.center[1] - self.radius + self.change_y < 260 or self.rect.center[1] + self.radius + self.change_y > 433)):
        #     self.change_x = 0
        self.max_min_velocity()
        if 1 > self.change_y > 0:
            self.rect.y += 1
        elif -1 < self.change_y < 0:
            self.rect.y -= 1
        else:
            self.rect.y += round(self.change_y)
        if 1 > self.change_x > 0:
            self.rect.x += 1
        elif -1 < self.change_x < 0:
            self.rect.x -= 1
        else:
            self.rect.x += round(self.change_x)
        self.collision.collisionBall2Wall(self, self.ball_vs_wall_observable)
        self.change_x /= self.prevent
        self.change_y /= self.prevent

        if self.change_x == 0:
            if self.change_y > 0:
                self.degree = -90
            else:
                self.degree = 90
        elif self.change_y == 0:
            if self.change_x > 0:
                self.degree = 0
            else:
                self.degree = 180
        else:
            self.degree = math.atan(math.fabs(self.change_y) / math.fabs(self.change_x)) * 180 / math.pi
            if self.change_x > 0 and self.change_y > 0:
                self.degree = -self.degree
            elif self.change_x > 0 > self.change_y:
                pass
            elif self.change_x < 0 < self.change_y:
                self.degree += 180
            elif self.change_x < 0 and self.change_y < 0:
                self.degree += (90 - self.degree) * 2
        # print(self.degree)
        self.rotate(self.degree)

    def set_velocity(self, vx, vy):
        self.change_x = vx
        self.change_y = vy

    def max_min_velocity(self):
        if self.change_y > Ball.MAX_VELOCITY:
            self.change_y = Ball.MAX_VELOCITY
        if self.change_x > Ball.MAX_VELOCITY:
            self.change_x = Ball.MAX_VELOCITY
        if (
            Ball.BALL_STOP_BOUND > self.change_x > -Ball.BALL_STOP_BOUND
            and Ball.BALL_STOP_BOUND > self.change_y > -Ball.BALL_STOP_BOUND
        ):
            self.change_x = 0
            self.change_y = 0
class GameManager:
    clock = pygame.time.Clock()

    def __init__(self):
        self.number_of_user = 0
        self.userList = []
        self.player_list = []
        self.screen = None
        self.sfx = SoundEffects()
        self.display_init()
        self.sprite_group = pygame.sprite.Group()
        self.focus_effect_group = pygame.sprite.Group()
        self.goal_effect_group = pygame.sprite.Group()
        self.ball = self.ball_init(self.sfx)
        self.user_init(self.ball, self.sfx)
        self.platform = None
        self.platform_init()
        self.done = False
        self.focus_effect_blue = None
        self.focus_effect_red = None
        self.focus_effect_list = []
        self.focus_effect_init()
        self.collision = Collision()
        self.scoreboard = Scoreboard(self.screen)
        self.ball_reset_delay = 2000
        self.goal_effect_init()
        self.max_score = 3

    def display_init(self):
        size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
        self.screen = pygame.display.set_mode(size)
        pygame.display.set_caption("Hello world")

    def user_init(self, ball, sfx):
        player_sprite = SpriteFactory("images/player.png")
        user1_players_initial_positions = constants.USER1_PLAYERS_INITIAL_POS
        user2_players_initial_positions = constants.USER2_PLAYERS_INITIAL_POS
        user1 = User(self.sprite_group, player_sprite, data.playerBlueFramesData, user1_players_initial_positions, ball, sfx)
        self.add_user(user1)
        self.add_player(user1)
        user2 = User(self.sprite_group, player_sprite, data.playerRedFramesData, user2_players_initial_positions, ball, sfx)
        self.add_user(user2)
        self.add_player(user2)

    def ball_init(self, sfx):
        ball_sprite = SpriteFactory("images/ball-small.png")
        ball_frames = SpriteFactory.generate_frames(ball_sprite, data.ballFramesData)
        ball = Ball(self.sprite_group, (constants.BALL_INIT_POS[0], constants.BALL_INIT_POS[1]), ball_frames, sfx, speed=100)
        ball.play(Animation.INFINITE)

        ball_shadow_sprite = SpriteFactory("images/ball-shadow.png")
        ball_shadow_frames = SpriteFactory.generate_frames(ball_shadow_sprite, data.ballShadowFramesData)
        ball_shadow = BallShadow(self.focus_effect_group, ball, ball_shadow_frames, speed=1000)
        ball_shadow.play(Animation.INFINITE)
        return ball

    def platform_init(self):
        self.platform = Platform(self.screen)

    def focus_effect_init(self):
        focus_effect_sprite_red = SpriteFactory("images/hover-red.png")
        focus_effect_frames_red = SpriteFactory.generate_frames(focus_effect_sprite_red, data.hoverEffectFramesData)
        focus_effect_sprite_blue = SpriteFactory("images/hover-blue.png")
        focus_effect_frames_blue = SpriteFactory.generate_frames(focus_effect_sprite_blue, data.hoverEffectFramesData)
        focus_effect_blue = FocusEffect(self.focus_effect_group,
                                        self.userList[0].players_list[self.userList[0].current_selected_player],
                                        focus_effect_frames_blue, speed=1000)
        self.focus_effect_list.append(focus_effect_blue)
        self.focus_effect_list[0].play(Animation.INFINITE)
        focus_effect_red = FocusEffect(self.focus_effect_group,
                                       self.userList[1].players_list[self.userList[1].current_selected_player],
                                       focus_effect_frames_red, speed=1000)
        self.focus_effect_list.append(focus_effect_red)
        self.focus_effect_list[1].play(Animation.INFINITE)

    def goal_effect_init(self):
        goal_effect_sprite = SpriteFactory("images/goal-screen.png")
        goal_effect_frames = SpriteFactory.generate_frames(goal_effect_sprite, data.goalEffectFramesData)
        self.goal_effect = GoalScreen(self.goal_effect_group, goal_effect_frames)

        # self.userList[0].players_list[1].rect.x = 200
        # self.userList[1].players_list[1].rect.y = 700

    # @param user: type User
    def add_user(self, user):
        self.userList.append(user)

    def add_player(self, user):
        for x in range(0, user.num_of_players):
            self.player_list.append(user.players_list[x])

    def is_game_over(self):
        user1_score = self.scoreboard.scores[0]
        user2_score = self.scoreboard.scores[1]
        if user1_score > self.max_score / 2 and user1_score > user2_score:  # user1 win
            return True
        elif user2_score > self.max_score / 2 and user2_score > user1_score:  # user2 win
            return True
        else:
            return False

    def gameover_screen(self):
        exitLoop = False
        while not exitLoop:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exitLoop = True
                    self.done = True
                if event.type == pygame.MOUSEBUTTONDOWN:
                    for i in range(0, len(self.platform.gameover_button_list), 1):
                        if self.platform.gameover_button_list[i].is_mouse_over(mouse.get_pos()):
                            if i == constants.GAMEOVER_BUTTON_TYPE["mute"]:
                                self.sfx.play_mouseover()
                                if self.sfx.is_muted == True:
                                    self.sfx.set_unmute()
                                else:
                                    self.sfx.set_mute()
                            elif i == constants.GAMEOVER_BUTTON_TYPE["replay"]:
                                self.sfx.play_mouseover()
                                exitLoop = True
                                self.scoreboard.reset_score()
                                self.start(False)
                            elif i == constants.GAMEOVER_BUTTON_TYPE["exit"]:
                                self.sfx.play_mouseover()
                                exitLoop = True
                                self.done = True
            self.platform.gameover_screen(mouse.get_pos(), pygame.event.get(), self.scoreboard.scores)
            pygame.display.update()
            GameManager.clock.tick(constants.FPS)


    def start_screen(self):
        exitLoop = False
        self.sfx.play_start_screen()
        while not exitLoop:
            # for i in range(0, len(self.platform.gamestart_button_list), 1):
            #      if self.platform.gamestart_button_list[i].is_mouse_over(mouse.get_pos()) and i is not constants.GAMESTART_BUTTON_TYPE["mute"]:
            #              self.sfx.play_mouseover()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    for i in range(0, len(self.platform.gamestart_button_list), 1):
                        if self.platform.gamestart_button_list[i].is_mouse_over(mouse.get_pos()):
                            if i == constants.GAMESTART_BUTTON_TYPE["mute"]:
                                self.sfx.play_mouseover()
                                self.platform.gamestart_mute_button.toggle_frame()
                                if self.sfx.is_muted == True:
                                    self.sfx.set_unmute()
                                else:
                                    self.sfx.set_mute()
                            elif i == constants.GAMESTART_BUTTON_TYPE["play"]:
                                self.sfx.play_mouseover()
                                exitLoop = True
                                self.sfx.stop_start_screen()
                                self.scoreboard.reset_score()
                                self.start(False)
                            elif i == constants.GAMESTART_BUTTON_TYPE["exit"]:
                                self.sfx.play_mouseover()
                                exitLoop = True
                                self.done = True
            self.platform.gamestart_screen(mouse.get_pos(), pygame.event.get())
            pygame.display.update()
            GameManager.clock.tick(constants.FPS)

    def start(self, is_show_start_screen):
        if is_show_start_screen:
            self.start_screen()
        pygame.mixer.music.play(-1)  # Play the fans cheering music
        self.sfx.play_start_game()
        last_time_updated = pygame.time.get_ticks()
        is_resetting_game = False
        for user in self.userList:
            user.reset_players_position()
        pygame.key.set_repeat(1, 20)
        # Main Program Loop
        while not self.done:
            # Move all players in a team at the same time
            keys = pygame.key.get_pressed()
            # Move all user1's players
            if keys[pygame.K_LSHIFT]:
                if keys[pygame.K_d]:
                    for player in self.userList[0].players_list:
                        player.go_right()
                elif keys[pygame.K_a]:
                    for player in self.userList[0].players_list:
                        player.go_left()
                elif keys[pygame.K_w]:
                    for player in self.userList[0].players_list:
                        player.go_up()
                elif keys[pygame.K_s]:
                    for player in self.userList[0].players_list:
                        player.go_down()
            # Move all user2's players
            if keys[pygame.K_RCTRL]:
                if keys[pygame.K_RIGHT]:
                    for player in self.userList[1].players_list:
                        player.go_right()
                elif keys[pygame.K_LEFT]:
                    for player in self.userList[1].players_list:
                        player.go_left()
                elif keys[pygame.K_UP]:
                    for player in self.userList[1].players_list:
                        player.go_up()
                elif keys[pygame.K_DOWN]:
                    for player in self.userList[1].players_list:
                        player.go_down()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.done = True

                    # User1 input handlers
                    for i in range(0, len(data.controllerSetting), 1):
                        user_setting = data.controllerSetting[i]
                        user = self.userList[i]
                        # if event.key == user_setting['next'] and not self.automatic_choose:
                        #     user.players_list[user.current_selected_player].stop()
                        #     user.current_selected_player = (user.current_selected_player + 1) % user.num_of_players
                        #     user.focused_player_index = user.current_selected_player
                        #     self.focus_effect_list[i].set_player(user.players_list[user.current_selected_player])
                        if event.key == user_setting['left']:
                            user.players_list[user.current_selected_player].go_left()
                        if event.key == user_setting['right']:
                            user.players_list[user.current_selected_player].go_right()
                        if event.key == user_setting['up']:
                            user.players_list[user.current_selected_player].go_up()
                        if event.key == user_setting['down']:
                            user.players_list[user.current_selected_player].go_down()

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_F5:
                        # Hot reset the game
                        self.scoreboard.reset_score()
                        self.ball.goal = False
                        self.ball.is_ball_going_in = False
                        self.ball.change_x = 0
                        self.ball.change_y = 0
                        self.ball.set_position_center(constants.BALL_INIT_POS[0], constants.BALL_INIT_POS[1])
                        self.ball.is_ball_hit_wall = False
                        self.start(False)
                    if event.key == pygame.K_m:
                        if self.sfx.is_muted == True:
                            self.sfx.set_unmute()
                        else:
                            self.sfx.set_mute()
                    for i in range(0, len(data.controllerSetting), 1):
                        user_setting = data.controllerSetting[i]
                        user = self.userList[i]
                        if event.key == user_setting['next'] or event.key == user_setting['left'] or event.key == \
                                user_setting['right'] or event.key == user_setting['up'] or event.key == user_setting[
                            'down']:
                            user.players_list[user.current_selected_player].stop()
                            user.isInControl = False

            # TODO a goal scored !
            if self.ball.goal:
                self.goal_effect.play(2)
                if is_resetting_game == False:
                    self.sfx.play_goal()
                now = pygame.time.get_ticks()
                if is_resetting_game == True and (now - last_time_updated) >= self.ball_reset_delay:
                    # Update score
                    self.scoreboard.inc_score(data.winner)
                    self.ball.goal = False
                    self.ball.is_ball_going_in = False
                    self.ball.change_x = 0
                    self.ball.change_y = 0
                    self.ball.set_position_center(constants.BALL_INIT_POS[0], constants.BALL_INIT_POS[1])
                    self.ball.is_ball_hit_wall = False
                    for user in self.userList:
                        user.reset_players_position()
                    if self.is_game_over():
                        print("GAME OVER")
                        self.sfx.play_goal()
                        self.sfx.play_end_game()
                        self.gameover_screen()
                    else:
                        self.sfx.play_start_game()
                        is_resetting_game = False
                        continue
                is_resetting_game = True

            if is_resetting_game == False:
                last_time_updated = pygame.time.get_ticks()

            # Update the players
            self.focus_effect_group.update()
            # test
            for x in range(0, len(self.player_list)):
                for y in range(x + 1, len(self.player_list)):
                    self.collision.collisionPlayer2Player(self.player_list[x], self.player_list[y], self.sfx)
                            
            # Update the player
            self.focus_effect_group.update()
            self.sprite_group.update()
            self.platform.update()
            self.goal_effect_group.update()
            for i in range(0, len(self.userList), 1):
                self.userList[i].update(self.focus_effect_list[i])
            # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
            self.platform.draw()
            self.focus_effect_group.draw(self.screen)
            self.sprite_group.draw(self.screen)
            self.platform.draw_goal()
            self.scoreboard.update()
            self.goal_effect_group.draw(self.screen)
            # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
            # rect = self.user_init(self.ball_init()).players_list[0].rect.center
            # pygame.draw.circle(self.screen, (255,255,255), (rect[0]+2,rect[1]), 37)
            # Limit to 60 frames per second
            GameManager.clock.tick(constants.FPS)

            # Go ahead and update the screen with what we've drawn
            pygame.display.flip()

        # Be IDLE friendly. If you forget this line, the program will 'hange'
        # on exit.
        pygame.quit()
Esempio n. 38
0
    def _process_messages(self):
        """
        Message Processor:
            - processes incoming messages from CarTalker
            - creates collision objects and adds them to collisions
        """

        while not self._kill:
            message = self._talker.get_message()
            if message is None:
                time.sleep(utils.THREAD_SLEEP)
                continue

            if message.other_name not in self._collisions:
                if message.type != Message.ROW:
                    print "ERROR: Got response for nonexistant collision"
                else:
                    print "NEW MESSAGE RECEIVED"
                    message.my_name = self.name
                    c = Collision(message.other_name, message.frame_num, message.location, message=message)
                    c.state = CollisionState.RECEIVED_MESSAGE
                    self._collisions[message.other_name] = c
            else:
                collision = self._collisions[message.other_name]
                collision.lock.acquire()

                if message.type == Message.ROW:
                    if collision.state == CollisionState.WAITING:
                        # we are already waiting, so just send a confirmation that other has ROW
                        print "ALREADY WAITING"
                        self._talker.send_message(Message(Message.GO, self.name, message.other_name,
                            collision.location, collision.frame_num))

                    elif collision.state == CollisionState.RESOLVED:
                        # we are already going, so send a stay message
                        print "ALREADY RESOLVED"
                        self._talker.send_message(Message(Message.STAY, self.name, message.other_name,
                            collision.location, collision.frame_num))

                    elif collision.state == CollisionState.NEW:
                        # if we haven't already sent a message, set collision to received in interim
                        collision.state = CollisionState.RECEIVED_MESSAGE
                        message.my_name = self.name
                        collision.message = message
                        print "Got message about unprocessed collision"

                    elif collision.state == CollisionState.SENT_MESSAGE:
                        # if collision.message.type == Message.ROW:

                        print "ALREADY SENT ROW... RESOLVING CONFLICT"
                        # compare the ROW we sent and the one we received
                        if collision.priority_val > message.priority_val:
                            # we win
                            self._talker.send_message(Message(Message.STAY, self.name, message.other_name,
                                collision.location, collision.frame_num))
                            collision.state = CollisionState.RESOLVED
                            print "RESOLVED DUPLICATED ROW... WE GO"

                        elif collision.priority_val < message.priority_val:
                            # we lose
                            self._talker.send_message(Message(Message.GO, self.name, message.other_name,
                                collision.location, collision.frame_num))
                            collision.state = CollisionState.WAITING
                            print "RESOLVED DUPLICATED ROW... WE WAIT"

                        else:
                            # tie, restart process by sending ROW
                            self._talker.send_message(Message(Message.ROW, self.name, message.other_name,
                                collision.location, collision.frame_num))
                            collision.state = CollisionState.SENT_MESSAGE
                            print "TIED DUPLICATED ROW... RESEND"

                        collision.message = None
                else:
                    if collision.state == CollisionState.SENT_MESSAGE:
                        if message.type == Message.STAY:
                            collision.state = CollisionState.WAITING
                            collision.message = None
                            print "WE STAY"
                        else:
                            collision.state = CollisionState.RESOLVED
                            collision.message = None
                            print "RESOLVED... WE GO"
                    else:
                        print "ERROR: got response without having sent a message"

                collision.lock.release()

            time.sleep(utils.THREAD_SLEEP)