pygame.time.get_ticks

Here are the examples of the python api pygame.time.get_ticks taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

43 Examples 7

Example 1

Project: RxPY Source File: pygamescheduler.py
Function: now
    @property
    def now(self):
        """Represents a notion of time for this scheduler. Tasks being scheduled
        on a scheduler will adhere to the time denoted by this property."""

        return self.to_datetime(pygame.time.get_ticks())

Example 2

Project: MonitorDarkly Source File: cnc_display.py
def display_packet(packet, screen):
    screen.fill((255, 255, 255))

    # display the pixel for as many frames it takes to read it
    start = pg.time.get_ticks()
    blue = 0
    for bytes in group(8, map(ord, packet), fillvalue=255):
        screen.set_at((675, 641), (bytes[0], bytes[1], blue))
        screen.set_at((676, 641), (bytes[2], bytes[3], bytes[4]))
        screen.set_at((677, 641), (bytes[5], bytes[6], bytes[7]))
        for _ in xrange(3):
            display_frame()
        pg.time.delay(20 * 3)
        blue = 1 - blue
    end = pg.time.get_ticks()

Example 3

Project: flappy-bird-pygame Source File: flappybird.py
Function: image
    @property
    def image(self):
        """Get a Surface containing this bird's image.

        This will decide whether to return an image where the bird's
        visible wing is pointing upward or where it is pointing downward
        based on pygame.time.get_ticks().  This will animate the flapping
        bird, even though pygame doesn't support animated GIFs.
        """
        if pygame.time.get_ticks() % 500 >= 250:
            return self._img_wingup
        else:
            return self._img_wingdown

Example 4

Project: flappy-bird-pygame Source File: flappybird.py
Function: mask
    @property
    def mask(self):
        """Get a bitmask for use in collision detection.

        The bitmask excludes all pixels in self.image with a
        transparency greater than 127."""
        if pygame.time.get_ticks() % 500 >= 250:
            return self._mask_wingup
        else:
            return self._mask_wingdown

Example 5

Project: pi-tracking-telescope Source File: mainscreen.py
    def update(self, screenSurface, fpsClock):
        if pygame.time.get_ticks() - self.timer > 100:
            self.focusText.setText("Focus: %d" % self.focus.focus)
            self.timer = pygame.time.get_ticks()
            self.trackingText.setText("Track: %s" % self.tracker.getStatus())
            

            
        if (self.image != None):
            screenSurface.blit(self.image,
                # placement of preview window
                (100, 100),  
                # area of image to display
                Rect(100, 100, self.image.get_width(), self.image.get_height())) 

Example 6

Project: pi-tracking-telescope Source File: screen.py
    def getDeltaTime(self, fpsClock):
        """
        Return the amount of time in milliseconds since last frame 
        """
        t = pygame.time.get_ticks()
        deltaTime = (t - self.lastFrameTicks)
        self.lastFrameTicks = t
        return deltaTime

Example 7

Project: pygame_cffi Source File: run_benchmark.py
def sample_fps(clock, warmup_time, stats_all, stats_warmup, stats_postwarmup):
    fps = clock.get_fps()
    stats_all.add_sample(fps)
    if pygame.time.get_ticks() < warmup_time:
        stats_warmup.add_sample(fps)
    else:
        stats_postwarmup.add_sample(fps)

Example 8

Project: BoilerPlate2D Source File: level.py
Function: update
    def update(self):
        now = pygame.time.get_ticks()/1000.0
        self.elapsed =  now - self.timer

        if self.intro:
            if self.elapsed > 2:
                self.intro = False
        else:
            self.entities.update()

Example 9

Project: BoilerPlate2D Source File: level.py
Function: load_next
    def load_next(self):
        # Fix looping levels ASAP
        self.level_index += 1
        if self.level_index >= len(self.levels):
            self.level_index = 0

        i = self.level_index
        self.level = self.levels[i]

        self.level.timer = pygame.time.get_ticks()/1000.0

Example 10

Project: pygameui Source File: textfield.py
    def draw(self):
        if not view.View.draw(self) or not self.has_focus():
            return False

        if (not self.blink_cursor or
            pygame.time.get_ticks() / self.cursor_blink_duration % 2 == 0):
            size = self.label.font.size(self.text)
            rect = pygame.Rect(
                self.label.frame.left + self.label.padding[0] + size[0],
                self.label.frame.bottom - self.label.padding[1],
                10, 2)
            pygame.draw.rect(self.surface, self.text_color, rect)
        return True

Example 11

Project: ThePythonGameBook Source File: vgrade.py
Function: stop_watch
def stopwatch(message = None):
    "simple routine to time python code"
    global timer
    if not message:
        timer = pygame.time.get_ticks()
        return
    now = pygame.time.get_ticks()
    runtime = (now - timer)/1000.0 + .001
    print ("%s %s %s" %
           (message, runtime, ('seconds\t(%.2ffps)'%(1.0/runtime))))
    timer = now

Example 12

Project: The-Stolen-Crown-RPG Source File: tools.py
Function: update
    def update(self):
        self.current_time = pg.time.get_ticks()
        if self.state.quit:
            self.done = True
        elif self.state.done:
            self.flip_state()
        self.state.update(self.screen, self.keys, self.current_time)

Example 13

Project: pykaraoke Source File: pykplayer.py
Function: play
    def Play(self):
        self.doPlay()

        if manager.options.dump:
            self.setupDump()
        else:
            self.PlayStartTime = pygame.time.get_ticks()
            self.State = STATE_PLAYING

Example 14

Project: pyorpg-client Source File: timer.py
Function: init
    def __init__(self,fps):
        if fps == 0: 
            self.tick = self._blank
            return
        self.wait = 1000/fps
        self.nt = pygame.time.get_ticks()
        pygame.time.wait(0)

Example 15

Project: pyorpg-client Source File: timer.py
Function: tick
    def tick(self):
        """Wait correct amount of time each frame.  Call this once per frame."""
        self.ct = pygame.time.get_ticks()
        if self.ct < self.nt:
            pygame.time.wait(self.nt-self.ct)
            self.nt+=self.wait
        else: 
            self.nt = pygame.time.get_ticks()+self.wait

Example 16

Project: pyorpg-client Source File: timer.py
Function: tick
    def tick(self):
        """ Call this once per frame."""
        r = None
        self.frames += 1
        self.ct = pygame.time.get_ticks()
        if (self.ct - self.st) >= 1000: 
            r = self.fps = self.frames
            #print "%s: %d fps"%(self.__class__.__name__,self.fps)
            self.frames = 0
            self.st += 1000
        pygame.time.wait(0) #NOTE: not sure why, but you gotta call this now and again
        return r

Example 17

Project: bambam Source File: bambam.py
Function: get_color
def get_color():
    col = Color('white');
    
    hue = pygame.time.get_ticks() / 50 % 360
    col.hsva = (hue, 100, 100, 50)
    
    return Color(col.r, col.g, col.b)

Example 18

Project: OpenSesame Source File: video_player.py
Function: run
	def run(self):

		"""Handles the actual video playback."""

		# Log the onset time of the item
		self.set_item_onset()

		t = pygame.time.get_ticks()
		start_t = t
		# Loop until a key is pressed
		go = True
		while go:
			# Get the frame
			self.src = cv.QueryFrame(self.video)
			# Check for the end of the video
			if self.src is None:
				break
			# Resize if requested and convert the resulting image to
			# RGB format, which is compatible with PyGame
			if self._fullscreen:
				cv.Resize(self.src, self.src_tmp)
				cv.CvtColor(self.src_tmp, self.src_rgb, cv.CV_BGR2RGB)
			else:
				cv.CvtColor(self.src, self.src_rgb, cv.CV_BGR2RGB)
			# Convert the image to PyGame format
			pg_img = pygame.image.frombuffer(self.src_rgb.tostring(), \
				cv.GetSize(self.src_rgb), u"RGB")
			# Show the video frame!
			self.experiment.surface.blit(pg_img, (self._x, self._y))
			pygame.display.flip()
			# Pause before jumping to the next frame
			pygame.time.wait(
				self.var.get(u'frame_dur') - pygame.time.get_ticks() + t)
			t = pygame.time.get_ticks()
			if type(self.var.get(u'duration')) == int:
				# Wait for a specified duration
				if t - start_t >= self.var.get(u'duration'):
					go = False
			# Catch escape presses
			for event in pygame.event.get():
				if event.type == KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						self.experiment.pause()
					if self.var.get(u'duration') == u"keypress":
						go = False
				if event.type == MOUSEBUTTONDOWN and self.var.get(u'duration') == \
					u"mouseclick":
					go = False

Example 19

Project: ultimate-smash-friends Source File: main.py
    def manage_menu(self):
        """ manage input and update menu if we are in the menu state
        """
        # return of the menu update function may contain a new game
        # instance to switch to.
        start_loop = pygame.time.get_ticks()
        menu_was = self.menu.current_screen
        newgame, game_ = self.menu.update()
        if menu_was == 'keyboard' and self.menu.current_screen != 'keyboard':
            self.controls.load_keys()
            self.controls.load_sequences()

        if newgame:
            self.state = 'game'
            if game_ is not self.game:
                print "starting game"
                self.ai_instance = AI()

                del(self.game)
                self.game = game_

        max_fps = 1000/CONFIG.general.MAX_GUI_FPS

        if self.menu.current_screen == 'about':
            self.music_state = 'credits'
        else:
            self.music_state = self.state

        if pygame.time.get_ticks() < max_fps + start_loop:
            pygame.time.wait(max_fps + start_loop - pygame.time.get_ticks())

Example 20

Project: pykaraoke Source File: pykaraoke_mini.py
Function: start
    def start(self):
        self.appStart = pygame.time.get_ticks()
        self.heldStartTicks = self.appStart
        manager.OpenCPUControl()
        manager.setCpuSpeed('startup')

        self.numSongInfoLines = 1
        
        self.setupSplashScreen()
        manager.InitPlayer(self)
        self.setupScrollWindow()

        self.screenDirty = True

        needsSave = False

        if manager.options.scan_dir:
            # Replace the old scan list.
            self.songDb.Settings.FolderList = [ manager.options.scan_dir ]
            needsSave = True

        if manager.options.scan_dirs:
            # Add one or more new directories to the list.
            self.songDb.Settings.FolderList += manager.options.scan_dirs
            needsSave = True
        
        if manager.options.scan:
            # Re-scan the files.
            self.songDb.BuildSearchDatabase(pykdb.AppYielder(), MiniBusyCancelDialog(self))
            needsSave = True
        else:
            # Read the existing database.
            self.songDb.LoadDatabase(self.errorPopupCallback)

        if needsSave:
            self.songDb.SaveSettings()
            self.songDb.SaveDatabase()

        if not self.songDb.FullSongList:
            # No files.
            self.errorPopupCallback("No songs in catalog.")
            return

        if manager.options.validate:
            manager.ValidateDatabase(self.songDb)
            return

        if self.songDb.GotTitles:
            self.numSongInfoLines += 1
        if self.songDb.GotArtists:
            self.numSongInfoLines += 1
        self.setupScrollWindow()

        self.readMarkedSongs()

        if self.songDb.GotTitles:
            self.songDb.SelectSort('title')
        elif self.songDb.GotArtists:
            self.songDb.SelectSort('artist')
        else:
            self.songDb.SelectSort('filename')

        self.currentRow = 0
        self.searchString = ''
        self.heldKey = None
        self.heldStartTicks = 0
        self.heldRepeat = 0

        manager.setCpuSpeed('wait')

        # Now that we've finished loading, wait up a second and give
        # the user a chance to view the splash screen, in case we
        # loaded too fast.
        if self.splashStart != None:
            splashTime = pygame.time.get_ticks() - self.splashStart
            remainingTime = 2500 - splashTime
            if remainingTime > 0:
                pygame.time.wait(remainingTime)
        
        self.running = True

        manager.setCpuSpeed('menu_fast')
        self.heldStartTicks = pygame.time.get_ticks()
        
        while self.running:
            manager.Poll()

        self.writeMarkedSongs()
        manager.CloseDisplay()

Example 21

Project: pykaraoke Source File: pykplayer.py
Function: pause
    def Pause(self):
        if self.State == STATE_PLAYING:
            self.doPause()
            self.PlayTime = pygame.time.get_ticks() - self.PlayStartTime
            self.State = STATE_PAUSED
        elif self.State == STATE_PAUSED:
            self.doUnpause()
            self.PlayStartTime = pygame.time.get_ticks() - self.PlayTime
            self.State = STATE_PLAYING

Example 22

Project: MysticMine Source File: app.py
Function: run
    def run( self ):
        try:
            self.init_pygame()

            self.before_gameloop()

            self.fps = 0
            frame_count = 0

            next_game_tick = pygame.time.get_ticks()
            next_half_second = pygame.time.get_ticks()

            # main loop
            self.game_is_done = False
            while not self.game_is_done:
                # events
                self.handle_events()

                # game tick
                loop_count = 0
                while pygame.time.get_ticks() > next_game_tick and loop_count < 4:
                    x, y = pygame.mouse.get_pos()
                    self.userinput.mouse.feed_pos( Vec2D(x, y) )

                    self.do_tick( self.userinput )
                    self.userinput.update()
                    next_game_tick += GAMETICKS
                    loop_count += 1

##                    gc.collect()

                if loop_count >= 4: # don't overdo the ticks
                    next_game_tick = pygame.time.get_ticks()

                # render
                time_sec = pygame.time.get_ticks() * 0.001
                interpol = 1 - ((next_game_tick - pygame.time.get_ticks()) / float(GAMETICKS))
                self.render(pygame.display.get_surface(), interpol, time_sec )
                pygame.display.flip()

                frame_count += 1
                if pygame.time.get_ticks() > next_half_second:
                    self.fps = 2 * frame_count
                    frame_count = 0
                    next_half_second += 500

            self.after_gameloop()

            self.deinit_pygame()

        except:
            self.deinit_pygame()
            print "Unexpected error:", sys.exc_info()[0]
            raise

Example 23

Project: MysticMine Source File: monkey.py
Function: run
    def run( self, timeout = None ):
        try:
            self.init_pygame()

            self.before_gameloop()

            self.fps = 0
            frame_count = 0

            next_game_tick = pygame.time.get_ticks()
            next_half_second = pygame.time.get_ticks()
            if timeout is not None:
                end_game_tick = pygame.time.get_ticks() + timeout * 1000

            # main loop
            self.game_is_done = False
            while not self.game_is_done:
                # events
                self.handle_events()

                # game tick
                loop_count = 0
                while loop_count < 1:
                    self.do_tick( self.userinput )
                    self.userinput.update()
                    next_game_tick += GAMETICKS
                    loop_count += 1

                # render
                time_sec = pygame.time.get_ticks() * 0.001
                interpol = 1 - ((next_game_tick - pygame.time.get_ticks()) / GAMETICKS)
                self.render(pygame.display.get_surface(), interpol, time_sec )
                pygame.display.flip()

                frame_count += 1
                if pygame.time.get_ticks() > next_half_second:
                    self.fps = 2 * frame_count
                    frame_count = 0
                    next_half_second += 500

                if timeout is not None and \
                                pygame.time.get_ticks() > end_game_tick:
                    self.game_is_done = True

            self.after_gameloop()

            self.deinit_pygame()

            self.replay_file.close()

            if self.record or not self.user_exit:
                os.remove(self.replay_filename)


        except Exception, ex:
            print "exceptje"
            self.deinit_pygame()
            self.replay_file.close()
            if self.record:
                shutil.move("monkeyTemp", self.create_failed())
            raise

Example 24

Project: pivaders Source File: pivaders.py
Function: main_loop
    def main_loop(self):
        while not GameState.end_game:
            while not GameState.start_screen:
                GameState.game_time = pygame.time.get_ticks()
                GameState.alien_time = pygame.time.get_ticks()
                self.control()
                self.make_missile()
                self.calc_collisions()
                self.refresh_screen()
                if self.is_dead() or self.defenses_breached():
                    GameState.start_screen = True
                for actor in [self.player_group, self.bullet_group,
                              self.alien_group, self.missile_group]:
                    for i in actor:
                        i.update()
                if GameState.shoot_bullet:
                    self.make_bullet()
                if self.win_round():
                    self.next_round()
            self.splash_screen()
        pygame.quit()

Example 25

Project: OpenSesame Source File: legacy.py
Function: time
	def time(self):

		return float(pygame.time.get_ticks())

Example 26

Project: OpenSesame Source File: droid.py
Function: get_key
	@configurable
	def get_key(self):

		if not self.persistent_virtual_keyboard and android is not None:
			android.show_keyboard()
		start_time = pygame.time.get_ticks()
		time = start_time
		keylist = self.keylist
		timeout = self.timeout
		while True:
			time = pygame.time.get_ticks()
			for event in pygame.event.get():
				if event.type != pygame.KEYDOWN:
					continue
				if event.key == pygame.K_ESCAPE:
					self.experiment.pause()
				# TODO The unicode mechanism that ensures compatibility between
				# keyboard layouts doesn't work for Android, so we use key
				# names. I'm not sure what effect this will have on non-QWERTY
				# virtual keyboards.
				if android is not None:
					key = pygame.key.name(event.key)
					if len(key) == 1 and (event.mod & pygame.KMOD_LSHIFT or \
						event.mod & pygame.KMOD_RSHIFT):
						key = key.upper()
				else:
					# If we're not on Android, simply use the same logic as the
					# legacy back-end.
					if event.unicode in invalid_unicode:
						key = self.key_name(event.key)
					else:
						key = event.unicode
				if keylist is None or key in keylist:
					if not self.persistent_virtual_keyboard and android is not None:
						android.hide_keyboard()
					return key, time
			if timeout is not None and time-start_time >= timeout:
				break
			# Allow Android interrupt
			if android is not None and android.check_pause():
				android.wait_for_resume()
		if not self.persistent_virtual_keyboard and android is not None:
			android.hide_keyboard()
		return None, time

Example 27

Project: OpenSesame Source File: legacy.py
Function: get_key
	@configurable
	def get_key(self):

		start_time = pygame.time.get_ticks()
		time = start_time
		keylist = self.keylist
		timeout = self.timeout
		while True:
			time = pygame.time.get_ticks()
			for event in pygame.event.get():
				if event.type != pygame.KEYDOWN:
					continue
				if event.key == pygame.K_ESCAPE:
					self.experiment.pause()
				if event.unicode in invalid_unicode:
					key = self.key_name(event.key)
				else:
					key = event.unicode
				if keylist is None or key in keylist:
					return key, time
			if timeout is not None and time-start_time >= timeout:
				break
		return None, time

Example 28

Project: OpenSesame Source File: legacy.py
Function: get_joybutton
	def get_joybutton(self, joybuttonlist=None, timeout=None):

		"""See _libjoystick.basejoystick"""

		if joybuttonlist is None or joybuttonlist == []:
			joybuttonlist = self._joybuttonlist
		if timeout is None:
			timeout = self.timeout

		start_time = pygame.time.get_ticks()
		time = start_time

		while timeout is None or time - start_time <= timeout:
			time = pygame.time.get_ticks()
			for event in pygame.event.get():
				if event.type == KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						self.experiment.pause()
				if event.type == JOYBUTTONDOWN:
					if joybuttonlist is None or event.button + 1 in \
						joybuttonlist:
						bpress = event.button + 1
						return bpress, time

		return None, time

Example 29

Project: OpenSesame Source File: legacy.py
Function: get_joyaxes
	def get_joyaxes(self, timeout=None):

		"""See _libjoystick.basejoystick"""

		if timeout is None:
			timeout = self.timeout

		pos = []
		start_time = pygame.time.get_ticks()
		time = start_time

		while timeout is None or time - start_time < timeout:
			time = pygame.time.get_ticks()
			for event in pygame.event.get():
				if event.type == KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						self.experiment.pause()
				if event.type == JOYAXISMOTION:
					for axis in range(self.js.get_numaxes()):
						pos.append(self.js.get_axis(axis))
					return pos, time

		return None, time

Example 30

Project: OpenSesame Source File: legacy.py
Function: get_joyballs
	def get_joyballs(self, timeout=None):

		"""See _libjoystick.basejoystick"""

		if timeout is None:
			timeout = self.timeout

		ballpos = []
		start_time = pygame.time.get_ticks()
		time = start_time

		while timeout is None or time - start_time < timeout:
			time = pygame.time.get_ticks()
			for event in pygame.event.get():
				if event.type == KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						self.experiment.pause()
				if event.type == JOYBALLMOTION:
					for ball in range(self.js.get_numballs()):
						ballpos.append(self.js.get_ball(ball))
					return ballpos, time

		return None, time

Example 31

Project: OpenSesame Source File: legacy.py
Function: get_joyhats
	def get_joyhats(self, timeout=None):

		"""See _libjoystick.basejoystick"""

		if timeout is None:
			timeout = self.timeout

		hatpos = []
		start_time = pygame.time.get_ticks()
		time = start_time

		while timeout is None or time - start_time < timeout:
			time = pygame.time.get_ticks()
			for event in pygame.event.get():
				if event.type == KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						self.experiment.pause()
				if event.type == JOYHATMOTION:
					for hat in range(self.js.get_numhats()):
						hatpos.append(self.js.get_hat(hat))
					return hatpos, time

		return None, time

Example 32

Project: OpenSesame Source File: legacy.py
Function: get_joyinput
	def get_joyinput(self, joybuttonlist=None, timeout=None):

		"""See _libjoystick.basejoystick"""

		if joybuttonlist is None or joybuttonlist == []:
			joybuttonlist = self._joybuttonlist
		if timeout is None:
			timeout = self.timeout

		pos = []
		ballpos = []
		hatpos = []
		eventtype = None
		start_time = pygame.time.get_ticks()
		time = start_time

		while timeout is None or time - start_time <= timeout:
			time = pygame.time.get_ticks()
			for event in pygame.event.get():
				if event.type == KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						self.experiment.pause()
				if event.type == JOYBUTTONDOWN:
					if joybuttonlist is None or event.button + 1 in \
						joybuttonlist:
						eventtype = u'joybuttonpress'
						bpress = event.button + 1
						return eventtype, bpress, time
				if event.type == JOYAXISMOTION:
					eventtype = u'joyaxismotion'
					for axis in range(self.js.get_numaxes()):
						pos.append(self.js.get_axis(axis))
					return eventtype, pos, time
				if event.type == JOYBALLMOTION:
					eventtype = u'joyballmotion'
					for ball in range(self.js.get_numballs()):
						ballpos.append(self.js.get_ball(ball))
					return eventtype, ballpos, time
				if event.type == JOYHATMOTION:
					eventtype = u'joyhatmotion'
					for hat in range(self.js.get_numhats()):
						hatpos.append(self.js.get_hat(hat))
					return eventtype, hatpos, time

		return eventtype, None, time

Example 33

Project: rpi_lcars Source File: main.py
Function: update
    def update(self, screenSurface, fpsClock):
        if pygame.time.get_ticks() - self.lastClockUpdate > 1000:
            self.stardate.setText("STAR DATE {}".format(datetime.now().strftime("%d%m.%y %H:%M:%S")))
            self.lastClockUpdate = pygame.time.get_ticks()
        LcarsScreen.update(self, screenSurface, fpsClock)

Example 34

Project: Tuxemon Source File: control.py
Function: update
    def update(self, dt):
        """Checks if a state is done or has called for a game quit.
        State is flipped if neccessary and State.update is called. This
        also calls the currently active state's "update" function each
        frame.

        The screen will be drawn here as well.

        :param dt: Time delta - Amount of time passed since last frame.

        :type dt: Float

        :rtype: None
        :returns: None

        **Example:**

        >>> dt
        0.031

        """
        # TODO: phase out use of this attribute
        self.current_time = pg.time.get_ticks()

        # only the top most state gets updates
        state = self.current_state

        # handle case where the top state has been dismissed
        if state is None:
            self.exit = True

        if state in self._state_resume_set:
            state.resume()
            self._state_resume_set.remove(state)

        # iterate through layers and determine optimal drawing strategy
        # this is a big performance boost for states covering other states
        # force_draw is used for transitions, mostly

        to_draw = list()
        full_screen = self.screen.get_rect()
        for state in self.active_states:
            state.update(dt)
            to_draw.append(state)
            if state.rect == full_screen and not state.force_draw:
                break

        # draw from bottom up for proper layering
        for state in reversed(to_draw):
            # might not be in draw if it has been removed for some reason
            if state in self.active_states:
                state.draw(self.screen)

        if self.config.controller_overlay == "1":
            self.controller.draw(self)

Example 35

Project: pyff Source File: ERPHex.py
Function: log_data
    def log_data(self):
        """
        Structure of logfile
        Word Letter TrialNr Speller Fix_condition Trigger Time targetx targety currentx currenty Duration Invalid(-> added at flush)
        """
        #print self.et.x, self.et.y, self.et.duration
        if self.state == self.STIM_START_FLASH:
            word = self.words[self.current_word]
            items = []
            items.append(word)
            items.append(word[self.current_letter])
            items.append(str(self.trial_nr))
            items.append("hex")
            if self.et_fixate_center:
                items.append("center")
            else:
                items.append("target")
            items.append(str(self.flash_sequence[self.current_flash]))
            items.append(str(pygame.time.get_ticks()))
            if self.use_eyetracker:
                items.append(str(self.et_targetxy[0]))
                items.append(str(self.et_targetxy[1]))
                items.append(str(self.et_currentxy[0]))
                items.append(str(self.et_currentxy[1]))
                items.append(str(self.et_duration))
                #items.append(str(self.et_outside))
            line = "\t".join(items)
            self.datalines.append(line) 

Example 36

Project: pyff Source File: ERPMatrix.py
Function: log_data
    def log_data(self):
        """
        Structure of logfile
        Word Letter Trial Speller Fix_condition Trigger Time targetx targety currentx currenty Duration FlashCount Invalid(->added at flush)
        """
        #print self.et.x, self.et.y, self.et.duration
        if self.state == self.STIM_START_FLASH:
            word = self.words[self.current_word]
            items = []
            items.append(word)
            items.append(word[self.current_letter])
            items.append(str(self.trial_nr))
            items.append("matrix")
            if self.et_fixate_center:
                items.append("center")
            else:
                items.append("target")
            items.append(str(self.flash_sequence[self.current_flash]))
            items.append(str(pygame.time.get_ticks()))
            if self.use_eyetracker:
                items.append(str(self.et_targetxy[0]))
                items.append(str(self.et_targetxy[1]))
                items.append(str(self.et_currentxy[0]))
                items.append(str(self.et_currentxy[1]))
                items.append(str(self.et_duration))
                #items.append(str(self.et_outside))
            line = "\t".join(items)
            self.datalines.append(line) 

Example 37

Project: raspi Source File: 3d-display.py
Function: render
    def render(self):
        then = pygame.time.get_ticks()
        vertices = self.vertices
        # Draw all 6 faces of the cube
        glBegin(GL_QUADS)

        for face_no in xrange(self.num_faces):
            
            if face_no == 1:
                glColor(1.0, 0.0, 0.0)
            else:
                glColor(self.color)
            
            glNormal3dv(self.normals[face_no])
            v1, v2, v3, v4 = self.vertex_indices[face_no]
            glVertex(vertices[v1])
            glVertex(vertices[v2])
            glVertex(vertices[v3])
            glVertex(vertices[v4])
        glEnd()

Example 38

Project: fofix Source File: Font.py
Function: accessed
    def accessed(self):
        self.lastUse = pygame.time.get_ticks()

Example 39

Project: fofix Source File: FoFiX.py
Function: run
    def run(self):

        # Perhapse this could be implemented in a better way...
        # Play the intro video if it is present, we have the capability, and
        # we are not in one-shot mode.
        if not self.engine.cmdPlay:
            themename = Config.get("coffee", "themename")
            vidSource = os.path.join(Version.dataPath(), 'themes', themename, 'menu', 'intro.ogv')
            if os.path.isfile(vidSource):
                try:
                    vidPlayer = VideoLayer(self.engine, vidSource, cancellable=True)
                except (IOError, VideoPlayerError):
                    log.error("Error loading intro video:")
                else:
                    vidPlayer.play()
                    self.engine.view.pushLayer(vidPlayer)
                    self.videoLayer = True
                    self.engine.ticksAtStart = pygame.time.get_ticks()
                    while not vidPlayer.finished:
                        self.engine.run()
                    self.engine.view.popLayer(vidPlayer)
                    self.engine.view.pushLayer(MainMenu(self.engine))
        if not self.videoLayer:
            self.engine.setStartupLayer(MainMenu(self.engine))

        # Run the main game loop.
        try:
            self.engine.ticksAtStart = pygame.time.get_ticks()
            while self.engine.run():
                pass
        except KeyboardInterrupt:
            log.notice("Left mainloop due to KeyboardInterrupt.")
            # don't reraise

        # Restart the program if the engine is asking that we do so.
        if self.engine.restartRequested:
            self.restart()

        # evilynux - MainMenu class already calls this - useless?
        self.engine.quit()

Example 40

Project: mapengine Source File: base.py
def simpleloop(scene, size, godmode=False):
    controller = Controller(size, scene)

    try:
        controller = Controller(size, scene)
        continue_ = True
        while continue_:
            try:
                while True:
                    frame_start = pygame.time.get_ticks()
                    pygame.event.pump()
                    controller.update()
                    if controller.inside_cut:
                        continue
                    pygame.display.flip()
                    delay = max(0, FRAME_DELAY - (pygame.time.get_ticks() - frame_start))
                    pygame.time.delay(delay)

                    keys = pygame.key.get_pressed()
                    if keys[pygame.K_ESCAPE]:
                        raise GameOver
                    main_character = (controller.protagonist) if not godmode else None
                    for direction_name in "RIGHT LEFT UP DOWN".split():
                        if keys[getattr(pygame, "K_" + direction_name)]:
                            direction = getattr(Directions, direction_name)
                            if godmode:
                                scene.move(direction)
                            else:
                                main_character.move(direction)
                        if keys[pygame.K_SPACE] and not godmode:
                            main_character.on_fire()


            except GameOver:
                continue_ = False
            except RestartGame:
                scene.top = scene.left = 0
                controller.load_scene(scene)
                try:
                    controller.hard_reset()
                except Reset:
                    pass

    finally:
        controller.quit()

Example 41

Project: pykaraoke Source File: pykaraoke_mini.py
Function: do_stuff
    def doStuff(self):
        pykPlayer.doStuff(self)

        if self.screenDirty:
            self.paintWindow()
            self.screenDirty = False

        if self.heldKey:
            elapsed = pygame.time.get_ticks() - self.heldStartTicks
            repeat = 0
            if elapsed > 4000:
                repeat = int((elapsed - 4000) / 5.) + 256
            else:
                repeat = int(math.pow((elapsed / 1000.), 4))

            if elapsed > 1000:
                manager.setCpuSpeed('menu_fast')
            elif manager.cpuSpeed != 'menu_fast':
                manager.setCpuSpeed('menu_slow')

            if repeat > self.heldRepeat:
                self.handleRepeatable(self.heldKey[0], self.heldKey[1],
                                      self.heldKey[2], repeat - self.heldRepeat)
                self.heldRepeat = repeat
        else:
            elapsed = pygame.time.get_ticks() - self.heldStartTicks
            if elapsed > 20000:
                manager.setCpuSpeed('menu_idle')
            elif elapsed > 2000:
                manager.setCpuSpeed('menu_slow')

Example 42

Project: pykaraoke Source File: pykplayer.py
Function: get_pos
    def GetPos(self):
        if self.State == STATE_PLAYING:
            return pygame.time.get_ticks() - self.PlayStartTime
        else:
            return self.PlayTime

Example 43

Project: pyorpg-client Source File: timer.py
Function: init
    def __init__(self):
        self.frames = 0
        self.st = pygame.time.get_ticks()
        self.fps = 0