コード例 #1
0
    def __init__(self,
                 learning=True,
                 epsilon=1,
                 alpha=0.1,
                 discount=1,
                 tolerance=0.01):

        self.Q = dict()
        self.Q1 = dict()
        self.Q2 = dict()

        self.s = states.States()
        self.s.buildAllStates()

        self.cnn = Cnn()

        self.learning = learning
        self.epsilon = epsilon
        self.alpha = alpha
        self.discount = discount
        self.tolerance = tolerance
        self.t = 2

        self.convolutionLayersNumber = 0
        self.poolingLayersNumber = 0
        self.fullyConnectedLayersNumber = 0

        self.convolutionLayersLimit = 3
        self.poolingLayersLimit = 2
        self.fullyConnectedLayersLimit = 2

        self.actionsInitialState()
        self.actionsConvolutionState()
        self.actionsPoolingState()
        self.actionsFullyConnectedState()
コード例 #2
0
class Message (BaseObject, pygame.sprite.Sprite):
    font = None
    states = states.States('displaying', 'finished')
    state = None
    message_count = None
    verticle_padding = 5
    
    def __init__ (self, manager, message, display_duration=3500, font_path='./fonts/'):
        BaseObject.__init__(self)
        pygame.sprite.Sprite.__init__(self)
        
        if Message.font == None:
            # Bitstream Vera Sans Mono
            Message.font = pygame.font.Font(font_path+'VeraMoBd.ttf', 12)
            
        # Increment the number of messages being displayed
        if Message.message_count == None:
            Message.message_count = 0
        else:
            Message.message_count += 1
            
        # Basically a duplication of damage animation - damage animation should probably be derived from this
        self.manager = manager
        
        shadow_offset = 3
        text = Message.font.render(message, True, (200,200,200)).convert_alpha()
        shadow = Message.font.render(message, True, (50,50,50)).convert_alpha()
        
        self.image = pygame.surface.Surface(
            (text.get_width() + shadow_offset,  text.get_height() + shadow_offset), 0, 32).convert_alpha()
        self.image.fill((0,0,0,0))
        self.image.blit(shadow, (shadow_offset, shadow_offset))
        self.image.blit(text, (0, 0))
        
        display_geometery = pygame.display.get_surface().get_rect()
        x = (display_geometery.width - self.image.get_width()) / 2
        y = (display_geometery.height - self.image.get_height()) / 2 + (self.image.get_height() * (Message.message_count-1))
        
        self.rect = pygame.rect.Rect(x, y, self.image.get_width(), self.image.get_height())
        
        self.display_duration = float(display_duration)        
        self.state = self.states.displaying
        
        self.timestamp = pygame.time.get_ticks()

        self.emit(constants.EVENT_ENTITY_WAIT, 0)
        
    def update (self, ticks):
        if self.state == self.states.displaying:
            if ticks > self.timestamp + self.display_duration:
                self.state = self.states.finished
                # Decrement the number of messages being displayed
                Message.message_count -= 1
                # Clean up
                self.emit(constants.EVENT_ENTITY_READY, 0)
                self.destroy()
                self.kill()
コード例 #3
0
class LaserBlast(BaseObject, pygame.sprite.Sprite):
    states = states.States('idle', 'animating')
    state = None

    def __init__(self, manager, weapon, source_position, destination_position):
        BaseObject.__init__(self)
        pygame.sprite.Sprite.__init__(self)

        self.manager = manager

        self.weapon = weapon
        self.weapon.duration = float(
            self.weapon.duration)  # ensure we are using floats
        self.padding = self.weapon.width

        self.source_position = source_position
        self.destination_position = destination_position

        self.idle_image = pygame.surface.Surface((0, 0))
        self.image = self.idle_image
        self.rect = pygame.rect.Rect(self.source_position[0],
                                     self.source_position[1],
                                     self.image.get_width(),
                                     self.image.get_height())

        self.framecount = 0
        self.frameskip = 2

        # Prerender the laser
        self.draw_laser()

        # Start animation
        self.current_pulse = 0
        self.image = self.laser_image
        self.rect = self.laser_rect
        self.timestamp = pygame.time.get_ticks()
        self.state = self.states.animating

        self.emit(constants.EVENT_ENTITY_WAIT, self)

    def draw_laser(self):

        # determin width
        xwidth = (self.destination_position[0] - self.source_position[0])
        ywidth = (self.destination_position[1] - self.source_position[1])

        # alter width for padding
        if xwidth < 0:
            xwidth -= self.padding * 2
        else:
            xwidth += self.padding * 2

        if ywidth < 0:
            ywidth -= self.padding * 2
        else:
            ywidth += self.padding * 2

        # Create the laser alpha channel surface
        tmp_image = pygame.surface.Surface(
            (abs(xwidth), abs(ywidth))).convert_alpha()
        tmp_image.fill((0, 0, 0))

        self.laser_rect = tmp_image.get_rect()

        # reorganise position variables depending on which quater we are in, also update our rect
        if xwidth > 0:
            if ywidth > 0:
                pos0 = [self.padding, self.padding]
                pos1 = [
                    self.laser_rect.width - self.padding,
                    self.laser_rect.height - self.padding
                ]
                self.laser_rect.move_ip(
                    (self.source_position[0] - self.padding,
                     self.source_position[1] - self.padding))
            else:
                pos0 = [self.laser_rect.width - self.padding, self.padding]
                pos1 = [self.padding, self.laser_rect.height - self.padding]
                self.laser_rect.move_ip(
                    (self.source_position[0] - self.padding,
                     self.destination_position[1] - self.padding))
        else:
            if ywidth > 0:
                pos0 = [self.laser_rect.width - self.padding, self.padding]
                pos1 = [self.padding, self.laser_rect.height - self.padding]
                self.laser_rect.move_ip(
                    (self.destination_position[0] - self.padding,
                     self.source_position[1] - self.padding))
            else:
                pos0 = [self.padding, self.padding]
                pos1 = [
                    self.laser_rect.width - self.padding,
                    self.laser_rect.height - self.padding
                ]
                self.laser_rect.move_ip(
                    (self.destination_position[0] - self.padding,
                     self.destination_position[1] - self.padding))

        # Draw laser
        pygame.draw.line(tmp_image, (255, 255, 255), pos0, (pos1[0], pos1[1]),
                         self.weapon.width)

        # Blur surface (this will be a gaussian blur later and facilitate a less-poor looking beam)
        utility.blur_surface(tmp_image)
        utility.blur_surface(tmp_image)
        utility.blur_surface(tmp_image)

        tmp_array = pygame.surfarray.array3d(tmp_image)

        self.laser_image = tmp_image
        self.laser_image.fill(self.weapon.color)

        # cheap gradient, need to change this into a LUT of some kind
        w = self.weapon.width
        tm = (255 / w)
        color = (self.weapon.color[0], self.weapon.color[1],
                 self.weapon.color[2])
        while w > 0:
            color = (min(255, color[0] + tm), min(255, color[1] + tm),
                     min(255, color[2] + tm))
            pygame.draw.line(self.laser_image, color, pos0, (pos1[0], pos1[1]),
                             w)
            w -= 1

        pygame.surfarray.pixels_alpha(self.laser_image)[:, :] = tmp_array[:, :,
                                                                          0]

        # Record of original alpha for blending
        self.laser_alpha = pygame.surfarray.array_alpha(
            self.laser_image.copy().convert_alpha())

        #print self.laser_alpha, self.laser_image, self.laser_rect

    def update(self, ticks):
        if self.state == self.states.animating:
            self.framecount += 1
            if self.framecount < self.frameskip:
                return
            self.framecount = 0
            n = min(1, (ticks - self.timestamp) / self.weapon.duration)
            # Alpha fade
            pygame.surfarray.pixels_alpha(self.image)[:, :] = Numeric.multiply(
                self.laser_alpha, 1 - n).astype(Numeric.UInt8)
            if n == 1:
                # Loop
                if self.current_pulse < self.weapon.pulse:
                    self.current_pulse += 1
                    self.timestamp = ticks
                else:
                    # Complete animation
                    self.state = self.states.idle
                    # Clean up
                    self.emit(constants.EVENT_ENTITY_READY, self)
                    self.destroy()
                    self.kill()
コード例 #4
0
from connector.NeuroskyConnector import NeuroskyConnector
from bluetooth.btcommon import BluetoothError
from neurosky.parser import ThinkGearParser, TimeSeriesRecorder
import wink, states
from Talk import Talk
import sys
from nnet.A4NN import A4NN

conn = NeuroskyConnector()
socket = conn.getConnectionInstance()
recorder = TimeSeriesRecorder()
parser = ThinkGearParser(recorders=[recorder])

w = wink.Wink()
s = states.States()
t = Talk()
net = A4NN()
net.train()
test_dataset = [
    87, 87, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 107, 107, 107, 107, 107,
    107, 167, 247, 55, 29, 59, 59, 29, 29, 29, 129, 129, 129, 129, 307, 309,
    92, 37, 60, 72, 75, 97
]
result = net.predict(test_dataset)
print("test-set validation.  Expected: ~0 - Result:" + repr(result))

test_dataset = [
    85, 85, 85, 85, 85, 85, 85, 85, 85, 72, 72, 72, 97, 149, 337, 436, 436,
    436, 436, 436, 436, 436, 436, 436, 436, 401, 295, 55, 55, 55, 55, 65, 121,
    141, 141, 141, 141, 141, 141
]
コード例 #5
0
    def __init__(self,
                 *,
                 rs=1.2,
                 n_k_points=12,
                 n_dimensions=2,
                 instability_type='cRHF2cUHF',
                 cylinder_radius=None,
                 delta_fxn_magnitude=None,
                 safe_eri=True):
        """Create the parameters object for the given parameters.

        :param rs: The wigner seitz radius, in 1 / bohr
        :type rs: float
        :param n_k_points: The number of reciprocal space grid points. Must be > 2
        :type n_k_points: int
        :param n_dimensions: Number of physical dimensions: 1, 2 or 3.
        :type n_dimensions: int
        :param instability_type: The type of instability to be investigated. Must be one of the strings in the set __class__.instabilities_supported.
        :type instability_type: string
        :param cylinder_radius: The radius of the cylinder for the pseudo - 1 dimensional system. This is meant to be small such that motion in the radial dimension is 'frozen'. See the appendix of Guiliani and Vignale for a discussion on this.
        :type cylinder_radius: float
        :param delta_fxn_magnitude: The multiplicative constant for the delta function potential in 1 dimension. ( v(r12) = delta_fxn_magnitude * delta(r12) )
        :type delta_fxn_magnitude: float
        :param safe_eri: Whether to check for momentum conservation explicitly in the two ERI.
        :type safe_eri: bool
        """

        self.rs = rs
        self.n_k_points = n_k_points
        self.n_dimensions = n_dimensions
        self.safe_eri = safe_eri

        if self.n_dimensions == 1:
            if (cylinder_radius is None) and (delta_fxn_magnitude is None):
                raise ValueError(
                    'In one dimension, must specify exactly one of cylinder_radius or delta_fxn_magnitude, got Neither.'
                )
            elif (cylinder_radius is not None) and (delta_fxn_magnitude
                                                    is not None):
                raise ValueError(
                    'In one dimension, must specify exactly one of cylinder_radius or delta_fxn_magnitude, got Both.'
                )
            elif (cylinder_radius
                  is not None) and (delta_fxn_magnitude is None):
                self.cylinder_radius = cylinder_radius
            elif (cylinder_radius is None) and (delta_fxn_magnitude
                                                is not None):
                self.delta_fxn_magnitude = delta_fxn_magnitude

        self.instability_type = instability_type
        self.k_fermi = __class__._calc_k_fermi(rs=self.rs,
                                               n_dimensions=self.n_dimensions)
        self.k_max = (2.0 +
                      1E-8) * self.k_fermi  # A bit offset from 2 helps with
        # not getting states exactly at kmax.

        # Make a grid 1 point too big then remove the last. This gives the desired
        # number of points in the grid, while removing equivalent points at
        # opposite ends of the first Brillouin zone.
        self.k_grid = np.linspace(-self.k_max, self.k_max,
                                  self.n_k_points + 1)[:-1]
        self.k_grid_spacing = np.diff(self.k_grid)[0]

        self.states = states.States(self)
        self.n_electrons = 2 * self.states.n_occupied
        self.volume = __class__._calc_volume(self.rs, self.n_electrons,
                                             self.n_dimensions)

        self.eri = twoERI.TwoElectronIntegral(self)
        self.states.calc_energies()
        self.states.sort_by_energy()

        self.excitations = excitations.Excitations(self)
コード例 #6
0
class BasicEntity(BaseObject, pygame.sprite.Sprite):
    states = states.States('idle', 'death')
    state = None

    def __init__(self,
                 manager,
                 side,
                 reference,
                 name,
                 model,
                 weapon=None,
                 weapon_points=[]):

        BaseObject.__init__(self)
        pygame.sprite.Sprite.__init__(self)

        self._signals[constants.EVENT_ENTITY_FIRE] = []
        self._signals[constants.EVENT_ENTITY_DAMAGE] = []
        self._signals[constants.EVENT_ENTITY_DEATH] = []

        self._signals[constants.EVENT_ANIMATION_DAMAGE_COMPLETE] = []

        self.manager = manager

        self.side = side
        self.reference = reference
        self.name = name
        self.weapon = weapon
        self.weapon_points = weapon_points

        self.damage_animation_queue = []

        self.death_duration = 1500.0

        self.image = pygame.image.load(model)
        self.rect = pygame.rect.Rect(0, 0, self.image.get_width(),
                                     self.image.get_height())
        self.state = self.states.idle

        self.framecount = 0
        self.frameskip = 3

    def on_entity_fire(self, destination_reference):
        if isinstance(self.weapon, weapons.BasicLaser):
            # laser weapon
            # temporary until weapon hardpoints work
            spread = 12
            x, y = self.get_position()
            laser_entity0 = entities.LaserBlast(
                self.manager, self.weapon, (x - spread, y),
                destination_reference.get_position())
            laser_entity1 = entities.LaserBlast(
                self.manager, self.weapon, (x + spread, y),
                destination_reference.get_position())
            self.emit(constants.EVENT_ANIMATION_LASER, laser_entity0)
            self.emit(constants.EVENT_ANIMATION_LASER, laser_entity1)
        else:
            print 'Warning Unknown weapon', self, self.weapon

    def get_position(self):
        return self.rect.center

    def on_entity_damage(self, amount):
        entity_instance = entities.DamageAnimation(self.manager, amount,
                                                   self.get_position(), 2000,
                                                   400)
        self.damage_animation_queue.append(entity_instance)
        if len(self.damage_animation_queue) == 1:
            # Tell view to add this animation instance
            self.emit(constants.EVENT_ANIMATION_DAMAGE, (entity_instance))

    def on_animation_damage_complete(self, animation_reference):
        if self.damage_animation_queue and id(animation_reference) == id(
                self.damage_animation_queue[0]):
            self.damage_animation_queue = self.damage_animation_queue[1:]
            if len(self.damage_animation_queue) > 0:
                # Trigger next animation
                self.emit(constants.EVENT_ANIMATION_DAMAGE,
                          self.damage_animation_queue[0])

    def on_entity_death(self):
        self.death()

    def notify(self, event):
        if event.signal == constants.EVENT_ENTITY_FIRE:
            if event.data[0] == self.reference:
                self.on_entity_fire(event.data[1])
        elif event.signal == constants.EVENT_ENTITY_DAMAGE:
            if event.data[0] == self.reference:
                self.on_entity_damage(event.data[1])
        elif event.signal == constants.EVENT_ANIMATION_DAMAGE_COMPLETE:
            # identify if it is our event inside callback
            self.on_animation_damage_complete(event.data)
        elif event.signal == constants.EVENT_ENTITY_DEATH:
            if event.data == self.reference:
                self.on_entity_death()

    def move(self, position):
        # Update our rect position
        self.rect.move_ip(position[0], position[1])

    def death(self):
        self.emit(constants.EVENT_ENTITY_WAIT, self)
        self.timestamp = pygame.time.get_ticks()
        # Play fancy kill animation!
        self.state = self.states.death

    def update(self, ticks):
        if self.state == self.states.death:
            self.framecount += 1
            if self.framecount < self.frameskip:
                return
            self.framecount = 0
            n = min(1, (ticks - self.timestamp) / self.death_duration)
            # We can destroy this since this is the final use of this entities image
            pygame.surfarray.pixels3d(
                self.image)[:, :, 0] = 126 + 126 * math.cos(n * 24)
            if n == 1:
                self.visible = False
                self.state = self.states.idle
                # Clean up - This may need to be changed a bit
                self.emit(constants.EVENT_ENTITY_READY, self)
                self.destroy()
                self.kill()
コード例 #7
0
class BattleView(BaseObject):
    verbose = False
    states = states.States('ready', 'waiting')

    def __init__(self, display_surface):
        BaseObject.__init__(self)

        # Set up list of signals to listen for
        for signal in (constants.EVENT_ROUND_START, constants.EVENT_MESSAGE,
                       constants.EVENT_ENTITY_NEW, constants.EVENT_ENTITY_WAIT,
                       constants.EVENT_ENTITY_READY,
                       constants.EVENT_BATTLE_START,
                       constants.EVENT_ANIMATION_LASER,
                       constants.EVENT_ANIMATION_DAMAGE):
            self._signals[signal] = []

        # Initialize the display
        self.display_surface = display_surface

        # Create a background surface
        background_color = (0, 0, 0)
        self.background_surface = pygame.surface.Surface(
            (self.display_surface.get_width(),
             self.display_surface.get_height()))
        self.background_surface.fill(background_color)

        # Create starfield background
        star_count = 200
        utility.static_starfield(self.background_surface, star_count)

        # Blit the background surface to the display surface
        self.display_surface.blit(self.background_surface, (0, 0))

        # Update the whole display
        pygame.display.flip()

        # Sprite group for drawing all messages
        self.message_group = pygame.sprite.RenderUpdates()

        # Sprite group for drawing all entities
        self.entity_group = pygame.sprite.RenderUpdates()

        # Sprite group for drawing all entities
        self.weapon_group = pygame.sprite.RenderUpdates()

        # Sprite group for damage animations
        self.damage_group = pygame.sprite.RenderUpdates()

        self.battle_active = False

        self.round_timestamp = None
        self.round_delay = 1500  # Should come from config file

        # Number of objects who have requested we wait for them before ending the round
        self.waiting_counter = 0

        self.state = BattleView.states.ready

    def on_message(self, message):
        if self.verbose: print "'" + str(message) + "'"
        self.message_group.add(entities.Message(self.manager, str(message)))

    def on_entity_new(self, entity_instance):
        self.entity_group.add(entity_instance)

    def on_entity_wait(self, entity_ref):
        self.waiting_counter += 1

    def on_entity_ready(self, entity_ref):
        self.waiting_counter -= 1

    def on_round_start(self):
        self.state = BattleView.states.waiting

    def on_battle_start(self):
        # start waiting. must do this first incase on_entity_wait is called
        self.state = BattleView.states.waiting
        self.waiting_counter = 0

        # Determin placement of entities and move them
        sides = {}
        for entity in self.entity_group:
            if not sides.has_key(entity.side):
                sides[entity.side] = []
            sides[entity.side].append(entity)

        # right now will only work with 2 fleets until a suitable algo is decided upon
        # probably use a circle! send events to your brothers and parents, not to your children!

        y_padding = 64
        x_padding = 64

        entity_size = 138
        y = y_padding
        for side in sides.values():
            x = x_padding
            for entity in side:
                entity.move((x, y))
                # add warp-in code here
                x += entity_size
            y += self.display_surface.get_height() - (y_padding *
                                                      2) - entity_size

    def on_start_round(self, data):
        # start waiting. must do this first incase on_entity_wait is called
        self.state = BattleView.states.waiting
        self.waiting_counter = 0

    def on_animation_laser(self, animation_instance):
        self.weapon_group.add(animation_instance)

    def on_animation_damage(self, animation_instance):
        self.damage_group.add(animation_instance)

    def notify(self, event):
        if event.signal == constants.EVENT_ROUND_START:
            self.on_round_start()
        elif event.signal == constants.EVENT_MESSAGE:
            self.on_message(event.data)
        elif event.signal == constants.EVENT_ENTITY_NEW:
            self.on_entity_new(event.data)
        elif event.signal == constants.EVENT_BATTLE_START:
            self.on_battle_start()
        elif event.signal == constants.EVENT_ENTITY_WAIT:
            self.on_entity_wait(event.data)
        elif event.signal == constants.EVENT_ENTITY_READY:
            self.on_entity_ready(event.data)
        elif event.signal == constants.EVENT_ANIMATION_LASER:
            self.on_animation_laser(event.data)
        elif event.signal == constants.EVENT_ANIMATION_DAMAGE:
            self.on_animation_damage(event.data)

    def append_round(self, round_label, action_list):
        if self.verbose:
            print 'Added new round with', len(action_list), 'actions.'
        self.round_list.append({'label': round_label, 'actions': action_list})

    def update(self):
        # update sprite groups.  waiting_counter will be incrimented here by sprites calling a
        # EVENT_ENTITY_WAIT event and decrimented by an EVENT_ENTITY_READY event

        now = pygame.time.get_ticks()
        self.entity_group.update(now)
        self.weapon_group.update(now)
        self.damage_group.update(now)
        self.message_group.update(now)

        # Redraw sprites
        rectlist = self.entity_group.draw(self.display_surface)
        rectlist += self.weapon_group.draw(self.display_surface)
        rectlist += self.damage_group.draw(self.display_surface)
        rectlist += self.message_group.draw(self.display_surface)

        # Update the surface
        pygame.display.update(rectlist)

        # Clear the entities - Would be nice to know of a faster way to do this instead of using 3 seperate commands
        self.entity_group.clear(self.display_surface, self.background_surface)
        self.weapon_group.clear(self.display_surface, self.background_surface)
        self.damage_group.clear(self.display_surface, self.background_surface)
        self.message_group.clear(self.display_surface, self.background_surface)

        if self.state == BattleView.states.waiting and self.waiting_counter == 0:
            if self.round_timestamp == None:
                self.round_timestamp = pygame.time.get_ticks(
                ) + self.round_delay
            elif self.round_timestamp < pygame.time.get_ticks():
                self.round_timestamp = None
                self.state = BattleView.states.ready
                # not waiting on any sprites. call a EVENT_VIEW_READY so the controller can continue
                self.emit(constants.EVENT_VIEW_READY, None)
コード例 #8
0
class DamageAnimation(BaseObject, pygame.sprite.Sprite):
    states = states.States('waiting', 'animating', 'finished')
    state = None
    font = None

    def __init__(self,
                 manager,
                 damage_amount,
                 position,
                 animation_duration=0,
                 wait_duration=0,
                 font_path='./fonts/'):
        BaseObject.__init__(self)
        pygame.sprite.Sprite.__init__(self)

        if DamageAnimation.font == None:
            # Bitstream Vera Sans Mono
            DamageAnimation.font = pygame.font.Font(font_path + 'VeraMoBd.ttf',
                                                    18)

        if manager:
            self.manager = manager

        self.x = position[0]
        self.y = position[1]

        shadow_offset = 3
        text = DamageAnimation.font.render(str(int(damage_amount)), False,
                                           (255, 0, 0)).convert()
        shadow = DamageAnimation.font.render(str(int(damage_amount)), False,
                                             (50, 50, 50)).convert()
        self.display_image = pygame.surface.Surface(
            (text.get_width() + shadow_offset,
             text.get_height() + shadow_offset), 0, 32).convert_alpha()
        self.display_image.fill((0, 0, 0, 0))
        self.display_image.blit(shadow, (shadow_offset, shadow_offset))
        self.display_image.blit(text, (0, 0))
        self.idle_image = pygame.surface.Surface((0, 0))
        self.image = self.idle_image
        self.rect = pygame.rect.Rect(self.x, self.y, self.image.get_width(),
                                     self.image.get_height())

        self.wait_duration = wait_duration
        self.duration = float(animation_duration)

        # Record of original alpha for blending
        self.original_alpha = pygame.surfarray.array_alpha(self.display_image)

        self.state = self.states.waiting
        self.timestamp = pygame.time.get_ticks()

        self.emit(constants.EVENT_ENTITY_WAIT, self)

    def update(self, ticks):
        if self.state == self.states.waiting:
            if ticks > self.timestamp + self.wait_duration:
                self.timestamp = ticks
                self.state = self.states.animating
                self.image = self.display_image

        if self.state == self.states.animating:
            distance = 150
            n = min(1, (ticks - self.timestamp) / self.duration)
            self.rect.left = self.x + self.image.get_width() * math.sin(n * 10)
            self.rect.top = self.y + (-distance * n)

            # Alpha fade
            pygame.surfarray.pixels_alpha(self.image)[:, :] = Numeric.multiply(
                self.original_alpha, 1 - n).astype(Numeric.UInt8)

            if n == 1:
                self.emit(constants.EVENT_ANIMATION_DAMAGE_COMPLETE, self)
                self.state = self.states.finished
                # Clean up
                self.emit(constants.EVENT_ENTITY_READY, self)
                self.destroy()
                self.kill()
コード例 #9
0
class LaserSprite(pygame.sprite.Sprite):
    states = states.States('idle', 'active')
    state = None

    def __init__(self,
                 laser_color=(255, 255, 255),
                 width=1,
                 duration=150.0,
                 repeat=1):
        pygame.sprite.Sprite.__init__(self)
        self.laser_color = laser_color
        self.weapon_thickness = width
        self.padding = self.weapon_thickness
        self.idle_image = pygame.surface.Surface((0, 0))
        self.original_alpha = None
        self.duration = float(duration)
        self.repeats = repeat
        self.current_repeat = 0
        self.timestamp = 0
        self.fire_halt()

    def fire_halt(self):
        self.image = self.idle_image
        self.rect = self.image.get_rect()
        self.state = self.states.idle
        self.original_alpha = None

    def draw_laser(self, p0, p1):

        # determin width
        xwidth = (p1[0] - p0[0])
        ywidth = (p1[1] - p0[1])

        # alter width for padding
        if xwidth < 0:
            xwidth -= self.padding * 2
        else:
            xwidth += self.padding * 2

        if ywidth < 0:
            ywidth -= self.padding * 2
        else:
            ywidth += self.padding * 2

        # Create the laser alpha channel surface
        mask_image = pygame.surface.Surface(
            (abs(xwidth), abs(ywidth))).convert_alpha()
        mask_image.fill((0, 0, 0))

        self.rect = mask_image.get_rect()

        # reorganise position variables depending on which quater we are in, also update our rect
        if xwidth > 0:
            if ywidth > 0:
                pos0 = [self.padding, self.padding]
                pos1 = [
                    self.rect.width - self.padding,
                    self.rect.height - self.padding
                ]
                self.rect.move_ip((p0[0] - self.padding, p0[1] - self.padding))
            else:
                pos0 = [self.rect.width - self.padding, self.padding]
                pos1 = [self.padding, self.rect.height - self.padding]
                self.rect.move_ip((p0[0] - self.padding, p1[1] - self.padding))
        else:
            if ywidth > 0:
                pos0 = [self.rect.width - self.padding, self.padding]
                pos1 = [self.padding, self.rect.height - self.padding]
                self.rect.move_ip((p1[0] - self.padding, p0[1] - self.padding))
            else:
                pos0 = [self.padding, self.padding]
                pos1 = [
                    self.rect.width - self.padding,
                    self.rect.height - self.padding
                ]
                self.rect.move_ip((p1[0] - self.padding, p1[1] - self.padding))

        # Draw laser
        pygame.draw.line(mask_image, (255, 255, 255), pos0, (pos1[0], pos1[1]),
                         self.weapon_thickness)

        # Blur surface (this will be a gaussian blur later and facilitate a less-poor looking beam)
        blur_surface(mask_image)
        blur_surface(mask_image)
        blur_surface(mask_image)

        mask_array = pygame.surfarray.array3d(mask_image)

        self.image = mask_image
        self.image.fill(self.laser_color)

        # cheap gradient
        w = self.weapon_thickness
        tm = (255 / self.weapon_thickness)
        color = (self.laser_color[0], self.laser_color[1], self.laser_color[2])
        while w > 0:
            color = (min(255, color[0] + tm), min(255, color[1] + tm),
                     min(255, color[2] + tm))
            pygame.draw.line(self.image, color, pos0, (pos1[0], pos1[1]), w)
            w -= 1

        pygame.surfarray.pixels_alpha(self.image)[:, :] = mask_array[:, :, 0]

        # Record of original alpha for blending
        self.original_alpha = pygame.surfarray.array_alpha(
            self.image.copy().convert_alpha())

        self.timestamp = pygame.time.get_ticks()

        self.state = self.states.active

    def update(self, ticks):
        if self.original_alpha != None:
            n = min(1, (ticks - self.timestamp) / self.duration)
            # Alpha fade
            pygame.surfarray.pixels_alpha(self.image)[:, :] = Numeric.multiply(
                self.original_alpha, 1 - n).astype(Numeric.UInt8)
            if n == 1:
                # Loop
                if self.current_repeat < self.repeats:
                    self.current_repeat + 1
                    self.timestamp = pygame.time.get_ticks()
コード例 #10
0
ファイル: root.py プロジェクト: ninghang/accompany
import handlers, os
import states

name = "Live Sensor Details"
__dir = os.path.dirname(os.path.realpath(__file__))

root = handlers.Index(os.path.join(__dir, 'sensorstates.html'))
root.images = handlers.StaticFiles(os.path.join(__dir, 'images'))
root.js = handlers.StaticFiles(os.path.join(__dir, 'js'))
root.css = handlers.StaticFiles(os.path.join(__dir, 'css'))
root.data = states.States()