Example #1
0
 def toppost(self, waveid, txt):
     """ output to the root id. """
     if not self.domain in waveid:
         logging.warn("%s - not connected - %s" % (self.name, waveid))
         return
     wave = Wave(waveid)
     if wave and wave.data.waveid: wave.toppost(self, txt)
     else: logging.warn("%s - we are not joined to %s" % (self.name, waveid))
Example #2
0
 def toppost(self, waveid, txt):
     """ output to the root id. """
     if not self.domain in waveid:
         logging.warn("%s - not connected - %s" % (self.name, waveid))
         return
     wave = Wave(waveid)
     if wave and wave.data.waveid: wave.toppost(self, txt)
     else:
         logging.warn("%s - we are not joined to %s" % (self.name, waveid))
Example #3
0
 def outnocb(self, waveid, txt, result=[], event=None, origin="", dot=", ", *args, **kwargs):
     """ output to the root id. """
     if not self.domain in self._server_rpc_base:
         credentials = _import_byfile("credentials", getdatadir() + os.sep + "config" + os.sep + "credentials.py")
         rpc_base = credentials.RPC_BASE[waveid.split("!")[0]]
         self._server_rpc_base = rpc_base
         logging.warn("%s - %s - server_rpc_base is %s" % (self.name, waveid, self._server_rpc_base))
     if not event: logging.error("wave - event not set - %s" % calledfrom(sys._getframe(0)))
     logging.warn("wave - creating new event.")
     wave = Wave(waveid)
     wave.say(self, txt)
Example #4
0
 def outnocb(self,
             waveid,
             txt,
             result=[],
             event=None,
             origin="",
             dot=", ",
             *args,
             **kwargs):
     """ output to the root id. """
     if not self.domain in self._server_rpc_base:
         credentials = _import_byfile(
             "credentials",
             getdatadir() + os.sep + "config" + os.sep + "credentials.py")
         rpc_base = credentials.RPC_BASE[waveid.split("!")[0]]
         self._server_rpc_base = rpc_base
         logging.warn("%s - %s - server_rpc_base is %s" %
                      (self.name, waveid, self._server_rpc_base))
     if not event:
         logging.error("wave - event not set - %s" %
                       calledfrom(sys._getframe(0)))
     logging.warn("wave - creating new event.")
     wave = Wave(waveid)
     wave.say(self, txt)
Example #5
0
#         if event.type == pygame.KEYDOWN:
#             if event.key == pygame.K_ESCAPE:
#                 print("Closing the simulation..")
#                 sys.exit()
#         if event.type == pygame.USEREVENT:



if __name__ == '__main__':    

    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    clock.tick(40)
    pygame.time.set_timer(pygame.USEREVENT, 1000)
    w = Wave(screen, 320, 240)

    while True:
        screen.fill((255, 255, 255))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("Closing the simulation..")
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    print("Closing the simulation..")
                    sys.exit()
            if event.type == pygame.USEREVENT:
                w.create_particles()
        # handle_events(pygame.event.get())
        # print(pygame.time.get_ticks())
Example #6
0
def main():

    # start pygame
    pygame.init()

    # pygame font
    pygame.font.init()
    font = pygame.font.Font(None, constants.SCORE_FONT_SIZE)

    # screen size
    screen = pygame.display.set_mode(constants.size)

    # background setup
    background_image = pygame.image.load(constants.WORLD).convert()
    bg_image_rect = background_image.get_rect()
    background_image = pygame.transform.scale(
        background_image,
        (int(bg_image_rect.width * constants.WORLD_MULTIPLIER),
         int(bg_image_rect.height * constants.WORLD_MULTIPLIER)))
    bg_image_rect = background_image.get_rect()  # after expanding

    # water splash
    WaterSplash = pygame.image.load(constants.WATER_SPLASH).convert()
    ws_image_rect = WaterSplash.get_rect()

    # game name
    pygame.display.set_caption(constants.GAME_NAME)

    # player
    player = Player()

    # enemy
    enemy_sprite_list = pygame.sprite.Group()
    enemy = Enemy(int(random.randint(400, 800)), 50)

    # coins
    coin_sprite_list = pygame.sprite.Group()
    coin = Coin(int(random.randint(400, 800)), 50)
    coin_score = 0

    # wave
    wave_sprite_list = pygame.sprite.Group()
    wave = Wave(constants.GROUND_HEIGHT, constants.SCREEN_WIDTH)

    # complete sprite list group
    all_sprite_list = pygame.sprite.Group()
    all_sprite_list.add(player)  # add player
    #all_sprite_list.add(enemy)			# add enemy

    # is done constant
    done = False

    # clock
    clock = pygame.time.Clock()

    # camera
    camera_x = 0
    camera_y = 0
    """
	move_x = -1 * constants.PLAYER_START_POS
	temp_x = 0
	L = constants.SCREEN_WIDTH / 2
	R = bg_image_rect.right - L
	"""
    # other constants
    prev_camera_x = camera_x

    # start times
    start_time_bomb = time.time()
    start_time_coin = time.time()
    start_time_wave = time.time()

    # -- Main Program Loop --
    while not done:

        # events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if done:
                break

            # till key is pressed
            if event.type == pygame.KEYDOWN:
                #if event.key == pygame.K_LEFT:
                #	player.MoveLeft()
                if event.key == pygame.K_RIGHT:
                    player.MoveRight()
                if event.key == pygame.K_UP:
                    player.jump()

            # if key is taken
            if event.type == pygame.KEYUP:
                #if event.key == pygame.K_LEFT and player.change_x < 0:
                #	player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # calculating player state
        if player.change_x > 0:
            player.state = 'r'
        elif player.change_x < 0:
            player.state = 'l'
        else:
            player.state = 's'

        # infinite scrolling window created
        if abs(camera_x) > constants.SCREEN_WIDTH / 2:  # end of viewport
            player.end_of_viewport = 0
            rel_x = (camera_x +
                     (constants.SCREEN_WIDTH / 2)) % bg_image_rect.width
            screen.blit(background_image,
                        [rel_x - bg_image_rect.width, camera_y])
            if rel_x < constants.SCREEN_WIDTH:
                screen.blit(background_image, [rel_x, camera_y])
            if player.sstop == 0:  # if screen moves
                camera_x += -1 * player.change_x
        else:
            player.end_of_viewport = 1
            screen.blit(background_image, [0, camera_y])
            if player.sstop == 0:  # if screen moves
                camera_x += -1 * player.change_x

        if abs(camera_x) > 0:  # game starts
            # for bombs
            if time.time() - start_time_bomb >= 6.5:
                start_time_bomb = time.time()
                rn = int(random.randint(300, 800))
                enemy = Enemy(rn, 50)
                enemy_sprite_list.add(enemy)

            # for coins
            if time.time() - start_time_coin >= 2.0:
                start_time_coin = time.time()
                rn = int(random.randint(400, 800))
                coin = Coin(rn, 350)
                coin_sprite_list.add(coin)

            # for waves
            if time.time() - start_time_wave >= 5.0:
                start_time_wave = time.time()
                wave = Wave(constants.SCREEN_WIDTH,
                            constants.GROUND_HEIGHT - 65)
                wave_sprite_list.add(wave)

        # update every sprite list
        all_sprite_list.update()
        enemy_sprite_list.update(player.state, player.end_of_viewport,
                                 player.sstop)
        coin_sprite_list.update(player.state, player.end_of_viewport,
                                player.sstop)
        wave_sprite_list.update(player.state, player.end_of_viewport,
                                player.sstop)

        # if bombs off screen - remove
        for enemies in enemy_sprite_list:
            if enemies.rect.y > constants.SCREEN_HEIGHT:
                enemy_sprite_list.remove(enemies)

        # if coins off screen - remove
        for coins in coin_sprite_list:
            if coins.rect.x < 0:
                coin_sprite_list.remove(coins)

        # if waves of screen remove
        for waves in wave_sprite_list:
            if waves.rect.x < 0:
                wave_sprite_list.remove(waves)

        # bombs and player collision detection
        if len(enemy_sprite_list) > 0:
            bullet_hit_list = pygame.sprite.spritecollide(
                player, enemy_sprite_list, True)
            if len(bullet_hit_list) > 0:
                break

        # coins and player collision
        if len(coin_sprite_list) > 0:
            coin_hit_list = pygame.sprite.spritecollide(
                player, coin_sprite_list, True)
            coin_score += len(coin_hit_list)

        # waves and player collsion
        if len(wave_sprite_list) > 0:
            wave_hit_list = pygame.sprite.spritecollide(
                player, wave_sprite_list, False)
            if len(wave_hit_list) > 0:
                break

        # FILL SCREEN
        # blit score
        distance = font.render("Distance = " + str(abs(camera_x) / 10), True,
                               constants.RED, None)
        stars = font.render("Stars = " + str(coin_score), True, constants.RED,
                            None)
        screen.blit(distance, [0, 0])
        screen.blit(stars, [0, 20])

        # blit water splash if and only if he is steady and moving
        if player.pos_state == 's' and player.change_x > 0:
            ws_image_rect.right = player.rect.left - (player.rect.width / 2)
            ws_image_rect.bottom = player.rect.bottom - (player.rect.height /
                                                         2)
            screen.blit(WaterSplash,
                        [ws_image_rect.right, ws_image_rect.bottom])

        # draw everthing
        all_sprite_list.draw(screen)
        player.block_sprite_list.draw(screen)
        enemy_sprite_list.draw(screen)
        coin_sprite_list.draw(screen)
        wave_sprite_list.draw(screen)

        # fps
        clock.tick(60)

        # update screen
        pygame.display.flip()

    # exit pygame
    pygame.quit()
Example #7
0
     #calculation of wind direction and speed
     print ('Calculating wind layers')
     wi = WIND(dataset = wind_ds, output = wind_ds, drop_var_output = True, inter_layer = wind_extra_layers)
     wi.get_direction_matrix()
     wi.get_speed_matrix()
     result = wi.return_ds(wi.out)
 else:
     #just prepare canvas
     gen_amp = WIND(dataset=amp, output=None)
     canvas = gen_amp.drop_var(gen_amp.ds, list(gen_amp.ds.data_vars))
     result = gen_amp.return_ds(canvas)
     
 if wav and sla:   
     #merging sigma and slant 10x10 products
     print ('Calculating wave layers')
     gen_wav = Wave(dataset=wav, output=None)
     gen_sla = Wave(dataset=sla, output=None)
     wave_ds = gen_wav.merge_datasets([gen_wav.ds, gen_sla.ds])
     
     #calculating wave parameters
     wa = Wave(dataset = wave_ds, output = result, inter_layer = wave_extra_layers)
     wa.get_wave_arrays()
     result = wa.return_ds(wa.out)
 
 if obj:
     #calculating objects
     print ('Calculating object layers')
     ob = Object(dataset = obj, output = result, inter_layer = object_extra_layers)
     ob.get_objects_array()
     result = ob.return_ds(ob.out)
 
Example #8
0
    def prepare_run(self):
        self.logger.info(
            '----------------------------------------------------------')
        self.logger.info('\tRunning: %s' % (self.exe_dirs))
        self.logger.info('\ttemplate: %s' % (self.param_tmp))
        self.logger.info('\trootdir: %s' % (self.rootdir))
        self.logger.info(
            '----------------------------------------------------------')
        self._set_environment()

        #----------------------- Load horizontal grid objects ----------
        self.logger.info('\tReading: %s' % (self.hfile))
        self.hgrid = HorizontalGrid(self.hfile,
                                    format='gr3',
                                    epsg=self.epsg,
                                    logger=self.logger)
        self.hgrid.copy_to_root(self.rootdir)

        #----------------------- Load vertical grid objects ----------
        vgrid_reader = VerticalGrid(logger=self.logger)
        if 'vfile' not in self.vgrid_config:
            self.vgrid_config['vfile'] = join(self.rootdir, 'vgrid.in')

        if not os.path.isfile(self.vgrid_config['vfile']):
            self.logger.info('\tCreating: %s' % (self.vgrid_config['vfile']))
            vgrid_reader.write(**self.vgrid_config)

        self.vgrid = vgrid_reader.load(self.vgrid_config['vfile'])

        lat0 = sum(self.hgrid.latitude) / len(self.hgrid.latitude)
        self.logger.info('\tModel starts: %s' % (self.timing["time start"]))
        self.logger.info('\tModel ends: %s' % (self.timing["time end"]))
        if isinstance(self.timing["time start"], str):
            t0 = dateutil.parser.parse(self.timing["time start"])
        else:
            t0 = self.timing["time start"]
        if isinstance(self.timing["time end"], str):
            t1 = dateutil.parser.parse(self.timing["time end"])
        else:
            t1 = self.timing["time end"]

        #  #----------------------- Download Initial and Boundary fields ----------
        if self.input_files != None:
            dwnl = download_data(t0, t1, logger=self.logger)
            for file in self.input_files.keys():
                dwnl.get_input_data(self.input_files[file])

            self.logger.info(
                '----------------------------------------------------------')
            #----------------------- Write command file (param.in) ------------------
        cfg = ModelConfig(hydro=self.hydro_config,
                          t0=t0,
                          t1=t1,
                          logger=self.logger)
        cfg.make_config(self.param_tmp, join(self.rootdir, 'param.nml'),
                        'hydro')

        # #----------------------- Set Boundary Conditions (bctides.in) -----------
        # # Store boundary arrays in each obc bctype object (Ex: self.obc['btype']['7']['iettype'])
        #t0+(t1-t0)/2 mid run ????
        if not os.path.isfile(join(self.rootdir, 'bctides.in')):
            bcinput = BCinputs(obc=self.obc,
                               hgrid=self.hgrid,
                               lat0=lat0,
                               t0=t0,
                               t0ref=t0 + (t1 - t0) / 2,
                               logger=self.logger)
            bcinput.make_bctides(join(self.rootdir, 'bctides.in'))

    #  # ------------------- Create Ocean boundary forcing -----------------
        if self.forcings:
            for key in self.forcings.keys():
                if not os.path.isfile(join(self.rootdir, key)):
                    Obf = OpenBoundaries(obc=self.forcings[key],
                                         hgrid=self.hgrid,
                                         vgrid=self.vgrid,
                                         t0=t0,
                                         t1=t1,
                                         logger=self.logger)
                    if 'tidal' in self.forcings[key]:
                        Obf.add_tide(self.forcings[key]['tidal'])

                    if 'residual' in self.forcings[key]:
                        Obf.add_res(self.forcings[key]['residual'])

                    Obf.make_boundary(join(self.rootdir, key),
                                      self.forcings[key].get('dt', 3600))

    #  # ------------------- Create Oceanic initial conditions ---------------------
        if self.ic:
            for key in self.ic:
                filename = os.path.join(self.rootdir, key)
                if not os.path.isfile(filename):
                    ic = InitialConditions(filename,hgrid=self.hgrid,t0=t0,value=self.ic[key].get('value',None),\
                     ncfile=self.ic[key].get('filename',None),\
                     var=self.ic[key].get('var',None),\
                     shapefile=self.ic[key].get('shapefile',None),
                     strength=self.ic[key].get('strength',None),
                     bnd=self.ic[key].get('bnd',None),
                     distance=self.ic[key].get('distance',None),
                     logger=self.logger)

    # #------------------------- Check/Prepare for hotstart --------------------
        if self.hotstart and not os.path.isfile(
                os.path.join(self.rootdir, 'hotstart.nc')):
            hot = HotStart(os.path.join(self.rootdir, 'hotstart.nc'),
                           config=self.hotstart,
                           hgrid=self.hgrid,
                           vgrid=self.vgrid,
                           t0=t0,
                           logger=self.logger)
            hot.set_hotstart()

        # ------------------- Create Atmospheric forcing --------------------
        if self.meteo and not os.path.isfile(
                os.path.join(self.rootdir, 'sflux', 'sflux_inputs.txt')):

            atm = Meteo(os.path.join(self.rootdir, 'sflux'),
                        t0=t0,
                        t1=t1,
                        dt=self.meteo.pop('dt'),
                        logger=self.logger)
            for key in range(1, len(self.meteo.keys()) + 1):
                filename = self.meteo[key].pop('filename')
                atm.add_dataset(filename, self.meteo[key])

            atm.make_meteo()

        if self.meteo and not os.path.isfile(
                os.path.join(self.rootdir, 'windrot_geo2proj.gr3')):
            ## Create the GR3 files
            filename = os.path.join(self.rootdir, 'windrot_geo2proj.gr3')
            ic = InitialConditions(filename,hgrid=self.hgrid,t0=t0,value=get_convergence(self.hgrid.latitude,self.hgrid.longitude,self.epsg),\
              logger=self.logger)

        if self.stations and not os.path.isfile(
                os.path.join(self.rootdir, 'station.in')):
            outputs = self.stations.pop('outputs')
            st = Station(os.path.join(self.rootdir, 'station.in'),
                         self.hgrid,
                         outputs,
                         logger=self.logger)
            for key in self.stations:
                st.add_station(self.stations[key], name=key)

            st.write_station()

        # ------------------- Create Wave boundary forcing -----------------
        if self.wave:

            h0 = cfg.config['hydro']['h0']
            deltc = cfg.config['hydro']['dt'] * cfg.config['hydro']['nstep_wwm']

            wave = Wave(root=self.rootdir,
                        hgrid=self.hgrid,
                        wwm=self.wave['config'],
                        t0=t0,
                        t1=t1,
                        deltc=deltc,
                        h0=h0,
                        logger=self.logger)
            wave.make_wave(self.wave_tmp,
                           os.path.join(self.rootdir, 'wwminput.nml'))
            wave.make_forcing(self.wave['config'].get('FILEWAVE',
                                                      'bndfiles.dat'),
                              ww3=self.wave.get('ww3', None))

        self.logger.info('FINISHED')