Exemple #1
0
    def __init__(self, scanId, show_rays=True, show_grid=True): 
        self.scanId = scanId
        self.root, self.target, agent_pose, goal_pose = scanId.split('-')
        self.root = os.path.join(Files.basedir, dirname(self.root))
        self.agent_pose_ini = to_array(agent_pose)
        self.goal_pose_ini  = to_array(goal_pose)
        
        # Cache variables
        self.pmc_var = None
        # Visualization settnigs
        self.show_rays = show_rays
        self.show_grid = show_grid 
        
        # Floyd warshall algorithm for shortest path supervision
        self.mapfile_var = join(self.root, Files.objfile)
        self.planner = FloydWarshallRobotslang(self.mapfile_var)
        
        # Navigation pixels for  visualization
        self.nav_pixels   = self.planner.navigable_pixels

        ## Target poses
        self.target_poses  = get_targets()[scanId]
        self.target_pixels = pose2pixel(np.asarray(self.target_poses), MC.mazeshape)
        self.target_pixels = list(zip(["jar", "mug", "paddle"], self.target_pixels))

        # Randomize location of agent and goal
        self.agent   = Particles(1)
        self.goal    = Particles(1)

        # Start by resetting
        self.reset()
Exemple #2
0
 def run_temporal_moments_calculation(number_of_moments,
                                      segmentation_tuple,
                                      kind_of='not_norm'):
     p = Particles('./data/position_data_1_1.txt')
     segmentations = np.arange(*segmentation_tuple)
     moments_n = np.zeros((len(segmentations), number_of_moments))
     if kind_of == 'norm':
         mom = Moments.normalized_temporal_moment
     elif kind_of == 'not_norm':
         mom = Moments.temporal_moment
     for n in np.arange(0, number_of_moments):  # order of the moment
         for i, l in enumerate(segmentations):  # lengths to be tested
             moments_n[i, n] = mom(
                 n, p.time,
                 p.discrete_particle_distribution(l, p.time, p.qy))
             #   print(np.trapz(p.discrete_particle_distribution(l, p.time, p.qy)))
     moment_list = []
     for i in np.arange(0, number_of_moments):
         moment_list.append('m_' + str(i))
     moments_n_df = pd.DataFrame(moments_n,
                                 columns=moment_list,
                                 index=segmentations)
     moments_n_df.to_csv('./data/temporal_moments.csv')
     moments_n_df = moments_n_df.drop('m_0',
                                      axis=1)  # drop in order not to plot
     moments_n_df.plot()
     plt.xlabel('Segmentation L [m]')
     plt.xlim(segmentations[1], segmentations[-1])
     plt.ylabel('Moment []')
     plt.title('Moment versus L')
     plt.savefig('./data/temporal_moments.png')
    def __init__(self, env, num_particles, particle_angle_range, num_rays,
                 r_mean, r_std, ang_mean, ang_std, visualize, background, save_to,
                 row_min, row_max, n_angle_bins, front_angle_range):
        """Instantiates the visual particle filter with initial constraints.
        Args:
            run (dataset object): Provides access to an experiment
            experiment  Location of the experiment
            mapfile     Image location of top down maze image that is in turn converted
                        to gridmap file via the Gridmap class
            num_particles   Number of particles used for tracking
            particle_size   Size for scatter plot particles
            arrow_size      Arrow size (in meters)
        """
        # Set the run
        self.env = env
        # Setup the particles
        self.particles = Particles(num_particles, r_mean, r_std, ang_mean, ang_std)
        
        ## Matplotlib based visualization
        self.visualize = visualize
        self.viz_map   = env.mapfile 

        self.featurizer = HistogramFeatures()

        # Color gradient
        self.num_cgs = 100
        self.color_gradient = list(Color("red").range_to(Color("green"), self.num_cgs))
Exemple #4
0
class particlesTest(unittest.TestCase):
    def setUp(self):
        self.particles1 = Particles(20, 1, (200, 2))

    def tearDown(self):
        self.Particles1 = None

    def testNone(self):
        self.assertFalse(None, self.particles1)

    def testEmitter(self):
        emitter = (20, 30)
        self.assertFalse(emitter == self.particles1._emitter)

        self.particles1.set_emitter(emitter)
        self.assertTrue(emitter == self.particles1._emitter)

    def testUpdate(self):
        pass

    def testResetParticle(self):
        pass

    def testGet(self):
        self.assertFalse(None, self.particles1.get())
class particlesTest(unittest.TestCase):    
    def setUp(self):
        self.particles1 = Particles(20,1, (200,2))

    def tearDown(self):
        self.Particles1 = None

    def testNone(self):
        self.assertFalse(None, self.particles1)
        
    def testEmitter(self):
        emitter = (20,30)
        self.assertFalse(emitter == self.particles1._emitter)

        self.particles1.set_emitter(emitter)
        self.assertTrue(emitter == self.particles1._emitter)
        
    def testUpdate(self):
        pass

    def testResetParticle(self):
        pass
        
    def testGet(self):
        self.assertFalse(None, self.particles1.get())
 def heatmap(self, viz):
     viz = viz * 0
     planner = self.env.planner
     particles = Particles(planner.poses.shape[0])
     particles.pose[:,:2] = planner.poses[:,:2]
     particles.pose[:, 2] = self.env.agent.pose[:,2]
     pixels = pose2pixel(particles.pose, MC.mazeshape)
     
     weights = np.zeros(len(particles))
     measurement = self.env.get_visual_obs(self.env.agent.pose)
     for i, (pose, pix) in enumerate(zip(particles.pose, pixels)):
         pose_measurement = self.env.get_visual_obs(pose)
         weights[i] = (pose_measurement == measurement).sum()
     #print(weights.max(), weights.min(), weights.mean())
     #weights = softmax(weights, t=.05)
     
     for i, (pose, pix) in enumerate(zip(particles.pose, pixels)):
         c_indx = int((self.num_cgs-1) * weights[i]/weights.max())
         color  = color2bgr(self.color_gradient[c_indx])
         self.env.draw_circle(viz, pix, rad=20, color=color)
         self.env.draw_orientation(viz, pose, thickness=2)
     
     for i, (pose, pix) in enumerate(zip(particles.pose, pixels)):
         cv2.putText(viz, str(int(weights[i])), point(pix), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
     return viz
Exemple #7
0
    def run_particle_distibution_graphs(self):
        p = Particles('./data/position_data_example_1.txt',
                      dimension=2,
                      time_start=0,
                      time_end=500000,
                      time_step=100)
        dist_cum = p.cumulative_distribution(0.0000505, p.qx)
        # dist_disc = p.discrete_particle_distribution(0.00005, p.time, p.qy)

        plt.scatter(range(len(dist_cum)), dist_cum)
        plt.xlabel('time')
        plt.ylabel('N')
        plt.grid(1)
        plt.show()
Exemple #8
0
 def generate(self):
     ''' Returns a particle  object with the parameters specified
     in the constructor of the Generator object
     '''
     coords = self._create_phase_space()
     particles = Particles(self.macroparticlenumber,
                           self.intensity/self.macroparticlenumber,
                           self.charge, self.mass, self.circumference,
                           self.gamma,
                           coords_n_momenta_dict=coords)
     self._linear_match_phase_space(particles)
     return particles
Exemple #9
0
    def __init__(self, ai_game, simple: bool = True) -> None:
        self.settings = ai_game.settings
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()

        self.image = pygame.image.load("images/ship.png")
        self.orig_image = self.image
        self.rect = self.image.get_rect()

        self.rect.midbottom = self.screen_rect.midbottom
        self.rect.y -= 10

        self.moving_right = False
        self.moving_left = False
        self.moving_down = False
        self.moving_up = False
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
        self.simple = simple
        self.hide = False
        self.particles = Particles(self.screen)
Exemple #10
0
def main():
    parser = argparse.ArgumentParser(description="FluidSim")
    parser.add_argument("--USE_SPHERICAL_GRAV", default=False)
    parser.add_argument("--SimType", type=str, default='PIC')
    parser.add_argument("--GRAV_FACTOR", type=float, default=0.01)
    parser.add_argument('--out_dir', type=str, default='output/')
    parser.add_argument('--n_iter', type=int, default=50)
    args = parser.parse_args()

    gravity = 9.8
    if (args.USE_SPHERICAL_GRAV):
        gravity *= args.GRAV_FACTOR

    grid = Grid3D(gravity, (30, 30, 30), 1)  #g, (nx,ny,nz),lx

    if not os.path.exists(args.out_dir):
        os.makedirs(args.out_dir)

    particles = Particles(grid, args.SimType)
    init_water_drop(grid, particles, 2, 2, 2)
    particles.write_to_file("{}/frameparticles{:0>4}".format(args.out_dir, 0))

    for i in range(args.n_iter):
        print(
            "===================================================> step {}...\n"
            .format(i))
        advance_one_frame(grid, particles, 1 / 30)
        particles.write_to_file("{}/frameparticles{:0>4}".format(
            args.out_dir, i))
Exemple #11
0
    def __init__(self):
        rospy.init_node('pf')

        # pose_listener responds to selection of a new approximate robot
        # location (for instance using rviz)
        rospy.Subscriber("initialpose",
                         PoseWithCovarianceStamped,
                         self.update_initial_pose)

        # publisher for the particle cloud for visualizing in rviz.
        self.particle_pub = rospy.Publisher("particlecloud",
                                            PoseArray,
                                            queue_size=10)

        # create instances of two helper objects that are provided to you
        # as part of the project
        self.occupancy_field = OccupancyField()
        self.transform_helper = TFHelper()

        self.particles = Particles()
        self.particles.initialize_particles()

        self.ranges = []
    def __init__(self):
        super(wg, self).__init__()
        cb = QtGui.QCheckBox('Show title', self)
        cb.move(20, 20)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)
        cb1 = QtGui.QCheckBox('Show title', self)
        cb1.move(40, 20)
        cb1.toggle()
        cb1.stateChanged.connect(self.changeTitle1)
 
        self.map=MapContinous()
        self.map.segments.append(Segment(vector(0,0),vector(320,0)))
        self.map.segments.append(Segment(vector(320,0),vector(320,240)))
        self.map.segments.append(Segment(vector(320,240),vector(0,240)))        
        self.map.segments.append(Segment(vector(0,240),vector(0,0)))  
         
        self.map.segments.append(Segment(vector(0,90),vector(50,90)))  
        self.map.segments.append(Segment(vector(50,90),vector(50,150)))  
        self.map.segments.append(Segment(vector(50,150),vector(0,150)))  
         
        self.map.segments.append(Segment(vector(270,0),vector(270,50)))  
        self.map.segments.append(Segment(vector(270,50),vector(320,50)))
         
        self.map.segments.append(Segment(vector(230,120),vector(320,120)))  
        self.map.segments.append(Segment(vector(230,120),vector(230,180)))  
        self.map.segments.append(Segment(vector(230,180),vector(320,180)))
        #f=file('map0.dat')
        #p=pickle.load(f)
        #f.close()
        #self.map.segments=getSegments(p)
        self.s=SensorLIDAR(8)
        self.k=KinematicTurtle()
        #self.k=KinematicBicycle()
        self.r=Robot(self.s,self.k,self.map)
        self.r.pos=vector(160,120)
        self.p=self.s.sensePoints(self.r)
        self.pt=Particles(self.r,500)
        self.initUI()
Exemple #13
0
 def two_particles_1d_random(self):
     return Particles(num_particles=2,
                      num_dimensions=1,
                      mass=1,
                      diameter=0.1)
Exemple #14
0
 def particles(self):
     if self._particles is None:
         self._particles = Particles(self.CONST_G)
     return self._particles
Exemple #15
0
    def __init__(self, screen, usealpha = True, noparticles = False, endless = False):
        self.screen = screen
        self.usealpha = usealpha
        self.noparticles = noparticles

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water #Water(self.usealpha)
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        self.sky = util.load_image("taivas")
        self.sky = pygame.transform.scale(self.sky, (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.pause_icon = util.load_image("pause")
        
        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles(self.usealpha)
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)
        self.cheat_current = 0
        
        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        font = util.load_font("Cosmetica", 40) #pygame.font.Font(pygame.font.get_default_font(), 36)
        self.pause_image = font.render("Pause", True, (0,0,0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center
Exemple #16
0
class Ship:
    def __init__(self, ai_game, simple: bool = True) -> None:
        self.settings = ai_game.settings
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()

        self.image = pygame.image.load("images/ship.png")
        self.orig_image = self.image
        self.rect = self.image.get_rect()

        self.rect.midbottom = self.screen_rect.midbottom
        self.rect.y -= 10

        self.moving_right = False
        self.moving_left = False
        self.moving_down = False
        self.moving_up = False
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
        self.simple = simple
        self.hide = False
        self.particles = Particles(self.screen)

    def update(self):
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.x += self.settings.ship_speed
        if self.moving_left and self.rect.left > self.screen_rect.left:
            self.x -= self.settings.ship_speed
        if self.moving_up and self.rect.top > self.screen_rect.top:
            self.y -= self.settings.ship_speed
        if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
            self.y += self.settings.ship_speed

        if self.rect.y != 0 and self.rect.x != 0:
            self.rect.x /= 1.414
            self.rect.y /= 1.414

        self.rect.x = self.x
        self.rect.y = self.y

    def blitme(self):
        if self.hide:
            return
        if not self.simple:
            self.particles.update(self.rect)
        self.screen.blit(self.image, self.rect)

    def hide_ship(self):
        self.hide = True

    def show_ship(self):
        self.hide = False

    def center_ship(self):
        if not self.simple:
            self.particles.start()
        self.show_ship()
        self.rect.midbottom = self.screen_rect.midbottom
        self.rect.y -= 10
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
Exemple #17
0
    def __init__(self, screen, endless = False):
        self.screen = screen

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        if not Game.sky:
            Game.sky = util.load_image("taivas")
            Game.sky = pygame.transform.scale(self.sky, (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles()
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)

        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        self.pause_image = util.bigfont.render("Pause", Variables.alpha, (0,0,0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center

        self.spacepressed = None
Exemple #18
0
 def _create_sampler(self, alpha):
     parts = Particles(**self.particles_params)
     wave_function = WaveFunction(parts,
                                  **self.wave_function_params,
                                  alpha=alpha)
     return self.sampler_type(step_size=0.1, wave_function=wave_function)
Exemple #19
0
def single_point_particle_1d():
    return Particles(num_particles=1, num_dimensions=1, mass=1, diameter=0)
Exemple #20
0
class RobotSlangSimulator:

    def __init__(self, scanId, show_rays=True, show_grid=True): 
        self.scanId = scanId
        self.root, self.target, agent_pose, goal_pose = scanId.split('-')
        self.root = os.path.join(Files.basedir, dirname(self.root))
        self.agent_pose_ini = to_array(agent_pose)
        self.goal_pose_ini  = to_array(goal_pose)
        
        # Cache variables
        self.pmc_var = None
        # Visualization settnigs
        self.show_rays = show_rays
        self.show_grid = show_grid 
        
        # Floyd warshall algorithm for shortest path supervision
        self.mapfile_var = join(self.root, Files.objfile)
        self.planner = FloydWarshallRobotslang(self.mapfile_var)
        
        # Navigation pixels for  visualization
        self.nav_pixels   = self.planner.navigable_pixels

        ## Target poses
        self.target_poses  = get_targets()[scanId]
        self.target_pixels = pose2pixel(np.asarray(self.target_poses), MC.mazeshape)
        self.target_pixels = list(zip(["jar", "mug", "paddle"], self.target_pixels))

        # Randomize location of agent and goal
        self.agent   = Particles(1)
        self.goal    = Particles(1)

        # Start by resetting
        self.reset()

    @property
    def pmc(self):
        if self.pmc_var is None:
            obj_map = join(self.root, Files.objfile) 
            self.pmc_var = LUT(obj_map)
        return self.pmc_var

    @property
    def mapfile(self):
        if type(self.mapfile_var) == str:
            self.mapfile_var = cv2.imread(self.mapfile_var)
        return self.mapfile_var

    def face_object(self):
        """Start trials facing the target object"""
        self.step_counter = -1
        
        # Move away from starting pose / object
        for i in range(20):
            action = self.next_shortest_path_action()
            self.makeActions(action)
            self.agent.pose = self.cnl(self.agent.pose)
        
        # Find starting object pose
        ndx = 0 if self.target == 'mug' else 1
        back_to = self.target_poses[ndx]

        # Face starting object 
        while l2(back_to, self.agent.pose) >= 3*MM.R:
            action = self.next_shortest_path_action(self.agent.pose, back_to) 
            self.makeActions(action)
            self.agent.pose = self.cnl(self.agent.pose)
        
    def reset(self):
        self.goal.pose[ ...,:2] = self.goal_pose_ini
        self.goal.pose[:]  = self.cnl(self.goal.pose)
        
        # Set poses
        if self.target == 'jar':
            self.agent.pose[:] = self.agent_pose_ini[:]
            self.agent.pose[:] = self.cnl(self.agent.pose)
        else:
            self.agent.pose[...,:2] = self.agent_pose_ini
            self.agent.pose[:] = self.cnl(self.agent.pose)
            self.face_object()
        
        # Reinit the step counte
        self.step_counter = -1
    
    def cnl(self, pose):
        """Closes Navigable Location according to choices of discretization"""
        pose[:,:2] = self.planner.closest_node_pose(pose)
        if pose.shape[-1] == 3:
            pose[:,2] = round_angle(pose[:,2], MM.T)
        return pose
    
    def check_collision(self):
        R = self.getR()
        new_pose = self.agent.next_pose(R, 0)
        collision = self.planner.get_top_dist(self.agent.pose, new_pose)
        collision  = collision > .11 # if not a side or hypotenuse away 
        return collision

    def draw_circle(self, viz, px, rad=MC.ORAD, color=BLUE):
        cv2.circle(viz, point(px), rad, tuple([int(c) for c in color]), thickness=-1)
        return viz

    def display(self, viz=None, draw_measurements=False):
        # Draw agent
        viz = self.mapfile.copy() if viz is None else viz.copy()
        
        # Draw the navigable locations
        if self.show_grid:
            for p in self.nav_pixels:
                self.draw_circle(viz, p,  rad=5, color=(128, 128, 0))
        
        # Draw rays cast from the agent
        if self.show_rays:
            self.draw_rays(viz, self.agent.pose)
        
        # Draw the orientation
        self.draw_orientation(viz, self.agent.pose)
        
        # Draw the agent
        self.draw_agent(viz, self.agent.pose)
        
        # Draw the trajectory
        traj = self.planner(self.agent.pose, self.goal.pose)
        self.draw_trajectory(viz, traj)
        
        if draw_measurements:
            # Add visualization lines
            colors, depths = self.draw_measurement_lines()
            # Resize for visualization
            itype = cv2.INTER_NEAREST
            colors = cv2.resize(colors, (viz.shape[1], 100), interpolation=itype)
            depths = cv2.resize(depths, (viz.shape[1], 100), interpolation=itype)
            viz = np.concatenate((viz, colors, colors * 0, depths), 0)

        return viz

    def draw_agent(self, viz, pose):
        stp, enp = self.orientation_vector(pose)
        st_pix = pose2pixel(stp, viz.shape)
        self.draw_circle(viz, st_pix, rad=MC.PRAD*2, color=BLUE)

    def orientation_vector(self, pose, r=.03):
        stp = np.squeeze(pose)
        enp = stp[:2] + r * np.asarray([np.cos(stp[2]), np.sin(stp[2])])
        return stp, enp
    
    def draw_orientation(self, viz, pose, thickness=10): 
        # Start and end pose for arrow
        stp, enp = self.orientation_vector(pose)

        # Convert to pixel
        st_pix = pose2pixel(stp, viz.shape)
        en_pix = pose2pixel(enp, viz.shape)
        
        # Draw orientation
        cv2.arrowedLine(viz, point(st_pix), point(en_pix), GREEN, thickness=thickness)
        return viz
    
    def draw_rays(self, viz, pose):
        stp, enp = self.orientation_vector(pose)
        st_pix = pose2pixel(stp, viz.shape)
        out = self.pmc.get_rays(pose)
        for o in out:
            cv2.line(viz, point(st_pix), point(o), WHITE, thickness=4)
        return viz

    def draw_measurement_lines(self):
        # Add measurement below
        color = self.get_visual_obs(self.agent.pose)
        measurement = np.expand_dims(color, 0)
        measurement = label2color(measurement)

        depth = self.get_depth_obs(self.agent.pose)
        depth /= max(depth.max(), 1e-12)
        depth = depth.reshape(1,-1, 1)
        cvec = 255*np.ones((1, color.shape[0], 3))
        cvec = np.uint8(255 - depth * cvec)

        return measurement, cvec

    def get_input(self):
        c = click.getchar()
        if   c == '\x1b[A': #forward
            action = Action.FORWARD
        elif c == '\x1b[C': #left
            action = Action.LEFT
        elif c == '\x1b[D': #right
            action = Action.RIGHT
        else:
            print("Not supported")
            action = 3
        #elif c == '\x1b[B': #backward
        #    action = Action.BACKWARD

        return action
    
    def play(self):
        while True:
            show(self.display(draw_measurements=True), 30)
            action = self.get_input()
            self.makeActions(action)

    
    def getR(self):
        # Hypotenuse or straight motion
        degrees = np.abs(np.degrees(self.agent.pose[:,2]) - np.asarray([0, 90, 180, 270, 360]))
        
        if degrees.min() < 1 : 
            R = MM.R
        else:
            R = MM.R * np.sqrt(2)
        return R
    
    #def next_shortest_path_action(self):
    #    """RANDOM BASELINE"""
    #    if self.step_counter < 119:
    #        if not self.check_collision():
    #            action = random.sample([Action.FORWARD, Action.LEFT, Action.RIGHT], 1)[0]
    #        else:
    #            action = random.sample([Action.LEFT, Action.RIGHT], 1)[0]
    #        return action
    #    else:
    #        return Action.END 
    
    def next_shortest_path_action(self, pose1=None, pose2=None):
        """teacher action"""
        if pose1 is None:
            pose1 = self.agent.pose
        if pose2 is None:
            pose2 = self.goal.pose
        next_node = self.planner.next_node(pose1, pose2)
        if next_node.sum() > 0:
            action = self.get_action(next_node)
            return action 
        else:
            return Action.END 
    
    def get_action(self, next_node):
        
        if self.step_counter < EC.max_len:
            stp, enp = self.orientation_vector(self.agent.pose)
            angle    = angle_between(next_node - stp[:2], enp - stp[:2])
            
            if np.abs(angle) < np.radians(1):
                action = Action.FORWARD
            elif np.sign(angle) == 1:
                action = Action.LEFT
            else:
                action = Action.RIGHT
        else:
            # End the episode after step counter threshold passed
            action = Action.END

        return action
    
    def makeActions(self, action):
        self.step_counter += 1
        R = self.getR()

        if action == Action.FORWARD:   # Forward
            dr = R
            da =  0
        elif action == Action.RIGHT: # Right
            dr = 0
            da = MM.T
        elif action == Action.LEFT: # Left
            dr = 0
            da = -MM.T 
        else:
            dr = da = 0
        
        # move the agent
        self.agent.move(dr, da)
        self.agent.pose[:] = self.cnl(self.agent.pose)
        
        #self.visualize_every_episode()
    
    def get_visual_obs(self, pose):
        colors = self.pmc[pose]
        return colors
    
    def get_depth_obs(self, pose):
        rays   = self.pmc.get_rays(pose)
        agent = self.agent.pose[:,:2]
        poses = pixel2pose(rays, MC.mazeshape)
        dists = np.linalg.norm(agent-poses, axis=1)
        return dists 
    
    def get_obs(self, pose=None):
        if pose is None:
            pose = self.agent.pose
        colors = self.get_visual_obs(pose).flatten() 
        colors = to_onehot_array(colors, len(LABELS)).flatten()
        dists = self.get_depth_obs(pose).flatten()
        out = np.concatenate((colors, dists, [self.check_collision()]))
        return out

    def draw_trajectory(self, viz, traj_poses, color=(59,181,207)):
        if traj_poses is not None:
            traj_pix = pose2pixel(traj_poses, viz.shape)
            for i in range(len(traj_pix)-1):
                cv2.line(viz, point(traj_pix[i]), point(traj_pix[i+1]), color, thickness=4)
            return viz
     
    
    def __repr__(self):
        return "{}-{}".format(numify(self.root), self.target)
    
    def shortest_agent(self):
        action = None
        while action != Action.END:
            action = self.next_shortest_path_action()
            self.makeActions(action)
        return self.step_counter

    def shortest_agent_images(self):
        action = None
        while action != Action.END:
            yield self.display(draw_measurements=True) 
            action = self.next_shortest_path_action()
            self.makeActions(action)
    
    def get_all_data(self):
        """
        Used to make a zero mean / unit variance scaler
        """
        data = []
        action = None
        while action != Action.END:
            data.append(self.get_obs(self.agent.pose))
            # Move along shortest path
            action = self.next_shortest_path_action()
            self.makeActions(action)
        return np.asarray(data)
    
    def make_video(self, folder):
        width  = 700
        height = 588
        fps    = 30
        fourcc = VideoWriter_fourcc(*'MP42')
        vfile  = '{}/{}.avi'.format(folder, str(self)) 
        video  = VideoWriter(vfile, fourcc, float(fps), (width, height))
        
        traj = self.planner(self.agent.pose, self.goal.pose)
        
        while True:
            img = self.display()
            self.draw_trajectory(img, traj)
            img = resize50(img)
            video.write(img)
            # Move along shortest path
            action = self.next_shortest_path_action()
            self.makeActions(action)
            if action == Action.END:
                break

        video.release()

        print('Video saved to: {}'.format(vfile))
        return self.step_counter
Exemple #21
0
class ParticleFilter(object):
    """ The class that represents a Particle Filter ROS Node
    """
    def __init__(self):
        rospy.init_node('pf')

        # pose_listener responds to selection of a new approximate robot
        # location (for instance using rviz)
        rospy.Subscriber("initialpose",
                         PoseWithCovarianceStamped,
                         self.update_initial_pose)

        # publisher for the particle cloud for visualizing in rviz.
        self.particle_pub = rospy.Publisher("particlecloud",
                                            PoseArray,
                                            queue_size=10)

        # create instances of two helper objects that are provided to you
        # as part of the project
        self.occupancy_field = OccupancyField()
        self.transform_helper = TFHelper()

        self.particles = Particles()
        self.particles.initialize_particles()

        self.ranges = []

    def update_initial_pose(self, msg):
        """ Callback function to handle re-initializing the particle filter
            based on a pose estimate.  These pose estimates could be generated
            by another ROS Node or could come from the rviz GUI """
        xy_theta = \
            self.transform_helper.convert_pose_to_xy_and_theta(msg.pose.pose)

        # TODO this should be deleted before posting
        self.transform_helper.fix_map_to_odom_transform(msg.pose.pose,
                                                        msg.header.stamp)
        # initialize your particle filter based on the xy_theta tuple

    def add_noise_to_particles(self, position_change):
        # OUTPUT FORMAT : List[Tuple(x, y, theta, original particle position)]
        current_particles = self.particles.get_locations()
        new_particles = []

        for particle in current_particles:
            for i in range(NEW_PARTICLES):
                x_noise = np.random.normal(loc=0, scale=.25)
                y_noise = np.random.normal(loc=0, scale=.25)
                theta_noise = np.random.randint(360)
                # appending (x, y, theta, original particle position)
                new_particles.append((particle[0] + position_change.x + x_noise, particle[1] + position_change.y + y_noise, (particle[2] + position_change.z + theta_noise) % 360, particle))

            return new_particles

    def calculate_particle_probs(self, particles):
        # OUTPUT FORMAT : List[Tuple(cur_loc, prev_loc, confidence weight)]
        # iterate through particles, determine likelihood of each
        total_weight = 0
        potential_locations = []
        for loc_tuple in particles:
            # get actual measured distance and the map's distance to the closest obstacle
            measured_distance = self.get_closest_obstacle_from_laserscan()[1]
            map_distance = self.occupancy_field.get_closest_obstacle_distance(loc_tuple[0], loc_tuple[1])
            
            # basic weight calculator based on measured and map distances
            if measured_distance == 0 and map_distance == 0:
                new_weight == 0
            elif measured_distance == 0 or map_distance == 0:
                new_weight == 0
            elif measured_distance-map_distance != 0:
                new_weight = 1/abs(measured_distance-map_distance)
            else:
                new_weight = 500

            # appending in format (cur_loc, prev_loc, confidence weight)
            potential_locations.append(((loc_tuple[0], loc_tuple[1], loc_tuple[2]), loc_tuple[3], new_weight))
            total_weight += new_weight

        # normalize the weight to be a probability
        if total_weight:
            return [(cur_loc, prev_loc, new_weight / total_weight) for cur_loc, prev_loc, new_weight in potential_locations]
        return potential_locations


    def get_closest_obstacle_from_laserscan(self):
        # this function is used to calculate probabilties of each particle
        closest_laserscan = (0,0)
        for i, scan_val in enumerate(self.ranges):
            if scan_val > 0 and (scan_val < closest_laserscan[1] or closest_laserscan[1] == 0):
                closest_laserscan = (i, scan_val)
        return closest_laserscan

    def run(self):
        r = rospy.Rate(5)
        scan_sub = rospy.Subscriber('/scan', LaserScan, self.update_ranges)
        scan_sub = rospy.Subscriber('/pos_change', Vector3, self.position_update_listener)
        while not(rospy.is_shutdown()):
            # in the main loop all we do is continuously broadcast the latest
            # map to odom transform
            self.transform_helper.send_last_map_to_odom_transform()
            r.sleep()
        
    def position_update_listener(self, msg):
        # function serves to update the positions of the particles each time it is called
        pos_change = msg
        new_particles = self.add_noise_to_particles(pos_change)
        potential_locations = self.calculate_particle_probs(new_particles)
        self.particles.update_locations(potential_locations)


    def update_ranges(self, msg):
        # callback function from listener
        self.ranges = msg.ranges
class wg(QtGui.QWidget):
    
    def __init__(self):
        super(wg, self).__init__()
        cb = QtGui.QCheckBox('Show title', self)
        cb.move(20, 20)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)
        cb1 = QtGui.QCheckBox('Show title', self)
        cb1.move(40, 20)
        cb1.toggle()
        cb1.stateChanged.connect(self.changeTitle1)
 
        self.map=MapContinous()
        self.map.segments.append(Segment(vector(0,0),vector(320,0)))
        self.map.segments.append(Segment(vector(320,0),vector(320,240)))
        self.map.segments.append(Segment(vector(320,240),vector(0,240)))        
        self.map.segments.append(Segment(vector(0,240),vector(0,0)))  
         
        self.map.segments.append(Segment(vector(0,90),vector(50,90)))  
        self.map.segments.append(Segment(vector(50,90),vector(50,150)))  
        self.map.segments.append(Segment(vector(50,150),vector(0,150)))  
         
        self.map.segments.append(Segment(vector(270,0),vector(270,50)))  
        self.map.segments.append(Segment(vector(270,50),vector(320,50)))
         
        self.map.segments.append(Segment(vector(230,120),vector(320,120)))  
        self.map.segments.append(Segment(vector(230,120),vector(230,180)))  
        self.map.segments.append(Segment(vector(230,180),vector(320,180)))
        #f=file('map0.dat')
        #p=pickle.load(f)
        #f.close()
        #self.map.segments=getSegments(p)
        self.s=SensorLIDAR(8)
        self.k=KinematicTurtle()
        #self.k=KinematicBicycle()
        self.r=Robot(self.s,self.k,self.map)
        self.r.pos=vector(160,120)
        self.p=self.s.sensePoints(self.r)
        self.pt=Particles(self.r,500)
        self.initUI()
    def initUI(self):              
        self.setGeometry(300, 300, 320, 240)
        self.setWindowTitle('pyRobot2D')
        self.show()
    def changeTitle(self, state):
        self.r=self.r.move(0.0,10)
        self.p=self.s.sensePoints(self.r)
        self.pt.prediction(0.0,10)
        print self.pt.eval(self.r)
        if state == QtCore.Qt.Checked:
            self.setWindowTitle('Checkbox')
        else:
            self.setWindowTitle('')
        self.repaint()
    def changeTitle1(self, state):
        #self.r=self.r.move(0.2,10)
        #self.pt.run(self.r,0.2,10)
        Z = self.r.sense()
        self.pt.correction(Z)
        print self.pt.eval(self.r)
        #self.p=self.s.sensePoints(self.r)
        if state == QtCore.Qt.Checked:
            self.setWindowTitle('Checkbox')
        else:
            self.setWindowTitle('')
        self.repaint()
        
    def paintEvent(self, e):     
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
        qp.setPen(QtGui.QPen(QtGui.QColor(0,0,0,255)))
        for s in self.map.segments:
            xo=s.getOrigin().x
            yo=240-s.getOrigin().y
            xe=s.getEnd().x
            ye=240-s.getEnd().y
            qp.drawLine(xo,yo,xe,ye)
        xo=self.r.pos.x
        yo=240-self.r.pos.y
        qp.setPen(QtGui.QPen(QtGui.QColor(180,255,0,255)))
        for d,p in self.p:
            xe=p.x
            ye=240-p.y
            qp.drawLine(xo,yo,xe,ye)
        d,p=self.p[0]
        xe=p.x
        ye=240-p.y
        qp.setPen(QtGui.QPen(QtGui.QColor(128,128,0,255)))
        qp.drawLine(xo,yo,xe,ye)
        qp.setPen(QtGui.QPen(QtGui.QColor(0,255,0,255)))
        for r in self.pt.getParticles():
            x=r.pos.x
            y=240-r.pos.y
            qp.drawEllipse(x,y,5,5)           
        qp.end()
Exemple #23
0
    def __init__(self, screen, endless = False):
        self.screen = screen

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        if not Game.sky:
            Game.sky = util.load_image("taivas")
            Game.sky = pygame.transform.scale(self.sky, (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles()
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)

        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        self.pause_image = util.bigfont.render("Pause", Variables.alpha, (0,0,0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center

        self.spacepressed = None
Exemple #24
0
class Game:
    sky = None
    
    
    
        

    def __init__(self, screen, endless = False):
        self.screen = screen

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        if not Game.sky:
            Game.sky = util.load_image("taivas")
            Game.sky = pygame.transform.scale(self.sky, (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles()
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)

        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        self.pause_image = util.bigfont.render("Pause", Variables.alpha, (0,0,0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center

        self.spacepressed = None

    def run(self):
        while not self.done:
            if not self.pause:
                if not self.gameover:
                    self.spawn_enemies()

                self.update_enemies()
                self.player.update()
                self.health.update()
                cloud.update()
                for cb in self.cannonballs:
                    if not cb.underwater:
                        #~ particle_point=cb.rect.left, cb.rect.top
                        particle_point = cb.tail_point()
                        self.particles.add_trace_particle(particle_point)
                        particle_point = [particle_point[i] + cb.vect[i]/2 for i in (0,1)]
                        self.particles.add_trace_particle(particle_point)
                    if cb.special and (not cb.underwater or rr()>0.6) :
                        particle_point = cb.tail_point()
                        self.particles.add_explosion_particle(particle_point)
                    und_old=cb.underwater
                    cb.update()
                    if cb.underwater and not und_old:
                        for i in xrange(5):
                            particle_point=cb.rect.right-4.0+rr()*8.0, cb.rect.top+rr()*2.0
                            self.particles.add_water_particle(particle_point)
                    if (cb.rect.right < 0 and cb.vect[0] < 0) or (cb.rect.left > SCREEN_WIDTH and cb.vect[0] > 0) or (cb.rect.top > SCREEN_HEIGHT):
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                self.score.update()

                # Add steam particles
                if Variables.particles:
                    particle_point = self.player.get_point((5.0 + rr() * 9.0, 0))
                    particle_point[0] += self.player.rect.centerx
                    particle_point[1] += self.player.rect.centery
                    if self.spacepressed and self.t > self.spacepressed + FPS * 3:
                        pass
                        #~ self.particles.add_fire_steam_particle(particle_point)
                    else:
                        self.particles.add_steam_particle(particle_point)

                    particle_point = self.player.get_point((19.0 + rr() * 7.0, 5.0))
                    particle_point[0] += self.player.rect.centerx
                    particle_point[1] += self.player.rect.centery
                    if self.spacepressed and self.t > self.spacepressed + FPS * 3:
                        pass
                        #~ self.particles.add_fire_steam_particle(particle_point)
                    else:
                        self.particles.add_steam_particle(particle_point)

                    if self.titanic:
                        for j in xrange(4):
                            particle_point = self.titanic.get_point((49 + rr() * 9.0 + 28 * j, 25))
                            particle_point[0] += self.titanic.rect.centerx
                            particle_point[1] += self.titanic.rect.centery
                            self.particles.add_steam_particle(particle_point)

                    self.particles.update()

                self.water.update()

                if self.player.splash:
                    if Variables.particles:
                        for i in xrange(10):
                            r = rr()
                            x = int(r * self.player.rect.left + (1.0-r) * self.player.rect.right)
                            point = (x, self.water.get_water_level(x))
                            self.particles.add_water_particle(point)
    
                for powerup in self.powerups:
                    powerup.update()
                    if powerup.picked:
                        self.powerups.remove(powerup)
                        self.powerup_sprites.remove(powerup)

                if not self.gameover:
                    self.check_collisions()

                if self.health.hearts_left == 0 and not self.player.dying:
                    self.player.die()

                if self.player.dying and not self.player.dead:
                    if Variables.particles:
                        self.particles.add_explosion_particle((self.player.rect.centerx, self.player.rect.centery))
                        self.particles.add_debris_particle((self.player.rect.centerx, self.player.rect.centery))

                if self.player.dead:
                    #self.done = True
                    self.set_gameover()

                if self.damage_count > 0:
                    self.damage_count -= 1
                self.lastshot += 1
                self.t += 1

            self.draw()

            self.handle_events()

        return self.score.get_score()

    def damage_player(self):
        self.health.damage()
        for i in xrange(10):
            particle_point = self.player.get_point((rr() * 26.0, rr() * 10.0))
            particle_point[0] += self.player.rect.centerx
            particle_point[1] += self.player.rect.centery
            self.particles.add_debris_particle(particle_point)
        self.player.blinks+=12


    def set_gameover(self, message = "Game Over"):
        self.gameover = True
        images = []
        height = 0
        width = 0
        for text in message.split("\n"):
            images.append(util.bigfont.render(text, Variables.alpha, (0,0,0)))
            height += images[-1].get_height()
            if images[-1].get_width() > width:
                width = images[-1].get_width()
        self.gameover_image = pygame.Surface((width, height), SRCALPHA, 32)
        self.gameover_image.fill((0,0,0,0))
        for i in xrange(len(images)):
            rect = images[i].get_rect()
            rect.top = i * images[i].get_height()
            rect.centerx = width / 2
            self.gameover_image.blit(images[i], rect)

        self.gameover_rect = self.gameover_image.get_rect()
        self.gameover_rect.center = self.screen.get_rect().center

    def take_screenshot(self):
        i = 1
        filename = "sshot.tga"
        while os.path.exists(filename):
            i += 1
            filename = "sshot" + str(i) + ".tga"
        
        pygame.image.save(self.screen, filename)
        print "Screenshot saved as " + filename

    def handle_events(self):
        nextframe = False
        framecount = 0
        while not nextframe:
          # wait until there's at least one event in the queue
          #nextframe = True
          pygame.event.post(pygame.event.wait())
          for event in pygame.event.get():
            #event = pygame.event.wait()
            if event.type == QUIT or \
               event.type == KEYDOWN and event.key == K_ESCAPE:
                self.done = True
                nextframe = True
            elif event.type == NEXTFRAME:
                framecount += 1
                nextframe = True
            elif self.gameover:
                if event.type == JOYBUTTONDOWN:
                    self.done = True
                    nextframe = True
                elif event.type == KEYDOWN:
                    self.done = True
                    nextframe = True
                continue
            elif event.type == JOYAXISMOTION:
                if event.axis == 0:
                    if event.value < -0.5:
                        self.player.move_left(True)
                    elif event.value > 0.5:
                        self.player.move_right(True)
                    else:
                        self.player.move_left(False)
                        self.player.move_right(False)
            elif event.type == JOYBUTTONDOWN:
                if event.button == 0:
                    if not self.pause:
                        self.player.jump()
                elif event.button == 1:
                    if not self.pause:
                        if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in xrange(4):
                                self.particles.add_fire_steam_particle(particle_point)
                            self.lastshot = 0
                            self.spacepressed = self.t
                elif event.button == 5:
                    self.take_screenshot()
                elif event.button == 8:
                    self.set_pause()
            elif event.type == KEYDOWN:
                if event.key == K_LEFT:
                    self.player.move_left(True)
                elif event.key == K_RIGHT:
                    self.player.move_right(True)
                elif event.key == K_SPACE:
                    if not self.pause:
                    # Only 3 cannonballs at once
                    # Maximum firing rate set at the top
                        if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in xrange(4):
                                self.particles.add_fire_steam_particle(particle_point)
                            self.lastshot = 0
                            self.spacepressed = self.t
                elif event.key == K_UP:
                    if not self.pause:
                        self.player.jump()
                elif event.key == K_s:
                    self.take_screenshot()
                elif event.key == K_p:
                    self.set_pause()
            elif event.type == KEYUP:
                if event.key == K_LEFT:
                    self.player.move_left(False)
                elif event.key == K_RIGHT:
                    self.player.move_right(False)
                elif event.key == K_SPACE:
                    if not self.pause:
                        if self.spacepressed and self.t > self.spacepressed + FPS * 3 and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle, special=True)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in xrange(30):
                                self.particles.add_fire_steam_particle((particle_point[0]+rrr(-4,4),particle_point[1]+rrr(-3,3)))
                            self.lastshot = 0
                        self.spacepressed = None
            elif event.type == JOYBUTTONUP:
                if event.button == 1:
                    if not self.pause:
                        if self.spacepressed and self.t > self.spacepressed + FPS * 3 and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle, special=True)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in xrange(30):
                                self.particles.add_fire_steam_particle((particle_point[0]+rrr(-4,4),particle_point[1]+rrr(-3,3)))
                            self.lastshot = 0
                        self.spacepressed = None

        #if framecount > 1:
        #    print str(self.t) + ": missed " + str(framecount - 1) + " frames!"

    def set_pause(self):
        self.pause = not self.pause

        #if framecount > 1:
        #    print str(self.t) + ": missed " + str(framecount - 1) + " frames!"

    def set_pause(self):
        self.pause = not self.pause

    def draw(self):
        self.screen.blit(Game.sky, self.screen.get_rect())
        self.health_sprite.draw(self.screen)
        self.score_sprite.draw(self.screen)
        self.player_sprite.draw(self.screen)
        self.powerup_sprites.draw(self.screen)
        self.pirate_sprites.draw(self.screen)
        if self.titanic:
            self.titanic_sprite.draw(self.screen)
        self.seagull_sprites.draw(self.screen)
        cloud.draw(self.screen)
        self.shark_sprites.draw(self.screen)
        self.mine_sprites.draw(self.screen)
        self.cannonball_sprites.draw(self.screen)
        self.water_sprite.draw(self.screen)
        if Variables.particles:
            self.particle_sprite.draw(self.screen)

        if self.pause:
            self.screen.blit(self.pause_image, self.pause_rect)

        if self.gameover:
            self.screen.blit(self.gameover_image, self.gameover_rect)

        if self.level.t < 120:
            image = None
            i = 0
            if self.level.phase < len(self.level.phase_messages):
              for text in self.level.phase_messages[self.level.phase].split("\n"):
                image = util.smallfont.render(text, Variables.alpha, (0,0,0))
                rect = image.get_rect()
                rect.centerx = self.screen.get_rect().centerx
                rect.top = 100 + rect.height * i
                blit_image = pygame.Surface((image.get_width(), image.get_height()))
                blit_image.fill((166,183,250))
                blit_image.set_colorkey((166,183,250))
                blit_image.blit(image, image.get_rect())
                if self.level.t > 60:
                    blit_image.set_alpha(255 - (self.level.t - 60) * 255 / 60)
                self.screen.blit(blit_image, rect)
                i += 1

        pygame.display.flip()



    def check_collisions(self):
        collisions = PixelPerfect.spritecollide_pp(self.player, self.powerup_sprites, 0)
        for powerup in collisions:
            if not powerup.fading:
                if not self.player.dying:
                    self.health.add()
                    powerup.pickup()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.mine_sprites, 0)

        for mine in collisions:
            if not mine.exploding:
                if not self.player.dying:
                    self.damage_player()
                    mine.explode()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.shark_sprites, 0)

        for shark in collisions:
            if not shark.dying:
                if not self.player.dying:
                    self.damage_player()
                    shark.die()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.cannonball_sprites, 0)

        for cb in collisions:
            if not self.player.dying:
                self.damage_player()
                self.cannonballs.remove(cb)
                self.cannonball_sprites.remove(cb)
                if (Variables.sound):
                   Mine.sound.play() # Umm... the mine has a nice explosion sound.

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.shark_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for shark in collisions[cb]:
                # The test on cb.vect is a rude hack preventing cannonballs from pirate ships from killing sharks.
                if not shark.dying and cb.vect[0] > 0:
                    self.score.add(15)
                    shark.die()
                    # give her a part of ball's momentum:
                    shark.dx+=cb.vect[0]*0.6
                    shark.dy+=cb.vect[1]*0.4
                    if not cb.special:
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.seagull_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for seagull in collisions[cb]:
                # cb.vect test is a rude hack preventing pirates from killing seagulls
                if not seagull.dying and cb.vect[0] > 0:
                    self.score.add(75)
                    seagull.die()
                    # give her a part of ball's momentum:
                    seagull.vect[0]+=cb.vect[0]*0.4
                    seagull.vect[1]+=cb.vect[1]*0.4
                    if not cb.special:
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.pirate_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for pirate in collisions[cb]:
                # cb.vect hack for preventing pirates from killing each other
                if not pirate.dying and cb.vect[0] > 0:
                    if (Variables.sound):
                       Mine.sound.play() # Umm... the mine has a nice sound.
                    self.score.add(25)
                    pirate.damage()
                    for i in range(6):
                        self.particles.add_wood_particle((pirate.rect.centerx+rrr(-0,15), pirate.rect.centery+rrr(-10,20)))
                    if not cb.special:
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                    break

        if self.titanic:
            collisions = PixelPerfect.spritecollide_pp(self.titanic, self.cannonball_sprites, 0)
            for cb in collisions:
                if not self.titanic.dying and cb.vect[0] > 0:
                    if (Variables.sound):
                       Mine.sound.play()
                    if cb.special: 
                        #special round is hard to fire, so lets reward our crafty player
                        self.titanic.damage(12)
                        self.score.add(100)
                    else:
                        self.score.add(7)
                        self.titanic.damage()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

    def update_enemies(self):
        self.mine_sprites.update()
        for mine in self.mines:
            if mine.exploding:
                if mine.explode_frames == 0:
                    self.mines.remove(mine)
                    self.mine_sprites.remove(mine)
                # this should really be done in the Mine class, but oh well, here's some explosion effects:
                if Variables.particles:
                    self.particles.add_explosion_particle((mine.rect.centerx, mine.rect.top + mine.image.get_rect().centerx))
                    self.particles.add_debris_particle((mine.rect.centerx, mine.rect.top + mine.image.get_rect().centerx))
            if mine.rect.right < self.screen.get_rect().left:
                self.mines.remove(mine)
                self.mine_sprites.remove(mine)

        self.shark_sprites.update()
        for shark in self.sharks:
            if shark.dying:
                if Variables.particles:
                    self.particles.add_blood_particle(shark.rect.center)
            if shark.rect.right < self.screen.get_rect().left or shark.dead:
                self.sharks.remove(shark)
                self.shark_sprites.remove(shark)

        self.pirate_sprites.update()
        for pirate in self.pirates:
            if pirate.t % 50 == 0 and not pirate.dying:
                # Pirate shoots, this should probably be handled by the Pirateboat class
                cb = Cannonball(pirate.rect, pirate.angle, left = True)
                self.cannonballs.append(cb)
                self.cannonball_sprites.add(cb)
                particle_point = pirate.get_point((0.0,10.0))
                particle_point[0] += pirate.rect.centerx
                particle_point[1] += pirate.rect.centery
                for i in xrange(4):
                    self.particles.add_fire_steam_particle(particle_point)
                
            if pirate.rect.right < self.screen.get_rect().left or pirate.dead:
                self.pirates.remove(pirate)
                self.pirate_sprites.remove(pirate)
            elif pirate.dying:
                if Variables.particles:
                    self.particles.add_explosion_particle((pirate.rect.centerx, pirate.rect.centery))
                    self.particles.add_wood_particle((pirate.rect.centerx, pirate.rect.centery))

        if self.titanic:
            self.titanic.update()
            if self.titanic.t % 100 == 0 and not self.titanic.dying:
                for i in xrange(3):
                    cb = Cannonball(self.titanic.rect, self.titanic.angle + (i-1)*10 - 50, left = True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            elif self.titanic.t % 100 == 50 and not self.titanic.dying:
                for i in xrange(3):
                    cb = Cannonball(self.titanic.rect, self.titanic.angle + (i-1)*10 - 52.5, left = True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            if self.titanic.dead:
                self.set_gameover("Congratulations!\nYou sunk Titanic!")
                self.titanic = None

        self.seagull_sprites.update()
        for seagull in self.seagulls:
            if seagull.rect.right < 0 or seagull.dead:
                self.seagulls.remove(seagull)
                self.seagull_sprites.remove(seagull)

    def spawn_enemies(self):
        spawns = self.level.get_spawns()
        if spawns[Level.SHARKS]:
            # Make a new shark
            self.sharks.append(Shark())
            self.shark_sprites.add(self.sharks[-1])

        if spawns[Level.PIRATES]:
            # Make a new pirate ship
            self.pirates.append(Pirateboat())
            self.pirate_sprites.add(self.pirates[-1])

        if spawns[Level.MINES]:
            self.mines.append(Mine())
            self.mine_sprites.add(self.mines[-1])

        if spawns[Level.SEAGULLS]:
            self.seagulls.append(Seagull())
            self.seagull_sprites.add(self.seagulls[-1])

        if spawns[Level.TITANIC]:
            self.titanic = Titanic()
            self.titanic_sprite.add(self.titanic)

        if spawns[Level.POWERUPS]:
            self.powerups.append(Powerup())
            self.powerup_sprites.add(self.powerups[-1])
Exemple #25
0
 def setUp(self):
     self.particles1 = Particles(20, 1, (200, 2))
Exemple #26
0
        cv.imshow(
            'map',
            draw_field(field=FIELD.copy(),
                       robot=robot,
                       particles=particles,
                       obstacles=obstacles))
        user_input = cv.waitKey(1)

        if start_localization:
            cv.setMouseCallback(
                'map', on_mouse=lambda event, x, y, flags, param: None)

            # Create particles at the current robot pose
            particles = Particles(row=robot.row,
                                  column=robot.column,
                                  angle=robot.angle,
                                  map_rows=NUM_MAP_ROWS,
                                  map_columns=NUM_MAP_COLUMNS)

            rospy.loginfo('[SLAM] start localization')
            t0 = time()
            start_localization = False
            pause_localization = False
            started_once = True

        elif not pause_localization:
            localize()

        elif pause_localization and started_once:
            # Pause localization and update with "actions"
def main():

    parameters = dict()
    read_parameters_file(parameters)
    check_parameters_consistency(parameters)
    print_parameters(parameters)

    # gas density field:
    density = Field(field="rho", parameters=parameters)

    # number of grid cells in the radial and azimuthal directions
    nrad = density.nrad
    ncol = density.ncol
    nsec = density.nsec

    # volume of each grid cell (code units)
    # calculate_volume(density)

    volume = np.zeros((nsec, ncol, nrad))
    for i in range(nsec):
        for j in range(ncol):
            for k in range(nrad):
                volume[i, j,
                       k] = (density.rmed[k]**2 * np.sin(density.tmed[j]) *
                             density.dr[k] * density.dth[j] * density.dp[i])

    # Mass of gas in units of the star's mass
    Mgas = np.sum(density.data * volume)
    print("Mgas / Mstar= " + str(Mgas) + " and Mgas [kg] = " +
          str(Mgas * density.cumass))

    # Allocate arrays
    nbin = parameters["nbin"]
    # bins = np.asarray([0.0001, 0.001, 0.01, 0.1, 0.3, 1, 3, 10, 100, 1000, 3000])
    bins = np.asarray([0.0001, 0.001, 0.01, 0.1, 0.2])
    particles_per_bin_per_cell = np.zeros(nbin * nsec * ncol * nrad)
    dust_cube = np.zeros((nbin, nsec, ncol, nrad))
    particles_per_bin = np.zeros(nbin)
    tstop_per_bin = np.zeros(nbin)

    # =========================
    # Compute dust mass volume density for each size bin
    # =========================
    if (parameters["RTdust_or_gas"] == "dust"
            and parameters["recalc_density"] == "Yes"
            and parameters["polarized_scat"] == "No"):
        print("--------- computing dust mass volume density ----------")

        particle_data = Particles(ns=parameters["particle_file"],
                                  directory=parameters["dir"])
        populate_dust_bins(
            density,
            particle_data,
            nbin,
            bins,
            particles_per_bin_per_cell,
            particles_per_bin,
            tstop_per_bin,
        )
        dust_cube = particles_per_bin_per_cell.reshape(
            (nbin, density.nsec, density.ncol, density.nrad))
        frac = np.zeros(nbin)
        buf = 0.0
        # finally compute dust surface density for each size bin
        for ibin in range(nbin):
            # fraction of dust mass in current size bin 'ibin', easy to check numerically that sum_frac = 1
            frac[ibin] = (pow(bins[ibin + 1], (4.0 - parameters["pindex"])) -
                          pow(bins[ibin], (4.0 - parameters["pindex"]))) / (
                              pow(parameters["amax"],
                                  (4.0 - parameters["pindex"])) -
                              pow(parameters["amin"],
                                  (4.0 - parameters["pindex"])))
            # total mass of dust particles in current size bin 'ibin'
            M_i_dust = parameters["ratio"] * Mgas * frac[ibin]
            buf += M_i_dust
            print("Dust mass [in units of Mstar] in species ", ibin, " = ",
                  M_i_dust)
            # dustcube, which contained N_i(r,phi), now contains sigma_i_dust (r,phi)
            dust_cube[
                ibin, :, :, :] *= M_i_dust / volume / particles_per_bin[ibin]
            # conversion in g/cm^2
            # dimensions: nbin, nrad, nsec
            dust_cube[ibin, :, :, :] *= (density.cumass * 1e3) / (
                (density.culength * 1e2)**2.0)

        # Overwrite first bin (ibin = 0) to model extra bin with small dust tightly coupled to the gas
        if parameters["bin_small_dust"] == "Yes":
            frac[0] *= 5e3
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            print(
                "Bin with index 0 changed to include arbitrarilly small dust tightly coupled to the gas"
            )
            print("Mass fraction of bin 0 changed to: ", str(frac[0]))
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            # radial index corresponding to 0.3"
            imin = np.argmin(np.abs(density.rmed - 1.4))
            # radial index corresponding to 0.6"
            imax = np.argmin(np.abs(density.rmed - 2.8))
            dust_cube[0, :, :, imin:imax] = (density.data[:, :, imin:imax] *
                                             parameters["ratio"] * frac[0] *
                                             (density.cumass * 1e3) /
                                             ((density.culength * 1e2)**2.0))

        print(
            "Total dust mass [g] = ",
            np.sum(dust_cube[:, :, :, :] * volume *
                   (density.culength * 1e2)**2.0),
        )
        print(
            "Total dust mass [Mgas] = ",
            np.sum(dust_cube[:, :, :, :] * volume *
                   (density.culength * 1e2)**2.0) /
            (Mgas * density.cumass * 1e3),
        )
        print(
            "Total dust mass [Mstar] = ",
            np.sum(dust_cube[:, :, :, :] * volume *
                   (density.culength * 1e2)**2.0) / (density.cumass * 1e3),
        )

        # Total dust surface density
        dust_surface_density = np.sum(dust_cube, axis=0)
        print("Maximum dust surface density [in g/cm^2] is ",
              dust_surface_density.max())

        DUSTOUT = open("dust_density.inp", "w")
        DUSTOUT.write("1 \n")  # iformat
        DUSTOUT.write(str(nrad * nsec * ncol) + " \n")  # n cells
        DUSTOUT.write(str(int(nbin)) + " \n")  # nbin size bins

        rhodustcube = np.zeros((nbin, nsec, ncol, nrad))

        # dust aspect ratio as function of ibin and r (or actually, R, cylindrical radius)
        hd = np.zeros((nbin, nrad))

        # gus aspect ratio
        hgas = np.zeros(nrad)
        for irad in range(nrad):
            hgas[irad] = (density.rmed[irad] * np.cos(density.tmed[:]) *
                          density.data[0, :, irad]).sum(
                              axis=0) / (density.data[0, :, irad]).sum(axis=0)

        for ibin in range(nbin):
            if parameters["polarized_scat"] == "No":
                for irad in range(nrad):
                    hd[ibin, irad] = hgas[irad] / np.sqrt(
                        1.0 +
                        tstop_per_bin[ibin] / parameters["alphaviscosity"] *
                        (1.0 + 2.0 * tstop_per_bin[ibin]) /
                        (1.0 + tstop_per_bin[ibin]))
            else:
                print(
                    "Set of initial conditions not implemented for pluto yet. Only parameters['polarized_scat'] == 'No'"
                )
                sys.exit("I must exit!")

        # work out exponential and normalization factors exp(-z^2 / 2H_d^2)
        # with z = r cos(theta) and H_d = h_d x R = h_d x r sin(theta)
        # r = spherical radius, R = cylindrical radius
        rho_dust_cube = dust_cube
        rho_dust_cube = np.nan_to_num(rho_dust_cube)

        # for plotting purposes
        axirhodustcube = np.sum(rho_dust_cube,
                                axis=3) / nsec  # ncol, nbin, nrad

        # Renormalize dust's mass volume density such that the sum over the 3D grid's volume of
        # the dust's mass volume density x the volume of each grid cell does give us the right
        # total dust mass, which equals ratio x Mgas.
        rhofield = np.sum(rho_dust_cube, axis=0)  # sum over dust bins

        Cedge, Aedge, Redge = np.meshgrid(
            density.tedge, density.pedge,
            density.redge)  # ncol+1, nrad+1, Nsec+1

        r2 = Redge * Redge
        jacob = r2[:-1, :-1, :-1] * np.sin(Cedge[:-1, :-1, :-1])
        dphi = Aedge[1:, :-1, :-1] - Aedge[:-1, :-1, :-1]  # same as 2pi/nsec
        dr = Redge[:-1, :-1, 1:] - Redge[:-1, :-1, :-1]  # same as Rsup-Rinf
        dtheta = Cedge[:-1, 1:, :-1] - Cedge[:-1, :-1, :-1]
        # volume of a cell in cm^3
        vol = (jacob * dr * dphi * dtheta * ((density.culength * 1e2)**3)
               )  # ncol, nrad, Nsec

        total_mass = np.sum(rhofield * vol)

        normalization_factor = (parameters["ratio"] * Mgas *
                                (density.cumass * 1e3) / total_mass)
        rho_dust_cube = rho_dust_cube * normalization_factor
        print(
            "total dust mass after vertical expansion [g] = ",
            np.sum(np.sum(rho_dust_cube, axis=0) * vol),
            " as normalization factor = ",
            normalization_factor,
        )

        # write mass volume densities for all size bins
        for ibin in range(nbin):
            print("dust species in bin", ibin, "out of ", nbin - 1)
            for k in range(nsec):
                for j in range(ncol):
                    for i in range(nrad):
                        DUSTOUT.write(
                            str(rho_dust_cube[ibin, k, j, i]) + " \n")

        # print max of dust's mass volume density at each colatitude
        for j in range(ncol):
            print(
                "max(rho_dustcube) [g cm-3] for colatitude index j = ",
                j,
                " = ",
                rho_dust_cube[:, :, j, :].max(),
            )

        DUSTOUT.close()

        # plot azimuthally-averaged density vs. radius and colatitude
        if parameters["plot_density"] == "Yes":
            plot_density(nbin, nsec, ncol, nrad, density, rho_dust_cube)

        # free RAM memory
        del rho_dust_cube, dust_cube, particles_per_bin_per_cell

    elif parameters["RTdust_or_gas"] == "gas":
        print(
            "Set of initial conditions not implemented for pluto yet. Only parameters['RTdust_or_gas'] == 'dust'"
        )
        sys.exit("I must exit!")
    elif parameters["polarized_scat"] == "Yes":
        print(
            "Set of initial conditions not implemented for pluto yet. Only parameters['polarized_scat'] == 'No'"
        )
        sys.exit("I must exit!")
    else:
        print(
            "--------- I did not compute dust densities (recalc_density = No in params.dat file) ----------"
        )

    # =========================
    # Compute dust opacities
    # =========================
    if parameters["RTdust_or_gas"] == "dust" and parameters[
            "recalc_opac"] == "Yes":
        print("--------- computing dust opacities ----------")

        # Calculation of opacities uses the python scripts makedustopac.py and bhmie.py
        # which were written by C. Dullemond, based on the original code by Bohren & Huffman.

        logawidth = 0.05  # Smear out the grain size by 5% in both directions
        na = 20  # Use 10 grain size samples per bin size
        chop = 1.0  # Remove forward scattering within an angle of 5 degrees
        # Extrapolate optical constants beyond its wavelength grid, if necessary
        extrapol = True
        verbose = False  # If True, then write out status information
        ntheta = 181  # Number of scattering angle sampling points
        # link to optical constants file
        optconstfile = (os.path.expanduser(parameters["opacity_dir"]) + "/" +
                        parameters["species"] + ".lnk")

        # The material density in gram / cm^3
        graindens = 2.0  # default density in g / cc
        if (parameters["species"] == "mix_2species_porous"
                or parameters["species"] == "mix_2species_porous_ice"
                or parameters["species"] == "mix_2species_porous_ice70"):
            graindens = 0.1  # g / cc
        if (parameters["species"] == "mix_2species"
                or parameters["species"] == "mix_2species_60silicates_40ice"):
            graindens = 1.7  # g / cc
        if parameters["species"] == "mix_2species_ice70":
            graindens = 1.26  # g / cc
        if parameters["species"] == "mix_2species_60silicates_40carbons":
            graindens = 2.7  # g / cc

        # Set up a wavelength grid (in cm) upon which we want to compute the opacities
        # 1 micron -> 1 cm
        lamcm = 10.0**np.linspace(0, 4, 200) * 1e-4

        # Set up an angular grid for which we want to compute the scattering matrix Z
        theta = np.linspace(0.0, 180.0, ntheta)

        for ibin in range(int(nbin)):
            # median grain size in cm in current bin size:
            agraincm = 10.0**(
                0.5 *
                (np.log10(1e2 * bins[ibin]) + np.log10(1e2 * bins[ibin + 1])))

            print("====================")
            print("bin ", ibin + 1, "/", nbin)
            print(
                "grain size [cm]: ",
                agraincm,
                " with grain density [g/cc] = ",
                graindens,
            )
            print("====================")
            pathout = parameters["species"] + str(ibin)
            opac = compute_opac_mie(
                optconstfile,
                graindens,
                agraincm,
                lamcm,
                theta=theta,
                extrapolate=extrapol,
                logawidth=logawidth,
                na=na,
                chopforward=chop,
                verbose=verbose,
            )
            if parameters["scat_mode"] >= 3:
                print("Writing dust opacities in dustkapscatmat* files")
                write_radmc3d_scatmat_file(opac, pathout)
            else:
                print("Writing dust opacities in dustkappa* files")
                write_radmc3d_kappa_file(opac, pathout)
    else:
        print(
            "------- taking dustkap* opacity files in current directory (recalc_opac = No in params.dat file) ------ "
        )

    # Write dustopac.inp file even if we don't (re)calculate dust opacities
    if parameters["RTdust_or_gas"] == "dust":
        print("-> writing dust opacities")
        write_dustopac(
            species=parameters["species"],
            scat_mode=parameters["scat_mode"],
            nbin=parameters["nbin"],
        )
        if parameters["plot_opac"] == "Yes":
            print("-> plotting dust opacities")
            plot_opacities(
                species=parameters["species"],
                amin=parameters["amin"],
                amax=parameters["amax"],
                nbin=parameters["nbin"],
                lbda1=parameters["wavelength"] * 1e3,
            )

    print("-> writing radmc3d script")
    write_radmc3d_script(parameters)

    # =========================
    # Call to RADMC3D thermal solution and ray tracing
    # =========================
    if parameters["recalc_radmc"] == "Yes" or parameters[
            "recalc_rawfits"] == "Yes":
        # Write other parameter files required by RADMC3D
        print("--------- printing auxiliary files ----------")

        # need to check why we need to output wavelength...
        if parameters["recalc_rawfits"] == "No":
            write_wavelength()
            write_stars(Rstar=parameters["rstar"], Tstar=parameters["teff"])
            # Write 3D spherical grid for RT computational calculation
            write_AMRgrid(density, Plot=False)

            # rto_style = 3 means that RADMC3D will write binary output files
            # setthreads corresponds to the number of threads (cores) over which radmc3d runs
            write_radmc3dinp(
                incl_dust=parameters["incl_dust"],
                incl_lines=parameters["incl_lines"],
                lines_mode=parameters["lines_mode"],
                nphot_scat=parameters["nb_photons_scat"],
                nphot=parameters["nb_photons"],
                rto_style=3,
                tgas_eq_tdust=parameters["tgas_eq_tdust"],
                modified_random_walk=1,
                scattering_mode_max=parameters["scat_mode"],
                setthreads=parameters["nbcores"],
            )

        # Add 90 degrees to position angle so that RADMC3D's definition of
        # position angle be consistent with observed position
        # angle, which is what we enter in the params.dat file
        M = RTmodel(
            distance=parameters["distance"],
            Lambda=parameters["wavelength"] * 1e3,
            label=parameters["label"],
            line=parameters["gasspecies"],
            iline=parameters["iline"],
            vkms=parameters["vkms"],
            widthkms=parameters["widthkms"],
            npix=parameters["nbpixels"],
            phi=parameters["phiangle"],
            incl=parameters["inclination"],
            posang=parameters["posangle"] + 90.0,
        )

        # Set dust / gas temperature if Tdust_eq_Thydro == 'Yes'
        if (parameters["recalc_rawfits"] == "No"
                and parameters["Tdust_eq_Thydro"] == "Yes"
                and parameters["RTdust_or_gas"] == "dust"
                and parameters["recalc_temperature"] == "Yes"):
            print("--------- Writing temperature file (no mctherm) ----------")
            os.system("rm -f dust_temperature.bdat")  # avoid confusion!...
            TEMPOUT = open("dust_temperature.dat", "w")
            TEMPOUT.write("1 \n")  # iformat
            TEMPOUT.write(str(nrad * nsec * ncol) + " \n")  # n cells
            TEMPOUT.write(str(int(nbin)) + " \n")  # nbin size bins

            gas_temp = np.zeros((ncol, nrad, nsec))
            thydro = (parameters["aspectratio"] * parameters["aspectratio"] *
                      density.cutemp *
                      density.rmed**(-1.0 + 2.0 * parameters["flaringindex"]))
            for k in range(nsec):
                for j in range(ncol):
                    gas_temp[j, :, k] = thydro

            # write dust temperature for all size bins
            for ibin in range(nbin):
                print(
                    "writing temperature of dust species in bin",
                    ibin,
                    "out of ",
                    nbin - 1,
                )
                for k in range(nsec):
                    for j in range(ncol):
                        for i in range(nrad):
                            TEMPOUT.write(str(gas_temp[j, i, k]) + " \n")
            TEMPOUT.close()
            del gas_temp

        # Now run RADMC3D
        if parameters["recalc_rawfits"] == "No":
            print("--------- Now executing RADMC3D ----------")
            os.system("./script_radmc")

        print("--------- exporting results in fits format ----------")
        outfile = exportfits(M, parameters)

        if parameters["plot_temperature"] == "Yes":
            plot_temperature(nbin, nsec, ncol, nrad, density, parameters)
    else:
        print(
            "------- I did not run RADMC3D, using existing .fits file for convolution "
        )
        print(
            "------- (recalc_radmc = No in params.dat file) and final image ------ "
        )

        if parameters["RTdust_or_gas"] == "dust":
            outfile = ("image_" + str(parameters["label"]) + "_lbda" +
                       str(parameters["wavelength"]) + "_i" +
                       str(parameters["inclination"]) + "_phi" +
                       str(parameters["phiangle"]) + "_PA" +
                       str(parameters["posangle"]))
        else:
            print(
                "Set of initial conditions not implemented for pluto yet. Only parameters['RTdust_or_gas'] == 'dust'"
            )
            sys.exit("I must exit!")

        if parameters["secondorder"] == "Yes":
            outfile = outfile + "_so"
        if parameters["dustdens_eq_gasdens"] == "Yes":
            outfile = outfile + "_ddeqgd"
        if parameters["bin_small_dust"] == "Yes":
            outfile = outfile + "_bin0"

        outfile = outfile + ".fits"

    # =========================
    # Convolve raw flux with beam and produce final image
    # =========================
    if parameters["recalc_fluxmap"] == "Yes":
        print("--------- Convolving and writing final image ----------")

        f = fits.open("./" + outfile)

        # remove .fits extension
        outfile = os.path.splitext(outfile)[0]

        # add bmaj information
        outfile = outfile + "_bmaj" + str(parameters["bmaj"])

        outfile = outfile + ".fits"

        hdr = f[0].header
        # pixel size converted from degrees to arcseconds
        cdelt = np.abs(hdr["CDELT1"] * 3600.0)

        # get wavelength and convert it from microns to mm
        lbda0 = hdr["LBDAMIC"] * 1e-3

        # no polarized scattering: fits file directly contains raw intensity field
        if parameters["polarized_scat"] == "No":
            nx = hdr["NAXIS1"]
            ny = hdr["NAXIS2"]
            raw_intensity = f[0].data
            if parameters["recalc_radmc"] == "No" and parameters[
                    "plot_tau"] == "No":
                # sum over pixels
                print("Total flux [Jy] = " + str(np.sum(raw_intensity)))
            # check beam is correctly handled by inserting a source point at the
            # origin of the raw intensity image
            if parameters["check_beam"] == "Yes":
                raw_intensity[:, :] = 0.0
                raw_intensity[nx // 2 - 1, ny // 2 - 1] = 1.0
            # Add white (Gaussian) noise to raw flux image to simulate effects of 'thermal' noise
            if (parameters["add_noise"] == "Yes"
                    and parameters["RTdust_or_gas"] == "dust"
                    and parameters["plot_tau"] == "No"):
                # beam area in pixel^2
                beam = ((np.pi / (4.0 * np.log(2.0))) * parameters["bmaj"] *
                        parameters["bmin"] / (cdelt**2.0))
                # noise standard deviation in Jy per pixel (I've checked the expression below works well)
                noise_dev_std_Jy_per_pixel = parameters[
                    "noise_dev_std"] / np.sqrt(0.5 * beam)  # 1D
                # noise array
                noise_array = np.random.normal(
                    0.0,
                    noise_dev_std_Jy_per_pixel,
                    size=parameters["nbpixels"] * parameters["nbpixels"],
                )
                noise_array = noise_array.reshape(parameters["nbpixels"],
                                                  parameters["nbpixels"])
                raw_intensity += noise_array
            if parameters["brightness_temp"] == "Yes":
                # beware that all units are in cgs! We need to convert
                # 'intensity' from Jy/pixel to cgs units!
                # pixel size in each direction in cm
                pixsize_x = cdelt * parameters["distance"] * au
                pixsize_y = pixsize_x
                # solid angle subtended by pixel size
                pixsurf_ster = (pixsize_x * pixsize_y /
                                parameters["distance"] /
                                parameters["distance"] / pc / pc)
                # convert intensity from Jy/pixel to erg/s/cm2/Hz/sr
                intensity_buf = raw_intensity / 1e23 / pixsurf_ster
                # beware that lbda0 is in mm right now, we need to have it in cm in the expression below
                raw_intensity = (h * c / kB / (lbda0 * 1e-1)) / np.log(
                    1.0 +
                    2.0 * h * c / intensity_buf / pow((lbda0 * 1e-1), 3.0))
                # raw_intensity = np.nan_to_num(raw_intensity)
        else:
            print(
                "Set of initial conditions not implemented for pluto yet. Only parameters['polarized_scat'] == 'No'"
            )
            sys.exit("I must exit!")

        # ------------
        # smooth image
        # ------------
        # beam area in pixel^2
        beam = ((np.pi / (4.0 * np.log(2.0))) * parameters["bmaj"] *
                parameters["bmin"] / (cdelt**2.0))
        # stdev lengths in pixel
        stdev_x = (parameters["bmaj"] /
                   (2.0 * np.sqrt(2.0 * np.log(2.0)))) / cdelt
        stdev_y = (parameters["bmin"] /
                   (2.0 * np.sqrt(2.0 * np.log(2.0)))) / cdelt

        # a) case with no polarized scattering
        if parameters["polarized_scat"] == "No" and parameters[
                "plot_tau"] == "No":
            # Call to Gauss_filter function
            if parameters["moment_order"] != 1:
                smooth = Gauss_filter(raw_intensity,
                                      stdev_x,
                                      stdev_y,
                                      parameters["bpaangle"],
                                      Plot=False)
            else:
                smooth = raw_intensity

            # convert image from Jy/pixel to mJy/beam or microJy/beam
            # could be refined...
            if parameters["brightness_temp"] == "Yes":
                convolved_intensity = smooth
            else:
                convolved_intensity = smooth * 1e3 * beam  # mJy/beam

            strflux = "Flux of continuum emission (mJy/beam)"
            if parameters["gasspecies"] == "co":
                strgas = r"$^{12}$CO"
            elif parameters["gasspecies"] == "13co":
                strgas = r"$^{13}$CO"
            elif parameters["gasspecies"] == "c17o":
                strgas = r"C$^{17}$O"
            elif parameters["gasspecies"] == "c18o":
                strgas = r"C$^{18}$O"
            elif parameters["gasspecies"] == "hco+":
                strgas = r"HCO+"
            elif parameters["gasspecies"] == "so":
                strgas = r"SO"
            else:
                strgas = parameters["gasspecies"]
            if parameters["gasspecies"] != "so":
                strgas += r" ($%d \rightarrow %d$)" % (
                    parameters["iline"],
                    parameters["iline"] - 1,
                )
            if parameters["gasspecies"] == "so" and parameters["iline"] == 14:
                strgas += r" ($5_6 \rightarrow 4_5$)"

            if parameters["brightness_temp"] == "Yes":
                if parameters["RTdust_or_gas"] == "dust":
                    strflux = r"Brightness temperature (K)"
            else:
                if convolved_intensity.max() < 1.0:
                    convolved_intensity = smooth * 1e6 * beam  # microJy/beam
                    strflux = r"Flux of continuum emission ($\mu$Jy/beam)"

        if parameters["plot_tau"] == "Yes":
            convolved_intensity = raw_intensity
            strflux = r"Absorption optical depth $\tau"

        # -------------------------------------
        # SP: save convolved flux map solution to fits
        # -------------------------------------
        hdu = fits.PrimaryHDU()
        hdu.header["BITPIX"] = -32
        hdu.header["NAXIS"] = 2  # 2
        hdu.header["NAXIS1"] = parameters["nbpixels"]
        hdu.header["NAXIS2"] = parameters["nbpixels"]
        hdu.header["EPOCH"] = 2000.0
        hdu.header["EQUINOX"] = 2000.0
        hdu.header["LONPOLE"] = 180.0
        hdu.header["CTYPE1"] = "RA---SIN"
        hdu.header["CTYPE2"] = "DEC--SIN"
        hdu.header["CRVAL1"] = float(0.0)
        hdu.header["CRVAL2"] = float(0.0)
        hdu.header["CDELT1"] = hdr["CDELT1"]
        hdu.header["CDELT2"] = hdr["CDELT2"]
        hdu.header["LBDAMIC"] = hdr["LBDAMIC"]
        hdu.header["CUNIT1"] = "deg     "
        hdu.header["CUNIT2"] = "deg     "
        hdu.header["CRPIX1"] = float((parameters["nbpixels"] + 1.0) / 2.0)
        hdu.header["CRPIX2"] = float((parameters["nbpixels"] + 1.0) / 2.0)
        if strflux == "Flux of continuum emission (mJy/beam)":
            hdu.header["BUNIT"] = "milliJY/BEAM"
        if strflux == r"Flux of continuum emission ($\mu$Jy/beam)":
            hdu.header["BUNIT"] = "microJY/BEAM"
        if strflux == "":
            hdu.header["BUNIT"] = ""
        hdu.header["BTYPE"] = "FLUX DENSITY"
        hdu.header["BSCALE"] = 1
        hdu.header["BZERO"] = 0
        del hdu.header["EXTEND"]
        # keep track of all parameters in params.dat file
        # for i in range(len(lines_params)):
        #    hdu.header[var[i]] = par[i]
        hdu.data = convolved_intensity
        inbasename = os.path.basename("./" + outfile)
        if parameters["add_noise"] == "Yes":
            substr = "_wn" + str(parameters["noise_dev_std"]) + "_JyBeam.fits"
            jybeamfileout = re.sub(".fits", substr, inbasename)
        else:
            jybeamfileout = re.sub(".fits", "_JyBeam.fits", inbasename)
        hdu.writeto(jybeamfileout, overwrite=True)

        plot_image(nx, cdelt, lbda0, strflux, convolved_intensity,
                   jybeamfileout, parameters)

    print("--------- done! ----------")
Exemple #28
0
    def __init__(self,
                 screen,
                 usealpha=True,
                 noparticles=False,
                 endless=False):
        self.screen = screen
        self.usealpha = usealpha
        self.noparticles = noparticles

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water  #Water(self.usealpha)
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        self.sky = util.load_image("taivas")
        self.sky = pygame.transform.scale(self.sky,
                                          (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles(self.usealpha)
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)

        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        font = util.load_font(
            "Cosmetica",
            40)  #pygame.font.Font(pygame.font.get_default_font(), 36)
        self.pause_image = font.render("Pause", True, (0, 0, 0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center
 def setUp(self):
     self.particles1 = Particles(20,1, (200,2))
Exemple #30
0
class Game:
    def __init__(self,
                 screen,
                 usealpha=True,
                 noparticles=False,
                 endless=False):
        self.screen = screen
        self.usealpha = usealpha
        self.noparticles = noparticles

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water  #Water(self.usealpha)
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        self.sky = util.load_image("taivas")
        self.sky = pygame.transform.scale(self.sky,
                                          (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles(self.usealpha)
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)

        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        font = util.load_font(
            "Cosmetica",
            40)  #pygame.font.Font(pygame.font.get_default_font(), 36)
        self.pause_image = font.render("Pause", True, (0, 0, 0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center

    def run(self):
        while not self.done:
            if not self.pause:
                if not self.gameover:
                    self.spawn_enemies()

                self.update_enemies()
                self.player.update()
                self.health.update()
                cloud.update()
                for cb in self.cannonballs:
                    cb.update()
                    if (cb.rect.right < 0
                            and cb.vect[0] < 0) or (cb.rect.left > SCREEN_WIDTH
                                                    and cb.vect[0] > 0):
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                self.score.update()

                # Add steam particles
                if not self.noparticles:
                    for i in range(3):
                        particle_point = self.player.get_point(
                            (5.0 + random.random() * 9.0, 0))
                        particle_point[0] += self.player.rect.centerx
                        particle_point[1] += self.player.rect.centery
                        self.particles.add_steam_particle(particle_point)

                    for i in range(3):
                        particle_point = self.player.get_point(
                            (19.0 + random.random() * 7.0, 5.0))
                        particle_point[0] += self.player.rect.centerx
                        particle_point[1] += self.player.rect.centery
                        self.particles.add_steam_particle(particle_point)

                    if self.titanic:
                        for j in range(4):
                            for i in range(3):
                                particle_point = self.titanic.get_point(
                                    (49 + random.random() * 9.0 + 28 * j, 25))
                                particle_point[0] += self.titanic.rect.centerx
                                particle_point[1] += self.titanic.rect.centery
                                self.particles.add_steam_particle(
                                    particle_point)

                    self.particles.update()

                self.water.update()

                if self.player.splash:
                    if not self.noparticles:
                        for i in range(30):
                            r = random.random()
                            x = int(r * self.player.rect.left +
                                    (1.0 - r) * self.player.rect.right)
                            point = (x, self.water.get_water_level(x))
                            self.particles.add_water_particle(point)

                for powerup in self.powerups:
                    powerup.update()
                    if powerup.picked:
                        self.powerups.remove(powerup)
                        self.powerup_sprites.remove(powerup)

                if not self.gameover:
                    self.check_collisions()

                if self.health.hearts_left == 0 and not self.player.dying:
                    self.player.die()

                if self.player.dying and not self.player.dead:
                    if not self.noparticles:
                        for i in range(3):
                            self.particles.add_explosion_particle(
                                (self.player.rect.centerx,
                                 self.player.rect.centery))
                            self.particles.add_debris_particle(
                                (self.player.rect.centerx,
                                 self.player.rect.centery))

                if self.player.dead:
                    #self.done = True
                    self.set_gameover()

                if self.damage_count > 0:
                    self.damage_count -= 1
                self.lastshot += 1
                self.t += 1

            self.draw()

            self.handle_events()

        return self.score.get_score()

    def set_gameover(self, message="Game Over"):
        self.gameover = True
        images = []
        font = util.load_font(
            "Cosmetica",
            40)  #pygame.font.Font(pygame.font.get_default_font(), 36)
        height = 0
        width = 0
        for text in message.split("\n"):
            images.append(font.render(text, True, (0, 0, 0)))
            height += images[-1].get_height()
            if images[-1].get_width() > width:
                width = images[-1].get_width()
        self.gameover_image = pygame.Surface((width, height), SRCALPHA, 32)
        self.gameover_image.fill((0, 0, 0, 0))
        for i in range(len(images)):
            rect = images[i].get_rect()
            rect.top = i * images[i].get_height()
            rect.centerx = width / 2
            self.gameover_image.blit(images[i], rect)

        self.gameover_rect = self.gameover_image.get_rect()
        self.gameover_rect.center = self.screen.get_rect().center

    def handle_events(self):
        nextframe = False
        framecount = 0
        while not nextframe:
            # wait until there's at least one event in the queue
            pygame.event.post(pygame.event.wait())
            for event in pygame.event.get():
                #event = pygame.event.wait()
                if event.type == QUIT or \
                   event.type == KEYDOWN and event.key == K_ESCAPE:
                    self.done = True
                    nextframe = True
                elif event.type == NEXTFRAME:
                    nextframe = True
                    framecount += 1
                elif self.gameover:
                    if event.type == JOYBUTTONDOWN:
                        self.done = True
                        nextframe = True
                    elif event.type == KEYDOWN:
                        self.done = True
                        nextframe = True
                    continue
                elif event.type == JOYAXISMOTION:
                    if event.axis == 0:
                        if event.value < -0.5:
                            self.player.move_left(True)
                        elif event.value > 0.5:
                            self.player.move_right(True)
                        else:
                            self.player.move_left(False)
                            self.player.move_right(False)
                elif event.type == JOYBUTTONDOWN:
                    if event.button == 0:
                        if not self.pause:
                            self.player.jump()
                    elif event.button == 1:
                        if not self.pause:
                            if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                                cb = Cannonball(self.player.rect,
                                                self.player.angle)
                                self.cannonballs.append(cb)
                                self.cannonball_sprites.add(cb)
                                self.lastshot = 0
                    elif event.button == 5:
                        pygame.image.save(self.screen, "sshot.tga")
                        print "Screenshot saved as sshot.tga"
                    elif event.button == 8:
                        self.set_pause()
                elif event.type == KEYDOWN:
                    if event.key == K_LEFT:
                        self.player.move_left(True)
                    elif event.key == K_RIGHT:
                        self.player.move_right(True)
                    elif event.key == K_SPACE:
                        if not self.pause:
                            # Only 3 cannonballs at once
                            # Maximum firing rate set at the top
                            if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                                cb = Cannonball(self.player.rect,
                                                self.player.angle)
                                self.cannonballs.append(cb)
                                self.cannonball_sprites.add(cb)
                                self.lastshot = 0
                    elif event.key == K_UP:
                        if not self.pause:
                            self.player.jump()
                    elif event.key == K_s:
                        pygame.image.save(self.screen, "sshot.tga")
                        print "Screenshot saved as sshot.tga"
                    elif event.key == K_p:
                        self.set_pause()
                elif event.type == KEYUP:
                    if event.key == K_LEFT:
                        self.player.move_left(False)
                    elif event.key == K_RIGHT:
                        self.player.move_right(False)

        #if framecount > 1:
        #    print "Missed " + str(framecount - 1) + " frames!"

    def set_pause(self):
        self.pause = not self.pause

    def draw(self):
        self.screen.blit(self.sky, self.screen.get_rect())
        self.health_sprite.draw(self.screen)
        self.score_sprite.draw(self.screen)
        self.player_sprite.draw(self.screen)
        self.powerup_sprites.draw(self.screen)
        self.pirate_sprites.draw(self.screen)
        if self.titanic:
            self.titanic_sprite.draw(self.screen)
        self.seagull_sprites.draw(self.screen)
        cloud.draw(self.screen)
        self.shark_sprites.draw(self.screen)
        self.mine_sprites.draw(self.screen)
        self.cannonball_sprites.draw(self.screen)
        self.water_sprite.draw(self.screen)
        if not self.noparticles:
            self.particle_sprite.draw(self.screen)

        if self.pause:
            self.screen.blit(self.pause_image, self.pause_rect)

        if self.gameover:
            self.screen.blit(self.gameover_image, self.gameover_rect)

        if self.level.t < 120:
            font = util.load_font("Cosmetica", 16)
            image = None
            i = 0
            if self.level.phase < len(self.level.phase_messages):
                for text in self.level.phase_messages[self.level.phase].split(
                        "\n"):
                    image = font.render(text, True, (0, 0, 0))
                    rect = image.get_rect()
                    rect.centerx = self.screen.get_rect().centerx
                    rect.top = 100 + rect.height * i
                    blit_image = pygame.Surface(
                        (image.get_width(), image.get_height()))
                    blit_image.fill((166, 183, 250))
                    blit_image.set_colorkey((166, 183, 250))
                    blit_image.blit(image, image.get_rect())
                    if self.level.t > 60:
                        blit_image.set_alpha(255 -
                                             (self.level.t - 60) * 255 / 60)
                    self.screen.blit(blit_image, rect)
                    i += 1

        pygame.display.flip()

    def check_collisions(self):
        collisions = PixelPerfect.spritecollide_pp(self.player,
                                                   self.powerup_sprites, 0)
        for powerup in collisions:
            if not powerup.fading:
                if not self.player.dying:
                    self.health.add()
                    powerup.pickup()

        collisions = PixelPerfect.spritecollide_pp(self.player,
                                                   self.mine_sprites, 0)

        for mine in collisions:
            if not mine.exploding:
                if not self.player.dying:
                    self.health.damage()
                    mine.explode()

        collisions = PixelPerfect.spritecollide_pp(self.player,
                                                   self.shark_sprites, 0)

        for shark in collisions:
            if not shark.dying:
                if not self.player.dying:
                    self.health.damage()
                    shark.die()

        collisions = PixelPerfect.spritecollide_pp(self.player,
                                                   self.cannonball_sprites, 0)

        for cb in collisions:
            if not self.player.dying:
                self.health.damage()
                self.cannonballs.remove(cb)
                self.cannonball_sprites.remove(cb)
                Mine.sound.play(
                )  # Umm... the mine has a nice explosion sound.

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites,
                                                  self.shark_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for shark in collisions[cb]:
                # The test on cb.vect is a rude hack preventing cannonballs from pirate ships from killing sharks.
                if not shark.dying and cb.vect[0] > 0:
                    self.score.add(15)
                    shark.die()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites,
                                                  self.seagull_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for seagull in collisions[cb]:
                # cb.vect test is a rude hack preventing pirates from killing seagulls
                if not seagull.dying and cb.vect[0] > 0:
                    self.score.add(75)
                    seagull.die()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites,
                                                  self.pirate_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for pirate in collisions[cb]:
                # cb.vect hack for preventing pirates from killing each other
                if not pirate.dying and cb.vect[0] > 0:
                    Mine.sound.play()  # Umm... the mine has a nice sound.
                    self.score.add(25)
                    pirate.damage()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

        if self.titanic:
            collisions = PixelPerfect.spritecollide_pp(self.titanic,
                                                       self.cannonball_sprites,
                                                       0)
            for cb in collisions:
                if not self.titanic.dying and cb.vect[0] > 0:
                    Mine.sound.play()
                    self.score.add(7)
                    self.titanic.damage()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

    def update_enemies(self):
        for mine in self.mines:
            mine.update()
            if mine.exploding:
                if mine.explode_frames == 0:
                    self.mines.remove(mine)
                    self.mine_sprites.remove(mine)
                # this should really be done in the Mine class, but oh well, here's some explosion effects:
                if not self.noparticles:
                    for i in range(3):
                        self.particles.add_explosion_particle(
                            (mine.rect.centerx,
                             mine.rect.top + mine.image.get_rect().centerx))
                        self.particles.add_debris_particle(
                            (mine.rect.centerx,
                             mine.rect.top + mine.image.get_rect().centerx))
            if mine.rect.right < self.screen.get_rect().left:
                self.mines.remove(mine)
                self.mine_sprites.remove(mine)

        for shark in self.sharks:
            shark.update()
            if shark.dying:
                if not self.noparticles:
                    self.particles.add_blood_particle(shark.rect.center)
            if shark.rect.right < self.screen.get_rect().left or shark.dead:
                self.sharks.remove(shark)
                self.shark_sprites.remove(shark)

        for pirate in self.pirates:
            pirate.update()
            if pirate.t % 50 == 0 and not pirate.dying:
                # Pirate shoots, this should probably be handled by the Pirateboat class
                cb = Cannonball(pirate.rect, pirate.angle, left=True)
                self.cannonballs.append(cb)
                self.cannonball_sprites.add(cb)
            if pirate.rect.right < self.screen.get_rect().left or pirate.dead:
                self.pirates.remove(pirate)
                self.pirate_sprites.remove(pirate)
            elif pirate.dying:
                if not self.noparticles:
                    for i in range(3):
                        self.particles.add_explosion_particle(
                            (pirate.rect.centerx, pirate.rect.centery))
                        self.particles.add_wood_particle(
                            (pirate.rect.centerx, pirate.rect.centery))

        if self.titanic:
            self.titanic.update()
            if self.titanic.t % 100 == 0 and not self.titanic.dying:
                for i in range(3):
                    cb = Cannonball(self.titanic.rect,
                                    self.titanic.angle + (i - 1) * 10 - 50,
                                    left=True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            elif self.titanic.t % 100 == 50 and not self.titanic.dying:
                for i in range(3):
                    cb = Cannonball(self.titanic.rect,
                                    self.titanic.angle + (i - 1) * 10 - 60,
                                    left=True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            if self.titanic.dead:
                self.set_gameover("Congratulations!\nYou sunk Titanic!")
                self.titanic = None

        for seagull in self.seagulls:
            seagull.update()
            if seagull.rect.right < 0 or seagull.dead:
                self.seagulls.remove(seagull)
                self.seagull_sprites.remove(seagull)

    def spawn_enemies(self):
        spawns = self.level.get_spawns()
        if spawns[Level.SHARKS]:
            # Make a new shark
            self.sharks.append(Shark())
            self.shark_sprites.add(self.sharks[-1])

        if spawns[Level.PIRATES]:
            # Make a new pirate ship
            self.pirates.append(Pirateboat())
            self.pirate_sprites.add(self.pirates[-1])

        if spawns[Level.MINES]:
            self.mines.append(Mine())
            self.mine_sprites.add(self.mines[-1])

        if spawns[Level.SEAGULLS]:
            self.seagulls.append(Seagull())
            self.seagull_sprites.add(self.seagulls[-1])

        if spawns[Level.TITANIC]:
            self.titanic = Titanic()
            self.titanic_sprite.add(self.titanic)

        if spawns[Level.POWERUPS]:
            self.powerups.append(Powerup())
            self.powerup_sprites.add(self.powerups[-1])
Exemple #31
0
class Game:
    sky = None
    
    
    
        

    def __init__(self, screen, endless = False):
        self.screen = screen

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        if not Game.sky:
            Game.sky = util.load_image("taivas")
            Game.sky = pygame.transform.scale(self.sky, (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles()
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)

        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        self.pause_image = util.bigfont.render("Pause", Variables.alpha, (0,0,0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center

        self.spacepressed = None

    def run(self):
        while not self.done:
            if not self.pause:
                if not self.gameover:
                    self.spawn_enemies()

                self.update_enemies()
                self.player.update()
                self.health.update()
                cloud.update()
                for cb in self.cannonballs:
                    if not cb.underwater:
                        #~ particle_point=cb.rect.left, cb.rect.top
                        particle_point = cb.tail_point()
                        self.particles.add_trace_particle(particle_point)
                        particle_point = [particle_point[i] + cb.vect[i]/2 for i in (0,1)]
                        self.particles.add_trace_particle(particle_point)
                    if cb.special and (not cb.underwater or rr()>0.6) :
                        particle_point = cb.tail_point()
                        self.particles.add_explosion_particle(particle_point)
                    und_old=cb.underwater
                    cb.update()
                    if cb.underwater and not und_old:
                        for i in range(5):
                            particle_point=cb.rect.right-4.0+rr()*8.0, cb.rect.top+rr()*2.0
                            self.particles.add_water_particle(particle_point)
                    if (cb.rect.right < 0 and cb.vect[0] < 0) or (cb.rect.left > SCREEN_WIDTH and cb.vect[0] > 0) or (cb.rect.top > SCREEN_HEIGHT):
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                self.score.update()

                # Add steam particles
                if Variables.particles:
                    particle_point = self.player.get_point((5.0 + rr() * 9.0, 0))
                    particle_point[0] += self.player.rect.centerx
                    particle_point[1] += self.player.rect.centery
                    if self.spacepressed and self.t > self.spacepressed + FPS * 3:
                        pass
                        #~ self.particles.add_fire_steam_particle(particle_point)
                    else:
                        self.particles.add_steam_particle(particle_point)

                    particle_point = self.player.get_point((19.0 + rr() * 7.0, 5.0))
                    particle_point[0] += self.player.rect.centerx
                    particle_point[1] += self.player.rect.centery
                    if self.spacepressed and self.t > self.spacepressed + FPS * 3:
                        pass
                        #~ self.particles.add_fire_steam_particle(particle_point)
                    else:
                        self.particles.add_steam_particle(particle_point)

                    if self.titanic:
                        for j in range(4):
                            particle_point = self.titanic.get_point((49 + rr() * 9.0 + 28 * j, 25))
                            particle_point[0] += self.titanic.rect.centerx
                            particle_point[1] += self.titanic.rect.centery
                            self.particles.add_steam_particle(particle_point)

                    self.particles.update()

                self.water.update()

                if self.player.splash:
                    if Variables.particles:
                        for i in range(10):
                            r = rr()
                            x = int(r * self.player.rect.left + (1.0-r) * self.player.rect.right)
                            point = (x, self.water.get_water_level(x))
                            self.particles.add_water_particle(point)
    
                for powerup in self.powerups:
                    powerup.update()
                    if powerup.picked:
                        self.powerups.remove(powerup)
                        self.powerup_sprites.remove(powerup)

                if not self.gameover:
                    self.check_collisions()

                if self.health.hearts_left == 0 and not self.player.dying:
                    self.player.die()

                if self.player.dying and not self.player.dead:
                    if Variables.particles:
                        self.particles.add_explosion_particle((self.player.rect.centerx, self.player.rect.centery))
                        self.particles.add_debris_particle((self.player.rect.centerx, self.player.rect.centery))

                if self.player.dead:
                    #self.done = True
                    self.set_gameover()

                if self.damage_count > 0:
                    self.damage_count -= 1
                self.lastshot += 1
                self.t += 1

            self.draw()

            self.handle_events()

        return self.score.get_score()

    def damage_player(self):
        self.health.damage()
        for i in range(10):
            particle_point = self.player.get_point((rr() * 26.0, rr() * 10.0))
            particle_point[0] += self.player.rect.centerx
            particle_point[1] += self.player.rect.centery
            self.particles.add_debris_particle(particle_point)
        self.player.blinks+=12


    def set_gameover(self, message = "Game Over"):
        self.gameover = True
        images = []
        height = 0
        width = 0
        for text in message.split("\n"):
            images.append(util.bigfont.render(text, Variables.alpha, (0,0,0)))
            height += images[-1].get_height()
            if images[-1].get_width() > width:
                width = images[-1].get_width()
        self.gameover_image = pygame.Surface((width, height), SRCALPHA, 32)
        self.gameover_image.fill((0,0,0,0))
        for i in range(len(images)):
            rect = images[i].get_rect()
            rect.top = i * images[i].get_height()
            rect.centerx = width / 2
            self.gameover_image.blit(images[i], rect)

        self.gameover_rect = self.gameover_image.get_rect()
        self.gameover_rect.center = self.screen.get_rect().center

    def take_screenshot(self):
        i = 1
        filename = "sshot.tga"
        while os.path.exists(filename):
            i += 1
            filename = "sshot" + str(i) + ".tga"
        
        pygame.image.save(self.screen, filename)
        print("Screenshot saved as " + filename)

    def handle_events(self):
        nextframe = False
        framecount = 0
        while not nextframe:
          # wait until there's at least one event in the queue
          #nextframe = True
          pygame.event.post(pygame.event.wait())
          for event in pygame.event.get():
            #event = pygame.event.wait()
            if event.type == QUIT or \
               event.type == KEYDOWN and event.key == K_ESCAPE:
                self.done = True
                nextframe = True
            elif event.type == NEXTFRAME:
                framecount += 1
                nextframe = True
            elif self.gameover:
                if event.type == JOYBUTTONDOWN:
                    self.done = True
                    nextframe = True
                elif event.type == KEYDOWN:
                    self.done = True
                    nextframe = True
                continue
            elif event.type == JOYAXISMOTION:
                if event.axis == 0:
                    if event.value < -0.5:
                        self.player.move_left(True)
                    elif event.value > 0.5:
                        self.player.move_right(True)
                    else:
                        self.player.move_left(False)
                        self.player.move_right(False)
            elif event.type == JOYBUTTONDOWN:
                if event.button == 0:
                    if not self.pause:
                        self.player.jump()
                elif event.button == 1:
                    if not self.pause:
                        if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in range(4):
                                self.particles.add_fire_steam_particle(particle_point)
                            self.lastshot = 0
                            self.spacepressed = self.t
                elif event.button == 5:
                    self.take_screenshot()
                elif event.button == 8:
                    self.set_pause()
            elif event.type == KEYDOWN:
                if event.key == K_LEFT:
                    self.player.move_left(True)
                elif event.key == K_RIGHT:
                    self.player.move_right(True)
                elif event.key == K_SPACE:
                    if not self.pause:
                    # Only 3 cannonballs at once
                    # Maximum firing rate set at the top
                        if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in range(4):
                                self.particles.add_fire_steam_particle(particle_point)
                            self.lastshot = 0
                            self.spacepressed = self.t
                elif event.key == K_UP:
                    if not self.pause:
                        self.player.jump()
                elif event.key == K_s:
                    self.take_screenshot()
                elif event.key == K_p:
                    self.set_pause()
            elif event.type == KEYUP:
                if event.key == K_LEFT:
                    self.player.move_left(False)
                elif event.key == K_RIGHT:
                    self.player.move_right(False)
                elif event.key == K_SPACE:
                    if not self.pause:
                        if self.spacepressed and self.t > self.spacepressed + FPS * 3 and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle, special=True)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in range(30):
                                self.particles.add_fire_steam_particle((particle_point[0]+rrr(-4,4),particle_point[1]+rrr(-3,3)))
                            self.lastshot = 0
                        self.spacepressed = None
            elif event.type == JOYBUTTONUP:
                if event.button == 1:
                    if not self.pause:
                        if self.spacepressed and self.t > self.spacepressed + FPS * 3 and not self.player.dying:
                            cb = Cannonball(self.player.rect, self.player.angle, special=True)
                            self.cannonballs.append(cb)
                            self.cannonball_sprites.add(cb)
                            particle_point = self.player.get_point((42.0,10.0))
                            particle_point[0] += self.player.rect.centerx
                            particle_point[1] += self.player.rect.centery
                            for i in range(30):
                                self.particles.add_fire_steam_particle((particle_point[0]+rrr(-4,4),particle_point[1]+rrr(-3,3)))
                            self.lastshot = 0
                        self.spacepressed = None

        #if framecount > 1:
        #    print str(self.t) + ": missed " + str(framecount - 1) + " frames!"

    def set_pause(self):
        self.pause = not self.pause

        #if framecount > 1:
        #    print str(self.t) + ": missed " + str(framecount - 1) + " frames!"

    def set_pause(self):
        self.pause = not self.pause

    def draw(self):
        self.screen.blit(Game.sky, self.screen.get_rect())
        self.health_sprite.draw(self.screen)
        self.score_sprite.draw(self.screen)
        self.player_sprite.draw(self.screen)
        self.powerup_sprites.draw(self.screen)
        self.pirate_sprites.draw(self.screen)
        if self.titanic:
            self.titanic_sprite.draw(self.screen)
        self.seagull_sprites.draw(self.screen)
        cloud.draw(self.screen)
        self.shark_sprites.draw(self.screen)
        self.mine_sprites.draw(self.screen)
        self.cannonball_sprites.draw(self.screen)
        self.water_sprite.draw(self.screen)
        if Variables.particles:
            self.particle_sprite.draw(self.screen)

        if self.pause:
            self.screen.blit(self.pause_image, self.pause_rect)

        if self.gameover:
            self.screen.blit(self.gameover_image, self.gameover_rect)

        if self.level.t < 120:
            image = None
            i = 0
            if self.level.phase < len(self.level.phase_messages):
              for text in self.level.phase_messages[self.level.phase].split("\n"):
                image = util.smallfont.render(text, Variables.alpha, (0,0,0))
                rect = image.get_rect()
                rect.centerx = self.screen.get_rect().centerx
                rect.top = 100 + rect.height * i
                blit_image = pygame.Surface((image.get_width(), image.get_height()))
                blit_image.fill((166,183,250))
                blit_image.set_colorkey((166,183,250))
                blit_image.blit(image, image.get_rect())
                if self.level.t > 60:
                    blit_image.set_alpha(255 - (self.level.t - 60) * 255 / 60)
                self.screen.blit(blit_image, rect)
                i += 1

        pygame.display.flip()



    def check_collisions(self):
        collisions = PixelPerfect.spritecollide_pp(self.player, self.powerup_sprites, 0)
        for powerup in collisions:
            if not powerup.fading:
                if not self.player.dying:
                    self.health.add()
                    powerup.pickup()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.mine_sprites, 0)

        for mine in collisions:
            if not mine.exploding:
                if not self.player.dying:
                    self.damage_player()
                    mine.explode()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.shark_sprites, 0)

        for shark in collisions:
            if not shark.dying:
                if not self.player.dying:
                    self.damage_player()
                    shark.die()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.cannonball_sprites, 0)

        for cb in collisions:
            if not self.player.dying:
                self.damage_player()
                self.cannonballs.remove(cb)
                self.cannonball_sprites.remove(cb)
                if (Variables.sound):
                   Mine.sound.play() # Umm... the mine has a nice explosion sound.

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.shark_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for shark in collisions[cb]:
                # The test on cb.vect is a rude hack preventing cannonballs from pirate ships from killing sharks.
                if not shark.dying and cb.vect[0] > 0:
                    self.score.add(15)
                    shark.die()
                    # give her a part of ball's momentum:
                    shark.dx+=cb.vect[0]*0.6
                    shark.dy+=cb.vect[1]*0.4
                    if not cb.special:
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.seagull_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for seagull in collisions[cb]:
                # cb.vect test is a rude hack preventing pirates from killing seagulls
                if not seagull.dying and cb.vect[0] > 0:
                    self.score.add(75)
                    seagull.die()
                    # give her a part of ball's momentum:
                    seagull.vect[0]+=cb.vect[0]*0.4
                    seagull.vect[1]+=cb.vect[1]*0.4
                    if not cb.special:
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.pirate_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for pirate in collisions[cb]:
                # cb.vect hack for preventing pirates from killing each other
                if not pirate.dying and cb.vect[0] > 0:
                    if (Variables.sound):
                       Mine.sound.play() # Umm... the mine has a nice sound.
                    self.score.add(25)
                    pirate.damage()
                    for i in range(6):
                        self.particles.add_wood_particle((pirate.rect.centerx+rrr(-0,15), pirate.rect.centery+rrr(-10,20)))
                    if not cb.special:
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                    break

        if self.titanic:
            collisions = PixelPerfect.spritecollide_pp(self.titanic, self.cannonball_sprites, 0)
            for cb in collisions:
                if not self.titanic.dying and cb.vect[0] > 0:
                    if (Variables.sound):
                       Mine.sound.play()
                    if cb.special: 
                        #special round is hard to fire, so lets reward our crafty player
                        self.titanic.damage(12)
                        self.score.add(100)
                    else:
                        self.score.add(7)
                        self.titanic.damage()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

    def update_enemies(self):
        self.mine_sprites.update()
        for mine in self.mines:
            if mine.exploding:
                if mine.explode_frames == 0:
                    self.mines.remove(mine)
                    self.mine_sprites.remove(mine)
                # this should really be done in the Mine class, but oh well, here's some explosion effects:
                if Variables.particles:
                    self.particles.add_explosion_particle((mine.rect.centerx, mine.rect.top + mine.image.get_rect().centerx))
                    self.particles.add_debris_particle((mine.rect.centerx, mine.rect.top + mine.image.get_rect().centerx))
            if mine.rect.right < self.screen.get_rect().left:
                self.mines.remove(mine)
                self.mine_sprites.remove(mine)

        self.shark_sprites.update()
        for shark in self.sharks:
            if shark.dying:
                if Variables.particles:
                    self.particles.add_blood_particle(shark.rect.center)
            if shark.rect.right < self.screen.get_rect().left or shark.dead:
                self.sharks.remove(shark)
                self.shark_sprites.remove(shark)

        self.pirate_sprites.update()
        for pirate in self.pirates:
            if pirate.t % 50 == 0 and not pirate.dying:
                # Pirate shoots, this should probably be handled by the Pirateboat class
                cb = Cannonball(pirate.rect, pirate.angle, left = True)
                self.cannonballs.append(cb)
                self.cannonball_sprites.add(cb)
                particle_point = pirate.get_point((0.0,10.0))
                particle_point[0] += pirate.rect.centerx
                particle_point[1] += pirate.rect.centery
                for i in range(4):
                    self.particles.add_fire_steam_particle(particle_point)
                
            if pirate.rect.right < self.screen.get_rect().left or pirate.dead:
                self.pirates.remove(pirate)
                self.pirate_sprites.remove(pirate)
            elif pirate.dying:
                if Variables.particles:
                    self.particles.add_explosion_particle((pirate.rect.centerx, pirate.rect.centery))
                    self.particles.add_wood_particle((pirate.rect.centerx, pirate.rect.centery))

        if self.titanic:
            self.titanic.update()
            if self.titanic.t % 100 == 0 and not self.titanic.dying:
                for i in range(3):
                    cb = Cannonball(self.titanic.rect, self.titanic.angle + (i-1)*10 - 50, left = True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            elif self.titanic.t % 100 == 50 and not self.titanic.dying:
                for i in range(3):
                    cb = Cannonball(self.titanic.rect, self.titanic.angle + (i-1)*10 - 52.5, left = True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            if self.titanic.dead:
                self.set_gameover("Congratulations!\nYou sunk Titanic!")
                self.titanic = None

        self.seagull_sprites.update()
        for seagull in self.seagulls:
            if seagull.rect.right < 0 or seagull.dead:
                self.seagulls.remove(seagull)
                self.seagull_sprites.remove(seagull)

    def spawn_enemies(self):
        spawns = self.level.get_spawns()
        if spawns[Level.SHARKS]:
            # Make a new shark
            self.sharks.append(Shark())
            self.shark_sprites.add(self.sharks[-1])

        if spawns[Level.PIRATES]:
            # Make a new pirate ship
            self.pirates.append(Pirateboat())
            self.pirate_sprites.add(self.pirates[-1])

        if spawns[Level.MINES]:
            self.mines.append(Mine())
            self.mine_sprites.add(self.mines[-1])

        if spawns[Level.SEAGULLS]:
            self.seagulls.append(Seagull())
            self.seagull_sprites.add(self.seagulls[-1])

        if spawns[Level.TITANIC]:
            self.titanic = Titanic()
            self.titanic_sprite.add(self.titanic)

        if spawns[Level.POWERUPS]:
            self.powerups.append(Powerup())
            self.powerup_sprites.add(self.powerups[-1])
Exemple #32
0
 def five_particles_3d_random(self):
     return Particles(num_particles=5,
                      num_dimensions=3,
                      mass=1,
                      diameter=0.1)
Exemple #33
0
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.patches import Circle, Arrow

import numpy as np

from particles import Particles
from rotor import Rotor

rotor = Rotor()
particles = Particles(rotor=rotor)

fig = plt.figure()
subplot_shape = (2,4)
ax = plt.subplot2grid(subplot_shape, (0,0), rowspan=2, colspan=3)
ax_cumulative_theta = plt.subplot2grid(subplot_shape, (0,3) )
ax_cumulative_theta.xaxis.set_ticks([])

ax_cumulative_v_theta = plt.subplot2grid(subplot_shape, (1,3) )

plt.tight_layout()

ax_main_objs = []
cumulative_plot = None
cumulative_v_plot = None

def init():
    global ax_main_objs
    global cumulative_plot
    global cumulative_v_plot
Exemple #34
0
class Integrator(object):
    def __init__(self):
        """
        The constructor of an abstract integrator
        """
        # =================== CONSTANTS ==================
        # by default, using the square of the Gaussian gravitational constant
        self.CONST_G = 0.000295912208232213  # units: (AU^3/day^2)
        self.CONST_C = 0.0  # speed of light; PN terms will be calculated if CONST_C > 0

        # =================== VARIABLES ==================
        self._t = 0.0
        self.t_start = 0.0
        self.t_end = 0.0
        self.h = 0.01  # time step size
        self.store_dt = 100  # storage time step
        self._particles = None
        self.acceleration_method = 'ctypes'
        self.output_file = 'data.hdf5'
        self.collision_output_file = 'collisions.txt'
        self.close_encounter_output_file = 'close_encounters.txt'
        self.max_close_encounter_events = 1
        self.max_collision_events = 1
        self.close_encounter_distance = 0.0
        self.__energy_init = 0.0
        self.__energy = 0.0
        self.__buf = None
        self.buffer_len = 1024
        self.__initialized = False

        # =============== C Library =============
        self.libabie = CLibABIE()

    @property
    def t(self):
        return self._t

    @property
    def particles(self):
        if self._particles is None:
            self._particles = Particles(self.CONST_G)
        return self._particles

    @property
    def buf(self):
        if self.__buf is None:
            self.__buf = DataIO(buf_len=self.buffer_len,
                                output_file_name=self.output_file,
                                CONST_G=self.CONST_G)
        return self.__buf

    @staticmethod
    def load_integrators():
        """
        Load integrator modules
        :return: a dict of integrator class objects, mapping the name of the integrator to the class object
        """
        mod_dict = dict()
        module_candidates = glob.glob(
            os.path.join(__mpa_dir__, 'integrator_*.py'))
        sys.path.append(__mpa_dir__)  # append the python path
        if __mpa_dir__ != __user_shell_dir__:
            # load the integrator module (if any) also from the current user shell directory
            module_cwd = glob.glob(
                os.path.join(__user_shell_dir__, 'integrator_*.py'))
            for m_cwd in module_cwd:
                module_candidates.append(m_cwd)
            sys.path.append(__user_shell_dir__)  # append the python path
        for mod_name in module_candidates:
            mod_name = os.path.basename(mod_name)
            mod = __import__(mod_name.split('.')[0])
            if hasattr(mod, '__integrator__'):
                # it is a valid ABI module, register it as a module
                mod_dict[mod.__integrator__] = mod
        return mod_dict

    def initialize(self):
        if self.__buf is None:
            self.__buf = DataIO(
                buf_len=self.buffer_len,
                output_file_name=self.output_file,
                close_encounter_output_file_name=self.
                close_encounter_output_file,
                collision_output_file_name=self.collision_output_file,
                CONST_G=self.CONST_G)
        if self.particles.N > 0:
            # initialize the C library
            self.libabie.initialize_code(
                self.CONST_G,
                self.CONST_C,
                self.particles.N,
                MAX_CE_EVENTS=self.max_close_encounter_events,
                MAX_COLLISION_EVENTS=self.max_collision_events,
                close_encounter_distance=self.close_encounter_distance)
            self.buf.initialize_buffer(self.particles.N)

    def stop(self):
        if self.__buf is not None:
            self.__buf.close()

    def calculate_orbital_elements(self, primary=None):
        return self._particles.calculate_orbital_elements(primary)

    def calculate_energy(self):
        # return self._particles.energy
        if self.acceleration_method == 'ctypes':
            return self.libabie.get_total_energy()
        else:
            return self._particles.energy

    def set_additional_forces(self, ext_acc):
        self.libabie.set_additional_forces(ext_acc)

    def integrator_warmup(self):
        pos = self.particles.positions.copy()
        vel = self.particles.velocities.copy()
        self.libabie.set_state(pos, vel, self.particles.masses,
                               self.particles.radii, self.particles.N,
                               self.CONST_G, self.CONST_C)

    def integrate(self, to_time=None):
        """
        Integrate the system to a given time.
        :param to_time: The termination time. If None, it will use the self.t_end value, and the code will be stopped
                        when reaching self.t_end (i.e. if this function is called without argument, it can only be called
                        once; but if it is called with a to_time argument specificed, then it can be called iteratively.
        :return:
        """
        if to_time is not None:
            self.t_end = to_time

        if self.__initialized is False:
            self.initialize()
            self.integrator_warmup()
            self.__initialized = True
        if self.t >= self.t_end:
            return

        # Note: this dt is not the integrator time step h
        dt = min(self.store_dt, self.t_end - self.t)

        ret = 0
        # launch the integration
        while self.t < self.t_end:
            if self.__energy_init == 0:
                self.__energy_init = self.calculate_energy()
            next_t = self.t + dt - ((self.t + dt) % dt)
            if self.acceleration_method == 'numpy':
                ret = self.integrate_numpy(next_t)
            elif self.acceleration_method == 'ctypes':
                ret = self.integrate_ctypes(next_t)
            # the self.t is updated by the subclass
            # energy check
            self.__energy = self.calculate_energy()
            print(('t = %f, N = %d, dE/E0 = %g' %
                   (self.t, self.particles.N,
                    np.abs(self.__energy - self.__energy_init) /
                    self.__energy_init)))
            if os.path.isfile('STOP'):
                break

        if to_time is None:
            # triggering the termination of the code, save the buffer to the file and close it
            self.stop()
            # if ret > 0:
            #     break
        # if self.t == self.t_end:
        #     self.__energy = self.calculate_energy()
        #     print('t = %f, E/E0 = %g' % (self.t, np.abs(self.__energy - self.__energy_init) / self.__energy_init))
        return ret

    def integrate_numpy(self, to_time):
        """
        Integrate the system to a given time using python/numpy.
        This method must be implemented in the subclasses.
        :param to_time: The termination time. If None, it will use the self.t_end value
        :return:
        """
        raise NotImplementedError('integrate_numpy() method not implemented!')

    def integrate_ctypes(self, to_time):
        """
        Integrate the system to a given time using the ctypes (libabie.so)
        This method must be implemented in the subclasses.
        :param to_time: The termination time. If None, it will use the self.t_end value
        :return:
        """
        raise NotImplementedError('integrate_ctypes() method not implemented!')

    def store_state(self):
        if self.buf is None:
            self.initialize()
        self.buf.initialize_buffer(self.particles.N)
        elem = self.particles.calculate_aei()
        self.buf.store_state(self.t,
                             self.particles.positions,
                             self.particles.velocities,
                             self.particles.masses,
                             radii=self.particles.radii,
                             names=self.particles.hashes,
                             ptypes=self.particles.ptypes,
                             a=elem[:, 0],
                             e=elem[:, 1],
                             i=elem[:, 2])

    def store_collisions(self, collision_buffer):
        self.buf.store_collisions(collision_buffer)

    def store_close_encounters(self, ce_buffer):
        self.buf.store_close_encounters(ce_buffer)

    def handle_collisions(self, collision_buffer, actions=None):
        if actions is None:
            actions = ['merge', 'store']
        if 'store' in actions:
            self.store_state()
            self.store_collisions(collision_buffer)
        if 'merge' in actions:
            collision_buffer = collision_buffer.reshape(
                len(collision_buffer), 4)
            for coll_pair in range(collision_buffer.shape[0]):
                pid1 = int(collision_buffer[coll_pair, 1])
                pid2 = int(collision_buffer[coll_pair, 2])
                self.particles.merge_particles_inelastically(pid1, pid2)
                self.libabie.reset_collision_buffer()
                self.integrator_warmup()
                self.buf.flush()
                self.buf.reset_buffer()
                self.buf.initialize_buffer(self.particles.N)
        if 'halt' in actions:
            print('Simulation terminated due to a collision event.')
            sys.exit(0)

    def handle_close_encounters(self, ce_buffer, actions=None):
        if actions is None:
            actions = ['merge', 'store']
        if 'store' in actions:
            self.store_state()
            self.store_close_encounters(ce_buffer)
        if 'halt' in actions:
            print('Simulation terminated due to a collision event.')
            sys.exit(0)
class ParticleFilter:
    """
    Class representation of visual particle filter.
    """
    def __init__(self, env, num_particles, particle_angle_range, num_rays,
                 r_mean, r_std, ang_mean, ang_std, visualize, background, save_to,
                 row_min, row_max, n_angle_bins, front_angle_range):
        """Instantiates the visual particle filter with initial constraints.
        Args:
            run (dataset object): Provides access to an experiment
            experiment  Location of the experiment
            mapfile     Image location of top down maze image that is in turn converted
                        to gridmap file via the Gridmap class
            num_particles   Number of particles used for tracking
            particle_size   Size for scatter plot particles
            arrow_size      Arrow size (in meters)
        """
        # Set the run
        self.env = env
        # Setup the particles
        self.particles = Particles(num_particles, r_mean, r_std, ang_mean, ang_std)
        
        ## Matplotlib based visualization
        self.visualize = visualize
        self.viz_map   = env.mapfile 

        self.featurizer = HistogramFeatures()

        # Color gradient
        self.num_cgs = 100
        self.color_gradient = list(Color("red").range_to(Color("green"), self.num_cgs))
    
    
    def heatmap(self, viz):
        viz = viz * 0
        planner = self.env.planner
        particles = Particles(planner.poses.shape[0])
        particles.pose[:,:2] = planner.poses[:,:2]
        particles.pose[:, 2] = self.env.agent.pose[:,2]
        pixels = pose2pixel(particles.pose, MC.mazeshape)
        
        weights = np.zeros(len(particles))
        measurement = self.env.get_visual_obs(self.env.agent.pose)
        for i, (pose, pix) in enumerate(zip(particles.pose, pixels)):
            pose_measurement = self.env.get_visual_obs(pose)
            weights[i] = (pose_measurement == measurement).sum()
        #print(weights.max(), weights.min(), weights.mean())
        #weights = softmax(weights, t=.05)
        
        for i, (pose, pix) in enumerate(zip(particles.pose, pixels)):
            c_indx = int((self.num_cgs-1) * weights[i]/weights.max())
            color  = color2bgr(self.color_gradient[c_indx])
            self.env.draw_circle(viz, pix, rad=20, color=color)
            self.env.draw_orientation(viz, pose, thickness=2)
        
        for i, (pose, pix) in enumerate(zip(particles.pose, pixels)):
            cv2.putText(viz, str(int(weights[i])), point(pix), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
        return viz
    
    def display(self):
        viz = self.env.display().copy()
        pixels = pose2pixel(self.particles.pose, MC.mazeshape)
        for i, (pose, pixel) in enumerate(zip(self.particles.pose, pixels)):
            #viz = self.env.draw_rays(viz, pose)
            #viz = self.env.draw_orientation(viz, pose, thickness=2)

            norm = self.particles.weights[i]/self.particles.weights.max()
            c_indx = int((self.num_cgs-1) * norm)
            color  = color2bgr(self.color_gradient[c_indx])
            viz = self.env.draw_circle(viz, pixel, rad=5, color=color)

        # Make a heatmap
        heatmap = self.heatmap(viz)
        out = np.concatenate((viz, heatmap), 1)
        show(out, 30)
        return out


    def compute_likelihood(self, r, ps, epsilon=1e-12):
        """
        Histogram comparison
        """
        weights = np.zeros((len(self.particles)))
        r = self.featurizer.particle_features(r)
        for i, p in enumerate(ps):
            p = self.featurizer.particle_features(p) 
            weights[i] = self.featurizer.compare(r, p) 
        return weights / weights.sum()
    
    #def compute_likelihood(self, r, ps, epsilon=1e-12):
    #    weights = np.zeros((len(self.particles)))
    #    for i, p in enumerate(ps):
    #        weights[i] = (r * p).sum() 
    #    return weights / weights.sum()
    
    def localize(self):
        
        action = None
        while action != Action.END:
            # Display
            self.display()
            # Get robot measurements
            r_obs = self.env.get_visual_obs(self.env.agent.pose)
            #self.particles.pose[:,2] = self.env.agent.pose[:,2]
            # Get particle measurements
            p_obs = [self.env.get_visual_obs(p) for p in self.particles.pose]
            # Compute similarities between particle measures and real ms.
            self.particles.weights = self.compute_likelihood(r_obs, p_obs)
            # Resample
            self.particles.resample()

            # Move actions
            action = self.env.next_shortest_path_action()
            self.env.makeActions(action)

            # Evolve the particles
            self.particles.random_motion()

        import ipdb; ipdb.set_trace()
Exemple #36
0
class Game:
    def __init__(self, screen, usealpha = True, noparticles = False, endless = False):
        self.screen = screen
        self.usealpha = usealpha
        self.noparticles = noparticles

        self.sharks = []
        self.shark_sprites = pygame.sprite.Group()

        self.player = Steamboat()
        self.player_sprite = pygame.sprite.Group()
        self.player_sprite.add(self.player)

        self.health = Health()
        self.health_sprite = pygame.sprite.Group()
        self.health_sprite.add(self.health)

        self.damage_count = 0

        self.t = 0

        self.water = Water.global_water #Water(self.usealpha)
        #Water.global_water = self.water
        self.water_sprite = pygame.sprite.Group()
        self.water_sprite.add(self.water)

        self.sky = util.load_image("taivas")
        self.sky = pygame.transform.scale(self.sky, (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.pause_icon = util.load_image("pause")
        
        self.cannonballs = []
        self.cannonball_sprites = pygame.sprite.Group()

        self.pirates = []
        self.pirate_sprites = pygame.sprite.Group()

        self.titanic = None
        self.titanic_sprite = pygame.sprite.Group()

        self.seagulls = []
        self.seagull_sprites = pygame.sprite.Group()

        self.particles = Particles(self.usealpha)
        self.particle_sprite = pygame.sprite.Group()
        self.particle_sprite.add(self.particles)

        self.mines = []
        self.mine_sprites = pygame.sprite.Group()

        self.score = Score()
        self.score_sprite = pygame.sprite.Group()
        self.score_sprite.add(self.score)

        self.powerups = []
        self.powerup_sprites = pygame.sprite.Group()

        self.level = Level(endless)
        self.cheat_current = 0
        
        self.lastshot = MIN_FIRE_DELAY + 1

        self.gameover = False
        self.gameover_image = None
        self.gameover_rect = None
        self.done = False

        self.pause = False
        font = util.load_font("Cosmetica", 40) #pygame.font.Font(pygame.font.get_default_font(), 36)
        self.pause_image = font.render("Pause", True, (0,0,0))
        self.pause_rect = self.pause_image.get_rect()
        self.pause_rect.center = self.screen.get_rect().center

    def run(self):
        while not self.done:
            util.android_check_pause()
            if not self.pause:
                if not self.gameover:
                    self.spawn_enemies()

                self.update_enemies()
                self.player.update()
                self.health.update()
                cloud.update()
                for cb in self.cannonballs:
                    cb.update()
                    if (cb.rect.right < 0 and cb.vect[0] < 0) or (cb.rect.left > SCREEN_WIDTH and cb.vect[0] > 0):
                        self.cannonballs.remove(cb)
                        self.cannonball_sprites.remove(cb)
                self.score.update()

                # Add steam particles
                if not self.noparticles:
                    for i in range(STEAM_3):
                        particle_point = self.player.get_point((5.0 + random.random() * 9.0, 0))
                        particle_point[0] += self.player.rect.centerx
                        particle_point[1] += self.player.rect.centery
                        self.particles.add_steam_particle(particle_point)

                    for i in range(STEAM_3):
                        particle_point = self.player.get_point((19.0 + random.random() * 7.0, 5.0))
                        particle_point[0] += self.player.rect.centerx
                        particle_point[1] += self.player.rect.centery
                        self.particles.add_steam_particle(particle_point)

                    if self.titanic:
                        for j in range(4):
                            for i in range(STEAM_3):
                                particle_point = self.titanic.get_point((49 + random.random() * 9.0 + 28 * j, 25))
                                particle_point[0] += self.titanic.rect.centerx
                                particle_point[1] += self.titanic.rect.centery
                                self.particles.add_steam_particle(particle_point)

                    self.particles.update()

                self.water.update()

                if self.player.splash:
                    if not self.noparticles:
                        for i in range(SPLASH_30):
                            r = random.random()
                            x = int(r * self.player.rect.left + (1.0-r) * self.player.rect.right)
                            point = (x, self.water.get_water_level(x))
                            self.particles.add_water_particle(point)
    
                for powerup in self.powerups:
                    powerup.update()
                    if powerup.picked:
                        self.powerups.remove(powerup)
                        self.powerup_sprites.remove(powerup)

                if not self.gameover:
                    self.check_collisions()

                if self.health.hearts_left == 0 and not self.player.dying:
                    self.player.die()

                if self.player.dying and not self.player.dead:
                    if not self.noparticles:
                        for i in range(BLOOD_3):
                            self.particles.add_explosion_particle((self.player.rect.centerx, self.player.rect.centery))
                            self.particles.add_debris_particle((self.player.rect.centerx, self.player.rect.centery))

                if self.player.dead:
                    #self.done = True
                    self.set_gameover()

                if self.damage_count > 0:
                    self.damage_count -= 1
                self.lastshot += 1
                self.t += 1

            self.draw()

            self.handle_events()


        return self.score.get_score()

    def set_gameover(self, message = "Game Over"):
        self.gameover = True
        images = []
        font = util.load_font("Cosmetica", 40) #pygame.font.Font(pygame.font.get_default_font(), 36)
        height = 0
        width = 0
        for text in message.split("\n"):
            images.append(font.render(text, True, (0,0,0)))
            height += images[-1].get_height()
            if images[-1].get_width() > width:
                width = images[-1].get_width()
        self.gameover_image = pygame.Surface((width, height), SRCALPHA, 32)
        self.gameover_image.fill((0,0,0,0))
        for i in range(len(images)):
            rect = images[i].get_rect()
            rect.top = i * images[i].get_height()
            rect.centerx = width / 2
            self.gameover_image.blit(images[i], rect)

        self.gameover_rect = self.gameover_image.get_rect()
        self.gameover_rect.center = self.screen.get_rect().center
    
    def translate_mouse_event(self, event):
     if event.type in (MOUSEBUTTONDOWN, ):
       if event.pos[0] > SCREEN_WIDTH - 32 and event.pos[1] < 32:
          key = K_p
       else:
          rx = event.pos[0] / float(SCREEN_WIDTH)
          ry = event.pos[1] / float(SCREEN_HEIGHT)
          if rx < 0.0:
             key = K_LEFT
          elif rx > 1.0:
             key = K_RIGHT
          elif ry > 0.5:
             key = K_SPACE
          else:
             key = K_UP
       event = pygame.event.Event(KEYUP if event.type == MOUSEBUTTONUP else KEYDOWN, key=key)
     
     if util.android:
        self.player.move_left(False)
        self.player.move_right(False)
     return event
    
    def handle_events(self):
        nextframe = False
        framecount = 0
        while not nextframe:
          # wait until there's at least one event in the queue
          pygame.event.post(pygame.event.wait())
          for event in pygame.event.get():
            #event = pygame.event.wait()
            event = self.translate_mouse_event(event)
            if event.type == QUIT or \
               event.type == KEYDOWN and event.key == K_ESCAPE:
                self.done = True
                nextframe = True
            elif event.type == NEXTFRAME:
                nextframe = True
                framecount += 1
            elif self.gameover:
                if event.type == JOYBUTTONDOWN:
                    self.done = True
                    nextframe = True
                elif event.type == KEYDOWN:
                    self.done = True
                    nextframe = True
            elif event.type == MOUSEBUTTONDOWN:
                self.done = True
                nextframe = True
                continue
            elif event.type == JOYAXISMOTION:
                if event.axis == 0:
                    if event.value < -0.5:
                        self.player.move_left(True)
                    elif event.value > 0.5:
                        self.player.move_right(True)
                    else:
                        self.player.move_left(False)
                        self.player.move_right(False)
            elif event.type == JOYBUTTONDOWN:
                if event.button == 0:
                  if not self.pause:
                    self.player.jump()
                elif event.button == 1:
                  if not self.pause:
                    if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                        cb = Cannonball(self.player.rect, self.player.angle)
                        self.cannonballs.append(cb)
                        self.cannonball_sprites.add(cb)
                        self.lastshot = 0
                elif event.button == 5:
                    pygame.image.save(self.screen, "sshot.tga")
                    print "Screenshot saved as sshot.tga"
                elif event.button == 8:
                    self.set_pause()
            elif event.type == KEYDOWN:
                if event.key == K_LEFT:
                    self.player.move_left(True)
                elif event.key == K_RIGHT:
                    self.player.move_right(True)
                elif event.key == K_SPACE:
                  if not self.pause:
                    # Only 3 cannonballs at once
                    # Maximum firing rate set at the top
                    if self.lastshot > MIN_FIRE_DELAY and not self.player.dying:
                        cb = Cannonball(self.player.rect, self.player.angle)
                        self.cannonballs.append(cb)
                        self.cannonball_sprites.add(cb)
                        self.lastshot = 0
                elif event.key == K_UP:
                    if not self.pause:
                        self.player.jump()
                elif event.key == K_s:
                    pygame.image.save(self.screen, "sshot.tga")
                    print "Screenshot saved as sshot.tga"
                elif event.key == K_p:
                    self.set_pause()
                elif event.key == cheat_seq[self.cheat_current]:
                    self.cheat_current += 1
                    print self.cheat_current
                    if len(cheat_seq) == self.cheat_current:
                        print 'Cheater!'
                        self.cheat_current = 0
                        self.level.phase = 5
                        self.level.t = 0
                        self.spawn_enemies()
            elif event.type == KEYUP:
                if event.key == K_LEFT:
                    self.player.move_left(False)
                elif event.key == K_RIGHT:
                    self.player.move_right(False)
        
        tiling = util.get_tiling()
        if tiling == -1:
            self.player.move_left(True)
        elif tiling == 1:
            self.player.move_right(True)
        #if framecount > 1:
        #    print "Missed " + str(framecount - 1) + " frames!"

    def set_pause(self):
        self.pause = not self.pause

    def draw(self):
        self.screen.blit(self.sky, self.screen.get_rect())
        self.screen.blit(self.pause_icon, (SCREEN_WIDTH - 32, 0))
        self.health_sprite.draw(self.screen)
        self.score_sprite.draw(self.screen)
        self.player_sprite.draw(self.screen)
        self.powerup_sprites.draw(self.screen)
        self.pirate_sprites.draw(self.screen)
        if self.titanic:
            self.titanic_sprite.draw(self.screen)
        self.seagull_sprites.draw(self.screen)
        cloud.draw(self.screen)
        self.shark_sprites.draw(self.screen)
        self.mine_sprites.draw(self.screen)
        self.cannonball_sprites.draw(self.screen)
        self.water_sprite.draw(self.screen)
        if not self.noparticles:
            self.particle_sprite.draw(self.screen)

        if self.pause:
            self.screen.blit(self.pause_image, self.pause_rect)

        if self.gameover:
            self.screen.blit(self.gameover_image, self.gameover_rect)

        if self.level.t < 120:
            font = util.load_font("Cosmetica", 16)
            image = None
            i = 0
            if self.level.phase < len(self.level.phase_messages):
              for text in self.level.phase_messages[self.level.phase].split("\n"):
                image = font.render(text, True, (0,0,0))
                rect = image.get_rect()
                rect.centerx = self.screen.get_rect().centerx
                rect.top = 100 + rect.height * i
                blit_image = pygame.Surface((image.get_width(), image.get_height()))
                blit_image.fill((166,183,250))
                blit_image.set_colorkey((166,183,250))
                blit_image.blit(image, image.get_rect())
                if self.level.t > 60:
                    blit_image.set_alpha(255 - (self.level.t - 60) * 255 / 60)
                self.screen.blit(blit_image, rect)
                i += 1

        pygame.display.flip()



    def check_collisions(self):
        collisions = PixelPerfect.spritecollide_pp(self.player, self.powerup_sprites, 0)
        for powerup in collisions:
            if not powerup.fading:
                if not self.player.dying:
                    self.health.add()
                    powerup.pickup()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.mine_sprites, 0)

        for mine in collisions:
            if not mine.exploding:
                if not self.player.dying:
                    self.health.damage()
                    mine.explode()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.shark_sprites, 0)

        for shark in collisions:
            if not shark.dying:
                if not self.player.dying:
                    self.health.damage()
                    shark.die()

        collisions = PixelPerfect.spritecollide_pp(self.player, self.cannonball_sprites, 0)

        for cb in collisions:
            if not self.player.dying:
                self.health.damage()
                self.cannonballs.remove(cb)
                self.cannonball_sprites.remove(cb)
                Mine.sound.play() # Umm... the mine has a nice explosion sound.

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.shark_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for shark in collisions[cb]:
                # The test on cb.vect is a rude hack preventing cannonballs from pirate ships from killing sharks.
                if not shark.dying and cb.vect[0] > 0:
                    self.score.add(15)
                    shark.die()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.seagull_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for seagull in collisions[cb]:
                # cb.vect test is a rude hack preventing pirates from killing seagulls
                if not seagull.dying and cb.vect[0] > 0:
                    self.score.add(75)
                    seagull.die()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

        collisions = PixelPerfect.groupcollide_pp(self.cannonball_sprites, self.pirate_sprites, 0, 0)

        for cb in dict.keys(collisions):
            for pirate in collisions[cb]:
                # cb.vect hack for preventing pirates from killing each other
                if not pirate.dying and cb.vect[0] > 0:
                    Mine.sound.play() # Umm... the mine has a nice sound.
                    self.score.add(25)
                    pirate.damage()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

        if self.titanic:
            collisions = PixelPerfect.spritecollide_pp(self.titanic, self.cannonball_sprites, 0)
            for cb in collisions:
                if not self.titanic.dying and cb.vect[0] > 0:
                    Mine.sound.play()
                    self.score.add(7)
                    self.titanic.damage()
                    self.cannonballs.remove(cb)
                    self.cannonball_sprites.remove(cb)
                    break

    def update_enemies(self):
        for mine in self.mines:
            mine.update()
            if mine.exploding:
                if mine.explode_frames == 0:
                    self.mines.remove(mine)
                    self.mine_sprites.remove(mine)
                # this should really be done in the Mine class, but oh well, here's some explosion effects:
                if not self.noparticles:
                    for i in range(3):
                        self.particles.add_explosion_particle((mine.rect.centerx, mine.rect.top + mine.image.get_rect().centerx))
                        self.particles.add_debris_particle((mine.rect.centerx, mine.rect.top + mine.image.get_rect().centerx))
            if mine.rect.right < self.screen.get_rect().left:
                self.mines.remove(mine)
                self.mine_sprites.remove(mine)

        for shark in self.sharks:
            shark.update()
            if shark.dying:
                if not self.noparticles:
                    self.particles.add_blood_particle(shark.rect.center)
            if shark.rect.right < self.screen.get_rect().left or shark.dead:
                self.sharks.remove(shark)
                self.shark_sprites.remove(shark)

        for pirate in self.pirates:
            pirate.update()
            if pirate.t % 50 == 0 and not pirate.dying:
                # Pirate shoots, this should probably be handled by the Pirateboat class
                cb = Cannonball(pirate.rect, pirate.angle, left = True)
                self.cannonballs.append(cb)
                self.cannonball_sprites.add(cb)
            if pirate.rect.right < self.screen.get_rect().left or pirate.dead:
                self.pirates.remove(pirate)
                self.pirate_sprites.remove(pirate)
            elif pirate.dying:
                if not self.noparticles:
                    for i in range(3):
                        self.particles.add_explosion_particle((pirate.rect.centerx, pirate.rect.centery))
                        self.particles.add_wood_particle((pirate.rect.centerx, pirate.rect.centery))

        if self.titanic:
            self.titanic.update()
            if self.titanic.t % 100 == 0 and not self.titanic.dying:
                for i in range(3):
                    cb = Cannonball(self.titanic.rect, self.titanic.angle + (i-1)*10 - 50, left = True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            elif self.titanic.t % 100 == 50 and not self.titanic.dying:
                for i in range(3):
                    cb = Cannonball(self.titanic.rect, self.titanic.angle + (i-1)*10 - 60, left = True)
                    self.cannonballs.append(cb)
                    self.cannonball_sprites.add(cb)
            if self.titanic.dead:
                self.set_gameover("Congratulations!\nYou sunk Titanic!")
                self.titanic = None

        for seagull in self.seagulls:
            seagull.update()
            if seagull.rect.right < 0 or seagull.dead:
                self.seagulls.remove(seagull)
                self.seagull_sprites.remove(seagull)

    def spawn_enemies(self):
        spawns = self.level.get_spawns()
        if spawns[Level.SHARKS]:
            # Make a new shark
            self.sharks.append(Shark())
            self.shark_sprites.add(self.sharks[-1])

        if spawns[Level.PIRATES]:
            # Make a new pirate ship
            self.pirates.append(Pirateboat())
            self.pirate_sprites.add(self.pirates[-1])

        if spawns[Level.MINES]:
            self.mines.append(Mine())
            self.mine_sprites.add(self.mines[-1])

        if spawns[Level.SEAGULLS]:
            self.seagulls.append(Seagull())
            self.seagull_sprites.add(self.seagulls[-1])

        if spawns[Level.TITANIC]:
            self.titanic = Titanic()
            self.titanic_sprite.add(self.titanic)

        if spawns[Level.POWERUPS]:
            self.powerups.append(Powerup())
            self.powerup_sprites.add(self.powerups[-1])