当前位置: 首页>>代码示例>>Python>>正文


Python Timer.reset方法代码示例

本文整理汇总了Python中timer.Timer.reset方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.reset方法的具体用法?Python Timer.reset怎么用?Python Timer.reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在timer.Timer的用法示例。


在下文中一共展示了Timer.reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TimerTest

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
class TimerTest(unittest.TestCase):

    def setUp(self):
        self.timer=Timer(1)

    def test_parse_timer(self):
        timer = Timer('''interval: 10
                         event: test_timer_event''')

        self.assertEqual(timer.period, 10)
        self.assertEqual(timer.event, 'test_timer_event')

    def test_timer_poll(self):
        reset_time = self.timer.reset()
        while time() < reset_time + 1 - 0.05:
            self.assertEqual(self.timer.poll(), None)
        count = 0
        while time() < reset_time + 1 + 0.05:
            poll = self.timer.poll()
            if not poll == None:
                if round(poll) == 0:
                    count = count + 1
            sleep(0.01)
        self.assertEqual(count,1)

    def test_timer_poll_count(self):
        reset_time = self.timer.reset()
        count = 0
        while(time() < reset_time + 3.1):
            if self.timer.poll() != None:
                count = count + 1
            sleep(0.05)
        self.assertEqual(count,3)
开发者ID:sonologic,项目名称:thermo2,代码行数:35,代码来源:test_timer.py

示例2: run

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
	def run(self, dt): 
		"""Initialized Pywi and enters the mainloop.
			
		stepCallback - This callback is called until the gameTime is bigger or equal to the real time.
		dt - The time gameTime is incremented by in very simulation step
		title - The window title
		xres - The width of the window in pixels
		yres - The height of the window in piyels
		fullscreen - If the window created should be fullscreen (boolean)
		vsync - If vsync should be enabled (boolean)
		"""
		
		mainLoopTimer = Timer()
		fpsTimer = Timer()
		
		#bench = Timer()
		#stepcount = 0
		#stepcum = 0
	
		#framecount = 0
		#framecum = 0
		
		fpsRendered = 0
		while not self._closeIssued:
			while not self._closeIssued and self.gameTime < mainLoopTimer.total():
				#bench.reset()
				#print mainLoopTimer.total(),"-",self.gameTime,"=",mainLoopTimer.total()-self.gameTime
				self._window.dispatch_events()
				for obj in self.updateObjects:
					obj.update()
				
				self.step()
				self.gameTime += dt
				#d = bench.delta()
				#stepcount += 1
				#stepcum += d
				#print "STEP current:", d
				#print "STEP Avrg time:", float(stepcum)/stepcount
			
			fpsRendered += 1
			#bench.reset()
			self.prepareFrame()
			self._updateFrame()
			#d = bench.delta()
			#framecount += 1
			#framecum += d
			#print "FRAME current:", d
			#print "FRAME Avrg time:", float(framecum)/framecount
			
			if fpsTimer.total() > 1.0:
				self._window.set_caption( self._title + " - FPS: " + str(fpsRendered) )
				fpsRendered = 0
				fpsTimer.reset()
			
			
		#print "STEP COUNT: %d" % stepcount
		#print "FRAME COUNT: %d" % framecount
		
		self._terminate()
		self.terminate() # Should be overload
开发者ID:pfirsich,项目名称:Pywi,代码行数:62,代码来源:core.py

示例3: test_reset_reestablishes_original_exercise_list

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
 def test_reset_reestablishes_original_exercise_list(self):
     timer = Timer(exercises=['Push Ups', 'Burpees', 'Pull Ups'], break_time=10, time_limit=60)
     original_exercises = timer.exercises
     timer.get_current_exercises()
     timer.get_current_exercises()
     timer.get_current_exercises()
     timer.get_current_exercises()
     timer.reset()
     self.assertEqual(original_exercises, timer.exercises)
开发者ID:voidnologo,项目名称:6-3-interview,代码行数:11,代码来源:tests.py

示例4: ProjectileCreator

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
class ProjectileCreator(Aspect):
    """This aspect allows an entity to create projectiles that are owned by them.
    This class also is responsible for updating all projectiles it owns."""

    def init(self):
        self.projectiles = set()
        self.cooled_down = True
        self.cooldown_timer = Timer(0)  #Timer will always fire

    def tick(self, dtime):
        """Update projectile positions and cooldown timer."""
        to_remove = []
        for projectile in self.projectiles:
            # Check if the projectile is floating away forever
            if projectile.death_timer.check(dtime, reset=False):
                to_remove.append(projectile)
                continue
            projectile.position = projectile.motion_state.position
        # Must be removed separately since items can't be removed from a set during iteration.
        for projectile in to_remove:
            self.projectiles.remove(projectile)
            projectile.destroy()
        self.cooled_down = self.cooldown_timer.check(dtime)

    def set_projectile(self, projectile_type):
        self.projectile_type = projectile_type
        self.cooldown_timer = Timer(projectile_type.cooldown, randomize=False, fireFirstCheck=True)

    def create(self):
        """Spawn a new projectile."""
        if self.cooled_down:
            position = self.entity.position
            handle = self.engine.entity_manager.create_handle()
            projectile = self.engine.entity_manager.create_entity(handle, self.projectile_type, position=position)
            body = self.engine.physics_system.register_entity(projectile, 1, PlayerMotionState)
            direction = self.entity.motion_state.orientation * (0, 0, -1)
            body.setLinearVelocity(vector.ogre2bullet_vector(direction * projectile.speed))
            self.projectiles.add(projectile)
            projectile.start_death_timer()
            self.cooldown_timer.reset()

    def attach_controls(self):
        self.engine.input_system.register_handler(InputEvent.KEY_DOWN, OIS.KC_X, self.create)
开发者ID:kyphelps,项目名称:pynecraft,代码行数:45,代码来源:projectile_creator.py

示例5: FSM

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
class FSM(object):

    protocol = None
    state = False

    def __init__(self, factory=None, protocol=None):

        self.factory = factory
        self.protocl = protocol
        self.state = False
        self.connect_retry_time = CONNECT_RETRY_TIME
        self.connect_retry_timer = Timer(self.connect_retry_event)

    def __setattr__(self, name, value):

        if name == 'state' and value != getattr(self, name):
            LOG.info("State is now:%s" % value)

        super(FSM, self).__setattr__(name, value)

    def automatic_start(self):
        """
        automatic start
        """
        LOG.debug('automatic start')
        self.connect_retry_timer.reset(self.connect_retry_time)
        return True

    def connect_retry_event(self):

        """
        connect retry
        """
        LOG.debug('connect retry')
        self.connect_retry_timer.reset(self.connect_retry_time)
        if self.factory:
            self.factory.connect_retry()

    def keep_alive_time_event(self):
        pass

    def connection_made(self):

        self.connect_retry_timer.cancel()
        self.state = True

    def connection_failed(self):

        self.connect_retry_timer.reset(self.connect_retry_time)
        self.state = False
开发者ID:xiaopeng163,项目名称:twisted-fsm,代码行数:52,代码来源:fsm.py

示例6: __init__

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
class Ship:
    def __init__(self, x=50, y=50):
        self.pos = Vector(x, y);
        self.speed = Vector();
        self.accel = Vector();
        self.angle = 0;
        self.tmpAngle = 0;
        self.canShoot = 1;
        self.shootLimiter = Timer(2);
        self.keyb = 1;

        self.keys = {
            "up":0,
            "down":0,
            "left":0,
            "right":0,
            "shoot":0
            };
        self.mouse = Vector(0,0);
        self.mShoot = 0;
        
        self.accel.x = 1;
        self.points = (
            Vector(0,-10),
            Vector(0,10),
            Vector(30,0)
            );

    def update(self, shoot_function, index):
        if self.canShoot:
            self.shootLimiter.reset();
        else:
            self.canShoot = self.shootLimiter.update();
        if self.keyb:
            if self.keys["up"]:       self.accel.y = -0.5;
            elif self.keys["down"]:   self.accel.y = 0.5;
            else:
                self.accel.y = 0;
                self.speed.y *= 0.98;
            if self.keys["left"]:     self.accel.x = -0.5;
            elif self.keys["right"]:  self.accel.x = 0.5;
            else:
                self.accel.x = 0;
                self.speed.x *= 0.98;
            if self.keys["shoot"] and self.canShoot:
                self.canShoot = 0;
                self.shootLimiter.reset();
                shoot_function(index);
        else:
            if self.accel.hyp() < 1: self.accel = Vector(0,1);
            self.accel.rot_to(self.mouse.minus(self.pos).angle());
            if self.mshoot and self.canShoot:
                self.canShoot = 0;
                self.shootLimiter.reset();
                shoot_function(index);

        if not self.accel.isNull(): self.angle = self.accel.angle();
        self.speed.add(self.accel);
        if not self.speed.isNull():
            hyp = self.speed.hyp();
            if hyp > 10:
                self.speed.set_length(10);
            
        self.pos.add(self.speed);
        bounce = self.pos.moveWithinBounds(Vector(800, 600));
        if bounce:
            if bounce   == 1: self.speed.x = -self.speed.x;
            elif bounce == 2: self.speed.y = -self.speed.y;

    def hit(self):
        pass;

    def set_keys(self, up, down, left, right, shoot):
        self.keyb = 1;
        self.keys["up"] = up;
        self.keys["down"] = down;
        self.keys["left"] = left;
        self.keys["right"] = right;
        self.keys["shoot"] = shoot;

    def set_mouse(self, mpos, mshoot):
        self.keyb = 0;
        self.mouse.x = mpos[0];
        self.mouse.y = mpos[1];
        self.mshoot = mshoot;
    
    def net_data(self):
        # [0] = ( posX, posY )
        # [1] = ( speedX, speedY )
        # [2] = angle
        # ( ( posX, posY ), ( speedX, speedY ), angle )
        return (self.pos.get(1), self.speed.get(1), int(self.angle * 100));

    @staticmethod
    def collide(ships, shots, explosions=0):
        for i in ships:
            for shot in shots:
                if ships[i].pos.dist_to(shot.pos) < 10:
                    ships[i].hit();

#.........这里部分代码省略.........
开发者ID:strykejern,项目名称:strykejern-pythonGame,代码行数:103,代码来源:ship.py

示例7: Cursor

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
class Cursor(object):
    def __init__(self, screen, rad):
        self.init_base_vars(screen, rad)
        self.init_custom_vars()
        self.init_game_logic()

    def init_base_vars(self, screen, rad):
        self.RAD = rad
        self.OUTLINE_THK = 5
        self.BASE_COLOR = 240,240,140
        self.OUTLINE_COLOR = 20,20,20
        self.pos = np.array([0,0])
        self.screen = screen
        self.color = self.BASE_COLOR
        self.screen_mid = np.array([0.5*self.screen.get_width(),
                                    0.5*self.screen.get_height()])
        self.pos_lims = ((self.screen_mid[0]-self.screen_mid[0]+self.RAD
                          +self.OUTLINE_THK),
                         (self.screen_mid[0]+self.screen_mid[0]-self.RAD
                          -self.OUTLINE_THK),
                         self.RAD+self.OUTLINE_THK,
                         2*self.screen_mid[1]-self.RAD-self.OUTLINE_THK)

    def init_custom_vars(self):
        self.WARN_COLOR = 240,140,140
        self.WARN_TIME = .3
        self.warn_timer = Timer(self.WARN_TIME)
        self.warn_bool = False

    def init_game_logic(self):
        self.has_left = False
        self.start_ready = False
        self.in_start = False

    def update(self, new_pos): 
        self.pos[:] = new_pos[0], new_pos[1]
        self.trap()

    def update_warn(self, time_passed, target_status):
        if target_status:
            self.warn_bool = True
        if self.warn_bool:
            self.color = self.WARN_COLOR
            self.warn_timer.update(time_passed)
            if self.warn_timer.time_limit_hit:
                self.warn_timer.reset()
                self.warn_bool = False
                self.color = self.BASE_COLOR

    def trap(self):
        if self.pos[0] < self.pos_lims[0]:
            self.pos[0] = self.pos_lims[0]
        elif self.pos[0] > self.pos_lims[1]:
            self.pos[0] = self.pos_lims[1]
        if self.pos[1] < self.pos_lims[2]:
            self.pos[1] = self.pos_lims[2]
        elif self.pos[1] > self.pos_lims[3]:
            self.pos[1] = self.pos_lims[3]

    def check_within_dist(self, pos, dist):
        if (np.sqrt((self.pos[0]-pos[0])**2
                   +(self.pos[1]-pos[1])**2)
                < (dist)):
            return True
        else:
            return False


    def draw(self): 
        for idx in range(self.OUTLINE_THK):
            pygame.gfxdraw.aacircle(self.screen,
                                self.pos[0],
                                self.pos[1],
                                self.RAD+idx,
                                self.color)
            pygame.gfxdraw.aacircle(self.screen,
                                self.pos[0]+1,
                                self.pos[1],
                                self.RAD+idx,
                                self.color)
            pygame.gfxdraw.aacircle(self.screen,
                                self.pos[0],
                                self.pos[1]+1,
                                self.RAD+idx,
                                self.color)
开发者ID:efunn,项目名称:hemo-control,代码行数:87,代码来源:cursor.py

示例8: Mees

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]

#.........这里部分代码省略.........
            bullet.update_logic()

        if(self.speedTimer.end == True and self.saiJuurde != 0):
            self.speed -= self.saiJuurde
            self.saiJuurde = 0
            
    def show(self, scr):
        if(self.saiJuurde != 0):
            scr.blit(self.imageDisco,self.rect.get())
        else:
            scr.blit(self.image,self.rect.get())

        for bullet in self.bullets: # joonistame koik kuulid
            bullet.show(scr)
        if (self.dead == 1):
            scr.blit(self.image2,self.image2Rect)

    def switchWeapon(self,slot): # vahetab relva
        try:
            self.relv = self.relvakogu[slot]
        except Exception as e:
            print (e)
            return

    def drinkPotion(self,slot): # juuakse potti
        try:
            if(self.speed != 0): # kui pole surnud
                pot = self.potid[self.potikogu[slot]]
                if "heals" in pot:
                    self.lives += pot["heals"]
                if "speed" in pot:
                    self.saiJuurde = pot["speed"]
                    self.speed += self.saiJuurde
                    self.speedTimer.reset_n(pot["time"])
                    self.speedTimer.reset()
                    self.speedTimer.run()
            del self.potikogu[slot]
        except Exception as e:
            print (e)
            return

    def shoot(self,start,end,mouseButton):
        if(self.relvad[self.relv]["kokku"] <= 0 and self.relvad[self.relv]["bullets"] <= 0 and self.relvad[self.relv]["kokku"] != -1): # pole kuule?
            return

        temp = Bullet(start[0],start[1],end[0],end[1],self.relvad[self.relv])
        self.chan.queue(self.saund) 
        if(self.relv == "pump"): # 2 kuuli lisaks
            temp2 = Bullet(start[0],start[1],end[0]-50,end[1]-50,self.relvad[self.relv])
            temp3 = Bullet(start[0],start[1],end[0]+50,end[1]+50,self.relvad[self.relv])
            self.bullets.append(temp2)
            self.bullets.append(temp3)
        self.bullets.append(temp)
        self.relvad[self.relv]["bullets"] -= 1 # laseb yhe kuuli valja

        if(self.relvad[self.relv]["bullets"] <= 0):
            if(self.relvad[self.relv]["kokku"] > 0): #vaatame kas varupidemes
                if(self.relvad[self.relv]["kokku"] <= self.relvad[self.relv]["pide"]): # viimane pide
                    self.relvad[self.relv]["bullets"] += self.relvad[self.relv]["kokku"]
                    self.relvad[self.relv]["kokku"] = 0
                else:
                    self.relvad[self.relv]["bullets"] += self.relvad[self.relv]["pide"]
                    self.relvad[self.relv]["kokku"] -= self.relvad[self.relv]["pide"]

    def automatic(self):
        """
开发者ID:Kaspar94,项目名称:SpaceKappaShooter,代码行数:70,代码来源:mees.py

示例9: PandaController

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
class PandaController (object):

    DEFAULT_FULLSCREEN = False
    DEFAULT_WIDTH = 800
    DEFAULT_HEIGHT = 600
    DEFAULT_FPS = 60
    DEFAULT_FRAME_METER = False
    DEFAULT_MUSIC_VOLUME = .3
    DEFAULT_SOUND_VOLUME = .1
    DEFAULT_MAX_DELTA = 1. / 20.
    DEFAULT_SHADERS = True
    
    def __init__ (self):
        super (PandaController, self).__init__ ()
        self._timer = Timer ()
        self._timer.max_delta = self.DEFAULT_MAX_DELTA
        self._tasks = task.TaskGroup ()
        self._tasks.add (self._panda_task)
        self._music = None
        self._mouse_task = None
        self._relative_mouse = False
        
    @property
    def timer (self):
        return self._timer

    @property
    def tasks (self):
        return self._tasks

    def start (self, title):
        cfg = GlobalConf ().child ('panda') 

        self.set_defaults (cfg)
        self.base = ShowBase ()
        self.base.disableMouse ()
        self.audio = self.base.sfxManagerList [0]
        self.audio3d = Audio3DManager (self.audio, camera)
        self.audio3d.setListenerVelocityAuto ()
        self.audio3d.setDropOffFactor (0.1) # HACK
        
        self.create_properties (title)
        self.update_properties (cfg)
        self.listen_conf (cfg)

        loadPrcFileData ("", "interpolate-frames 1")
        loadPrcFileData ("", "support-threads #f")
        path = getModelPath ()
        path.prependPath ('./data')
                
        self.base.enableParticles ()
        
    def loop (self):        
        self._timer.reset ()
        self._timer.loop (self._loop_fn)

    def _loop_fn (self, timer):
        task_count = 1               # _panda_task
        if self._relative_mouse:
            task_count += 1          # _mouse_task
        if self._tasks.count > task_count:
            return self._tasks.update (timer)
        return False
    
    def set_defaults (self, cfg):
        cfg.child ('fps').default (self.DEFAULT_FPS)
        cfg.child ('width').default (self.DEFAULT_WIDTH)
        cfg.child ('height').default (self.DEFAULT_HEIGHT)
        cfg.child ('fullscreen').default (self.DEFAULT_FULLSCREEN)
        cfg.child ('frame-meter').default (self.DEFAULT_FRAME_METER)
        cfg.child ('music-volume').default (self.DEFAULT_MUSIC_VOLUME)
        cfg.child ('sound-volume').default (self.DEFAULT_SOUND_VOLUME)
                
    def listen_conf (self, cfg):
        cfg.on_conf_nudge += self.update_properties
        
        cfg.child ('fps').on_conf_change += self.update_fps
        cfg.child ('frame-meter').on_conf_change += self.update_frame_meter
        cfg.child ('music-volume').on_conf_change += self.update_music_volume
        cfg.child ('sound-volume').on_conf_change += self.update_sound_volume

        self.audio.setVolume (cfg.child ('sound-volume').value)
    
    def create_properties (self, title):
        self._prop = WindowProperties ()
        self._prop.setTitle (title)
        
    def relative_mouse (self):
        if not self._relative_mouse:
            self._prop.setCursorHidden (True)
            self._prop.setMouseMode (WindowProperties.MRelative)
            self.base.win.requestProperties (self._prop)
            self._mouse_task = self._tasks.add (MouseTask ())
            self._mouse_task.on_mouse_move += lambda x, y: \
                messenger.send ('mouse-move', [(x, y)])
            self._relative_mouse = True
        
    def absolute_mouse (self):
        if self._relative_mouse:
            self._relative_mouse = False
#.........这里部分代码省略.........
开发者ID:arximboldi,项目名称:pigeoncide,代码行数:103,代码来源:panda_controller.py

示例10: Fortress

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
class Fortress(Token):
    """represents the fortress object that typically appears in the center of the worldsurf"""
    def __init__(self, app):
        super(Fortress, self).__init__()
        self.app = app
        self.position.x = self.app.world.centerx
        self.position.y = self.app.world.centery
        self.color = (255, 255, 0)
        self.collision_radius = self.app.config['Fortress']['fortress_radius'] * self.app.aspect_ratio
        self.last_orientation = self.orientation 
        self.timer = Timer(self.app.gametimer.elapsed)
        self.sector_size = self.app.config['Fortress']['fortress_sector_size']
        self.lock_time = self.app.config['Fortress']['fortress_lock_time']
        self.reset_timer = Timer(self.app.gametimer.elapsed)
        self.alive = True
        if self.app.config['Graphics']['fancy']:
            self.fortress = pygl2d.image.Image(pkg_resources.resource_stream("resources", 'gfx/psf5.png'))
            self.fortress_rect = self.fortress.get_rect()
            self.fortress.scale((72 * self.app.aspect_ratio) / 128)
  
    def compute(self):
        """determines orientation of fortress"""
        if self.app.ship.alive:
            self.orientation = self.to_target_orientation(self.app.ship) // self.sector_size * self.sector_size #integer division truncates
        if self.orientation != self.last_orientation:
            self.last_orientation = self.orientation
            self.timer.reset()
        if self.timer.elapsed() >= self.lock_time and self.app.ship.alive and self.app.fortress.alive:
            self.app.gameevents.add("fire", "fortress", "ship")
            self.fire()
            self.timer.reset()
        if not self.alive and self.reset_timer.elapsed() > 1000:
            self.alive = True
            
    def fire(self):
        self.app.snd_shell_fired.play()
        self.app.shell_list.append(shell.Shell(self.app, self.to_target_orientation(self.app.ship)))
        
    def draw(self):
        """draws fortress to worldsurf"""
        if self.app.config['Graphics']['fancy']:
            self.fortress.rotate(self.orientation - 90)
            self.fortress_rect.center = (self.position.x, self.position.y)
            self.fortress.draw(self.fortress_rect.topleft)
        else:
            #pygame.draw.circle(worldsurf, (0, 0, 0), (self.position.x, self.position.y), int(30 * self.app.aspect_ratio))
            sinphi = math.sin(math.radians((self.orientation) % 360))
            cosphi = math.cos(math.radians((self.orientation) % 360))
            x1 = 18 * cosphi * self.app.aspect_ratio + self.position.x
            y1 = -(18 * sinphi) * self.app.aspect_ratio + self.position.y
            x2 = 36 * cosphi * self.app.aspect_ratio + self.position.x
            y2 = -(36 * sinphi) * self.app.aspect_ratio + self.position.y
            x3 = (18 * cosphi - -18 * sinphi) * self.app.aspect_ratio + self.position.x
            y3 = (-(-18 * cosphi + 18 * sinphi)) * self.app.aspect_ratio + self.position.y
            x4 = -(-18 * sinphi) * self.app.aspect_ratio + self.position.x
            y4 = -(-18 * cosphi) * self.app.aspect_ratio + self.position.y
            x5 = (18 * cosphi - 18 * sinphi) * self.app.aspect_ratio + self.position.x
            y5 = (-(18 * cosphi + 18 * sinphi)) * self.app.aspect_ratio + self.position.y
            x6 = -(18 * sinphi) * self.app.aspect_ratio + self.position.x
            y6 = -(18 * cosphi) * self.app.aspect_ratio + self.position.y
            pygl2d.draw.line((x1, y1), (x2, y2), self.color, self.app.linewidth)
            pygl2d.draw.line((x3, y3), (x5, y5), self.color, self.app.linewidth)
            pygl2d.draw.line((x3, y3), (x4, y4), self.color, self.app.linewidth)
            pygl2d.draw.line((x5, y5), (x6, y6), self.color, self.app.linewidth)
开发者ID:CogWorks,项目名称:SpaceFortress,代码行数:66,代码来源:fortress.py

示例11: test_reset_set_number_for_next_set

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
 def test_reset_set_number_for_next_set(self):
     timer = Timer(exercises=['Push Ups', 'Burpees', 'Pull Ups'], break_time=10, time_limit=60)
     before_reset_set = timer.set_number
     timer.reset()
     self.assertEqual(timer.set_number, before_reset_set + 1)
开发者ID:voidnologo,项目名称:6-3-interview,代码行数:7,代码来源:tests.py

示例12: test_reset_cycle_for_next_set

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
 def test_reset_cycle_for_next_set(self):
     timer = Timer(exercises=['Push Ups', 'Burpees', 'Pull Ups'], break_time=10, time_limit=60)
     timer.reset()
     self.assertEqual(timer.current_cycle, -1)
开发者ID:voidnologo,项目名称:6-3-interview,代码行数:6,代码来源:tests.py

示例13: ParticleFilter

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
                                  self.vel_uniform_dist)
            d_theta = ang_vel / self.odom_rate
            d_x = (lin_vel * math.cos(self.avg_theta))/self.odom_rate
            d_y = (lin_vel * math.sin(self.avg_theta))/self.odom_rate
            self.avg_x += d_x
            self.avg_y += d_y
            self.avg_theta += d_theta


if __name__ == "__main__":
    rospy.init_node("particle_filter")

    start = rospy.get_param("/robot_start", [-64.0, 0.0, 0.0])
    x, y, t = start[0], start[1], start[2]

    scan_topic = "noisy_base_scan"
    pf = ParticleFilter(odom_rate=20.0, sens_median=0.0, sens_std_dev=0.1, vel_uniform_dist=0.1,
                        num_particles=400, base_scan=scan_topic, start_pos=start, debug=True)

    # rospy.sleep(10.0)
    rate = rospy.Rate(1)
    t = Timer("Particle filter")
    try:
        while not rospy.is_shutdown():
            t.reset()
            pf.run()
            t.print_delta()
            rate.sleep()
    except KeyboardInterrupt:
        pass
开发者ID:thisisG,项目名称:laserbot-ROS,代码行数:32,代码来源:particle_filter.py

示例14: Bonus

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]

#.........这里部分代码省略.........
        elif self.app.config['General']['bonus_location'] == 'Probabilistic':
            w = self.app.world.width / 5
            h = self.app.world.height / 5
            probs = map(float, self.app.config['Bonus']['quadrant_probs'].split(','))
            r
            if r <= probs[0]:
                self.position.x = self.app.world.left + w
                self.position.y = self.app.world.top + h
            elif r <= probs[1]:
                self.position.x = self.app.world.left + w * 4
                self.position.y = self.app.world.top + h
            elif r <= probs[2]:
                self.position.x = self.app.world.left + w
                self.position.y = self.app.world.top + h * 4
            else:
                self.position.x = self.app.world.left + w * 4
                self.position.y = self.app.world.top + h * 4
        else:
            self.position.x = self.app.config['Bonus']['bonus_pos_x'] * self.app.aspect_ratio
            self.position.y = self.app.config['Bonus']['bonus_pos_y'] * self.app.aspect_ratio
        
    def draw(self):
        """draws bonus symbol to screen"""
        bonus = pygl2d.font.RenderText("%s" % self.current_symbol, (255, 200, 0), self.font)
        bonus_rect = bonus.get_rect()
        bonus_rect.center = (self.position.x, self.position.y)
        bonus.draw(bonus_rect.topleft)
    
    def get_new_symbol(self):
        """assigns new bonus symbol"""
        self.prior_symbol = self.current_symbol
        if random.random() < self.probability:
            self.current_symbol = self.bonus_symbol
        else:
            self.current_symbol = random.sample(self.symbols, 1)[0]
            self.flag = True
        self.set_bonus_location()
        self.bonus_count += 1
            
    def pick_next_pair(self):
        """picks next cue and target for ax-cpt task"""
        chance = random.random()
        if chance < self.ax_prob:
            self.current_pair = "ax"
            return([random.choice(self.a_symbols), random.choice(self.x_symbols)])
        elif chance < (self.ax_prob + self.ay_prob):
            self.current_pair = "ay"
            return([random.choice(self.a_symbols), random.choice(self.y_symbols)])
        elif chance < (self.ax_prob + self.ay_prob + self.bx_prob):
            self.current_pair = "bx"
            return([random.choice(self.b_symbols), random.choice(self.x_symbols)])
        else: 
            self.current_pair = "by"
            return([random.choice(self.b_symbols), random.choice(self.y_symbols)])
            
    def axcpt_update(self):
        """check what to do with ax-cpt task based on state and timer"""
        if self.state == "iti" and self.timer.elapsed() > self.iti_time: #time for a new pair, make cue visible
            self.timer.reset()
            self.state = "cue"
            self.app.bonus_captured = False
            self.current_symbols = self.pick_next_pair()
            # idk if this is the best place for this ~rmh
            self.set_bonus_location()
            self.axcpt_flag = True
            self.current_symbol = self.current_symbols[0]
            self.visible = True
            if self.current_symbol in self.a_symbols:
                self.app.gameevents.add("bonus", "cue_appears", "correct")
            else:
                self.app.gameevents.add("bonus", "cue_appears", "incorrect")
        elif self.state == "cue" and self.timer.elapsed() > self.cue_time: #make cue disappear
            self.timer.reset()
            self.state = "isi"
            self.visible = False
            self.app.gameevents.add("bonus", "cue_disappears")
            self.prior_symbol = self.current_symbol
        elif self.state == "isi" and self.timer.elapsed() > self.isi_time: #make target appear
            self.bonus_count += 1
            self.timer.reset()
            if self.isi_time == 800:
                self.isi_time = 4000
            else:
                self.isi_time = 800
            self.state = "target"
            self.app.bonus_captured = False
            self.current_symbol = self.current_symbols[1]
            self.visible = True
            if self.current_symbol in self.x_symbols:
                self.app.gameevents.add("bonus", "target_appears", "correct")
            else:
                self.app.gameevents.add("bonus", "target_appears", "incorrect")
            if self.current_pair == "ax":
                self.app.gameevents.add("bonus_available")
        elif self.state == "target" and self.timer.elapsed() > self.target_time: #make target disappear
            self.timer.reset()
            self.state = "iti"
            self.visible = False
            self.app.gameevents.add("bonus", "target_disappears")
            self.prior_symbol = self.current_symbol
开发者ID:CogWorks,项目名称:SpaceFortress,代码行数:104,代码来源:bonus.py

示例15: Timer

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import reset [as 别名]
from timer import Timer


print """
   Exercises: "push ups", "burpees", "pull ups", "up downs"
   Time Limit: 60
   Break Time: 10
   Sets: 2
"""

timer = Timer(exercises=['Push Ups', 'Burpees', 'Pull Ups', 'Up Downs'], break_time=3, time_limit=5)
num_of_sets = 2


while (timer.set_number <= num_of_sets):
   print ("\nBREAK! Up Next:")
   current_exercises = timer.get_current_exercises()
   print ("Person 1: " + current_exercises[0])
   print ("Person 2: " + current_exercises[1])
   timer.wait(timer.break_time)
   print ("\n**START")
   print ("\tPerson 1: " + current_exercises[0])
   print ("\tPerson 2: " + current_exercises[1])
   timer.wait(timer.time_limit)
   if timer.end_of_set():
      print ("\n\n*** END OF SET : " + str(timer.set_number) + " ***\n\n")
      timer.reset()
开发者ID:voidnologo,项目名称:6-3-interview,代码行数:29,代码来源:exerciseProgram.py


注:本文中的timer.Timer.reset方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。