class Controller:
    'State of the simulation'

    def __init__(self, num_steps=100):
        self.initialize_model()
        self.initialize_animation()
        self.num_steps = num_steps

    def initialize_model(self):
        self.grid = Grid()
        self.grid.print_map()
        for i in range(num_people):
            self.grid.make_random_person()

        for i in range(num_fires):
            self.grid.make_random_fire()

    def initialize_animation(self):
        self.animation = Animation(self.grid)

    def start_simulation(self):
        print("Start simulation")
        for i in range(self.num_steps):
            self.update(i)
        self.end_simulation()

    def update(self, i):
        self.grid.simulate_step()
        self.animation.update_data(self.grid)

    def end_simulation(self):
        ani = self.animation.make_animation(self.num_steps)
        plt.show()
        print("End simulation")
Exemplo n.º 2
0
    def next_stage(self):

        self.ship = Animation(frames_path['ship'], ((self.w/16)*14, 200), self.screen)
        self.ship.reduce_scale(4)
        self.ship.centralize()

        self.sound_queue.append(sounds['stage'])

        self.played_sections += 1

        self.last_dig = None
        self.curr_dig = None
        self.show_item = False

        self.stage_done = False
        self.treasure_found = False
        
        self.stage_begin = True

        self.block_index = 0

        self.stage_map = Map(3 + self.played_sections, self.screen, self.w, self.h)

        self.char = Character(self.screen, Gameplay.char_sex, self.stage_map.blocks[self.block_index])
        self.char.reduce_scale(4)
        self.char.centralize()

        self.elements = [self.bg, self.stage_map, self.ship, self.char]
Exemplo n.º 3
0
    def __init__(self, values):
        super(SuperGuinea, self).__init__(values)
        self.flying_r = self.img_folder + "/guinea-r-fly.png"
        self.flying_l = self.img_folder + "/guinea-l-fly.png"

        self.fly_fast_r_animation = Animation(self.img_folder + "/guinea-r-fly-fast-", 2, 1, True)
        self.fly_fast_l_animation = Animation(self.img_folder + "/guinea-l-fly-fast-", 2, 1, True)
Exemplo n.º 4
0
class WindShift(FrozenClass):
    def __init__(self, surfaceoranimation, xpos, ypos, endtime):
        self.scompscale = variables.compscale()

        self.animation = surfaceoranimation
        if type(self.animation) == Surface:
            # frame rate does not matter if static image
            self.animation = Animation([self.animation],
                                       10000,
                                       surfacelist=True)

        # map coordinates in pixels
        self.xpos = xpos
        self.ypos = ypos

        # when it expires
        self.endtime = endtime

        self._freeze()

    def draw(self, mapoffset, destination=variables.screen):

        cmpscale = variables.compscale()
        surf = self.animation.current_frame()
        offset = self.animation.current_offset()

        # only draw if it was spawned at the correct scale and on screen
        if cmpscale == self.scompscale:
            drawrect = Rect(
                self.xpos * cmpscale + mapoffset[0] + offset[0] * cmpscale,
                self.ypos * cmpscale + mapoffset[1] + offset[1] * cmpscale,
                surf.get_width(), surf.get_height())
            if screenrect.contains(drawrect):
                destination.blit(surf, drawrect)
                variables.dirtyrects.append(drawrect)
Exemplo n.º 5
0
    def __init__(self, fileName, keys, stick, stones, helps, ball, bar, rightBall, level, game):
        """
        Initialize a challenge

	        @param self -- the challenge
            @param fileName -- a string that contains the sound name 
            @param keys -- the key vector
            @param stick -- the stick
            @param stones -- the stones
            @param helps -- the helps
            @param ball -- the left ball that it is used in the animation
            @param bar -- the grey bar that it is used in the animation
            @param rightBall -- the right ball that it is used in the animation
            @param level -- the challenge level
            @param game -- the game
	    
		"""
		
        self.fileName = fileName
        self.music = Sound()
        self.music.setFileName("sound/music/" + fileName)
        self.section = Section()
        self.section.setFileName("sound/section/" + fileName)
        self.section.setKeys(keys)
        self.stick = stick
        self.animation = Animation(stones, keys, helps, ball, rightBall, bar, game)
        self.ball = ball
        self.level = level
        self.attempts = 0
        self.game = game
Exemplo n.º 6
0
    def __init__(self, text, on_click_deferred, on_click_return_value, window_values, surface, hover_animation_surface = None, mouse_down_animation = None, spritesheet_dimensions=(2, 2), font_size='big'): #spritesheet for potential fancy animations later
        self.x, self.y, self.w, self.h = window_values

        self.font_size = font_size

        self.text = text

        self.surface = surface

        self.text_label = render_text(text, (0,0,0), font_size)
        self.get_text_draw_coords()

        self.on_click_deferred = on_click_deferred
        self.on_click_return_value = on_click_return_value

        hover_animation_surface = None

        if hover_animation_surface:
            self.on_hover_animation = Animation(TileSheet(hover_animation_surface, 292, 120, spritesheet_dimensions[0], spritesheet_dimensions[1]), 10, 4)
        else:
            self.on_hover_animation = None

        if mouse_down_animation:
            self.mouse_down_animation = Animation(TileSheet(mouse_down_animation, 292, 120, 1, 1), 10, 1)
        else:
            self.mouse_down_animation = None

        self.on_hover_animation_active = False
        self.mouse_down_animation_active = False
Exemplo n.º 7
0
def test_Can_Get_Result_After_It_Is_Set():
    a = Animation([])
    a.SetResult(Rect(1, 2, 3, 4), 1, True)
    r = a.GetResult()
    assert r.area == Rect(1, 2, 3, 4)
    assert r.statusType == 1
    assert r.statusEnabled == True
Exemplo n.º 8
0
def test_Can_Resume():
    a = Animation([])
    assert a.running == True
    a.Pause()
    assert a.running == False
    a.Resume()
    assert a.running == True
Exemplo n.º 9
0
class Hint:

    scrol_frames = ['img/scrol_frame_1.png', 'img/scrol_frame_2.png']

    def __init__(self, pos, hint, screen):

        self.pos = pos
        self.hint = hint
        self.screen = screen

        self.overlay = Overlay(self.screen, (0, 0),
                               self.screen.get_size()[0],
                               self.screen.get_size()[1])
        self.textsurface = Text(self.screen, self.pos, self.hint, True,
                                (232, 197, 150))

        self.scrol = Animation(self.scrol_frames, self.pos, self.screen)
        self.scrol.reduce_scale(4)
        self.scrol.centralize()

        self.elements = [self.overlay, self.scrol, self.textsurface]

    def draw(self):

        for element in self.elements:
            element.draw()
Exemplo n.º 10
0
 def __init__(self, canvas, imageCenter, imagePath):
     Animation.__init__(self, canvas, self.drawCommand,
                        ImageCircleAnimation.cycleDuration)
     self.imageCenter = imageCenter
     image = Image.open(imagePath)
     self.croppedImageSource = cropCircleImage(image)
     self.easingFunction = easeOutElastic
Exemplo n.º 11
0
 def __init__(self, values):
     super(Nugget, self).__init__(values)
     self.nugget_animation = Animation("nugget-", 4, 2, True)
     self.collected_animation = Animation("yellow-particle-", 4, 1, False)
     self.x -= 4
     self.y -= 4
     self.w = 32
     self.h = 32
Exemplo n.º 12
0
def test_Is_Marked_For_Deletion_After_Animation_Complete():
    a = Animation([1, 2, 3])
    assert a.markedForDeletion == False
    a.Run()  # Frame 1
    assert a.markedForDeletion == False
    a.Run()  # Frame 2
    assert a.markedForDeletion == False
    a.Run()  # Frame 3
    assert a.markedForDeletion == True
Exemplo n.º 13
0
    def parse(self, node):
        self.id = int(node.attrib['id'])
        self.name = node.attrib['name']

        for elem in node:
            if elem.tag != 'animation':
                continue

            a = Animation(elem)
            self.animations[a.get_id()] = a
Exemplo n.º 14
0
class DecryptorGif:
    def __init__(self,
                 message,
                 fontfile="C:\\WINDOWS\\FONTS\\CONSOLA.TTF",
                 fontsize=50,
                 textcolor="green",
                 background="black",
                 outputfile="decryptor.gif",
                 margin=20):
        # FONT_FILE = '/System/Library/Fonts/Monaco.dfont'
        # FONT_FILE = "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf"
        self.font = ImageFont.truetype(font=fontfile, size=fontsize)
        self.textcolor = textcolor
        self.background = background
        self.margin = margin
        self.animation = Animation(filename=outputfile, duration=.1)
        self.make_images(message)
        self.animation.save_gif()

    def create_frame(self, size, message_string):
        img = Image.new('RGB', size, color=self.background)
        drawing = ImageDraw.Draw(img)
        drawing.text((10, 10),
                     message_string,
                     fill=self.textcolor,
                     font=self.font)
        self.animation.frames = img

    def get_text_size(self, text):
        img = Image.new('RGB', (1, 1), color='black')
        drawing = ImageDraw.Draw(img)
        size = drawing.textsize(text, font=self.font)
        return size[0] + self.margin, size[1] + self.margin

    def make_images(self, message_string):
        size = self.get_text_size(message_string)
        for i, guess in enumerate(self.crypt_strings(message_string)):
            self.create_frame(size, guess)

    @staticmethod
    def crypt_strings(message_string):
        previous_guesses = tuple(set() for _ in message_string)
        current_chars = random.choices(CHARS, k=len(message_string))
        current_string = "".join(current_chars)
        yield current_string
        while current_string != message_string:
            for idx, target_char in enumerate(message_string):
                if current_chars[idx] != target_char:
                    guess = random.choice(
                        tuple(CHARSET_CHARS - previous_guesses[idx]))
                    previous_guesses[idx].add(guess)
                    current_chars[idx] = guess
            current_string = "".join(current_chars)
            yield current_string
Exemplo n.º 15
0
 def __init__(self, message, fontfile="C:\\WINDOWS\\FONTS\\CONSOLA.TTF", fontsize=50, textcolor="green",
              background="black", outputfile="decryptor.gif", margin=20):
     # FONT_FILE = '/System/Library/Fonts/Monaco.dfont'
     # FONT_FILE = "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf"
     self.font = ImageFont.truetype(font=fontfile, size=fontsize)
     self.textcolor = textcolor
     self.background = background
     self.margin = margin
     self.animation = Animation(filename=outputfile, duration=.1)
     self.make_images(message)
     self.animation.save_gif()
Exemplo n.º 16
0
    def __init__(self):

        super().__init__()
        self.w, self.h = self.screen.get_size()
        self.next_state = "STARTMENU"

        self.sound_queue.append(sounds['menu'])

        bg = Animation(frames_path['play-background'], (0, 0), self.screen)
        image = Animation(frames_path['how-to-play'], (0, 0), self.screen)

        self.elements = [bg, image]
Exemplo n.º 17
0
    def __init__(self, var_dict):
        BaseObject.__init__(self, var_dict)
        self.type = PLAYER
        self.xvel = 0
        self.yvel = 0
        self.jumpvel = 1
        self.walkvel = 0.05
        self.maxXvel = 2.3
        self.maxYvel = 8
        self.direction = DIR_RIGHT
        self.iswalking = False
        self.on_object = None
        self.col_object = None
        self.jump_state = NOT_JUMPING
        self.airborne = True
        self.j_delay_timer = Timer(50, self.__next_jump_state, False)
        self.jump_timer = Timer(240, self.__next_jump_state, False)
        self._layer = 10
        #Array of objects currently colliding with rect - Tracks objects that are possible to interact with
        self.pos_interact = []
        self.held_item = None
        self.drop_item = None
        self.collidable = True
        self.held_ofs_x = 0.0
        self.held_ofs_y = 0.0
        self.obey_gravity = True
        self.visible = True

        self.idle_files = var_dict['idle_files'].split(',')
        self.idle_times = var_dict['idle_times'].split(',')
        self.jump_files = var_dict['jump_files'].split(',')
        self.jump_times = var_dict['jump_times'].split(',')
        self.walk_files = var_dict['walk_files'].split(',')
        self.walk_times = var_dict['walk_times'].split(',')
        self.idle_anim = Animation(self.idle_files, self.idle_times)
        self.jumping_anim = Animation(self.jump_files, self.jump_times)
        self.walking_anim = Animation(self.walk_files, self.walk_times)
        self.walking_anim.set_colorkey((255, 255, 255))

        if var_dict['w'] == 0 or var_dict['h'] == 0:
            self.rect.w = self.idle_anim.getRect().w
            self.rect.h = self.idle_anim.getRect().h
        else:
            pass
            #Needs to scale all animations while keeping aspect ratio.
            #self.walking_anim.scale((var_dict['w'], var_dict['h']))
            #self.jumping_anim.scale((var_dict['w'], var_dict['h']))
        self.anim_player = Animation_Player()
        self.anim_player.add(self.walking_anim, WALK_ANIM)
        self.anim_player.add(self.jumping_anim, JUMP_ANIM)
        self.anim_player.add(self.idle_anim, IDLE_ANIM)
        self.anim_player.set(IDLE_ANIM, True)
Exemplo n.º 18
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        # Database Reader Module
        self.dbReader = TestDatabaseReader()
        # NFC Reader Thread
        self.nfcReader = NFCReader()
        self.nfcReader.start()
        # Animation
        self.animation = Animation()

        # UI for the page
        self.ui = Ui_LogIn()
        self.ui.setupUi(self)

        # hide dialogue
        self.ui.DialogueShadow.hide()

        # Insert buttons into QButtonGroup
        self.keypadButtons = QButtonGroup()
        self.keypadButtons.addButton(self.ui.KeypadButton_0, 0)
        self.keypadButtons.addButton(self.ui.KeypadButton_1, 1)
        self.keypadButtons.addButton(self.ui.KeypadButton_2, 2)
        self.keypadButtons.addButton(self.ui.KeypadButton_3, 3)
        self.keypadButtons.addButton(self.ui.KeypadButton_4, 4)
        self.keypadButtons.addButton(self.ui.KeypadButton_5, 5)
        self.keypadButtons.addButton(self.ui.KeypadButton_6, 6)
        self.keypadButtons.addButton(self.ui.KeypadButton_7, 7)
        self.keypadButtons.addButton(self.ui.KeypadButton_8, 8)
        self.keypadButtons.addButton(self.ui.KeypadButton_9, 9)

        self.keyDisplays = QButtonGroup()
        self.keyDisplays.addButton(self.ui.NumberDisplay_1, 1)
        self.keyDisplays.addButton(self.ui.NumberDisplay_2, 2)
        self.keyDisplays.addButton(self.ui.NumberDisplay_3, 3)
        self.keyDisplays.addButton(self.ui.NumberDisplay_4, 4)
        self.keyDisplays.addButton(self.ui.NumberDisplay_5, 5)
        self.keyDisplays.addButton(self.ui.NumberDisplay_6, 6)
        self.keyDisplays.addButton(self.ui.NumberDisplay_7, 7)
        self.keyDisplays.addButton(self.ui.NumberDisplay_8, 8)

        self.displayIndex = 1
        self.password = ""

        for i in range(0, 10):
            self.keypadButtons.button(i).clicked.connect(
                partial(self.writeNumber, i))

        self.ui.DButtonYes.clicked.connect(lambda: print("playing piano!"))
        self.ui.DButtonNo.clicked.connect(lambda: self.hideDialogueCheck())
        self.nfcReader.nfc_connect.connect(self.checkValidUid)
Exemplo n.º 19
0
    def __init__(self,
                 curve,
                 cp,
                 col,
                 factor=1,
                 name="",
                 visible=False,
                 parent=None):
        """curve is something derived from Line"""
        GraphicObject.__init__(self, visible, parent)
        comp = SoComplexity()
        comp.value.setValue(.1)
        self.separator.addChild(comp)
        ## ============================
        points = curve.getPoints()
        pointsp = [
            curve[i] + cp(t) * factor
            for i, t in enumerate(intervalPartition(curve.iter))
        ]
        for p, pp in zip(points, pointsp):
            self.addChild(
                Arrow(p, pp, visible=True, escala=.005, extremos=True))

        self.animation = Animation(lambda num: self[num - 1].show(),
                                   (4000, 1, len(points)))
Exemplo n.º 20
0
    def __init__(self, var_dict):
        BaseObject.__init__(self, var_dict)
        self.type = LEVEL_OBJECT
        self.files = var_dict['files'].split(',')
        self.times = var_dict['times'].split(',')

        #HACK - ANIMATION WILL CHANGE THIS
        #If files is larger than 1, create animation with 2 frames
        # if len(self.files) > 1 and self.files[1] != '':
        #     self.idle_anim = pyganim.PygAnimation([(os.path.join(self.files[0]), .75),
        #                                            (os.path.join(self.files[1]), .75)])
        #     self.idle_anim.set_colorkey((255, 255, 255))
        # #Else if files has 1 file, create animation with 1 frame
        # elif len(self.files) > 0:
        #     self.idle_anim = pyganim.PygAnimation([(os.path.join(self.files[0]), 1)])
        #     self.idle_anim.set_colorkey((255, 255, 255))

        self.idle_anim = Animation(self.files, self.times)

        #If width or height is 0, use default w/h
        if var_dict['w'] == 0 or var_dict['h'] == 0:
            self.rect.w = self.idle_anim.getRect().w
            self.rect.h = self.idle_anim.getRect().h
        else:
            self.idle_anim.scale((var_dict['w'], var_dict['h']))
        self.rect.x = var_dict['x']
        self.rect.y = var_dict['y']
        self.col_objects = []
        self.on_object = None
        self._layer = var_dict['_layer']
        self.layer = self._layer
        self.collidable = to_bool(var_dict['collidable'])
        self.idle_anim.play()
        self.obey_gravity = to_bool(var_dict['obey_gravity'])
        self.visible = True
Exemplo n.º 21
0
    def __init__(self, pos, hint, screen):

        self.pos = pos
        self.hint = hint
        self.screen = screen

        self.overlay = Overlay(self.screen, (0, 0),
                               self.screen.get_size()[0],
                               self.screen.get_size()[1])
        self.textsurface = Text(self.screen, self.pos, self.hint, True,
                                (232, 197, 150))

        self.scrol = Animation(self.scrol_frames, self.pos, self.screen)
        self.scrol.reduce_scale(4)
        self.scrol.centralize()

        self.elements = [self.overlay, self.scrol, self.textsurface]
 def __init__(self, stance_path, action):
     print(stance_path)
     self.path = stance_path + "/" + action
     self.sub_dirs = glob.glob(self.path + '/*')
     self.animations = [
         Animation(x, ACTIVITY_PARAMS[action][0],
                   ACTIVITY_PARAMS[action][1]) for x in self.sub_dirs
     ]
Exemplo n.º 23
0
 def __init__(self, id: int, position: [float, float], type_name="MovableObject"):
     super(MovableObject, self).__init__(id, position, type_name=type_name)
     self._max_hp = game_objects_data[id]['max_hp']
     self._hp = self._max_hp
     self._speed = game_objects_data[id]['speed']
     self._velocity_vector = [0, 0]
     self.drop = game_objects_data[id]['drop']
     self.animation = Animation(id)
     self._position = position
Exemplo n.º 24
0
    def __init__(self, surfaceoranimation, xpos, ypos, endtime):
        self.scompscale = variables.compscale()

        self.animation = surfaceoranimation
        if type(self.animation) == Surface:
            # frame rate does not matter if static image
            self.animation = Animation([self.animation],
                                       10000,
                                       surfacelist=True)

        # map coordinates in pixels
        self.xpos = xpos
        self.ypos = ypos

        # when it expires
        self.endtime = endtime

        self._freeze()
Exemplo n.º 25
0
    def __init__(self):

        super().__init__()
        self.w, self.h = self.screen.get_size()
        
        self.sound_queue.append(sounds['stage'])

        self.menu = Menu(self.screen)
        self.menu.add_button('sound', frames_path['sound'],(int((self.w/16)*15), int((self.h/10)*1)),self.switch_sound)
        self.menu.buttons['sound'].reduce_scale(5)
        self.menu.buttons['sound'].centralize()

        self.msgs = {
            'lose': Text(self.screen, (int(self.w/2), 200), 'Oh não, os piratas chegaram na ilha, melhor zarparmos e tentarmos denovo outro dia!', True, (255,255,255))
        }

        ''' Sessões de Jogo '''
        self.played_sections = 0
        self.wins = 0
        self.stage_done = False
        self.stage_begin = True

        ''' Mapa '''
        self.block_index = 0
        self.stage_map = Map(3, self.screen, self.w, self.h)
        
        ''' Escavações '''
        self.last_dig = None
        self.curr_dig = None
        self.show_item = False

        ''' Personagem '''
        self.char = Character(self.screen, Gameplay.char_sex, self.stage_map.blocks[self.block_index])
        self.char.reduce_scale(4)
        self.char.centralize()

        ''' Cena '''
        self.ship = Animation(frames_path['ship'], ((self.w/16)*14, 200), self.screen)
        self.ship.reduce_scale(4)
        self.ship.centralize()
        self.bg = Animation(frames_path['play-background'], (0, 0), self.screen)
        self.elements = [self.bg, self.stage_map, self.ship, self.char]
Exemplo n.º 26
0
    def __init__(self, gmp, posX, posY, w, h, gms):
        pygame.init()  #Initialise le module pygame
        self.gamePanel = gmp  #Jesaispasquoimettrec'estevident
        self.gameScene = gms
        self.width = w  #Largeur du joueur
        self.height = h  #Hauteur du joueur
        self.FPS = Constants.FPS
        self.fast = Constants.screenHeight / 40 / Constants.FPS  #0.25 -> 60FPS/0.5 -> 30FPS          #De combien on bouge de pixel entre chaque update
        self.movingUp = False
        self.isPlaying = False
        self.dy = 0
        self.maxDy = 40 / (Constants.FPS / 15)
        self.lastPos = []
        self.pointSpeed = int((math.sqrt(Constants.screenWidth) / 4))
        self.maxPoint = 10
        self.dead = False

        self.ball = getBalls()[int(Helper.getSelectedBall())]

        self.currentThemeId = self.gameScene.getCurrentTheme().id

        self.shadow = pygame.image.load('./drawable/ball_shadow.png')
        self.shadow = pygame.transform.scale(self.shadow,
                                             (self.width, self.height))

        self.currentSpritesheet = self.ball.yellow_spritesheet

        self.animation = Animation(self.currentSpritesheet, 50, 50,
                                   self.ball.numFrames, self.ball.speed)

        self.pos = pygame.Rect(0, 0, 0, 0)

        self.pos.x = posX
        self.pos.y = posY

        #BONUS
        self.slow = False
        self.shield = False
        self.speed = False

        pygame.display.flip()
Exemplo n.º 27
0
def import_fbx_as_anim(filename, pelvis_name=None):
    joint_names, parents, offsets, qs, ts, qs_global, ts_global = import_fbx(
        filename, pelvis_name)
    orients = Quaternions.id(len(joint_names))
    # anim = Animation(rotations=Quaternions.id((qs.shape[0], qs.shape[1])),
    #                  positions=ts, orients=orients, offsets=offsets, parents=parents)
    anim = Animation(rotations=Quaternions(qs),
                     positions=ts,
                     orients=orients,
                     offsets=offsets,
                     parents=parents)

    return joint_names, parents, offsets, anim, ts_global
Exemplo n.º 28
0
def main():
    ''' Initialises the engine and loads the scene. For every frame it updates the
        camera, updates the animated entity (which updates the animation),
        renders the scene to the screen, and then updates the display. When the
        display is closed the engine gets cleaned up.
    '''
    # texture_path = 'data/models/assimp/duck_sample.jpg'
    # texture_path = 'data/shea-coulee.png'
    texture_path = 'data/models/farm_boy/diffuse.png'
    # model_path = 'data/models/duck/duck_triangles.dae'
    # model_path = 'data/models/basic/cow.obj'
    # model_path = 'data/models/regina/regina.dae'
    model_path = 'data/models/farm_boy/model.dae'

    engine = RenderEngine()
    loader = OpenGLLoader()

    model = ColladaParser(model_path)
    raw_model: RawModel = loader.load_to_VAO(model)
    textureID = loader.load_texture(texture_path)

    animated_model = AnimatedModel(raw_model,
                                   textureID,
                                   root_joint=model.root_joint,
                                   num_joints=16)
    entity = Entity(animated_model,
                    position=[0, -5, -30],
                    rotation=[-90, 30, 0],
                    scale=1.0)  # farm boy
    # entity = Entity(animated_model, position=[0, -160, -600], rotation=[0, 0, 0], scale=1.0)     # regina

    camera = Camera(model.vertices.max())
    scene = Scene(entity, camera)

    animation = Animation(model.key_frames)
    scene.entity.animator.set_animation(animation)

    while not engine.window_should_close():
        glfw.poll_events()
        scene.camera.move()

        scene.entity.increase_position([0, 0, 0])
        # scene.entity.increase_rotation([0, 0.2, 0])
        scene.entity.update()

        engine.render_scene(scene)
        engine.update()

    loader.clean_up()
    engine.close()
Exemplo n.º 29
0
class WindShift(FrozenClass):

    def __init__(self, surfaceoranimation, xpos, ypos, endtime):
        self.scompscale = variables.compscale()

        
        self.animation = surfaceoranimation
        if type(self.animation) == Surface:
            # frame rate does not matter if static image
            self.animation = Animation([self.animation], 10000, surfacelist = True)

        # map coordinates in pixels
        self.xpos = xpos
        self.ypos = ypos

        # when it expires
        self.endtime = endtime
        

        self._freeze()

    def draw(self, mapoffset, destination = variables.screen):
        
        cmpscale = variables.compscale()
        surf = self.animation.current_frame()
        offset = self.animation.current_offset()
        
        # only draw if it was spawned at the correct scale and on screen
        if cmpscale == self.scompscale:
            drawrect = Rect(self.xpos*cmpscale + mapoffset[0] + offset[0]*cmpscale,
                            self.ypos*cmpscale + mapoffset[1] + offset[1]*cmpscale,
                            surf.get_width(),
                            surf.get_height())
            if screenrect.contains(drawrect):
                destination.blit(surf, drawrect)
                variables.dirtyrects.append(drawrect)
Exemplo n.º 30
0
def test_Will_Loop_If_Marked_For_Looping():
    a = Animation([1, 2, 3])
    a.SetLooping(True)
    assert a.currentFrame == 0
    a.Run()
    assert a.currentFrame == 1
    a.Run()
    assert a.currentFrame == 2
    a.Run()
    assert a.currentFrame == 0
Exemplo n.º 31
0
    def __init__(self):

        super().__init__()
        self.w, self.h = self.screen.get_size()

        bg = Animation(frames_path['play-background'], (0, 0), self.screen)
        text = Text(self.screen, (int(self.w/2), 100), 'Escolha seu Pirata, marujo!', True, (255,255,255), 50)

        self.menu = Menu(self.screen)
        self.menu.add_button('boy-pirate', frames_path['boy-pirate'],((self.w/4), (self.h/2)),self.selectBoy)
        self.menu.buttons['boy-pirate'].reduce_scale(3)
        self.menu.buttons['boy-pirate'].centralize()

        self.menu.add_button('girl-pirate', frames_path['girl-pirate'],((self.w/4)*3, (self.h/2)),self.selectBoy)
        self.menu.buttons['girl-pirate'].reduce_scale(3)
        self.menu.buttons['girl-pirate'].centralize()

        self.elements = [bg, self.menu, text]
Exemplo n.º 32
0
    def __init__(self, surfaceoranimation, xpos, ypos, endtime):
        self.scompscale = variables.compscale()

        
        self.animation = surfaceoranimation
        if type(self.animation) == Surface:
            # frame rate does not matter if static image
            self.animation = Animation([self.animation], 10000, surfacelist = True)

        # map coordinates in pixels
        self.xpos = xpos
        self.ypos = ypos

        # when it expires
        self.endtime = endtime
        

        self._freeze()
Exemplo n.º 33
0
class FlyingNugget(Ob):
    img = "nugget-1.png"
    w = 8
    h = 8
    is_mover = True
    experiences_gravity = True
    collides_with_movers = False
    is_solid = False
    nugget_animation = Animation("nugget-", 4, 2, True)
    does_not_collide = True

    def __init__(self, values):
        super(FlyingNugget, self).__init__(values)
        self.created_at = datetime.datetime.now()

    def behave(self, engine):
        super().behave(engine)
        if datetime.datetime.now() - self.created_at > datetime.timedelta(seconds=5):
            engine.remove_ob(self)

    def animate(self, engine):
        self.set_animation(self.nugget_animation)
Exemplo n.º 34
0
def main_origin():
    parser = argparse.ArgumentParser()
    parser.add_argument("map", help="input file containing map")
    parser.add_argument("schedule", help="schedule for agents")
    parser.add_argument('--video', dest='video', default=None,
                      help="output video file (or leave empty to show on screen)")
    parser.add_argument("--speed", type=int, default=1, help="speedup-factor")
    args = parser.parse_args()

    with open(args.map) as map_file:
        map = yaml.load(map_file, Loader=yaml.FullLoader)

    with open(args.schedule) as states_file:
        schedule = yaml.load(states_file, Loader=yaml.FullLoader)

    animation = Animation(map, schedule)

    if args.video:
        animation.save(args.video, args.speed)
    else:
        animation.show()
Exemplo n.º 35
0
class LevelObject(BaseObject):
    def __init__(self, var_dict):
        BaseObject.__init__(self, var_dict)
        self.type = LEVEL_OBJECT
        self.files = var_dict['files'].split(',')
        self.times = var_dict['times'].split(',')

        #HACK - ANIMATION WILL CHANGE THIS
        #If files is larger than 1, create animation with 2 frames
        # if len(self.files) > 1 and self.files[1] != '':
        #     self.idle_anim = pyganim.PygAnimation([(os.path.join(self.files[0]), .75),
        #                                            (os.path.join(self.files[1]), .75)])
        #     self.idle_anim.set_colorkey((255, 255, 255))
        # #Else if files has 1 file, create animation with 1 frame
        # elif len(self.files) > 0:
        #     self.idle_anim = pyganim.PygAnimation([(os.path.join(self.files[0]), 1)])
        #     self.idle_anim.set_colorkey((255, 255, 255))

        self.idle_anim = Animation(self.files, self.times)

        #If width or height is 0, use default w/h
        if var_dict['w'] == 0 or var_dict['h'] == 0:
            self.rect.w = self.idle_anim.getRect().w
            self.rect.h = self.idle_anim.getRect().h
        else:
            self.idle_anim.scale((var_dict['w'], var_dict['h']))
        self.rect.x = var_dict['x']
        self.rect.y = var_dict['y']
        self.col_objects = []
        self.on_object = None
        self._layer = var_dict['_layer']
        self.layer = self._layer
        self.collidable = to_bool(var_dict['collidable'])
        self.idle_anim.play()
        self.obey_gravity = to_bool(var_dict['obey_gravity'])
        self.visible = True

    def draw(self, screen, translated):
        self.idle_anim.blit(screen, translated)

    def update(self):
        self.move()

    def do_gravity(self, gravity):
        self._change_vel(DIR_DOWN, gravity)

    def collide(self, obj):
        if self.rect.colliderect(obj.rect):
            if obj.collidable:
                self.col_objects.append(obj)
                if obj.type == PLAYER:
                    return
                if obj.rect.collidepoint(self.rect.midbottom):
                    self.yvel = 0
                    #save the object the object is on
                    self.on_object = obj.rect
        elif obj in self.col_objects:
            self.col_objects.remove(obj)

    def config_files(self, config, counter):
        config.set(self.name, 'file' + str(counter), self.files[counter])
        if counter >= len(self.files):
            counter += 1
            self.config_files(config, counter)

    def serialize(self, config):
        BaseObject.serialize(self, config)
Exemplo n.º 36
0
 def __init__(self, proxy):
     assert proxy.__class__ is ALProxy;
     self.__proxy = proxy;
     self.__ledsNames, self.__colorsNames = self.__getLedsNames();
     self.__animation = Animation();
     self.__parallelism = False;
Exemplo n.º 37
0
class PlayerSprite(BaseObject):
    def __init__(self, var_dict):
        BaseObject.__init__(self, var_dict)
        self.type = PLAYER
        self.xvel = 0
        self.yvel = 0
        self.jumpvel = 1
        self.walkvel = 0.05
        self.maxXvel = 2.3
        self.maxYvel = 8
        self.direction = DIR_RIGHT
        self.iswalking = False
        self.on_object = None
        self.col_object = None
        self.jump_state = NOT_JUMPING
        self.airborne = True
        self.j_delay_timer = Timer(50, self.__next_jump_state, False)
        self.jump_timer = Timer(240, self.__next_jump_state, False)
        self._layer = 10
        #Array of objects currently colliding with rect - Tracks objects that are possible to interact with
        self.pos_interact = []
        self.held_item = None
        self.drop_item = None
        self.collidable = True
        self.held_ofs_x = 0.0
        self.held_ofs_y = 0.0
        self.obey_gravity = True
        self.visible = True

        self.idle_files = var_dict['idle_files'].split(',')
        self.idle_times = var_dict['idle_times'].split(',')
        self.jump_files = var_dict['jump_files'].split(',')
        self.jump_times = var_dict['jump_times'].split(',')
        self.walk_files = var_dict['walk_files'].split(',')
        self.walk_times = var_dict['walk_times'].split(',')
        self.idle_anim = Animation(self.idle_files, self.idle_times)
        self.jumping_anim = Animation(self.jump_files, self.jump_times)
        self.walking_anim = Animation(self.walk_files, self.walk_times)
        self.walking_anim.set_colorkey((255, 255, 255))

        if var_dict['w'] == 0 or var_dict['h'] == 0:
            self.rect.w = self.idle_anim.getRect().w
            self.rect.h = self.idle_anim.getRect().h
        else:
            pass
            #Needs to scale all animations while keeping aspect ratio.
            #self.walking_anim.scale((var_dict['w'], var_dict['h']))
            #self.jumping_anim.scale((var_dict['w'], var_dict['h']))
        self.anim_player = Animation_Player()
        self.anim_player.add(self.walking_anim, WALK_ANIM)
        self.anim_player.add(self.jumping_anim, JUMP_ANIM)
        self.anim_player.add(self.idle_anim, IDLE_ANIM)
        self.anim_player.set(IDLE_ANIM, True)

    def draw(self, screen, rect_loc):
        if self.jump_state > 0:
            self.anim_player.set(JUMP_ANIM)
        elif self.iswalking is True:
            self.anim_player.set(WALK_ANIM)
        else:
            self.anim_player.set(IDLE_ANIM)

        self.anim_player.draw(screen, rect_loc)

    def move(self):
        if self.iswalking is False:
            if self.xvel <= 0:
                self.xvel = 0
            else:
                self.xvel -= 1
        if self.direction == DIR_RIGHT and self.iswalking:
            if self.col_object is None:
                self._change_vel(DIR_RIGHT, self.walkvel)
            else:
                #check what side the object is on, permit walking the other way
                if self.col_object.rect.x < self.rect.x:
                    self._change_vel(DIR_RIGHT, self.walkvel)
        elif self.direction == DIR_LEFT and self.iswalking:
            if self.col_object is None:
                self._change_vel(DIR_LEFT, self.walkvel)
            else:
                if self.col_object.rect.x > self.rect.x:
                    self._change_vel(DIR_LEFT, self.walkvel)

        #Is the player colliding with ANY objects?
        if self.col_object is not None:
            #Check if still colliding with col_object
            if not self.rect.colliderect(self.col_object.rect):
                self.col_object = None

        #If player was on top of an object last tick
        if self.on_object is not None:
            #Check if player is still on object
            if self.on_object.rect.collidepoint(self.rect.midbottom):
                self.airborne = False
                #If player is on an object and yvel is being modified by do_jump(), stop the jump
                #if self._is_jumping():
                 #   self._stop_jump()
            else:
                self.on_object = None
        else:
            self.airborne = True

        if self.jump_state == JUMP:
            self._do_jump()

        self.update_pos()

    def move_direction(self, player_dir):
        #check if changing direction, if so lessen x velocity
        if player_dir != self.direction:
            self.xvel -= self.xvel / 2
            self.anim_player.flip()
        self.direction = player_dir
        self.iswalking = True

    def collide(self, obj):
        """Returns if object is colliding, calls _respond_collision on True and _check_pos_interact every time"""
        colliding = False
        if self.rect.colliderect(obj.rect):
            colliding = True
            self._respond_collision(obj)

        self._check_pos_interact(obj, colliding)
        return colliding

    def _respond_collision(self, obj):
        """Responds to a collision, trusts the caller that the objects are colliding"""
        if obj.collidable:
                #save the last collided object
                self.col_object = obj
                if obj.rect.collidepoint(self.rect.midbottom):
                    self.yvel = 0
                    self.rect.bottom = obj.rect.top
                    #save the object the player is on
                    self.on_object = obj
                    #If falling, let jump state know player landed
                    if self.jump_state == FALLING:
                        self.__next_jump_state()
                elif obj.rect.collidepoint(self.rect.bottomleft):
                    if self.direction == DIR_LEFT:
                        self.xvel = 0
                elif obj.rect.collidepoint(self.rect.bottomright):
                    if self.direction == DIR_RIGHT:
                        self.xvel = 0

    def _check_pos_interact(self, obj, colliding):
        """Maintains list of objects with possible interaction"""
        if colliding:
            if obj not in self.pos_interact:
                self.pos_interact.append(obj)
        else:
            if obj in self.pos_interact:
                self.pos_interact.remove(obj)

    def __next_jump_state(self):
        if self.jump_state == NOT_JUMPING:
            self.jump_state = JUMP_DELAY
            self.j_delay_timer.start_timer()
        elif self.jump_state == JUMP_DELAY:
            self.jump_state = JUMP
            self.jump_timer.start_timer()
            self._change_vel(DIR_UP, 2)
        elif self.jump_state == JUMP:
            self.jump_state = FALLING
        elif self.jump_state == FALLING:
            self.jump_state = NOT_JUMPING
        else:
            print("Invalid player jump state: " + str(self.jump_state))

    def start_jump(self):
        self.__next_jump_state()

    def _do_jump(self):
        self._change_vel(DIR_UP, self.jumpvel)

    def update(self):
        self.move()

    def do_gravity(self, gravity):
        self._change_vel(DIR_DOWN, gravity)

    def check_interactions(self):
        if not self._use_timer:
            self._use_timer = Timer(self.use_timer_len, self._set_can_use)
        if self._can_use:
            #interact with held item
            if self.held_item:
                if self.interact(self.held_item, PLACE):
                    self._can_use = False
                    self._use_timer.start_timer()
                    return

            for obj in self.pos_interact:
                if self.interact(obj, TOGGLE_POWER):
                    return

    def interact(self, obj, behvaior):
        print('interacting with ' + obj.name)
        for behavior in self.behaviors:
            if self.delegate_behavior(obj, behavior):
                return True
        return False

    def delegate_behavior(self, obj, behavior):
        if behavior == PICKUP:
            return self.pickup(obj)
        if behavior == PLACE:
            return self.drop()

        return obj.interact(self, behavior)

    def drop(self):
        if self.held_item:
            self.drop_item = self.held_item
            self.drop_item.visible = True
            self.drop_item.obey_gravity = True
            self.held_item = None
            print('dropped item')
            return True
        return False

    def pickup(self, obj):
        if PICKUP in obj.behaviors and not self.held_item:
            obj.visible = False
            obj.obey_gravity = False
            self.held_item = obj
            #level.objects.change_layer(self.held_item, self._layer) #Check/update this in level.draw function
            self.held_item.rect.y = self.rect.centery + (self.rect.w / 6)
            self.held_item.rect.x = self.rect.centerx
            #save offsets from the top left of player sprite
            self.held_ofs_x = self.held_item.rect.x - self.rect.x
            self.held_ofs_y = self.held_item.rect.y - self.rect.y
            print('picked up item')
            return True
        return False

    def update_pos(self):
        self.rect.x += self.xvel
        self.rect.y += self.yvel
        if self.held_item:
            self.held_item.rect.x = self.held_ofs_x + self.rect.x
            self.held_item.rect.y = self.held_ofs_y + self.rect.y
Exemplo n.º 38
0
def set_animations(texture):
    
    walking_down = Animation()
    walking_up = Animation()
    walking_left = Animation()
    walking_right = Animation()
        
    walking_down.texture = texture
    walking_down.add_frame(sf.Rectangle((64, 0), (64, 64)))
    walking_down.add_frame(sf.Rectangle((128, 0), (64, 64)))
    walking_down.add_frame(sf.Rectangle((64, 0), (64, 64)))
    walking_down.add_frame(sf.Rectangle((0, 0), (64, 64)))

    walking_up.texture = texture
    walking_up.add_frame(sf.Rectangle((64, 192), (64, 64)))
    walking_up.add_frame(sf.Rectangle((128, 192), (64, 64)))
    walking_up.add_frame(sf.Rectangle((64, 192), (64, 64)))
    walking_up.add_frame(sf.Rectangle((0, 192), (64, 64)))

    walking_left.texture = texture
    walking_left.add_frame(sf.Rectangle((64, 64), (64, 64)))
    walking_left.add_frame(sf.Rectangle((128, 64), (64, 64)))
    walking_left.add_frame(sf.Rectangle((64, 64), (64, 64)))
    walking_left.add_frame(sf.Rectangle((0, 64), (64, 64)))

    walking_right.texture = texture
    walking_right.add_frame(sf.Rectangle((64, 128), (64, 64)))
    walking_right.add_frame(sf.Rectangle((128, 128), (64, 64)))
    walking_right.add_frame(sf.Rectangle((64, 128), (64, 64)))
    walking_right.add_frame(sf.Rectangle((0, 128), (64, 64)))
    
    return (walking_down, walking_left, walking_right, walking_up)
Exemplo n.º 39
0
Arquivo: main.py Projeto: akornmann/VF
#param rk2
dt=((b-a)/N)/(2*(ordre+1))
Tmax=20.

#param animation
ymin = -1.0
ymax = 1.0

#init galerkin
galerkin = GD(ordre,a,b,N)
#Array 3D contenant la solution
W = zeros((2,N,ordre))

#init animation
x = galerkin.getX()
anim = Animation(x,ymin,ymax)

#init rk2
rk2 = RK2(dt,galerkin.dW)

#avance temporelle
while(rk2.t<Tmax):
    
    def lim0():
        we = zeros((2,1))
        #we[:,0] = [10*exp(-100*(rk2.t-0.2)*(rk2.t-0.2)),0.]
        we[:,0] = [sin(5*rk2.t/pi),0.]
        return we
    
    def limN():
        we = zeros((2,1))
Exemplo n.º 40
0
class Button():

    def __init__(self, text, on_click_deferred, on_click_return_value, window_values, surface, hover_animation_surface = None, mouse_down_animation = None, spritesheet_dimensions=(2, 2), font_size='big'): #spritesheet for potential fancy animations later
        self.x, self.y, self.w, self.h = window_values

        self.font_size = font_size

        self.text = text

        self.surface = surface

        self.text_label = render_text(text, (0,0,0), font_size)
        self.get_text_draw_coords()

        self.on_click_deferred = on_click_deferred
        self.on_click_return_value = on_click_return_value

        hover_animation_surface = None

        if hover_animation_surface:
            self.on_hover_animation = Animation(TileSheet(hover_animation_surface, 292, 120, spritesheet_dimensions[0], spritesheet_dimensions[1]), 10, 4)
        else:
            self.on_hover_animation = None

        if mouse_down_animation:
            self.mouse_down_animation = Animation(TileSheet(mouse_down_animation, 292, 120, 1, 1), 10, 1)
        else:
            self.mouse_down_animation = None

        self.on_hover_animation_active = False
        self.mouse_down_animation_active = False

    def on_click(self):
        if self.mouse_down_animation:
            self.mouse_down_animation.done = True
        self.on_click_deferred.value = self.on_click_return_value

    def on_mouse_down(self):
        if not self.mouse_down_animation_active and self.mouse_down_animation:
            self.mouse_down_animation_active = True

    def on_hover(self):
        if not self.on_hover_animation_active and self.on_hover_animation:
            self.on_hover_animation_active = True

    def on_hover_off(self):
        self.mouse_down_animation_active = False

    def update(self, time=1):
        if self.mouse_down_animation_active:
            if self.mouse_down_animation.done:
                self.mouse_down_animation.done = False
                self.mouse_down_animation.reset()
                #self.mouse_down_animation_active = False

            self.mouse_down_animation.update(time)

        elif self.on_hover_animation_active:
            if self.on_hover_animation.done:
                self.on_hover_animation.done = False
                self.on_hover_animation.reset()
                self.on_hover_animation_active = False

            self.on_hover_animation.update(time)


    def draw(self):
        if self.mouse_down_animation_active:
            self.mouse_down_animation.draw(screen, self.x, self.y)
        elif self.on_hover_animation_active:
            self.on_hover_animation.draw(screen, self.x, self.y)
        else:
            screen.blit(self.surface, (self.x, self.y))

        screen.blit(self.text_label, (self.text_x, self.text_y))


    def mouse_over_button(self, mouse_pos):
        return Utils.point_in_rect(mouse_pos, (self.x, self.y, self.w, self.h))

    def get_text_draw_coords(self):
        if self.font_size == "big":
            text_w = font.size(self.text)[0]
            text_h = font.size(self.text)[1]
        elif self.font_size == "small":
            text_w = font_small.size(self.text)[0]
            text_h = font_small.size(self.text)[1]

        self.text_x = self.x + 0.5 * self.w - 0.5 * text_w
        self.text_y = self.y + 0.5 * self.h - 0.5 * text_h
Exemplo n.º 41
0
octopus_parts.extend(octopus_arms)

# add the body of the octopus
octopus_parts.append([AnimationPart("octopus/body")])

# now flip the list, because the body and the arms are drawn before the head
octopus_parts.reverse()

octopus_animation = MultiPartAnimation(octopus_parts,
                                       getpic("octopus/body").get_width(),
                                       getpic("octopus/body").get_height())


raisewing = Animation(["flyingchimney7", "flyingchimney4"], 100, False)
lowerwing = Animation(["flyingchimney5", "flyingchimney6"], 60, False)
chimneyanimation = Animation([raisewing, lowerwing], 600)
chimneyanimation.updatealwaysbattle = True

stevewave = [Animation(["scarysteven05", "scarysteven06"], 1/2),
             Animation(["scarysteven07", "scarysteven08"], 1/2),
             Animation(["scarysteven09", "scarysteven10"], 1/2),
             Animation(["scarysteven11", "scarysteven12"], 1/2),
             Animation(["scarysteven13", "scarysteven14"], 1/2),
             Animation(["scarysteven15", "scarysteven16"], 1/2)]

for a in stevewave:
    a.relativeframerate = True

stevehat = [Animation(["scarysteven17", "scarysteven18", "scarysteven19", "scarysteven20"], 1/4),
            Animation(["scarysteven21", "scarysteven22", "scarysteven23", "scarysteven24"], 1/4),
            Animation(["scarysteven25", "scarysteven26", "scarysteven27", "scarysteven28"], 1/4),
Exemplo n.º 42
0
    def __init__(self,name=0,adress=0,port=0):
        self.name=name
        self.membre=None

        # Différence par rapport à naoqi :
        # Dans l'interface OpenGL, les rotations des membres droits sont inversé par la symétrie
        # Donc en fait les angles pour la partie gauche et la partie droite sont les memes
        # alors que dans naoqi, les parties droite et gauche sont gérées indépendemment
        # Solution :
        # Après copie de la liste renvoyée par le naoqi réel,
        # on copie tous les éléments de la partie gauche pour les coller et remplacer ceux de
        # la partie droite.
        # Données : [angleMin, angleMax, vitesseMin, vitesseMax]
        self.limitsAll={"T14":[[-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.671951770782 , 0.514872133732 , 7.19407272339 , 1.20000004768 ],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.314159274101 , 1.32645022869 , 7.19407272339 , 1.20000004768 ], [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-1.54461634159 , -0.0349065847695 , 7.19407272339 , 1.20000004768 ], [-1.82386910915 , 1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [1.32645022869, -0.314159274101 , 7.19407272339 , 1.20000004768 ], [2.08566856384 , -2.08566856384 , 8.26797389984 , 1.20000004768 ], [ -0.0349065847695, -1.54461634159 , 7.19407272339 , 1.20000004768 ], [1.82386910915 , -1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ]],

                        "H21":[[-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-0.6719517707824707, 0.514872133731842, 7.194072723388672, 1.2000000476837158],
                               [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-0.3141592741012573, 1.326450228691101, 7.194072723388672, 1.2000000476837158], [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-1.5446163415908813, -0.03490658476948738, 7.194072723388672, 1.2000000476837158],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-0.3141592741012573, 1.326450228691101, 7.194072723388672, 1.2000000476837158], [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-1.5446163415908813, -0.03490658476948738, 7.194072723388672, 1.2000000476837158]],
                        #not tested
                        "H25":[[-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.671951770782 , 0.514872133732 , 7.19407272339 , 1.20000004768 ],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.314159274101 , 1.32645022869 , 7.19407272339 , 1.20000004768 ], [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-1.54461634159 , -0.0349065847695 , 7.19407272339 , 1.20000004768 ], [-1.82386910915 , 1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.314159274101 , 1.32645022869 , 7.19407272339 , 1.20000004768 ], [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-1.54461634159 , -0.0349065847695 , 7.19407272339 , 1.20000004768 ], [-1.82386910915 , 1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ]]
                        }

        self.ledMnM={'RightFaceLed8':"eye1D", 'RightFaceLed7':"eye2D",
                     'RightFaceLed6':"eye3D", 'RightFaceLed5':"eye4D",
                     'RightFaceLed4':"eye5D", 'RightFaceLed3':"eye6D",
                     'RightFaceLed2':"eye7D", 'RightFaceLed1':"eye8D",

                     'LeftFaceLed8':"eye8G", 'LeftFaceLed7':"eye7G",
                     'LeftFaceLed6':"eye6G", 'LeftFaceLed5':"eye5G",
                     'LeftFaceLed4':"eye4G", 'LeftFaceLed3':"eye3G",
                     'LeftFaceLed2':"eye2G", 'LeftFaceLed1':"eye1G"
                     }

        self.ledIntensities={'RightFaceLed1':[.0,.0,.0],
                             'RightFaceLed2':[.0,.0,.0],
                             'RightFaceLed3':[.0,.0,.0],
                             'RightFaceLed4':[.0,.0,.0],
                             'RightFaceLed5':[.0,.0,.0],
                             'RightFaceLed6':[.0,.0,.0],
                             'RightFaceLed7':[.0,.0,.0],
                             'RightFaceLed8':[.0,.0,.0],
                             'LeftFaceLed8':[.0,.0,.0],
                             'LeftFaceLed7':[.0,.0,.0],
                             'LeftFaceLed6':[.0,.0,.0],
                             'LeftFaceLed5':[.0,.0,.0],
                             'LeftFaceLed4':[.0,.0,.0],
                             'LeftFaceLed3':[.0,.0,.0],
                             'LeftFaceLed2':[.0,.0,.0],
                             'LeftFaceLed1':[.0,.0,.0]}

        self.ledColors={'RightFaceLed1': ['Face/Led/Red/Right/0Deg/Actuator/Value', 'Face/Led/Green/Right/0Deg/Actuator/Value', 'Face/Led/Blue/Right/0Deg/Actuator/Value'], 'RightFaceLed3': ['Face/Led/Red/Right/90Deg/Actuator/Value', 'Face/Led/Green/Right/90Deg/Actuator/Value', 'Face/Led/Blue/Right/90Deg/Actuator/Value'], 'RightFaceLed2': ['Face/Led/Red/Right/45Deg/Actuator/Value', 'Face/Led/Green/Right/45Deg/Actuator/Value', 'Face/Led/Blue/Right/45Deg/Actuator/Value'], 'RightFaceLed5': ['Face/Led/Red/Right/180Deg/Actuator/Value', 'Face/Led/Green/Right/180Deg/Actuator/Value', 'Face/Led/Blue/Right/180Deg/Actuator/Value'], 'RightFaceLed4': ['Face/Led/Red/Right/135Deg/Actuator/Value', 'Face/Led/Green/Right/135Deg/Actuator/Value', 'Face/Led/Blue/Right/135Deg/Actuator/Value'], 'RightFaceLed7': ['Face/Led/Red/Right/270Deg/Actuator/Value', 'Face/Led/Green/Right/270Deg/Actuator/Value', 'Face/Led/Blue/Right/270Deg/Actuator/Value'], 'RightFaceLed6': ['Face/Led/Red/Right/225Deg/Actuator/Value', 'Face/Led/Green/Right/225Deg/Actuator/Value', 'Face/Led/Blue/Right/225Deg/Actuator/Value'], 'RightFaceLed8': ['Face/Led/Red/Right/315Deg/Actuator/Value', 'Face/Led/Green/Right/315Deg/Actuator/Value', 'Face/Led/Blue/Right/315Deg/Actuator/Value'], 'LeftFaceLed1': ['Face/Led/Red/Left/0Deg/Actuator/Value', 'Face/Led/Green/Left/0Deg/Actuator/Value', 'Face/Led/Blue/Left/0Deg/Actuator/Value'], 'LeftFaceLed3': ['Face/Led/Red/Left/90Deg/Actuator/Value', 'Face/Led/Green/Left/90Deg/Actuator/Value', 'Face/Led/Blue/Left/90Deg/Actuator/Value'], 'LeftFaceLed2': ['Face/Led/Red/Left/45Deg/Actuator/Value', 'Face/Led/Green/Left/45Deg/Actuator/Value', 'Face/Led/Blue/Left/45Deg/Actuator/Value'], 'LeftFaceLed5': ['Face/Led/Red/Left/180Deg/Actuator/Value', 'Face/Led/Green/Left/180Deg/Actuator/Value', 'Face/Led/Blue/Left/180Deg/Actuator/Value'], 'LeftFaceLed4': ['Face/Led/Red/Left/135Deg/Actuator/Value', 'Face/Led/Green/Left/135Deg/Actuator/Value', 'Face/Led/Blue/Left/135Deg/Actuator/Value'], 'LeftFaceLed7': ['Face/Led/Red/Left/270Deg/Actuator/Value', 'Face/Led/Green/Left/270Deg/Actuator/Value', 'Face/Led/Blue/Left/270Deg/Actuator/Value'], 'LeftFaceLed6': ['Face/Led/Red/Left/225Deg/Actuator/Value', 'Face/Led/Green/Left/225Deg/Actuator/Value', 'Face/Led/Blue/Left/225Deg/Actuator/Value'], 'LeftFaceLed8': ['Face/Led/Red/Left/315Deg/Actuator/Value', 'Face/Led/Green/Left/315Deg/Actuator/Value', 'Face/Led/Blue/Left/315Deg/Actuator/Value']}

        self.language="french"
        self.volume=0
        self.listLimits={"Body":[]}

        self.animation = Animation()
Exemplo n.º 43
0
class LedsActuator:
    def __init__(self, proxy):
        assert proxy.__class__ is ALProxy;
        self.__proxy = proxy;
        self.__ledsNames, self.__colorsNames = self.__getLedsNames();
        self.__animation = Animation();
        self.__parallelism = False;

    def setParallelism(self, value):
        self.__parallelism = value;

    #test OK
    def getLedsNames(self):
        return self.__ledsNames;

    #test OK
    def __getLedsNames(self):
        names = [];
        colorsNames = {};
        for i in range(1,9):
            name = "RightFaceLed%s" %(i);
            names.append(name);
            degree = (i-1)*45;
            red = "Face/Led/Red/Right/%sDeg/Actuator/Value" %(degree);
            green = "Face/Led/Green/Right/%sDeg/Actuator/Value" %(degree);
            blue = "Face/Led/Blue/Right/%sDeg/Actuator/Value" %(degree);
            tab = [red,green,blue];
            colorsNames[name] = tab;
        for i in range(8,0,-1):
            name = "LeftFaceLed%s" %(i);
            names.append(name);
            degree = (i-1)*45;
            red = "Face/Led/Red/Left/%sDeg/Actuator/Value" %(degree);
            green = "Face/Led/Green/Left/%sDeg/Actuator/Value" %(degree);
            blue = "Face/Led/Blue/Left/%sDeg/Actuator/Value" %(degree);
            tab = [red,green,blue];
            colorsNames[name] = tab;

        return names, colorsNames;

    #test OK
    def getLedName(self, ledsNumber):
        assert ledsNumber < len(self.__ledsNames);
        return self.__ledsNames[ledsNumber];

    #test OK
    def getLedsNumber(self):
        return len(self.__ledsNames);

    #test OK
    def allLedsOn(self):
        name = "FaceLeds";
        self.__proxy.on(name);

    #test OK
    def rightLedsOn(self):
        name = "RightFaceLeds";
        self.__proxy.on(name);

    #test OK
    def leftLedsOn(self):
        name = "LeftFaceLeds";
        self.__proxy.on(name);

    #test OK
    def allLedsOff(self):
        name = "FaceLeds";
        self.__proxy.off(name);

    #test OK
    def rightLedsOff(self):
        name = "RightFaceLeds";
        self.__proxy.off(name);

    #test OK
    def leftLedsOff(self):
        name = "LeftFaceLeds";
        self.__proxy.off(name);

    #test OK
    def getIntensity(self, ledNumber):
        name = self.getLedName(ledNumber);
        return self.__proxy.getIntensity(name);

    #test OK
    #renvoie red, green, blue
    def getColor(self, ledNumber):
        red, green, blue = 0,0,0;

        name = self.getLedName(ledNumber);
        tabColor = self.__colorsNames[name];
        #print(self.__colorsNames)

        redIntensity = self.__proxy.getIntensity(tabColor[0]);
        greenIntensity = self.__proxy.getIntensity(tabColor[1]);
        blueIntensity = self.__proxy.getIntensity(tabColor[2]);

        red = int(redIntensity*255);
        green = int(greenIntensity*255);
        blue = int(blueIntensity*255);

        return red, green, blue;

    #test OK
    def setIntensity(self, ledNumber, intensity):
        name = self.getLedName(ledNumber);
        self.__proxy.setIntensity(name, intensity);

    #test OK
    def setIntensities(self, ledNumber, redIntensity, greenIntensity, blueIntensity):
        name = self.getLedName(ledNumber);
        tabColor = self.__colorsNames[name];
        self.__proxy.setIntensity(tabColor[0], redIntensity);
        self.__proxy.setIntensity(tabColor[1], greenIntensity);
        self.__proxy.setIntensity(tabColor[2], blueIntensity);

    #test OK
    def fadeIntensity(self, ledsNumber, intensity, duration):
        name = self.getLedName(ledsNumber);
        self.__proxy.fade(name, intensity, duration);

    #test OK
    def setColor(self, ledsNumber, red, green, blue):
        name = self.getLedName(ledsNumber);
        self.__setColor(name, red, green, blue);

    #test OK
    def __setColor(self, ledName, red, green, blue):
        assert type(red) is int;
        assert type(green) is int;
        assert type(blue) is int;
        assert red >= 0 and red <= 255;
        assert green >= 0 and green <= 255;
        assert blue >= 0 and blue <= 255;
        tabColor = self.__colorsNames[ledName];

        redIntensity = 0;
        greenIntensity = 0;
        blueIntensity = 0;

        if red != 0 :
            redIntensity = red/255.0;
        if green != 0 :
            greenIntensity = green/255.0;
        if blue != 0 :
            blueIntensity = blue/255.0;

##        print(tabColor)
##        print("ok")
##        print(self.__colorsNames)
        self.__proxy.setIntensity(tabColor[0], redIntensity);
        self.__proxy.setIntensity(tabColor[1], greenIntensity);
        self.__proxy.setIntensity(tabColor[2], blueIntensity);


    #test OK
    def fadeColor(self, ledNumber, red, green, blue, duration):
        name = self.getLedName(ledNumber);
        color = self.__RGBToInt(red, green, blue);

        self.__proxy.fadeRGB (name, color, duration);

    #test OK
    def addLedAnimation(self, ledNumber, red, green, blue, time):
        name = self.getLedName(ledNumber);
        rgb = self.__RGBToInt(red, green, blue);
        self.__animation.addValue(name, rgb, time);

    #test OK
    def resetAnimation(self):
        self.__animation.reset();

    #test OK
    def playAnimation(self):
        names = self.__animation.getNames();
        values = self.__animation.getValues();
        times = self.__animation.getTimes();
        threads = [];

        i = 0;
        for name in names :
            valuesTab = values[i];
            timesTab = times[i];
            thread = threading.Thread(None, self.__playLedAnimation, None, (name, valuesTab, timesTab), {});
            threads.append(thread);
            i=i+1;

        for thread in threads:
            thread.start();

    #test OK
    def __playLedAnimation(self, name, values, times):
        assert len(values) == len(times);
        durations = self.__getDurations(times);
        for i in range(len(times)):
            duration = durations[i];
            color = values[i];
            time.sleep(duration);
            red,green,blue = self.__intToRGB(color);
            self.__setColor(name, red, green, blue);

    #test OK
    def __getDurations(self, timesTab):
        durationTab = [];
        previousTime = -1;

        if len(timesTab)>0:
            previousTime = timesTab[0];
            durationTab.append(previousTime);
            for i in range(1, len(timesTab)):
                currentTime = timesTab[i];
                if currentTime <= previousTime :
                    string = "Times must be inscreasing at index %s : %s" %(i, timesTab[i])
                    raise Exception("TimeError", string);
                else:
                    duration = currentTime - previousTime;
                    previousTime = currentTime;
                    durationTab.append(duration);

        return durationTab;

    #test OK
    def displayLedsNumber(self, ledsWord):
        for i in range(len(self.__ledsNames)):
            print(ledsWord,i, ":", self.__ledsNames[i]);

    #test OK
    def displayAnimation(self, ledWord, valueWord, timeWord, characterNumbers):
        names = self.__animation.getNames();
        values = self.__animation.getValues();
        times = self.__animation.getTimes();

        for i in range(len(names)):
            ledNumber = self.__ledsNames.index(names[i]);
            print(ledWord,ledNumber," : ");
            for j in range(len(values[i])):
                string = "    %s : %s" %(valueWord, hex(values[i][j]));
                string = self.addSpaces(string, characterNumbers);
                print(string,"-",timeWord,":",times[i][j]);

    #test OK
    #doublon !!!!
    def addSpaces(self, string, characterTotalNumbers):
        characterNumbers = len(string);
        if characterTotalNumbers > characterNumbers:
            spaceNumbers = characterTotalNumbers - characterNumbers;
            string = string+spaceNumbers*' ';
        return string;

    #test OK
    def __displayColorsNames(self):

        for name in self.__ledsNames:
            print(name,' :');
            tab = self.__colorsNames[name];
            print("   ",tab[0]);
            print("   ",tab[1]);
            print("   ",tab[2]);


    #test OK
    def __RGBToInt(self, red, green, blue):
        assert type(red) is int;
        assert type(green) is int;
        assert type(blue) is int;
        assert red >= 0 and red <= 255;
        assert green >= 0 and green <= 255;
        assert blue >= 0 and blue <= 255;

        color = int('%02x%02x%02x' %(red, green, blue), 16);

        #to check
        #print(hex(color));

        return color;

    #test OK
    def __intToRGB(self, rgb):
        blue, green, red = [(rgb >> (8*i)) & 255 for i in range(3)];
        return red,green,blue;

    def test(self):
        rgb = self.__RGBToInt(85,127,12);
        print(self.__intToRGB(rgb));
Exemplo n.º 44
0
class Player(Dancer):
    xspeed = 0
    yspeed = 0
    leftpresstime = 0
    rightpresstime = 0
    uppresstime = 0
    downpresstime = 0
    normal_width = 10
    normal_height = 10
    xpos = 0
    ypos = 0
    lastxupdate = 0
    lastyupdate = 0
    storyprogress = 1

    #animation
    left_animation = Animation([
        GR["honeyside3"], GR["honeyside4"], GR["honeyside3"], GR["honeyside4"]
    ], 200)
    right_animation = Animation([
        GR["honeyside0"], GR["honeyside1"], GR["honeyside0"], GR["honeyside2"]
    ], 200)
    down_animation = Animation([
        GR["honeyback3"], GR["honeyback4"], GR["honeyback3"], GR["honeyback5"]
    ], 200)
    up_animation = Animation([
        GR["honeyback0"], GR["honeyback1"], GR["honeyback0"], GR["honeyback2"]
    ], 200)
    current_animation = left_animation

    def teleport(self, x, y):
        self.xpos = x
        self.ypos = y

    def draw(self
             ):  #movement is combination of top down scrolling and free range
        m = maps.current_map
        mw = m.finalimage.get_width()
        mh = m.finalimage.get_height()
        if self.xpos >= variables.hh and self.xpos <= (
                mw - variables.hh):  #If in scrolling area
            drawx = variables.hh  #middle of screen
        elif self.xpos > (mw - variables.hh):  #if on right side
            drawx = self.xpos - (mw - variables.height
                                 )  #normal x pos adjusted for scrolling area
        else:
            drawx = self.xpos  #otherwise make the coordinates normal
        if self.ypos >= variables.hh and self.ypos <= (
                mh - variables.hh):  #same logic for y pos
            drawy = variables.hh
        elif self.ypos > (mh - variables.hh):
            drawy = self.ypos - (
                mh - variables.height
            )  #mh - variables.height is the height of the scrolling area
        else:
            drawy = self.ypos
        self.current_pic_scaled()
        variables.screen.blit(self.current_display, [drawx, drawy])

    def change_animation(self):
        if self.xspeed == 0:
            if self.yspeed < 0:
                self.current_animation = self.up_animation
            elif self.yspeed > 0:
                self.current_animation = self.down_animation
        elif self.xspeed < 0:
            self.current_animation = self.left_animation
        elif self.xspeed > 0:
            self.current_animation = self.right_animation
        self.current_animation.reset()

    def keypress(self, k):
        self.move()
        t = variables.current_time
        s = variables.playerspeed * variables.scaleoffset
        if k == pygame.K_LEFT or k == pygame.K_a:
            self.leftpresstime = variables.current_time
            self.xspeed = -s
            self.lastxupdate = t
        if k == pygame.K_RIGHT or k == pygame.K_d:
            self.rightpresstime = variables.current_time
            self.lastxupdate = t
            self.xspeed = s
        if k == pygame.K_UP or k == pygame.K_w:
            self.uppresstime = variables.current_time
            self.yspeed = -s
            self.lastyupdate = t
        if k == pygame.K_DOWN or k == pygame.K_s:
            self.downpresstime = variables.current_time
            self.yspeed = s
            self.lastyupdate = t
        self.change_animation()

    def keyrelease(self, k):
        self.move()
        s = variables.playerspeed * variables.scaleoffset
        t = variables.current_time
        if k == pygame.K_LEFT or k == pygame.K_a:
            self.leftpresstime = 0
            self.lastxupdate = t
            if self.rightpresstime == 0:
                self.xspeed = 0
            else:
                self.xspeed = s
        elif k == pygame.K_RIGHT or k == pygame.K_d:
            self.rightpresstime = 0
            self.lastxupdate = t
            if self.leftpresstime == 0:
                self.xspeed = 0
            else:
                self.xspeed = -s
        elif k == pygame.K_UP or k == pygame.K_w:
            self.lastyupdate = t
            self.uppresstime = 0
            if self.downpresstime == 0:
                self.yspeed = 0
            else:
                self.yspeed = s
        elif k == pygame.K_DOWN or k == pygame.K_s:
            self.lastyupdate = t
            self.downpresstime = 0
            if self.uppresstime == 0:
                self.yspeed = 0
            else:
                self.yspeed = -s
        self.change_animation()

    #moves with collision detection
    def move(self):
        t = variables.current_time
        #calculate moved positions
        xtime_factor = t - self.lastxupdate
        ytime_factor = t - self.lastyupdate
        movedxpos = self.xpos + self.xspeed * xtime_factor
        movedypos = self.ypos + self.yspeed * ytime_factor

        #collision detection
        iscollisionx = False
        iscollisiony = False
        m = maps.current_map
        t = m.terrain
        colliderects = m.colliderects
        numofrocks = len(t)

        #checks if the player collides with a rock
        def collisioncheck(arock, x, y):
            if (arock.iscollideable):
                if (arock.mask.overlap(
                        self.mask,
                    [int(x - arock.collidex),
                     int(y - arock.collidey)]) == None):
                    return False
                else:
                    return True
            else:
                return False
            #return arock.iscollideable and (x+self.normal_width)>=arock.collidex and x<=(arock.collidex + arock.collidew) \
            #      and (y+self.normal_height)>=arock.collidey and y<=(arock.collidey + arock.collideh)

        if not self.xspeed == 0:
            #first check for edges of map
            if movedxpos < 0:
                self.xpos = 0
                iscollisionx = True
            elif movedxpos + self.normal_width > m.finalimage.get_width():
                self.xpos = m.finalimage.get_width() - self.normal_width
                iscollisionx = True
            else:
                #collision detection for the moved x pos with the unmoved y pos
                for x in range(0, len(colliderects)):
                    playerR = Rect(movedxpos, self.ypos, self.normal_width,
                                   self.normal_height)
                    if (playerR.colliderect(colliderects[x]) == 1):
                        iscollisionx = True
                        break
                for x in range(0, numofrocks):
                    r = t[x]
                    if collisioncheck(r, movedxpos, self.ypos):
                        iscollisionx = True
                        break

        if not self.yspeed == 0:
            if movedypos < 0:
                self.ypos = 0
                iscollisiony = True
            elif movedypos + self.normal_height > m.finalimage.get_height():
                self.ypos = m.finalimage.get_height() - self.normal_height
                iscollisiony = True
            else:
                #collision detection for the moved y pos with the unmoved x pos
                for x in range(0, len(colliderects)):
                    playerR = Rect(self.xpos, movedypos, self.normal_width,
                                   self.normal_height)
                    if (playerR.colliderect(colliderects[x]) == 1):
                        iscollisiony = True
                        break
                for x in range(0, numofrocks):
                    r = t[x]
                    if collisioncheck(r, self.xpos, movedypos):
                        iscollisiony = True
                        break

        if not iscollisionx:
            self.xpos = movedxpos

        if not iscollisiony:
            self.ypos = movedypos

        self.lastxupdate = variables.current_time
        self.lastyupdate = variables.current_time

    def current_pic_scaled(self):  #returns the current pic to display
        if self.leftpresstime == 0 and self.rightpresstime == 0 and \
            self.uppresstime == 0 and self.downpresstime == 0:
            c = self.current_animation.pics[0]
        else:
            c = self.current_animation.current_frame()
        c = pygame.transform.scale(c["img"], [
            int(c["w"] * variables.scaleoffset),
            int(c["h"] * variables.scaleoffset)
        ])
        self.current_display = c

    def scale_by_offset(self):
        self.current_pic_scaled()
        self.mask = pygame.mask.from_surface(self.current_display)
        self.normal_width = self.current_display.get_width()
        self.normal_height = self.current_display.get_height()
        s = variables.playerspeed * variables.scaleoffset
        if (self.xspeed > 0):
            self.xspeed = s
        if (self.xspeed < 0):
            self.xspeed = -s
        if (self.yspeed < 0):
            self.yspeed = -s
        if (self.yspeed > 0):
            self.yspeed = s

    def ismoving(self):
        return not (self.xspeed == 0 and self.yspeed == 0)

    def heal(self):
        self.health = stathandeling.max_health(self.lv)

    def change_of_state(self):
        self.downpresstime = 0
        self.uppresstime = 0
        self.leftpresstime = 0
        self.rightpresstime = 0
        self.xspeed = 0
        self.yspeed = 0
Exemplo n.º 45
0
class ALProxy():
    # staticNao = NaoCommunicationVirtual.AbstractNaoEvenement
    # (remplace les fonctions du robot réel pour les events)
    staticNao=None
    # virtualNao = Nao3D
    # (remplace les membres du robot réel)
    virtualNao=None

    vocabList = []
    typeRobot="T14"

    membres={0:"HeadYaw",1:"HeadPitch",
                    2:"LShoulderPitch",3:"LShoulderRoll",4:"LElbowYaw",5:"LElbowRoll",6:"LWristYaw",7:"LHand",
                    8:"RShoulderPitch",9:"RShoulderRoll",10:"RElbowYaw",11:"RElbowRoll",12:"RWristYaw",13:"RHand"}

    membresVirtual={0:"teteG2", 1:"teteG0",#ok
                            2:"bicepsG0",3:"bicepsG2",4:"coudeG1",5:"coudeG2",6:"mainG1",7:"doigt1G0",#ok
                            8:"bicepsD0",9:"bicepsD2",10:"coudeD1",11:"coudeD2",12:"mainD1",13:"doigt1D0"#ok
                            }

    jointsAll={"T14":["HeadYaw", "HeadPitch",
                       "LShoulderPitch", "LShoulderRoll", "LElbowYaw", "LElbowRoll", "LWristYaw", "LHand",
                       "RShoulderPitch", "RShoulderRoll", "RElbowYaw", "RElbowRoll", "RWristYaw", "RHand"],

               "H21":['HeadYaw', 'HeadPitch',
                       'LShoulderPitch', 'LShoulderRoll', 'LElbowYaw', 'LElbowRoll',
                       'LHipYawPitch', 'LHipRoll', 'LHipPitch', 'LKneePitch', 'LAnklePitch', 'LAnkleRoll',
                       'RHipYawPitch', 'RHipRoll', 'RHipPitch', 'RKneePitch', 'RAnklePitch', 'RAnkleRoll',
                       'RShoulderPitch', 'RShoulderRoll', 'RElbowYaw', 'RElbowRoll'],
               #not tested, may not work :
               "H25":['HeadYaw', 'HeadPitch',
                       'LShoulderPitch', 'LShoulderRoll', 'LElbowYaw', 'LElbowRoll', "LWristYaw", "LHand",
                       'LHipYawPitch', 'LHipRoll', 'LHipPitch', 'LKneePitch', 'LAnklePitch', 'LAnkleRoll',
                       'RHipYawPitch', 'RHipRoll', 'RHipPitch', 'RKneePitch', 'RAnklePitch', 'RAnkleRoll',
                       'RShoulderPitch', 'RShoulderRoll', 'RElbowYaw', 'RElbowRoll',"RWristYaw", "RHand"]
                }
    parallelism = False;


    def __init__(self,name=0,adress=0,port=0):
        self.name=name
        self.membre=None

        # Différence par rapport à naoqi :
        # Dans l'interface OpenGL, les rotations des membres droits sont inversé par la symétrie
        # Donc en fait les angles pour la partie gauche et la partie droite sont les memes
        # alors que dans naoqi, les parties droite et gauche sont gérées indépendemment
        # Solution :
        # Après copie de la liste renvoyée par le naoqi réel,
        # on copie tous les éléments de la partie gauche pour les coller et remplacer ceux de
        # la partie droite.
        # Données : [angleMin, angleMax, vitesseMin, vitesseMax]
        self.limitsAll={"T14":[[-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.671951770782 , 0.514872133732 , 7.19407272339 , 1.20000004768 ],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.314159274101 , 1.32645022869 , 7.19407272339 , 1.20000004768 ], [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-1.54461634159 , -0.0349065847695 , 7.19407272339 , 1.20000004768 ], [-1.82386910915 , 1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [1.32645022869, -0.314159274101 , 7.19407272339 , 1.20000004768 ], [2.08566856384 , -2.08566856384 , 8.26797389984 , 1.20000004768 ], [ -0.0349065847695, -1.54461634159 , 7.19407272339 , 1.20000004768 ], [1.82386910915 , -1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ]],

                        "H21":[[-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-0.6719517707824707, 0.514872133731842, 7.194072723388672, 1.2000000476837158],
                               [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-0.3141592741012573, 1.326450228691101, 7.194072723388672, 1.2000000476837158], [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-1.5446163415908813, -0.03490658476948738, 7.194072723388672, 1.2000000476837158],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-0.3141592741012573, 1.326450228691101, 7.194072723388672, 1.2000000476837158], [-2.0856685638427734, 2.0856685638427734, 8.267973899841309, 1.2000000476837158], [-1.5446163415908813, -0.03490658476948738, 7.194072723388672, 1.2000000476837158]],
                        #not tested
                        "H25":[[-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.671951770782 , 0.514872133732 , 7.19407272339 , 1.20000004768 ],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.314159274101 , 1.32645022869 , 7.19407272339 , 1.20000004768 ], [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-1.54461634159 , -0.0349065847695 , 7.19407272339 , 1.20000004768 ], [-1.82386910915 , 1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-1.1452850103378296, 0.7407177090644836, 4.161737442016602, 3.200000047683716], [-0.37943458557128906, 0.7904596328735352, 4.161737442016602, 3.200000047683716], [-1.535889744758606, 0.4839797914028168, 6.40239143371582, 3.200000047683716], [-0.09232791513204575, 2.112546443939209, 6.40239143371582, 3.200000047683716], [-1.1894419193267822, 0.9225810170173645, 6.40239143371582, 3.200000047683716], [-0.3977605402469635, 0.7689920663833618, 4.161737442016602, 3.200000047683716],
                               [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-0.314159274101 , 1.32645022869 , 7.19407272339 , 1.20000004768 ], [-2.08566856384 , 2.08566856384 , 8.26797389984 , 1.20000004768 ], [-1.54461634159 , -0.0349065847695 , 7.19407272339 , 1.20000004768 ], [-1.82386910915 , 1.82386910915 , 24.6229305267 , 0.759999990463 ], [0.0 , 1.0 , 8.32999992371 , 0.550000011921 ]]
                        }

        self.ledMnM={'RightFaceLed8':"eye1D", 'RightFaceLed7':"eye2D",
                     'RightFaceLed6':"eye3D", 'RightFaceLed5':"eye4D",
                     'RightFaceLed4':"eye5D", 'RightFaceLed3':"eye6D",
                     'RightFaceLed2':"eye7D", 'RightFaceLed1':"eye8D",

                     'LeftFaceLed8':"eye8G", 'LeftFaceLed7':"eye7G",
                     'LeftFaceLed6':"eye6G", 'LeftFaceLed5':"eye5G",
                     'LeftFaceLed4':"eye4G", 'LeftFaceLed3':"eye3G",
                     'LeftFaceLed2':"eye2G", 'LeftFaceLed1':"eye1G"
                     }

        self.ledIntensities={'RightFaceLed1':[.0,.0,.0],
                             'RightFaceLed2':[.0,.0,.0],
                             'RightFaceLed3':[.0,.0,.0],
                             'RightFaceLed4':[.0,.0,.0],
                             'RightFaceLed5':[.0,.0,.0],
                             'RightFaceLed6':[.0,.0,.0],
                             'RightFaceLed7':[.0,.0,.0],
                             'RightFaceLed8':[.0,.0,.0],
                             'LeftFaceLed8':[.0,.0,.0],
                             'LeftFaceLed7':[.0,.0,.0],
                             'LeftFaceLed6':[.0,.0,.0],
                             'LeftFaceLed5':[.0,.0,.0],
                             'LeftFaceLed4':[.0,.0,.0],
                             'LeftFaceLed3':[.0,.0,.0],
                             'LeftFaceLed2':[.0,.0,.0],
                             'LeftFaceLed1':[.0,.0,.0]}

        self.ledColors={'RightFaceLed1': ['Face/Led/Red/Right/0Deg/Actuator/Value', 'Face/Led/Green/Right/0Deg/Actuator/Value', 'Face/Led/Blue/Right/0Deg/Actuator/Value'], 'RightFaceLed3': ['Face/Led/Red/Right/90Deg/Actuator/Value', 'Face/Led/Green/Right/90Deg/Actuator/Value', 'Face/Led/Blue/Right/90Deg/Actuator/Value'], 'RightFaceLed2': ['Face/Led/Red/Right/45Deg/Actuator/Value', 'Face/Led/Green/Right/45Deg/Actuator/Value', 'Face/Led/Blue/Right/45Deg/Actuator/Value'], 'RightFaceLed5': ['Face/Led/Red/Right/180Deg/Actuator/Value', 'Face/Led/Green/Right/180Deg/Actuator/Value', 'Face/Led/Blue/Right/180Deg/Actuator/Value'], 'RightFaceLed4': ['Face/Led/Red/Right/135Deg/Actuator/Value', 'Face/Led/Green/Right/135Deg/Actuator/Value', 'Face/Led/Blue/Right/135Deg/Actuator/Value'], 'RightFaceLed7': ['Face/Led/Red/Right/270Deg/Actuator/Value', 'Face/Led/Green/Right/270Deg/Actuator/Value', 'Face/Led/Blue/Right/270Deg/Actuator/Value'], 'RightFaceLed6': ['Face/Led/Red/Right/225Deg/Actuator/Value', 'Face/Led/Green/Right/225Deg/Actuator/Value', 'Face/Led/Blue/Right/225Deg/Actuator/Value'], 'RightFaceLed8': ['Face/Led/Red/Right/315Deg/Actuator/Value', 'Face/Led/Green/Right/315Deg/Actuator/Value', 'Face/Led/Blue/Right/315Deg/Actuator/Value'], 'LeftFaceLed1': ['Face/Led/Red/Left/0Deg/Actuator/Value', 'Face/Led/Green/Left/0Deg/Actuator/Value', 'Face/Led/Blue/Left/0Deg/Actuator/Value'], 'LeftFaceLed3': ['Face/Led/Red/Left/90Deg/Actuator/Value', 'Face/Led/Green/Left/90Deg/Actuator/Value', 'Face/Led/Blue/Left/90Deg/Actuator/Value'], 'LeftFaceLed2': ['Face/Led/Red/Left/45Deg/Actuator/Value', 'Face/Led/Green/Left/45Deg/Actuator/Value', 'Face/Led/Blue/Left/45Deg/Actuator/Value'], 'LeftFaceLed5': ['Face/Led/Red/Left/180Deg/Actuator/Value', 'Face/Led/Green/Left/180Deg/Actuator/Value', 'Face/Led/Blue/Left/180Deg/Actuator/Value'], 'LeftFaceLed4': ['Face/Led/Red/Left/135Deg/Actuator/Value', 'Face/Led/Green/Left/135Deg/Actuator/Value', 'Face/Led/Blue/Left/135Deg/Actuator/Value'], 'LeftFaceLed7': ['Face/Led/Red/Left/270Deg/Actuator/Value', 'Face/Led/Green/Left/270Deg/Actuator/Value', 'Face/Led/Blue/Left/270Deg/Actuator/Value'], 'LeftFaceLed6': ['Face/Led/Red/Left/225Deg/Actuator/Value', 'Face/Led/Green/Left/225Deg/Actuator/Value', 'Face/Led/Blue/Left/225Deg/Actuator/Value'], 'LeftFaceLed8': ['Face/Led/Red/Left/315Deg/Actuator/Value', 'Face/Led/Green/Left/315Deg/Actuator/Value', 'Face/Led/Blue/Left/315Deg/Actuator/Value']}

        self.language="french"
        self.volume=0
        self.listLimits={"Body":[]}

        self.animation = Animation()

    #test ok
    @staticmethod
    def associateVirtualRobot(nao):
        ALProxy.virtualNao=nao

    @staticmethod
    def associateStaticNao(nao):
        ALProxy.staticNao=nao

    @staticmethod
    def getFunction(functionName):
        functionsByName={
            "onWordRecognized":ALProxy.staticNao._wordRecognizedEvent,
            "onPictureDetected":ALProxy.staticNao._pictureDetectedEvent,
            "onFaceDetected":ALProxy.staticNao._faceDetectedEvent,
            "onTactileDetected":ALProxy.staticNao._tactileEvent,
            "onWordDetected":ALProxy.staticNao._speechDetectedEvent}
        return functionsByName[functionName]

    @staticmethod
    def eventCall(function, args):
        ##try:
        if function != "onWordDetected":
            ALProxy.getFunction(function)(*args)
            return 1
        else :
            for mot in args[0].split():
                if mot.strip() in ALProxy.vocabList :
                    ALProxy.getFunction(function)()
                    return 1
                else :
                    print(mot.strip()+" is not in Vocabulary list")
        ##except:
        ##    print("Pas de AbstractNaoEvenement instancié")
        return 0

    @staticmethod
    def setType(robot="T14"):
        ALProxy.typeRobot=robot
        #reconstruction des membres
        ALProxy.membres={}
        for a in range(len(ALProxy.jointsAll[robot])):
            ALProxy.membres[a]=ALProxy.jointsAll[robot][a]

        if robot=="T14":
            ALProxy.membresVirtual={0:"teteG2", 1:"teteG0",#ok
                                2:"bicepsG0", 3:"bicepsG2", 4:"coudeG1", 5:"coudeG2", 6:"mainG1", 7:"doigt1G0",#ok
                                8:"bicepsD0", 9:"bicepsD2", 10:"coudeD1", 11:"coudeD2", 12:"mainD1", 13:"doigt1D0"#ok
                                }
        elif robot=="H21":
            ALProxy.membresVirtual={0:"teteG2", 1:"teteG0",#ok
                                2:"bicepsG0", 3:"bicepsG2", 4:"coudeG1", 5:"coudeG2",#ok
                                6:'hancheG1', 7:'cuisseG1', 8:'cuisseG0', 9:'molletG0', 10:'piedG0', 11:'piedG1',
                                12:'hancheD1', 13:'cuisseD1', 14:'cuisseD0', 15:'molletD0', 16:'piedD0', 17:'piedD1',
                                18:"bicepsD0", 19:"bicepsD2",20:"coudeD1",21:"coudeD2"
                                }
        elif robot=="H25":
            ALProxy.membresVirtual={0:"teteG2", 1:"teteG0",#ok
                                2:"bicepsG0", 3:"bicepsG2", 4:"coudeG1", 5:"coudeG2", 6:"mainG1", 7:"doigt1G0",
                                8:'hancheG1', 9:'cuisseG1', 10:'cuisseG0', 11:'molletG0', 12:'piedG0', 13:'piedG1',
                                14:'hancheD1', 15:'cuisseD1', 16:'cuisseD0', 17:'molletD0', 18:'piedD0', 19:'piedD1',
                                20:"bicepsD0", 21:"bicepsD2", 22:"coudeD1", 23:"coudeD2", 24:"mainD1", 25:"doigt1D0"
                                }


    @staticmethod
    def getKeys():
        l = []
        Virtual={0:"teteG2", 1:"teteG0",#ok
                                2:"bicepsG0", 3:"bicepsG2", 4:"coudeG1", 5:"coudeG2", 6:"mainG1", 7:"doigt1G0",
                                8:'hancheG1', 9:'cuisseG1', 10:'cuisseG0', 11:'molletG0', 12:'piedG0', 13:'piedG1',
                                14:'hancheD1', 15:'cuisseD1', 16:'cuisseD0', 17:'molletD0', 18:'piedD0', 19:'piedD1',
                                20:"bicepsD0", 21:"bicepsD2", 22:"coudeD1", 23:"coudeD2", 24:"mainD1", 25:"doigt1D0"
                                }
        for a in range(len(Virtual)):
            l.append(Virtual[a])
        return l


    @staticmethod
    def setParallelism(paral):
        ALProxy.parallelism = paral

    #test ok
    def setLanguage(self, language):
        self.language=language

    #test ok
    def getLanguage(self):
        return self.language

    #test ok
    def say(self, text):
        #print("NAO dit : "+str(text))
        self.virtualNao.addSpeaking(text)
        if not ALProxy.parallelism:
            self.timePerCharacter=0.1
            TimerT.sleep(len(text)*self.timePerCharacter)

    def setVolume(self, value):
        self.volume=value

    def getVolume(self):
        return self.volume

    #test ok
    def getJointNames(self, part="Body"):
        return self.jointsAll[self.typeRobot]

    #test ok
    def getLimits(self, part="Body"):
        return self.limitsAll[self.typeRobot]

    #test ok
    def getStiffnesses(self, part="Body"):
        r=[]
        for a in self.membres.keys():
            num=self.getNumberFromName(a)
            nom=self.membresVirtual[num][:-1]
            r.append(self.virtualNao.getMembre(nom).stiffness)
        return r

    def getStiffness(self, numeroMoteur):
            print("not implemented")

    def setStiffnesses(self, part="Body", value=1):
        names=self.getNamesFromPart(part)
        for a in names:
            self.virtualNao.getMembre(a[:-1]).stiffness=value

    def setStiffness(self, numeroMoteur, taux):
            print("not implemented")

    def getAngles(self, part="Body", isStg=True):
        return [0,0,0,0]

    #a verifier
    def getMinAngle(self, numero):
        return self.limitsAll[self.typeRobot][0]

    #a verifier
    def getMaxAngle(self, numero):
        return self.limitsAll[self.typeRobot][1]

    def angleInterpolation(self, name, motorAngle, time, isAbsolute):
        num=self.getNumberFromName(name)
        nom=self.membresVirtual[num][:-1]
        n=int(self.membresVirtual[num][-1])
        #print(self.virtualNao.getMembre(nom).rotate, nom)
        if nom[:5] == "doigt":
            self.virtualNao.getMembre("doigt3"+nom[-1]).setAngleFromPercent(0,100-motorAngle)
            self.virtualNao.getMembre("doigt2"+nom[-1]).setAngleFromPercent(0,100-motorAngle)
            self.virtualNao.getMembre("doigt1"+nom[-1]).setAngleFromPercent(0,100)#=fixe
        else :
            self.virtualNao.getMembre(nom).setAngle(n,motorAngle/3.14*180,time)

        if not ALProxy.parallelism:
            TimerT.sleep(time)

    def getAnimationData(self):
        names = self.animation.getNames()
        values = self.animation.getValues()
        times = self.animation.getTimes()
        return names, angles, times

    def addMotionAnimation(self, numeroMoteur, position, temps):
        self.animation.addValue(self.getNameFromNumber(numeroMoteur), position, temps);

    def resetAnimation(self):
        self.animation.reset();

    #test OK
    def playAnimation(self):
        names = self.animation.getNames();
        values = self.animation.getValues();
        times = self.animation.getTimes();
        threads = [];

        i = 0;
        for name in names :
            valuesTab = values[i];
            timesTab = times[i];
            thread = threading.Thread(None, self.__playMotorAnimation, None, (name, valuesTab, timesTab), {});
            threads.append(thread);
            i=i+1;

        for thread in threads:
            thread.start();

    #test OK
    def __playMotorAnimation(self, name, values, times):
        assert len(values) == len(times);
        durations = self.__getDurations(times);
        for i in range(len(times)):
            duration = durations[i];
            motorAngle = values[i];
            time.sleep(duration);
            self.angleInterpolation(name, motorAngle, duration, True);

    #test OK
    def __getDurations(self, timesTab):
        durationTab = [];
        previousTime = -1;

        if len(timesTab)>0:
            previousTime = timesTab[0];
            durationTab.append(previousTime);
            for i in range(1, len(timesTab)):
                currentTime = timesTab[i];
                if currentTime <= previousTime :
                    string = "Times must be inscreasing at index %s : %s" %(i, timesTab[i])
                    raise Exception("TimeError", string);
                else:
                    duration = currentTime - previousTime;
                    previousTime = currentTime;
                    durationTab.append(duration);

        return durationTab;

    def getNumberFromName(self, name):
        num=0
        for x in self.membres:
            if name==self.membres[x]:
                return x
        print("error numberName")
        return num

    def getNameFromNumber(self, number):
        return self.membres[number]

    def getNamesFromPart(self, part):
        if part.lower()=="body":
            return self.membresVirtual.values()
        for x in self.membres.keys():
            if self.membres[x]==part:
                return [self.membresVirtual[x]]
        print("error Names part", part)
        return []


    def getAvailableLanguages(self):
        return ["fr"]

    ###############" LED

    def getListFromName(self, name):
        result=[]
        if name in self.ledMnM.keys():
            return [self.ledMnM[name]]
        elif "Right" in name:
            for x in self.ledMnM.keys():
                if "Right" in x: result.append(self.ledMnM[x])
        elif "Left" in name:
            for x in self.ledMnM.keys():
                if "Left" in x: result.append(self.ledMnM[x])
        else:result=self.ledMnM.values()
        return result

    def getListNamesFromName(self, name):
        result=[]
        if name in self.ledMnM.keys():
            return [name]
        elif "Right" in name:
            for x in self.ledMnM.keys():
                if "Right" in x: result.append(x)
        elif "Left" in name:
            for x in self.ledMnM.keys():
                if "Left" in x: result.append(x)
        else:result=self.ledMnM.values()
        return result

    def setIntensity(self, name, intensity):
        #print(intensity)
        if name in self.ledMnM.keys():
            a=self.ledMnM[name]
            color=[intensity,intensity,intensity]
            self.ledIntensities[name]=color
        else:
            for b in self.ledColors.keys():
                if name in self.ledColors[b]:
                    #detection de la composante de couleur
                    pos=self.ledColors[b].index(name)
                    name=b
                    a=self.ledMnM[b]
                    self.ledIntensities[name][pos]=intensity
                    break
        self.virtualNao.setEye(self.ledIntensities[name],a)

    def getIntensity(self,name):
        return self.ledIntensities[name]

    def on(self,name):
        a=self.getListFromName(name)
        self.virtualNao.setEyes(1,a)

    def off(self,name):
        a=self.getListFromName(name)
        self.virtualNao.setEyes(0,a)

    def fade(self,name, intensity, duration):
        pass

    def fadeRGB (self, name, color, duration):
        pass

    def setWordListAsVocabulary(self, vocabList):
        ALProxy.vocabList = vocabList

    def startSpeechRecognition(self):
        pass
    ### SOUND
    def playFile(self, fichier):
        self.virtualNao.addSinging(fichier,5)
        if not ALProxy.parallelism:
            self.timePerCharacter=1
            TimerT.sleep(5)

    def stop(self):
        pass

    def playSine(self, frequence, gain, pan, duree):
        self.virtualNao.addSinging(" frequence : "+str(frequence), duree)
        if not ALProxy.parallelism:
            self.timePerCharacter=1
            TimerT.sleep(duree)
Exemplo n.º 46
0
	# checked out the code and can't get the bloody thing to
	# work!)
	continue

	bonemap = Props.getanimbonemap(a)

	# FIXME: if action in props.whatever.don't-do-this: next

	putlog(NBLog.INFO, "Processing animation %s" % a)
	action = actions[a]

	ipos = action.getAllChannelIpos()
	putlog(NBLog.DEBUG, "BoneIpos: %s" % ipos.keys())
	# NOTE: Channel names != bone names. F**k.

	anim = Animation()
	anim.setName(a)
	anim.setModelName(model)

	# Note: we're iterating Bones instead of Objects.
	# Thus, the goddamn Objects have to have same name as
	# their controlling Bones. (NOTE: this comment has no bearing
	# whatsoever to the reality. Reality is MUCH WORSE.)
	for boneipo in ipos:
		anode = AnimationNode()

		# The Theory: Now we're f*****g with the Ipo channel here.
		# We figure out what object the channel corresponds to.
		# (that seems to be the REALLY DAMN DIFFICULT part right now.)
		# Then, we just eval the ipo on keyframes OR at set intervals
		# (depending on what mode we're working on)