Ejemplo n.º 1
0
    def tick(self, maxMillis):
        currentTime = time.get_ticks()
        maxTime = currentTime + maxMillis

        queueToProcess = self._currentQueue
        queueToProcess = (self._currentQueue + 1) % self._numQueues
        del self._queues[queueToProcess][:]

        q = self._getCurrentQueue()
        while len(q) > 0:
            event = q.pop(0)
            if event.getType() in self._listenerList:
                for listener in self._listenerList[event.getType()]:
                    listener.handle(event)
            else:
                continue

            currentTime = time.get_ticks()
            if currentTime >= maxTime:
                break

        queueEmpty = len(q) == 0
        if not queueEmpty:
            q.extend(self._queues[self._currentQueue])
            self._queues[self._currentQueue], q = q, []

        return queueEmpty
Ejemplo n.º 2
0
 def endScene(self):
     fpsClock = PT.Clock()
     DURATION = 2000.0
     start_time = PT.get_ticks()
     ratio = 0.0
     while ratio < 1.0:
         current_time = PT.get_ticks()
         ratio = (current_time - start_time)/DURATION
         if ratio > 1.0:
             ratio = 1.0
         value = int(255*ratio)
         fade_color = PC.Color(0, 0, 0, 0)
         fade_color.a = value
         # PD.rect(Globals.SCREEN, fade_color, (0,0,400,300))
         surf = PG.Surface((800, 600))
         surf.set_alpha(value)
         surf.fill((0, 0, 0))
         Globals.SCREEN.blit(surf, (0, 0))
         PD.flip()
         fpsClock.tick(60)
     levelTwoEvents[1] = False
     Player.events[4] = False
     self.stone_mound = item.Item(54*Setup.PIXEL_SIZE, 26*Setup.PIXEL_SIZE, stone_mound_image)
     Globals.WORLD.addEntity(self.stone_mound)
     Globals.STATE = LevelTwo()
Ejemplo n.º 3
0
    def fire_weapon(self):
        """Fire the character's weapon."""

        last_fired = self.last_fired + self.weapon.fire_rate * 100
        if last_fired < time.get_ticks():
            self.weapon.fire()
            self.last_fired = time.get_ticks()
Ejemplo n.º 4
0
    def run(self):
        """Runs the main game loop


        """
        FPS = 1.0 / 8.0
        lastScreenUpdate = time.get_ticks()

        while self._run_game:
            if time.get_ticks() - lastScreenUpdate < FPS:
                continue

            self._processInput()

            if self._pause_game is False:
                self._moveSnake()

                if self._with_opponent:
                    self._moveOpponent()

                if self._collides():
                    self._run_game = False

                if self._eatsApple(self._snake) or \
                        (self._with_opponent and self._eatsApple(self._opponent)):

                    self._spawnApple()
            
            self._draw()

            self._frames = self._frames + 1
            
            # Slow things down a bit...
            lastScreenUpdate = time.get_ticks() + self._delay
Ejemplo n.º 5
0
def main_loop():
    """Main loop for running the actionRPM game"""
    # Clock code adapted from Peter's leftover-interval.py
    clock = time.Clock()
    current_time = time.get_ticks()
    leftover = 0.0

    while True:
        Constants.STATE.draw()
        # Set up clock stuff
        new_time = time.get_ticks()
        frame_time = (new_time - current_time) / 1000.0
        current_time = new_time
        clock.tick()

        #Update the Player & Enemy
        leftover += frame_time

        while leftover > Constants.INTERVAL:
            Constants.STATE.update(Constants.INTERVAL)
            leftover -= Constants.INTERVAL

        #Begin key presses
        pygame.event.pump()
        for eve in event.get():
            if eve.type == pygame.QUIT:
                exit()
            elif eve.type == pygame.KEYDOWN and eve.key == pygame.K_m and \
                    eve.mod & (pygame.KMOD_CTRL or pygame.KMOD_LCTRL):
                Constants.STATE = Menu.Menu()
                #elif eve.type == pygame.MOUSEBUTTONDOWN:
                #print(pygame.mouse.get_pos())
            else:
                Constants.STATE.keyEvent(eve)
Ejemplo n.º 6
0
    def authenticate(self):
        """ call this before opening the game
        gets the current tick from the server
        and synchronizes the game state """

        def threaded_recv(retlist):
            response, addr = self.client.recv()
            retlist.append(response)

        pkg_request = Packet(0)
        self.client.send(pkg_request)
        retlist = []
        t = Thread(target=lambda: threaded_recv(retlist))
        t.daemon = True
        t.start()
        wait_start = time.get_ticks()
        wait_end = wait_start + 1000
        while len(retlist) <= 0 and time.get_ticks() < wait_end:
            time.wait(1)

        if len(retlist) > 0:
            response = retlist[0]
            pkg_response = Packet.unpack(response)
            self.start_tick = pkg_response.tick
            if len(pkg_response.players) <= 0:
                raise RuntimeError("Invalid response: %s" % pkg_response)
            self.id = pkg_response.players[0][0]
            self.set_state(pkg_response, backtrack=False)
        else:
            raise RuntimeError("Server not responding")
Ejemplo n.º 7
0
    def run(self):
        self.net_tick = 0
        self.clients = {}
        self.lock = Lock()
        self.server = UdpServer(25000)

        self.socket_thread = SocketThread(self)
        self.socket_thread.start()

        print "Server up and running."

        self.input_thread = InputThread(self)
        self.input_thread.start()

        ticks_start = time.get_ticks()
        while not self.quit:
            ticks = time.get_ticks() - ticks_start - self.net_tick * FRAMETIME
            update_count = ticks / FRAMETIME
            with self.lock:
                for i in xrange(update_count):
                    self.update()
                    self.send_new_state()
                    dead_clients = []
                    for addr, client in self.clients.items():
                        client.countdown()
                        if client.is_dead():
                            dead_clients.append(addr)
                    for addr in dead_clients:
                        print "removing client %s (timeout)" % str(addr)
                        del self.clients[addr]
            time.wait(1)
Ejemplo n.º 8
0
    def run(self):
        running = True
        while running:
            new_time = PT.get_ticks()
            frame_time = (new_time - self.current_time)/1000.0
            self.current_time = new_time
            self.clock.tick()

            running = self.handleEvents()
            if(running == False):
                return False
            #Key Handling----------------------------
            # self.character.handle_keys() # handle the keys

            self.screen.fill((0,0,0)) # fill the screen with white

            # self.character.handle_collision(self.block_group)

            #move and draw the enemies
            player_face = self.character.get_face()
            for enemy in self.enemy_list.sprites():
                Enemy_face = enemy.get_face()
                enemy.set_face(player_face)
                enemy.draw()

            #draw blocks
            Draw.draw_map(self.block_group)

            self.character.draw(self.screen, self.block_group) # draw the character to the screen

            PD.flip()

            self.updates = 0

            #clock is added
            clock = PT.Clock()

            while frame_time > 0.0:
                delta = min(frame_time, self.interval)
                for enemy in self.enemy_list.sprites():
                    enemy.update(delta)
                self.character.handle_keys(self.block_group, self.interval)
                frame_time -= delta
                self.updates += 1

                last = PT.get_ticks()

                clock.tick()

                PD.flip()

                elapsed = (PT.get_ticks() - last) / 1000.0
                if (PG.key.get_pressed()):
                    self.update(self.character, elapsed)

            #camera handling
            self.cam.update(self.character)
            #end camera handle
            
            PD.update() # update the screen
Ejemplo n.º 9
0
    def game_loop(self):
        """Function for the main game loop."""
        clock = T.Clock()
        current_time = T.get_ticks()
        leftover = 0.0

        while True:
            self.play.draw()
            P.display.update()

            new_time = T.get_ticks()
            frame_time = (new_time - current_time) / 1000.0
            current_time = new_time
            clock.tick()
            leftover += frame_time
            while leftover > 0.01:
                self.play.update()
                leftover -= 0.01

            P.event.pump()
            for e in P.event.get():
                if e.type == P.QUIT:
                    exit()
                else:
                    self.play.handle_keys(e)
Ejemplo n.º 10
0
    def render(self):
        #Music
        if not PX.music.get_busy():
            if Globals.CURRENTSONG == HIGHSONG:
                PX.music.load(HIGHSONG)
                Globals.CURRENTSONG = SONG1
            elif Globals.CURRENTSONG == SONG1:
                PX.music.load(SONG1)
                Globals.CURRENTSONG = SONG0
            elif Globals.CURRENTSONG == SONG0:
                PX.music.load(SONG0)
                Globals.CURRENTSONG = HIGHSONG
            PX.music.set_volume(Globals.VOLUME)
            PX.music.play(0, 0.0)
        lasttime = PT.get_ticks()
        #screen.fill(BLACK)
        self.current_level.draw(screen, self.player_group)
            
        self.player_group.draw(screen)
        self.ui_group.draw(screen)
        
        clock.tick()
        PDI.flip()
        elapsed = (PT.get_ticks() - lasttime) / 1000.0
        if elapsed > 2.0:
            elapsed = 2.0

        #Update Player and Enemy
        while elapsed >= 0 and Globals.ALIVE:
            self.player_group.update(INTERVAL, self.PLAYER_X_POS, self.PLAYER_X_NEG, self.PLAYER_Y_POS, \
                                     self.PLAYER_Y_NEG, self.SELECTEDWEAPON, self.ATTACK, self.CROUCH, \
                                     self.USING, self.TOOLS, self.current_level)
            Globals.ALIVE = self.new_player.is_alive()
            self.current_level.update(INTERVAL, self.player_group)
            self.ui_group.update(self.new_player)
            elapsed -= INTERVAL
            if self.new_player.get_win():
                Globals.STATE = Win(self.level_num)
            self.USING = False
        
        #Reset jump status
        for this_player in self.player_group:
            if not this_player.on_ladder():
                self.PLAYER_Y_POS = False

        #Reset ladder status
        self.TOOLS = -1

        #Check to see if the player is alive
        if not Globals.ALIVE:
            while elapsed >= 0:
                self.new_player.die(INTERVAL)
                elapsed -= INTERVAL
            if self.new_player.finishedDying():
                #Reset Music
                if PX.music.get_busy():
                    PX.music.stop()
                Globals.LASTCHECK = self.current_level.get_last_check()
                Globals.STATE = Lose(self.new_player)
Ejemplo n.º 11
0
    def find_path_between_points(self, start_tile, end_tile, pathfinder_screen_s):
        """


        :param point_a: Tuple(int, int)
        :param point_b: Tuple(int, int)
        :rtype : List(Tuple)
        :rtype time_module: pygame.time
        """

        assert isinstance(start_tile, tuple)
        assert isinstance(end_tile, tuple)

        method_init_time = time.get_ticks()
        counter = 0

        # Create start and end nodes.
        start_node = self.grid.nodes[start_tile]
        target_node = self.grid.nodes[end_tile]

        # Keep track of the open and closed nodes.
        # Add the start node as the first node to start the flood from.
        open_nodes = priority_dict()
        open_nodes[start_node] = 0
        closed_nodes = set()

        # start looping
        while open_nodes.__len__() > 0:

            current_node = open_nodes.pop_smallest()


            # Remove the current node from open set and add it to closed set.
            #open_nodes.remove(current_node)
            closed_nodes.add(current_node)
            # Found the end tile.
            if current_node == target_node:
                complete_path = self.retrace_path(start_node, target_node)

                method_run_time = time.get_ticks() - method_init_time
                print 'Pathfinding completed in {}ms'.format(method_run_time)
                return complete_path

            for neighbour_node in self.get_neighbours(current_node):
                if neighbour_node in closed_nodes:
                    continue

                assert isinstance(current_node, PathFinder.Node)
                assert isinstance(neighbour_node, PathFinder.Node)
                new_movement_cost_to_neighbor = current_node.g_cost + 10
                # Try to find a lower cost for neighbor, or calculate if it doesn't have one.
                if new_movement_cost_to_neighbor < neighbour_node.g_cost or neighbour_node not in open_nodes.keys():

                    # Calculate the costs for the neighbor
                    neighbour_node.g_cost = new_movement_cost_to_neighbor
                    neighbour_node.h_cost = self.get_distance(neighbour_node, target_node)
                    neighbour_node.parent = current_node

                    open_nodes[neighbour_node] = neighbour_node.f_cost
Ejemplo n.º 12
0
    def update(self):
        if self.running:
            if keyboard.right:
                self.cannon.move_right()
            elif keyboard.left:
                self.cannon.move_left()

            if keyboard.space:
                if get_ticks(
                ) - self.cannon.last_fire > self.cannon.firing_interval:
                    self.bullets.append(Bullet('bullet', self.cannon.pos))
                    sounds.shot.play()
                    self.cannon.last_fire = get_ticks()

            for bullet in self.bullets[:]:
                bullet.update()
                if bullet.is_dead():
                    self.bullets.remove(bullet)

            for alien in self.aliens[:]:
                alien.update()
                if self.cannon.colliderect(alien):
                    self.explosions.append(
                        Explosion('cannon_explosion', self.cannon.pos))
                    sounds.explosion.play()
                    self.running = False
                if alien.bottom >= HEIGHT:
                    self.running = False
                for bullet in self.bullets[:]:
                    if alien.colliderect(bullet):
                        alien.lives -= 1
                        if alien.is_dead():
                            self.explosions.append(
                                Explosion('alien_explosion', alien.pos))
                            sounds.explosion.play()
                            self.aliens.remove(alien)
                            self.score += ALIEN_KILL_SCORE
                        self.bullets.remove(bullet)

            for explosion in self.explosions[:]:
                explosion.update()
                if explosion.is_finished():
                    self.explosions.remove(explosion)

            if len(self.aliens) == 0 and len(self.explosions) == 0:
                self.game.set_game_over_message("YOU WON!!!!!", "#00FFFF")
                self.game.change_scene(GAME_OVER_SCENE)
                sounds.winner.play()

        else:
            for explosion in self.explosions[:]:
                explosion.update()
                if explosion.is_finished():
                    self.explosions.remove(explosion)
            if len(self.explosions) == 0:
                self.game.set_game_over_message("YOU LOST...", "red")
                self.game.change_scene(GAME_OVER_SCENE)
                sounds.loser.play()
Ejemplo n.º 13
0
    def __call__(self, bean1Grid, bean2Grid, playerGrid, designValues):
        initialPlayerGrid = playerGrid
        initialTime = time.get_ticks()
        reactionTime = list()
        trajectory = [initialPlayerGrid]
        results = co.OrderedDict()
        aimActionList = list()
        firstIntentionFlag = False
        noiseStep = list()
        stepCount = 0
        goalList = list()

        # self.drawText("+", [0, 0, 0], [7, 7])
        # pg.time.wait(1300)
        # self.drawNewState(bean1Grid, bean2Grid, initialPlayerGrid)
        # pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT])

        priorList = self.initPrior
        realPlayerGrid = initialPlayerGrid
        pause = True
        while pause:
            aimPlayerGrid, aimAction = self.controller(realPlayerGrid,
                                                       bean1Grid, bean2Grid,
                                                       priorList)
            posteriorList = self.inferGoalPosterior(realPlayerGrid, aimAction,
                                                    bean1Grid, bean2Grid,
                                                    priorList)
            priorList = posteriorList

            goal = inferGoal(trajectory[-1], aimPlayerGrid, bean1Grid,
                             bean2Grid)
            goalList.append(goal)
            stepCount = stepCount + 1
            noisePlayerGrid, firstIntentionFlag, noiseStep = self.awayFromTheGoalNoise(
                trajectory[-1], bean1Grid, bean2Grid, aimAction, goal,
                firstIntentionFlag, noiseStep, stepCount)
            realPlayerGrid = self.checkBoundary(noisePlayerGrid)
            # self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid)
            # pg.time.delay(1000)
            reactionTime.append(time.get_ticks() - initialTime)
            trajectory.append(list(realPlayerGrid))
            aimActionList.append(aimAction)
            pause = self.checkTerminationOfTrial(bean1Grid, bean2Grid,
                                                 realPlayerGrid)
        # pg.time.wait(500)
        pg.event.set_blocked([pg.KEYDOWN, pg.KEYUP])
        results["bean1GridX"] = bean1Grid[0]
        results["bean1GridY"] = bean1Grid[1]
        results["bean2GridX"] = bean2Grid[0]
        results["bean2GridY"] = bean2Grid[1]
        results["playerGridX"] = initialPlayerGrid[0]
        results["playerGridY"] = initialPlayerGrid[1]
        results["reactionTime"] = str(reactionTime)
        results["trajectory"] = str(trajectory)
        results["aimAction"] = str(aimActionList)
        results["noisePoint"] = str(noiseStep)
        results["goal"] = str(goalList)
        return results
Ejemplo n.º 14
0
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface):
        if (self._data.health <= 0):
            self.kill()
            enemies.remove(self)
        try:

            for enemy in enemies:
                if sprite.collide_circle(self, enemy) and enemy != self:
                    distance = math.hypot((enemy.rect.x - self.rect.x),
                                          (enemy.rect.y - self.rect.y))

                    if (distance < 400):
                        target_direction = Vector2(
                            (self.rect.x - enemy.rect.x),
                            (self.rect.y - enemy.rect.y))
                        target_direction.scale_to_length(self._data.vel *
                                                         0.001)
                        self.rect.x += target_direction.x
                        self.rect.y += target_direction.y

                # Delete enemy when it comes into contact with player
            if sprite.collide_mask(
                    player, self) is not None and not player.invulnerable:
                player.take_damage(1)
                self.kill()
                enemies.remove(self)

                # Type 2 enemy specification
                # Auto fire towards player at a given rate

            n = time.get_ticks()

            if (self._charging) <= 1000:
                self._charging = n - self._start
                self._pstart = time.get_ticks()
                target_direction = Vector2(-self.rect.x + player.rect.x,
                                           -self.rect.y + player.rect.y)
                target_direction.scale_to_length(self._data.vel * 2)
                self.rect.x += target_direction.x
                self.rect.y += target_direction.y
            elif (self._charging > 1000):
                self._pausing = time.get_ticks() - self._pstart

            if (self._pausing) > 550:
                self._charging = 0
                self._pausing = 0
                self._start = time.get_ticks()

            screen_rect = screen.get_rect()

            self.rect.clamp_ip(screen_rect)

            self._data.pos = Vector2(self.rect.center)

            self._calc_rotation(player)

        except ValueError:
            return
Ejemplo n.º 15
0
    def __call__(self, bean1Grid, bean2Grid, playerGrid, obstacles,
                 designValues, decisionSteps):
        initialPlayerGrid = playerGrid
        reactionTime = list()
        trajectory = [initialPlayerGrid]
        results = co.OrderedDict()
        aimActionList = list()
        aimPlayerGridList = []
        leastStep = min([
            calculateGridDis(playerGrid, beanGrid)
            for beanGrid in [bean1Grid, bean2Grid]
        ])
        noiseStep = sorted(
            random.sample(list(range(1, leastStep)), designValues))

        stepCount = 0
        goalList = list()
        self.drawText("+", [0, 0, 0], [7, 7])
        pg.time.wait(1300)
        self.drawNewState(bean1Grid, bean2Grid, initialPlayerGrid, obstacles)
        pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT])

        realPlayerGrid = initialPlayerGrid
        pause = True
        initialTime = time.get_ticks()
        while pause:
            aimPlayerGrid, aimAction, isReactionTimely = self.controller(
                realPlayerGrid, bean1Grid, bean2Grid)
            reactionTime.append(time.get_ticks() - initialTime)
            goal = inferGoal(trajectory[-1], aimPlayerGrid, bean1Grid,
                             bean2Grid)
            goalList.append(goal)
            stepCount = stepCount + 1
            noisePlayerGrid, realAction = self.normalNoise(
                realPlayerGrid, aimAction, noiseStep, stepCount)
            if noisePlayerGrid in obstacles:
                noisePlayerGrid = tuple(trajectory[-1])
            realPlayerGrid = self.checkBoundary(noisePlayerGrid)
            trajectory.append(list(realPlayerGrid))
            aimActionList.append(aimAction)
            aimPlayerGridList.append(aimPlayerGrid)
            if isReactionTimely:
                self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid,
                                  obstacles)
                pause = checkTerminationOfTrial(bean1Grid, bean2Grid,
                                                realPlayerGrid)
            else:
                break
        pg.time.wait(500)
        pg.event.set_blocked([pg.KEYDOWN, pg.KEYUP])
        results["reactionTime"] = str(reactionTime)
        results["trajectory"] = str(trajectory)
        results["aimPlayerGridList"] = str(aimPlayerGridList)
        results["aimAction"] = str(aimActionList)
        results["noisePoint"] = str(noiseStep)
        results["goal"] = str(goalList)
        return results
Ejemplo n.º 16
0
    def __call__(self, bean1Grid, bean2Grid, playerGrid, obstacles):
        initialPlayerGrid = playerGrid
        reactionTime = list()
        trajectory = [initialPlayerGrid]
        results = co.OrderedDict()
        aimActionList = list()
        aimPlayerGridList = []
        firstIntentionFlag = False
        noiseStep = list()
        stepCount = 0
        goalList = list()
        self.drawText("+", [0, 0, 0], [7, 7])
        pg.time.wait(1300)
        self.drawNewState(bean1Grid, bean2Grid, initialPlayerGrid, obstacles)
        pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT])

        pause = True
        realPlayerGrid = initialPlayerGrid
        initialTime = time.get_ticks()
        while pause:
            aimPlayerGrid, aimAction, isReactionTimely = self.controller(
                realPlayerGrid, bean1Grid, bean2Grid)
            reactionTime.append(time.get_ticks() - initialTime)
            goal = inferGoal(realPlayerGrid, aimPlayerGrid, bean1Grid,
                             bean2Grid)
            goalList.append(goal)
            stepCount = stepCount + 1

            if len(trajectory) > 2:
                noisePlayerGrid, noiseStep, firstIntentionFlag = self.specialNoise(
                    trajectory, bean1Grid, bean2Grid, noiseStep,
                    firstIntentionFlag)
                if noisePlayerGrid:
                    realPlayerGrid = self.checkBoundary(noisePlayerGrid)
                else:
                    realPlayerGrid = self.checkBoundary(aimPlayerGrid)
            else:
                realPlayerGrid = self.checkBoundary(aimPlayerGrid)
            if realPlayerGrid in obstacles:
                realPlayerGrid = tuple(trajectory[-1])

            self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid, obstacles)
            trajectory.append(list(realPlayerGrid))
            aimActionList.append(aimAction)
            aimPlayerGridList.append(aimPlayerGrid)
            pause = checkTerminationOfTrial(bean1Grid, bean2Grid,
                                            realPlayerGrid)

        pg.time.wait(500)
        pg.event.set_blocked([pg.KEYDOWN, pg.KEYUP])
        results["reactionTime"] = str(reactionTime)
        results["trajectory"] = str(trajectory)
        results["aimPlayerGridList"] = str(aimPlayerGridList)
        results["aimAction"] = str(aimActionList)
        results["noisePoint"] = str(noiseStep)
        results["goal"] = str(goalList)
        return results
Ejemplo n.º 17
0
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface):
        if self._data.health <= 0:
            self.dead = True
            self.kill()

        if sprite.collide_mask(player,
                               self) is not None and not player.invulnerable:
            player.take_damage(1.5)
            self.take_damage(50)

        state = self._data.state
        if state is BossState.MOVEDOWN:
            target_direction = Vector2(0, 1)
            self._data.attack_speed = 2000
            self._calc_rotation(player)
            self.image.set_alpha(255)
            self._data.vel = 6
            self._weapon.fire(player, self._data.attack_speed, 10, self.rect)
            self._weapon.update()
            self.invulnerable_start = time.get_ticks()

        elif state is BossState.MOVEUP:
            target_direction = Vector2(0, -1)
            self._data.attack_speed = 2000
            self._calc_rotation(player)
            self.image.set_alpha(255)
            self._data.vel = 6
            self._weapon.fire(player, self._data.attack_speed, 10, self.rect)
            self._weapon.update()
            self.invulnerable_start = time.get_ticks()

        elif state is BossState.TRANSITION:
            target_direction = Vector2(0, 0)
            self._weapon = self.temp_weapon
            self._weapon.spawn()
            self._data.invulnerable = True
            self.image.set_alpha(100)
            self._set_enraged_image(ResourceContainer())

        elif state is BossState.ENRAGED:
            self._data.invulnerable = False
            target_direction = player._data.pos - self._data.pos
            target_direction = self._avoid_player(player, target_direction)
            self._data.attack_speed = 900
            self._calc_rotation(player)
            self.image.set_alpha(255)
            self._data.vel = 7
            self._weapon.fire(player, self._data.attack_speed, 20, self.rect,
                              3)
            self._weapon.update()

        if target_direction.length() != 0:
            target_direction.scale_to_length(self._data.vel)
        screen_rect = screen.get_rect()
        self._data.pos += target_direction
        self.rect = self.image.get_rect(center=self._data.pos)
        self.rect.clamp_ip(screen_rect)
 def continue_bgm(self):
     if not self.last_beat:
         self.bgm_index = 0
         self.music_channel.play(self.bgm[self.bgm_index])
         self.last_beat = time.get_ticks()
     elif abs(self.last_beat - time.get_ticks()) > self.music_interval and not self.music_channel.get_busy():
         self.bgm_index = (self.bgm_index + 1) % len(self.bgm)
         self.music_channel.play(self.bgm[self.bgm_index])
         self.last_beat = time.get_ticks()
Ejemplo n.º 19
0
    def render(self, shader):
        pygame.init()
        size = width, height = self.size
        screen_center = (size[0] / 2, size[1] / 2)
        fps = 60
        timer = 0
        screen = pygame.display.set_mode(size, DOUBLEBUF | OPENGL)
        pygame.mouse.set_visible(False)
        pygame.mouse.set_pos(screen_center)

        clock = pygame.time.Clock()

        program = glCreateProgram()

        fragment_shader = None

        fragment_shader = self.compile_shader(shader, GL_FRAGMENT_SHADER)
        glAttachShader(program, fragment_shader)

        glLinkProgram(program)

        if fragment_shader:
            glDeleteShader(fragment_shader)

        resID = glGetUniformLocation(program, "iResolution")
        mouseID = glGetUniformLocation(program, "iMouse")
        timeID = glGetUniformLocation(program, "iTime")

        glUseProgram(program)
        glUniform2fv(resID, 1, size)

        running = True
        pause = False
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_p:
                        pause = not pause
                    elif event.key == pygame.K_s:
                        pygame.image.save(screen, 'screenshot.png')
                    elif event.key == pygame.K_ESCAPE:
                        sys.exit(0)
            if not pause:
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
                glUniform1f(timeID, get_ticks() / 1000)
                m = pygame.mouse.get_pos()
                glUniform2fv(mouseID, 1, (m[0], height - m[1]))
                if get_ticks() - timer > 1000:
                    print('fps', round(clock.get_fps()))
                    timer = get_ticks()
                glRecti(-1, -1, 1, 1)
                clock.tick(fps)

                pygame.display.flip()
Ejemplo n.º 20
0
    def abrir(self, timeout = 2.0):
        self.crear()
        
        if self.init_time == 0:
            self.init_time = time.get_ticks()

        timeout =timeout*1000
        if time.get_ticks() - self.init_time > timeout:
            return True
        return False
Ejemplo n.º 21
0
 def virtual_status_change(self, power):
     from pygame.time import get_ticks
     if not self.opening_time:
         self.opening_time = get_ticks()
     self.opening = (get_ticks() - self.opening_time) * power
     if self.opening > self.hard:
         self.opening = 0
         self.opening_time = False
         self.passability = (self.passability + 1) % 2
         self.transparency = self.passability
Ejemplo n.º 22
0
def drawStage():
    global surface, numberBackgroundImage, lastBackgroundChange, stageToDraw
    if GAME_TIME.get_ticks() - timeToChangeBackground > lastBackgroundChange:
        lastBackgroundChange = GAME_TIME.get_ticks()
        numberBackgroundImage += 1
        numberBackgroundImage = numberBackgroundImage % len(stageToDraw)
    imageToDraw = stageToDraw[numberBackgroundImage]
    rect = imageToDraw.get_rect()
    rect.center = (WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
    surface.blit(imageToDraw, rect)
Ejemplo n.º 23
0
 def __init__(self, res_container: ResourceContainer, boss_data: BossData):
     super().__init__(res_container, boss_data, MultiShotWeapon)
     self.radius = 600
     self.flash = True
     self.health_bar = EnemyHealthBar(self._data.health, self.rect)
     self.pausing = 0
     self.charging = 0
     self.start = time.get_ticks()
     self.pstart = time.get_ticks()
     self.moved = False
Ejemplo n.º 24
0
    def __call__(self, bean1Grid, bean2Grid, playerGrid):
        initialPlayerGrid = playerGrid
        initialTime = time.get_ticks()
        reactionTime = list()
        trajectory = [initialPlayerGrid]
        results = co.OrderedDict()
        aimActionList = list()
        firstIntentionFlag = False
        noiseStep = list()
        stepCount = 0
        goalList = list()
        # self.drawNewState(bean1Grid, bean2Grid, initialPlayerGrid)

        avoidCommitmentZone = calculateAvoidCommitmnetZone(
            initialPlayerGrid, bean1Grid, bean2Grid)
        pause = True
        realPlayerGrid = initialPlayerGrid
        while pause:
            aimPlayerGrid, aimAction = self.controller(realPlayerGrid,
                                                       bean1Grid, bean2Grid,
                                                       self.goalRewardList)
            self.goalRewardList = rewardNoise(self.goalRewardList,
                                              self.variance)
            goal = inferGoal(trajectory[-1], aimPlayerGrid, bean1Grid,
                             bean2Grid)
            goalList.append(goal)
            stepCount = stepCount + 1

            if len(trajectory) > 1:
                noisePlayerGrid, noiseStep, firstIntentionFlag = self.backToZoneNoise(
                    realPlayerGrid, trajectory, avoidCommitmentZone, noiseStep,
                    firstIntentionFlag)
                # noisePlayerGrid, noiseStep, firstIntentionFlag = self.backToZoneNoiseNoLine(realPlayerGrid,bean1Grid, bean2Grid, trajectory, avoidCommitmentZone, noiseStep, firstIntentionFlag)

                if noisePlayerGrid:
                    realPlayerGrid = self.checkBoundary(noisePlayerGrid)
                else:
                    realPlayerGrid = self.checkBoundary(aimPlayerGrid)
            else:
                realPlayerGrid = self.checkBoundary(aimPlayerGrid)

            # self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid)
            reactionTime.append(time.get_ticks() - initialTime)
            trajectory.append(list(realPlayerGrid))
            aimActionList.append(aimAction)
            pause = checkTerminationOfTrial(bean1Grid, bean2Grid,
                                            realPlayerGrid)

        results["reactionTime"] = str(reactionTime)
        results["trajectory"] = str(trajectory)
        results["aimAction"] = str(aimActionList)
        results["noisePoint"] = str(noiseStep)
        results["goal"] = str(goalList)
        return results
Ejemplo n.º 25
0
 def attack(self):
     if(self.isInCar):
         return
     
     if self.attacking or time.get_ticks() < self.attack_delay + self.attack_end:
         return False
     
     self.attacking = True
     self.attack_start = time.get_ticks()
     self.current_image = self.attack_image
     return True
Ejemplo n.º 26
0
    def draw(self):
        if get_ticks() - self.old_time > self.interval:
            if self.n_renders:
                self.renders.append(self.n_renders.pop(0))
                self.old_time = get_ticks()

        self.renders = [r for r in self.renders if r.draw() is not None]

        if not len(self.renders):
            return None
        return True
Ejemplo n.º 27
0
def playing():
    global timeForEggs, WINDOW_WIDTH, alienPoints, humanoidPoints
    if (GAME_TIME.get_ticks() - TIMEBETWEENEGGS) >= timeForEggs:
        huevera.append(egg.egg())
        timeForEggs = GAME_TIME.get_ticks()
    for i, eachEgg in enumerate(huevera):
        eachEgg.draw(surface)
        if eachEgg.checkPosition([alien.getPos(), humanoid.getPos()], PLAYERDIMENSIONS) == 'alien':
            huevera.pop(i)
            alienPoints += 1
        if eachEgg.checkPosition([alien.getPos(), humanoid.getPos()], PLAYERDIMENSIONS) == 'humanoid':
            huevera.pop(i)
            humanoidPoints += 1
        if eachEgg.checkPosition([alien.getPos(), humanoid.getPos()], PLAYERDIMENSIONS) == 'alienParalyze':
            huevera.pop(i)
            alien.paralyze()
        if eachEgg.checkPosition([alien.getPos(), humanoid.getPos()], PLAYERDIMENSIONS) == 'humanoidParalyze':
            huevera.pop(i)
            humanoid.paralyze()
    alien.draw(surface, humanoid.getPos())
    humanoid.draw(surface, alien.getPos())

    # Para dibujar los puntos
    renderedText = textFont.render(str(alienPoints), 2, (255, 255, 255))
    surface.blit(renderedText, (50, 50))
    renderedText = textFont.render(str(humanoidPoints), 2, (255, 255, 255))
    surface.blit(renderedText, (WINDOW_WIDTH - 90, 50))

    # Controles del alien
    if aPressed:
        alien.move(WINDOW_WIDTH, WINDOW_HEIGHT, 'left')
    elif dPressed:
        alien.move(WINDOW_WIDTH, WINDOW_HEIGHT, 'right')
    else:
        alien.move(WINDOW_WIDTH, WINDOW_HEIGHT)
    if wPressed:
        alien.jump()
    if sPressed:
        alien.shoot()
    # Controles Humanoide
    if leftPressed:
        humanoid.move(WINDOW_WIDTH, WINDOW_HEIGHT, 'left')
    elif rightPressed:
        humanoid.move(WINDOW_WIDTH, WINDOW_HEIGHT, 'right')
    else:
        humanoid.move(WINDOW_WIDTH, WINDOW_HEIGHT)
    if upPressed:
        humanoid.jump()
    if downPressed:
        humanoid.shoot()
    if alien.harm():
        humanoid.paralyze()
    if humanoid.harm():
        alien.paralyze()
Ejemplo n.º 28
0
 def continue_bgm(self):
     if not self.last_beat:  # Music just started, initialize markers
         self.bgm_index = 0
         self.music_channel.play(self.bgm[self.bgm_index])
         self.last_beat = time.get_ticks()
     elif abs(self.last_beat - time.get_ticks()
              ) > self.music_interval and not self.music_channel.get_busy():
         # Music continuing
         self.bgm_index = (self.bgm_index + 1) % len(self.bgm)
         self.music_channel.play(self.bgm[self.bgm_index])
         self.last_beat = time.get_ticks()
    def __call__(self, bean1Grid, bean2Grid, playerGrid, obstacles, QDict):
        initialPlayerGrid = tuple(playerGrid)
        initialTime = time.get_ticks()
        reactionTime = list()
        trajectory = [initialPlayerGrid]
        results = co.OrderedDict()
        aimActionList = list()
        aimPlayerGridList = []
        firstIntentionFlag = False
        noiseStep = list()
        stepCount = 0
        goalList = list()

        pause = True
        realPlayerGrid = initialPlayerGrid
        while pause:
            if self.renderOn:
                self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid,
                                  obstacles)
            aimPlayerGrid, aimAction = self.controller(realPlayerGrid,
                                                       bean1Grid, bean2Grid,
                                                       QDict)
            goal = inferGoal(realPlayerGrid, aimPlayerGrid, bean1Grid,
                             bean2Grid)
            goalList.append(goal)
            stepCount = stepCount + 1

            if len(trajectory) > 3:
                noisePlayerGrid, noiseStep, firstIntentionFlag = self.specialNoise(
                    trajectory, bean1Grid, bean2Grid, noiseStep,
                    firstIntentionFlag)
                if noisePlayerGrid:
                    realPlayerGrid = self.checkBoundary(noisePlayerGrid)
                else:
                    realPlayerGrid = self.checkBoundary(aimPlayerGrid)
            else:
                realPlayerGrid = self.checkBoundary(aimPlayerGrid)
            if realPlayerGrid in obstacles:
                realPlayerGrid = tuple(trajectory[-1])
            reactionTime.append(time.get_ticks() - initialTime)
            trajectory.append(list(realPlayerGrid))
            aimActionList.append(aimAction)
            aimPlayerGridList.append(aimPlayerGrid)
            pause = checkTerminationOfTrial(bean1Grid, bean2Grid,
                                            realPlayerGrid)

        results["reactionTime"] = str(reactionTime)
        results["trajectory"] = str(trajectory)
        results["aimAction"] = str(aimActionList)
        results["aimPlayerGridList"] = str(aimPlayerGridList)
        results["noisePoint"] = str(noiseStep)
        results["goal"] = str(goalList)
        return results
Ejemplo n.º 30
0
 def check(self, field):
     if self.hexagon:
         from bin.Logic import coord_get_offset
         coord = coord_get_offset(self.hexagon, field)
         if field.map[coord[0]][coord[1]][1].exploration:
             self.hexagon = False
     if get_ticks() - self.find_time >= self.mob.stats.find_time:
         return 8
     if get_ticks() - self.path_time >= self.mob.stats.path_time:
         self.path_time = get_ticks()
         self.hexagon = False
     return True
Ejemplo n.º 31
0
 def update(self):
     touch_floor = False
     for rect in self.floor:
         if self.rect.bottom >= rect.top:
             self.rect.bottom = rect.top
             touch_floor = True
             break
     if abs(self.last_jump -
            time.get_ticks()) > self.jump_interval and touch_floor:
         self.jump()
         self.last_jump = time.get_ticks()
     super(StarMan, self).update()
Ejemplo n.º 32
0
 def __call__(self, bean1Grid, bean2Grid, playerGrid):
     initialPlayerGrid = playerGrid
     initialTime = time.get_ticks()
     reactionTime = list()
     actionList = list()
     goalList = list()
     trajectory = [initialPlayerGrid]
     pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT])
     results = co.OrderedDict()
     self.drawNewState(bean1Grid, bean2Grid, initialPlayerGrid)
     stepCount = 0
     playerGrid, action = self.controller(bean1Grid, bean2Grid, playerGrid)
     goal = inferGoal(trajectory[-1], playerGrid, bean1Grid, bean2Grid)
     goalList.append(goal)
     eatenFlag = self.checkEaten(bean1Grid, bean2Grid, playerGrid)
     realPlayerGrid = self.checkBoundary(playerGrid)
     self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid)
     reactionTime.append(time.get_ticks() - initialTime)
     trajectory.append(list(realPlayerGrid))
     actionList.append(action)
     stepCount = stepCount + 1
     pause = self.checkTerminationOfTrial(action, eatenFlag)
     while pause:
         playerGrid, action = self.controller(bean1Grid, bean2Grid,
                                              realPlayerGrid)
         goal = inferGoal(trajectory[-1], playerGrid, bean1Grid, bean2Grid)
         goalList.append(goal)
         eatenFlag = self.checkEaten(bean1Grid, bean2Grid, playerGrid)
         realPlayerGrid = self.checkBoundary(playerGrid)
         self.drawNewState(bean1Grid, bean2Grid, realPlayerGrid)
         reactionTime.append(time.get_ticks() - reactionTime[-1])
         trajectory.append(list(realPlayerGrid))
         actionList.append(action)
         stepCount = stepCount + 1
         pause = self.checkTerminationOfTrial(action, eatenFlag)
     pg.event.set_blocked([pg.KEYDOWN, pg.KEYUP])
     results["bean1GridX"] = bean1Grid[0]
     results["bean1GridY"] = bean1Grid[1]
     results["bean2GridX"] = bean2Grid[0]
     results["bean2GridY"] = bean2Grid[1]
     results["playerGridX"] = initialPlayerGrid[0]
     results["playerGridY"] = initialPlayerGrid[1]
     results["reactionTime"] = str(reactionTime)
     results["trajectory"] = str(trajectory)
     results["aimAction"] = str(actionList)
     results["goal"] = str(goalList)
     if True in eatenFlag:
         results["beanEaten"] = eatenFlag.index(True) + 1
         oldGrid = eval('bean' + str(eatenFlag.index(False) + 1) + 'Grid')
     else:
         results["beanEaten"] = 0
         oldGrid = None
     return results, oldGrid, playerGrid
Ejemplo n.º 33
0
 def get_image(self):
     # gets current image in the animation
     next_frame = abs(self.last_frame - time.get_ticks()) > self.frame_delay
     if next_frame and self.repeat:
         self.image_index = (self.image_index + 1) % len(self.images)
         self.last_frame = time.get_ticks()
     elif next_frame and not self.image_index >= len(self.images) - 1:
         self.image_index += 1
         self.last_frame = time.get_ticks()
     elif next_frame and not self.repeat:
         self.done = True
     return self.images[self.image_index]
Ejemplo n.º 34
0
 def update(self):
     """ Change the opacity based on the active effect. """
     if self.fadeout_active:
         self.opacity = 1 - (get_ticks() - self.fadeout_start) / 500
         if self.opacity <= 0:
             self.opacity = 0
             self.fadeout_active = False
     elif self.fadein_active:
         self.opacity = (get_ticks() - self.fadein_start) / 500
         if self.opacity >= 1:
             self.opacity = 1
             self.fadein_active = False
Ejemplo n.º 35
0
def drawTitle():
    global titleImage, timeForTitle, timeBetweenOff
    time = GAME_TIME.get_ticks()-timeForTitle
    if time <= timeBetweenOff:
        for state in LIGHTCHANGES:
            if time > state[0]:
                imageToDraw = titleImage[state[1]]
    else:
        imageToDraw = titleImage[0]
        timeForTitle = GAME_TIME.get_ticks()
        timeBetweenOff = random.randint(1500, 10000)  # El tiempo entre cada parpadeo
    surface.blit(imageToDraw, (100, 200))
Ejemplo n.º 36
0
 def check(self, field):
     if self.hexagon:
         from bin.Logic import coord_get_offset
         coord = coord_get_offset(self.hexagon, field)
         if field.map[coord[0]][coord[1]][1].exploration:
             self.hexagon = False
     if get_ticks() - self.find_time >= self.mob.stats.find_time:
         return 8
     if get_ticks() - self.path_time >= self.mob.stats.path_time:
         self.path_time = get_ticks()
         self.hexagon = False
     return True
Ejemplo n.º 37
0
 def going(self, field, path):
     if get_ticks() - self.step_time >= self.mob.stats.step_time:
         from bin.Logic import coord_get_offset
         coord = coord_get_offset(path, field)
         if not field.map[coord[0]][coord[1]][1].passability:
             field.map[coord[0]][coord[1]][1].virtual_status_change(1)
         else:
             from bin.Logic import hex_visible_false
             hex_visible_false(field, self.mob.coord, self.mob.stats.view_radius)
             self.mob.going(field, path)
             self.step_time = get_ticks()
     return True
Ejemplo n.º 38
0
 def update(self, field):
     from pygame.time import get_ticks
     if get_ticks() - self.merge >= self.mob.stats.merge_time:
         status = self.main_merger()
         if status == 1:
             self.mob.health += 1
             self.communication.health -= 1
         elif status == 0:
             self.mob.health -= 1
             self.communication.health += 1
         self.merge = get_ticks()
     return True
Ejemplo n.º 39
0
 def continue_bgm(self):
     """Create the background music by playing sound over the music channel"""
     if not self.last_beat:  # Music just started, initialize markers
         self.bgm_index = 0
         self.music_channel.play(self.bgm[self.bgm_index])
         self.last_beat = time.get_ticks()
     elif abs(self.last_beat - time.get_ticks()
              ) > self.music_interval and not self.music_channel.get_busy():
         # Music continuing
         self.bgm_index = (self.bgm_index + 1) % len(self.bgm)
         self.music_channel.play(self.bgm[self.bgm_index])
         self.last_beat = time.get_ticks()
Ejemplo n.º 40
0
    def update(self):
        if self.running:
            if keyboard.right:
                self.cannon.move_right()
            elif keyboard.left:
                self.cannon.move_left()
          
            if keyboard.space:
                if get_ticks() - self.cannon.last_fire > self.cannon.firing_interval:
                    self.bullets.append(Bullet('bullet', self.cannon.pos))
                    sounds.shot.play()
                    self.cannon.last_fire = get_ticks()      

            for bullet in self.bullets[:]:
                bullet.update()
                if bullet.is_dead():
                    self.bullets.remove(bullet)
            
            for alien in self.aliens[:]:
                alien.update()
                if self.cannon.colliderect(alien):
                    self.explosions.append(Explosion('cannon_explosion', self.cannon.pos))
                    sounds.explosion.play()
                    self.running = False
                if alien.bottom >= HEIGHT:
                    self.running = False
                for bullet in self.bullets[:]:
                    if alien.colliderect(bullet):
                        alien.lives -= 1
                        if alien.is_dead():
                            self.explosions.append(Explosion('alien_explosion', alien.pos))
                            sounds.explosion.play()
                            self.aliens.remove(alien)
                            self.score += ALIEN_KILL_SCORE
                        self.bullets.remove(bullet)                
            
            for explosion in self.explosions[:]:
                explosion.update()
                if explosion.is_finished():
                    self.explosions.remove(explosion)
            
            if len(self.aliens) == 0 and len(self.explosions) == 0:
                self.game.set_game_over_message("YOU WON!!!!!", "#00FFFF")
                self.game.change_scene(GAME_OVER_SCENE)
                
        else:
            for explosion in self.explosions[:]:
                explosion.update()
                if explosion.is_finished():
                    self.explosions.remove(explosion)
            if len(self.explosions) == 0:
                self.game.set_game_over_message("YOU LOST...", "red")
                self.game.change_scene(GAME_OVER_SCENE)
Ejemplo n.º 41
0
    def attack(self):
        if (self.isInCar):
            return

        if self.attacking or time.get_ticks(
        ) < self.attack_delay + self.attack_end:
            return False

        self.attacking = True
        self.attack_start = time.get_ticks()
        self.current_image = self.attack_image
        return True
Ejemplo n.º 42
0
    def draw(self):
        if not self.is_jumping:
            Player.draw(self)
            return
        
        if time.get_ticks() < self.last_jump + self.jump_init_time:
            self.current_image = self.jump_images[0]
        elif time.get_ticks() < self.last_jump + self.jump_time - self.jump_init_time:
            self.current_image = self.jump_images[1]
        elif time.get_ticks() < self.last_jump + self.jump_time:
            self.current_image = self.jump_images[2]

        Player.draw(self)
Ejemplo n.º 43
0
def _foo(e):
    global _Clic,_Ticks
    if e.type==MOUSEBUTTONDOWN:
        t = time.get_ticks()
        if e.button!=_Clic[0] or t-_Ticks[e.button]>LAPS: _Clic=[e.button,0,0,0,0,0]
        _Ticks[e.button] = t
    elif e.type==MOUSEBUTTONUP:
        t = time.get_ticks()
        if t-_Ticks[e.button]>LAPS: _Clic=[e.button,0,0,0,0,0]
        else:
            _Clic[e.button]+=1
            _Ticks[e.button] = t
        e.dict.update({'click':_Clic})
Ejemplo n.º 44
0
 def going(self, field, path):
     if get_ticks() - self.step_time >= self.mob.stats.step_time:
         from bin.Logic import coord_get_offset
         coord = coord_get_offset(path, field)
         if not field.map[coord[0]][coord[1]][1].passability:
             field.map[coord[0]][coord[1]][1].virtual_status_change(1)
         else:
             from bin.Logic import hex_visible_false
             hex_visible_false(field, self.mob.coord,
                               self.mob.stats.view_radius)
             self.mob.going(field, path)
             self.step_time = get_ticks()
     return True
Ejemplo n.º 45
0
def level_intro(ai_settings, screen, stats):
    if stats.is_game_active:
        level_text = Title(ai_settings.bg_color, screen,
                           'Level: ' + str(stats.level))
        level_text.prep_image()
        level_text.image_rect.centerx = (ai_settings.screen_width // 2)
        level_text.image_rect.centery = (ai_settings.screen_height //
                                         2) - level_text.image_rect.height
        start_time = time.get_ticks()
        while abs(start_time - time.get_ticks()) <= 1500:
            screen.fill(ai_settings.bg_color)
            level_text.blitme()
            display.flip()
Ejemplo n.º 46
0
	def transmit(self):
		#Transmit data to empty tx buffer, but for no longer than TIMEOUT. 
		start = time.get_ticks()
		while len(self.tx) and ((time.get_ticks() - start) < TIME_WRITE): #Transmit for no longer than timeout
			#Keep statistics on transmission data rate.
			self.txData.append(len(self.tx[0]))
			self.txTime.append(time.get_ticks())
		
			print '#' + self.tx[0],
			self.ser.write(self.tx.popleft())
				
		self.txRate = 1000 * sum(self.txData) / (self.txTime[-1]-self.txTime[0])
		self.rxRate = 1000 * sum(self.rxData) / (self.rxTime[-1]-self.rxTime[0])
Ejemplo n.º 47
0
def run_trial(trial_pars, subj_info, data_file):
    ''' Run a single trial.

    trial_pars -- a list specifying trial parameters,
                  [cue_pos, tar_pos, isi, cueing, cor_key]
    subj_info -- info about the subject [id, name, age]
    data_file -- an open file to save the trial data.'''

    # Show the fixation then wait for 1000 ms
    draw_frame('fix', trial_pars)
    time.wait(1000)

    # Show the cue for 100 ms
    draw_frame('cue', trial_pars)
    time.wait(100)

    # Inter-stimulus interval (ISI)
    draw_frame('fix', trial_pars)
    time.wait(trial_pars[2])

    # Show the target and register a keypress response
    draw_frame('target', trial_pars)
    tar_onset = time.get_ticks()
    tar_resp = -32768  # response time
    resp_key = -32768  # key pressed

    # Check for key presses
    time_out = False
    got_key = False
    event.clear()  # clear bufferred events
    while not (time_out or got_key):
        # Cehck for time out (1500 ms)
        if time.get_ticks() - tar_onset > 1500:
            time_out = True

        # Check if any key has been pressed
        for ev in event.get():
            if ev.type == KEYDOWN:
                if ev.key in [K_z, K_SLASH]:
                    tar_resp = time.get_ticks()
                    resp_key = key.name(ev.key)
                    got_key = True

    # write data to file
    trial_data = subj_info + trial_pars + [tar_onset, tar_resp, resp_key]
    trial_data = map(str, trial_data)
    data_file.write(','.join(trial_data) + '\n')

    # ITI (inter-trial_interval)
    draw_frame('fix', trial_pars)
    time.wait(1500)
Ejemplo n.º 48
0
def loop():
    clock = PT.Clock()
    leftover = 0.0
    updates = 0
    up = 0
    isPlayingMenu = False
    isPlaying = False
    while Globals.RUNNING:
        if not isPlayingMenu:
            if Globals.ISMAINMENU:
                Globals.MENU_MUSIC.set_volume(Globals.VOLUME/200.0)
                Globals.MENU_MUSIC.play(-1)
                isPlayingMenu = True
        else:
            if not Globals.ISMAINMENU:
                isPlayingMenu = False

        if not isPlaying:
            if Globals.ISLEVELONE:
                Globals.MUSIC.set_volume(Globals.VOLUME/200.0)
                print 'playing'
                Globals.MUSIC.play(-1)
                isPlaying = True
        else:
            
            if not Globals.ISLEVELONE:
                Globals.MUSIC.stop()
        
        start_time = PT.get_ticks()
        Globals.STATE.render()
        if Globals.BRIGHTNESS < 0:
            Globals.brightness.fill((0, 0, 0))
            Globals.brightness.set_alpha(-1 * Globals.BRIGHTNESS/100.0 * 100)
            Globals.SCREEN.blit(Globals.brightness, (0, 0))
        elif Globals.BRIGHTNESS > 0:
            Globals.brightness.fill((255, 255, 255))
            Globals.brightness.set_alpha(Globals.BRIGHTNESS/100.0 * 100)
            Globals.SCREEN.blit(Globals.brightness, (0, 0))
        PDI.flip()
        updates = 0
        clock.tick(60)
        last = PT.get_ticks()
        elapsed = (last - start_time) / 1000.0
        Globals.STATE.update(elapsed)
        leftover += elapsed
        for event in PE.get():
            if event.type == PG.QUIT:
                Globals.RUNNING = False
            else:
                Globals.STATE.event(event)
Ejemplo n.º 49
0
 def checkImpact(self, grid):
     # Hit top
     if self.body[0][0] <= 0:
         if self.direction == Direction.up and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
             self.hit = True
     # Hit bottom
     if self.body[0][0] >= grid.blocksInCol:
         if self.direction == Direction.down and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
             self.hit = True
     # Hit left
     if self.body[0][1] <= 0:
         if self.direction == Direction.left and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
             self.hit = True
     # Hit right
     if self.body[0][1] >= grid.blocksInRow:
         if self.direction == Direction.right and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
             self.hit = True
     # check if snake hit itself
     for i in range(len(self.body)):
         # hit from the top ==> if colHead == colBB and rowHead + 1 == rowBB and direction == down and time limit reached
         if self.body[0][1] == self.body[i][1] and self.body[0][0] + 1 == self.body[i][0]:
             if self.direction == Direction.down and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
                 self.hit = True
         # hit from the bottom ==> if colHead == colBB and rowHead - 1 == rowBB and direction == up and time limit reached
         elif self.body[0][1] == self.body[i][1] and self.body[0][0] - 1 == self.body[i][0]:
             if self.direction == Direction.up and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
                 self.hit = True
         # hit from the left ==> if rowHead == rowBB and colHead + 1 == colBB and direction == right and time limit reached
         elif self.body[0][0] == self.body[i][0] and self.body[0][1] + 1 == self.body[i][1]:
             if self.direction == Direction.right and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
                 self.hit = True
         # hit from the right ==> if rowHead == rowBB and colHead - 1 == colBB and direction == left and time limit reached
         elif self.body[0][0] == self.body[i][0] and self.body[0][1] - 1 == self.body[i][1]:
             if self.direction == Direction.left and GAME_TIME.get_ticks() - self.lastMove >= self.refreshFreq:
                 self.hit = True
Ejemplo n.º 50
0
 def update(self, field):
     if not self.hexagon:
         from bin.Logic import unexplored_finding
         self.hexagon = unexplored_finding(self.mob.coord, field, self.avoid)
         self.step_time = get_ticks()
     else:
         from bin.Logic import ex_path_finding
         self.find_time = get_ticks()
         path = ex_path_finding(self.mob.coord, self.hexagon, field, self.avoid)
         if path:
             self.path_time = get_ticks()
             self.going(field, path)
         else:
             self.step_time = get_ticks()
     return True
Ejemplo n.º 51
0
def _foo(l,e):
    global _Clic,_Ticks
    if e.type==MOUSEBUTTONDOWN:
        t = time.get_ticks()
        if e.button!=_Clic[0] or t-_Ticks[e.button]>200: _Clic=[e.button,0,0,0,0,0]
        _Ticks[e.button] = t
    elif e.type==MOUSEBUTTONUP:
        t = time.get_ticks()
        if t-_Ticks[e.button]>200: _Clic=[e.button,0,0,0,0,0]
        else:
            _Clic[e.button]+=1
            _Ticks[e.button] = t
        e.dict.update({'clic':_Clic})
    if e.type in (MOUSEBUTTONDOWN,MOUSEBUTTONUP) and  hasattr(l._Last_over,'wakeup'): l._Last_over.wakeup(e)
    else: process(l,e)
Ejemplo n.º 52
0
 def going(self, field):
     from pygame.time import get_ticks
     from bin.Logic import path_finding
     self.path = path_finding(self.mob.coord, self.strike.coord, field, self.avoid)
     if self.path and get_ticks() - self.step >= self.mob.stats.step_time:
         from bin.Logic import coord_get_offset
         hexagon = self.path[0]
         coord = coord_get_offset(hexagon, field)
         if not field.map[coord[0]][coord[1]][1].passability:
             field.map[coord[0]][coord[1]][1].virtual_status_change(1)
         else:
             self.path = self.path[1:]
             self.mob.going(field, hexagon)
             self.step = get_ticks()
     return True
Ejemplo n.º 53
0
    def update(self):
        
        self.tick = get_ticks()
        delta = self.tick - self.last_tick

        if self.slow_motion_delay > 0:
            self.slow_motion_delay -= 1

            if self.slow_motion_delay <= 0:
                self.frecuency = self.normal_frecuency


        if delta > self.frecuency:
            skips = delta / self.frecuency

            if skips > self.maxframeskip:
                skips = self.maxframeskip
                self.last_tick = self.tick
            else:
                self.last_tick += skips * self.frecuency

            self._update_status()
            return skips
        else:
            wait(1)
            return 0
Ejemplo n.º 54
0
 def __exit__(self, extype, exception, traceback):
     # Check exception type
     if extype is SystemExit:
         safe_exit()
     # Compute delta
     delta = self.enter_time + self.arg_ms - time.get_ticks()
     # Handle case delta == 0
     delta += not delta
     # Validate delta with sign of the argument
     delta *= self.arg_ms >= 0
     # Return if no need to wait
     if delta < 0:
         return
     # Prepare timer event
     custom_event = pyg.USEREVENT + 1
     clock = time.Clock()
     pyg.event.get()
     time.set_timer(custom_event, delta)
     # Game loop
     while True:
         for ev in pyg.event.get():
             if ev.type == pyg.QUIT or \
               (ev.type == pyg.KEYDOWN and ev.key == pyg.K_ESCAPE):
                 safe_exit()
             if ev.type in [custom_event, pyg.JOYBUTTONDOWN, pyg.KEYDOWN]:
                 time.set_timer(custom_event, 0)
                 return pyg.event.post(ev)
         clock.tick(FPS)
Ejemplo n.º 55
0
    def __init__(self, game, name, slides, press_enter):
        '''
        Slides is an array list of strings (the files that make up the slides).
        '''
        self.name = name
        
        self.images = slides #[image_util.load_image(slide)for slide in slides]
        self.slide = 0
        self.done = False
        self.game = game
        self.clock = pygame.time.Clock()
        self.screen = game.screen
        
        self.press_enter = press_enter
        self.current_press_enter_index = 0
        self.start_time = time.get_ticks()
        self.last_change = self.start_time
        self.wait_time = 200
        
        self.game = game
        
        #self.soundUtil.LoadSound('jungle.wav', "jungle")
        #self.soundUtil.PlaySound("jungle")
        
        #if not pygame.mixer: print 'Warning, sound disabled'

        self.pressed = []
        for key in pygame.key.get_pressed():
            self.pressed.append( True )
Ejemplo n.º 56
0
def shed_it():
    shed_lock.acquire()
    global shed_id
    shed_id = this_id = thread.get_ident()
    while shed_dict:
        t,proc = min(zip(shed_dict.values(),shed_dict.keys()))
        if t-time.get_ticks() <= 0:
            new_t = proc()
            if not new_t: del(shed_dict[proc])
            elif proc in shed_dict: shed_dict[proc] = new_t + t
        else:
            shed_lock.release()
            time.wait(t-time.get_ticks())
            if this_id != shed_id: break
            shed_lock.acquire()
    if this_id == shed_id: shed_lock.release()
Ejemplo n.º 57
0
 def _transition_out(self):
     ''' Transitions out of a game into the transition screen.'''
     self.game.stop()
     self.game = None
     self.timeSinceLast = get_ticks()
     self.count = self.count + 1
     self._load_thumbnail()
Ejemplo n.º 58
0
 def update(self, events):
     self._process_events(events)
     if self.lives < 0:
         self.finished = True
     elif self.game:
         self.game.update(events)
         if self.game.finished:
             if not self.game.winner:
                 self.lives = self.lives - 1
             self._transition_out()
         elif get_ticks() > self.timeSinceLast +  \
                            self.game.get_timelimit() * 1000:
             self.game.finished = True
     else:
         if get_ticks() > self.timeSinceLast + WAIT_PERIOD:
             self._transition_in()