コード例 #1
0
def main():
    filename = str(input("Filename (csv): "))
    if ".csv" not in filename:
        sys.exit("Input is not a csv file!")

    while True:
        try:
            timestep = int(
                input(
                    "Note: The time step should be small compared with the orbital"
                    " period of the bodies.\n"
                    "Time step (s): "))
            break
        except ValueError:
            print("Please insert an integer.")

    while True:
        try:
            total_frames = int(input("Total frames for the animation: "))
            break
        except ValueError:
            print("Please insert an integer")

    animation = Animate(filename, timestep)
    Animate.show(animation, total_frames)
コード例 #2
0
 def crushed_death_animation(self):
     time = pygame.time.get_ticks()
     # Animate and keep on screen for half a second before killing sprite
     self.animator = Animate(self.crushed_images)
     if abs(time - self.last_frame) > 1000:
         self.player.score += 100
         self.kill()
コード例 #3
0
 def __init__(self,
              x,
              y,
              image,
              speed,
              obstacles,
              floor,
              item_type,
              rise_from=None,
              animated=False):
     super(Item, self).__init__()
     if animated:
         self.animator = Animate(image)
         self.image = self.animator.get_image()
     else:
         self.animator = None
         self.image = image
     self.item_type = item_type
     self.rect = self.image.get_rect()
     self.rect.left, self.rect.top = x, y
     self.speed = speed
     self.jump_speed = 0
     self.obstacles = obstacles  # objects that the item may collide with
     self.floor = floor  # rects for the floor
     self.rise_from = rise_from
コード例 #4
0
 def __init__(self, x, y, screen, points=100):
     super(Coin, self).__init__()
     images = [
         'images/Coin-1.png', 'images/Coin-2.png', 'images/Coin-3.png',
         'images/Coin-4.png'
     ]
     self.animator = Animate(images)
     self.image = self.animator.get_image()
     self.rect = self.image.get_rect()
     self.rect.left, self.rect.top = x, y
     self.screen = screen
     self.points = points
コード例 #5
0
 def __init__(self, screen, x, y, player, floor, block, goombas, koopas):
     self.walk_images = [
         'images/GoombaLeftBoot.png', 'images/GoombaRightBoot.png'
     ]
     self.upside_down_images = [
         'images/GoombaUD1.png', 'images/GoombaUD2.png'
     ]
     self.crushed_images = ['images/GoombaCrushed.png']
     self.animator = Animate(self.walk_images)
     image = self.animator.get_image()
     super().__init__(screen, image, x, y, player, floor, block, goombas,
                      koopas)
コード例 #6
0
 def upside_down_death_animation(self):
     time = pygame.time.get_ticks()
     # Animate getting hit (Go up for two seconds)
     if self.death_animation_frame == 0:
         self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_SPEED)
     else:
         self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_SPEED * -1)
     # After two seconds fall down while upside down
     if self.death_animation_frame == 0 and abs(self.last_frame -
                                                time) > 2000:
         self.animator = Animate(self.UD_death_images)
         self.death_animation_frame += 1
     # Kill off after 10 seconds (Enough to be off screen)
     if abs(self.last_frame - time) > 10000:
         self.player.score += 100
         self.kill()
コード例 #7
0
def cozmo_run(robot, position=None, deliver=None):
    global count

    if robot.is_ready:
        if not robot.has_in_progress_actions:
            if robot.is_on_charger:
                robot.drive_off_charger_contacts().wait_for_completed()

            print("Count: %s" % count)
            if position:
                reward_run(robot, position=position, deliver=deliver)
                count = 0
            else:
                if count == 90:
                    anim = Animate()
                    anim.anim_run(robot)
                    count = 0
                else:
                    count += 1
コード例 #8
0
def plotPose(pose_list, dl):
    """
    Method for plotting a pose given a list of poses (in pca format).
    The PCA is trained on the training data, and we use the inverse
    transformation to translate the 10 learned factors back to real (normalized)
    coordinates.

    Keyword Arguments
    pose_list - one frame output of the decoder
    dl - dataloader object that contains our training data
    """
    # pose_list = dl.pca.inverse_transform(pose_list)
    # plt.plot(pose_list[0:10:2], pose_list[1:10:2])
    # plt.plot([pose_list[2], pose_list[10]], [pose_list[3], pose_list[11]])
    # plt.plot(pose_list[10::2], pose_list[11::2])
    # plt.show()

    pose_list = dl.pca.inverse_transform(pose_list)
    animation_object = Animate((-2, 2), (-2, 2))
    anim = animation_object.animate(pose_list, 500)
    anim.save('animation.html', writer='imagemick', fps=60)
コード例 #9
0
 def __init__(self, screen, x, y, player, floor, block, goombas, koopas):
     self.name_1, self.name_2 = None, None
     self.name_1 = Enemy.img_file('KoopaWalkLeft_1', 25, 40)
     self.name_2 = Enemy.img_file('KoopaWalkLeft_2', 25, 40)
     self.left_images = [self.name_1, self.name_2]
     self.name_1 = Enemy.img_file('KoopaWalkRight_1', 25, 40)
     self.name_2 = Enemy.img_file('KoopaWalkRight_2', 25, 40)
     self.right_images = [self.name_1, self.name_2]
     self.name_1 = Enemy.img_file('KoopaShell', 35, 30)
     self.death_images = [self.name_1]
     self.name_1 = Enemy.img_file('KoopaShellUD', 35, 30)
     self.UD_death_images = [self.name_1]
     self.name_1 = Enemy.img_file('KoopaLegs', 35, 30)
     self.feet_images = [self.name_1]
     self.animator = Animate(self.left_images)
     image = self.animator.get_image()
     super().__init__(screen, image, x, y, player, floor, block, goombas,
                      koopas)
     self.collision_flag = False
     self.feet_frame = 0
     self.counter = 0
コード例 #10
0
ファイル: searcher.py プロジェクト: rah/optimal-search
 def __init__(self,
              max_speed=1.0,
              average_turn=20.0,
              turn_std_dev=5.0,
              probability_positive_turn=0.5,
              x_pos=0.0,
              y_pos=0.0,
              parent=None):
     # super(Searcher, self).__init__(
     Animate.__init__(
         self,
         max_speed,
         average_turn,
         turn_std_dev,
         probability_positive_turn,
         x_pos,
         y_pos,
         parent=parent)
     self.giving_up_time = 0
     self.time_since_encounter = Searcher.MAX_TIME_SINCE_ENC
     self.detection_range = max_speed * Searcher.SPEED_DETECTION_RATIO
コード例 #11
0
class Coin(Sprite):
    # sprite for the coin
    def __init__(self, x, y, screen, points=100):
        super(Coin, self).__init__()
        images = [
            'images/Coin-1.png', 'images/Coin-2.png', 'images/Coin-3.png',
            'images/Coin-4.png'
        ]
        self.animator = Animate(images)
        self.image = self.animator.get_image()
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = x, y
        self.screen = screen
        self.points = points

    def update(self):
        # updates coin image
        self.image = self.animator.get_image()

    def blit(self):
        # blits the coin to the screen
        self.screen.blit(self.image, self.rect)
コード例 #12
0
	def set_emotion(self, valence=None, arousal=None, r=None, phi=None, degrees=False, anim_time=0):
		self.isEmotion = True

		# TODO: Phi in deg or radians? Internally probably radians
		e = 0 + 0j
		if valence is not None and arousal is not None:
			e = valence + arousal*1j
		elif r is not None and phi is not None:
			if degrees:
				phi = phi * math.pi/180.0
			e = cmath.rect(r, phi)
		else:
			raise RuntimeError("Bad combination of parameters. Either valence and arousal or r and phi need to be provided.")

		# Make sure emotion is restricted to within unity circle.
		if abs(e) > 1.0:
			e = cmath.rect(1.0, cmath.phase(e))

		if anim_time > 0:
			self._anim = Animate([0, anim_time], [self._emotion, e])
		else:
			self._emotion = e
コード例 #13
0
 def __init__(self,
              x,
              y,
              norm_images,
              explode_images,
              obstacles,
              floor,
              goomba,
              koopa,
              speed=5):
     self.norm_animator = Animate(norm_images)
     self.explode_animator = Animate(explode_images, repeat=False)
     self.image = self.norm_animator.get_image()
     self.rect = self.image.get_rect()
     self.rect.x, self.rect.y = x, y
     self.obstacles = obstacles
     self.floor = floor
     self.goomba, self.koopa = goomba, koopa
     self.speed_x = speed
     self.speed_y = speed
     self.active = True
     super(FireBall, self).__init__()
コード例 #14
0
class LuaAnimate(object):
    def __init__(self, times, values):
        # Workaround to convert lua tables to lists
        self._a = Animate(list(times.values()), list(values.values()))

    @classmethod
    def new(cls, times, values):
        return LuaAnimate(times, values)

    def __call__(self):
        return self._a()

    def has_ended(self):
        return self._a.has_ended()
コード例 #15
0
 def __init__(self,
              x,
              y,
              screen,
              map_group,
              game_objects,
              item=MUSHROOM,
              static_img=None):
     if not static_img:
         images = [
             'images/Question-Block-1.png', 'images/Question-Block-2.png',
             'images/Question-Block-3.png'
         ]
         self.animator = Animate(images)
         initial_image = self.animator.get_image()
     else:
         initial_image = static_img
         self.animator = None
     self.game_objects = game_objects
     if item in (QuestionBlock.MUSHROOM, QuestionBlock.FIRE_FLOWER,
                 QuestionBlock.STARMAN, QuestionBlock.ONE_UP):
         self.item = item
         coins = None
     else:
         self.item = None
         coins = 1
     super(QuestionBlock, self).__init__(x,
                                         y,
                                         initial_image,
                                         screen,
                                         map_group,
                                         coins=coins if coins else 0)
     if self.item:
         self.sound = mixer.Sound('audio/Powerup-Appear.wav')
     self.blank_img = image.load(
         'images/super-mario-empty-block.png')  # force blank image
     self.state['blank'] = False
コード例 #16
0
    def checkpoint(self, i, pop):
        init = self.initial_conditions()
        sim = self.simulate(pop[0], init)

        basename = self.checkpoint_basename.format(i)
        with open(basename + '.csv', 'w') as f:
            writer = csv.DictWriter(f, sim[0].keys())
            writer.writeheader()
            writer.writerows(sim)

        with open(basename + '.pickle', 'wb') as f:
            pickle.dump(pop, f)

        if self.checkpoint_animation:
            Animate(sim, init.l, 2 * init.dt * 1000, tight_layout=True).show()

        if self.checkpoint_summary:
            self.plot(sim)
コード例 #17
0
ファイル: main.py プロジェクト: Hogwarts250/physics-game
pygame.init()

settings = Settings()
screen_size = settings.screen_length, settings.screen_height
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Atom Land")

player = Player(screen, settings)
levels = LevelDesign(settings)

basic_enemies = Group()
game_functions.create_basic_enemies(screen, basic_enemies, levels, settings)

buttons = []
fight_enemies = Group()
question_box = []

animate_player = Animate("images/player_walk_down/player_walk", settings)
animate_player.start()

while True:
    game_functions.check_pygame_events(player, basic_enemies, fight_enemies,
                                       buttons, question_box, levels, screen,
                                       settings)
    game_functions.update_sprites(player, basic_enemies, fight_enemies,
                                  buttons, question_box, screen, levels,
                                  settings)

    game_functions.update_screen(player, basic_enemies, fight_enemies, buttons,
                                 question_box, screen, settings)
コード例 #18
0
class Item(Sprite):
    MUSHROOM = 'mushroom'
    ONE_UP = '1-up'
    FIRE_FLOWER = 'fire-flower'
    STARMAN = 'starman'

    def __init__(self,
                 x,
                 y,
                 image,
                 speed,
                 obstacles,
                 floor,
                 item_type,
                 rise_from=None,
                 animated=False):
        super(Item, self).__init__()
        if animated:
            self.animator = Animate(image)
            self.image = self.animator.get_image()
        else:
            self.animator = None
            self.image = image
        self.item_type = item_type
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = x, y
        self.speed = speed
        self.jump_speed = 0
        self.obstacles = obstacles  # objects that the item may collide with
        self.floor = floor  # rects for the floor
        self.rise_from = rise_from

    def rise(self):
        if not self.rise_from:
            raise ValueError(
                'Cannot rise from an object when that object is None')
        if self.rect.bottom <= self.rise_from.rect.top:
            self.rise_from = None
        else:
            self.rect.bottom -= 2

    def jump(self):
        if self.speed >= 0:
            self.jump_speed = -(self.speed * 5)
        else:
            self.jump_speed = (self.speed * 5)

    def flip_direction(self):
        # make the item go in the opposite direction
        self.speed = -self.speed
        self.rect.left += self.speed

    def bounce_off_obstacles(self):
        # checks if the item has hit any obstacles
        for obs in self.obstacles:
            pts = [
                obs.rect.bottomleft, obs.rect.midleft, obs.rect.bottomright,
                obs.rect.midright
            ]
            for pt in pts:
                if self.rect.collidepoint(pt):
                    self.flip_direction()
                    return
        for rect in self.floor:
            pts = [
                rect.midleft, rect.midright, rect.bottomleft, rect.bottomright
            ]
            y_cap = rect.top
            for pt in pts:
                if self.rect.collidepoint(pt) or \
                        ((self.rect.left == rect.right or self.rect.right == rect.left) and self.rect.top > y_cap):
                    self.flip_direction()
                    return

    def fall(self):
        # makes the item fall through gaps in the ground
        falling = True
        for rect in self.floor:
            # check if bottom is at the top of the floor rect and that the x pos is within floor area
            if self.rect.bottom == rect.top and (
                    rect.left < self.rect.center[0] < rect.right):
                self.rect.bottom = rect.top
                falling = False
                break
        if falling:
            for obj in self.obstacles:
                pts = [obj.rect.topleft, obj.rect.midtop, obj.rect.topright]
                for pt in pts:
                    if self.rect.collidepoint(pt):
                        falling = False
                        break
                if not falling:
                    break
        if falling:
            self.rect.bottom += abs(self.speed)

    def update(self):
        # updates item position
        if self.animator:
            self.image = self.animator.get_image()
        if not self.rise_from:
            if abs(self.jump_speed) > 0:
                self.rect.top += self.jump_speed
                self.jump_speed += 1  # simulate gravity reducing speed
            self.rect.left += self.speed
            self.bounce_off_obstacles()
            self.fall()
        else:
            self.rise()
コード例 #19
0
    def koopa_physics(self):
        self.check_boundary()

        if not self.check_floor() and self.start_movement:
            self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_GRAVITY)
            self.rect.x = self.rect.x + (self.ENEMY_DIRECTION *
                                         (self.ENEMY_SPEED - 1))
        if self.check_floor() and self.start_movement:
            self.rect.x = self.rect.x + (self.ENEMY_DIRECTION *
                                         self.ENEMY_SPEED)

        # If collision
        if self.check_collisions():
            # Gets stomped on -> stop
            # Collides with player when in shell -> Movement
            if self.enemy_player_collide_flag and self.shell_mode:
                time = pygame.time.get_ticks()
                # Only put in shell if needed
                if self.death_animation_frame == 0:
                    self.animator = Animate(self.death_images)
                    self.image = self.animator.get_image()
                    tempx, tempy = self.rect.x, self.rect.y
                    self.rect = self.image.get_rect()
                    self.rect.x = tempx
                    self.rect.y = tempy
                    self.death_animation_frame += 1
                # Collide with player in shell mode causes movement
                if self.check_player_shell_collision():
                    self.shell_movement = True
                # Move shell depending on which side was hit
                if self.shell_movement:
                    if self.death_animation_frame == 1:
                        # Left side was hit
                        if self.rect.x >= self.player.rect.x:
                            self.ENEMY_DIRECTION = abs(self.ENEMY_DIRECTION)
                        # Right side hit
                        else:
                            self.ENEMY_DIRECTION = abs(
                                self.ENEMY_DIRECTION) * -1
                        self.death_animation_frame += 1
                    if self.check_block_collision():
                        pass
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                # Not being hit by player again makes koopa pop out of shell
                if not self.check_player_shell_collision() and abs(self.last_frame - time) > 8000 and not\
                        self.shell_movement:
                    if self.counter == 0:
                        self.animator = Animate(self.feet_images)
                        self.feet_frame = pygame.time.get_ticks()
                        self.counter += 1
                    if abs(self.feet_frame - time) > 3000:
                        self.counter = 0
                        self.ENEMY_DIRECTION = abs(self.ENEMY_DIRECTION) * -1
                        self.animator = Animate(self.left_images)
                        self.enemy_player_collide_flag = False
                        self.shell_mode = False
            # Collision with map or block
            elif self.enemy_block_collide_flag:
                # Killed by player hitting block
                if self.block_enemy_kill:
                    self.dead = True
                    self.upside_down_death_animation()
                # If colliding with map (i.e. Pipe) change direction
                else:
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                    self.enemy_block_collide_flag = False
            # If colliding with goomba change direction
            elif self.enemy_goomba_collide_flag:
                self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                self.enemy_goomba_collide_flag = False
            elif self.enemy_koopa_collide_flag:
                # Colliding with koopa shell thats moving
                if self.shell_enemy_kill:
                    self.dead = True
                    self.upside_down_death_animation()
                # Colliding with koopa enemy or shell
                else:
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                    self.enemy_koopa_collide_flag = False
コード例 #20
0
class Koopa(Enemy):
    def __init__(self, screen, x, y, player, floor, block, goombas, koopas):
        self.name_1, self.name_2 = None, None
        self.name_1 = Enemy.img_file('KoopaWalkLeft_1', 25, 40)
        self.name_2 = Enemy.img_file('KoopaWalkLeft_2', 25, 40)
        self.left_images = [self.name_1, self.name_2]
        self.name_1 = Enemy.img_file('KoopaWalkRight_1', 25, 40)
        self.name_2 = Enemy.img_file('KoopaWalkRight_2', 25, 40)
        self.right_images = [self.name_1, self.name_2]
        self.name_1 = Enemy.img_file('KoopaShell', 35, 30)
        self.death_images = [self.name_1]
        self.name_1 = Enemy.img_file('KoopaShellUD', 35, 30)
        self.UD_death_images = [self.name_1]
        self.name_1 = Enemy.img_file('KoopaLegs', 35, 30)
        self.feet_images = [self.name_1]
        self.animator = Animate(self.left_images)
        image = self.animator.get_image()
        super().__init__(screen, image, x, y, player, floor, block, goombas,
                         koopas)
        self.collision_flag = False
        self.feet_frame = 0
        self.counter = 0

    def upside_down_death_animation(self):
        time = pygame.time.get_ticks()
        # Animate getting hit (Go up for two seconds)
        if self.death_animation_frame == 0:
            self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_SPEED)
        else:
            self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_SPEED * -1)
        # After two seconds fall down while upside down
        if self.death_animation_frame == 0 and abs(self.last_frame -
                                                   time) > 2000:
            self.animator = Animate(self.UD_death_images)
            self.death_animation_frame += 1
        # Kill off after 10 seconds (Enough to be off screen)
        if abs(self.last_frame - time) > 10000:
            self.player.score += 100
            self.kill()

    def update(self):
        self.koopa_physics()
        self.image = self.animator.get_image()

    def check_player_shell_collision(self):
        # Check player collision when in shell
        if self.rect.colliderect(self.player.rect):
            return True

    def koopa_physics(self):
        self.check_boundary()

        if not self.check_floor() and self.start_movement:
            self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_GRAVITY)
            self.rect.x = self.rect.x + (self.ENEMY_DIRECTION *
                                         (self.ENEMY_SPEED - 1))
        if self.check_floor() and self.start_movement:
            self.rect.x = self.rect.x + (self.ENEMY_DIRECTION *
                                         self.ENEMY_SPEED)

        # If collision
        if self.check_collisions():
            # Gets stomped on -> stop
            # Collides with player when in shell -> Movement
            if self.enemy_player_collide_flag and self.shell_mode:
                time = pygame.time.get_ticks()
                # Only put in shell if needed
                if self.death_animation_frame == 0:
                    self.animator = Animate(self.death_images)
                    self.image = self.animator.get_image()
                    tempx, tempy = self.rect.x, self.rect.y
                    self.rect = self.image.get_rect()
                    self.rect.x = tempx
                    self.rect.y = tempy
                    self.death_animation_frame += 1
                # Collide with player in shell mode causes movement
                if self.check_player_shell_collision():
                    self.shell_movement = True
                # Move shell depending on which side was hit
                if self.shell_movement:
                    if self.death_animation_frame == 1:
                        # Left side was hit
                        if self.rect.x >= self.player.rect.x:
                            self.ENEMY_DIRECTION = abs(self.ENEMY_DIRECTION)
                        # Right side hit
                        else:
                            self.ENEMY_DIRECTION = abs(
                                self.ENEMY_DIRECTION) * -1
                        self.death_animation_frame += 1
                    if self.check_block_collision():
                        pass
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                # Not being hit by player again makes koopa pop out of shell
                if not self.check_player_shell_collision() and abs(self.last_frame - time) > 8000 and not\
                        self.shell_movement:
                    if self.counter == 0:
                        self.animator = Animate(self.feet_images)
                        self.feet_frame = pygame.time.get_ticks()
                        self.counter += 1
                    if abs(self.feet_frame - time) > 3000:
                        self.counter = 0
                        self.ENEMY_DIRECTION = abs(self.ENEMY_DIRECTION) * -1
                        self.animator = Animate(self.left_images)
                        self.enemy_player_collide_flag = False
                        self.shell_mode = False
            # Collision with map or block
            elif self.enemy_block_collide_flag:
                # Killed by player hitting block
                if self.block_enemy_kill:
                    self.dead = True
                    self.upside_down_death_animation()
                # If colliding with map (i.e. Pipe) change direction
                else:
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                    self.enemy_block_collide_flag = False
            # If colliding with goomba change direction
            elif self.enemy_goomba_collide_flag:
                self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                self.enemy_goomba_collide_flag = False
            elif self.enemy_koopa_collide_flag:
                # Colliding with koopa shell thats moving
                if self.shell_enemy_kill:
                    self.dead = True
                    self.upside_down_death_animation()
                # Colliding with koopa enemy or shell
                else:
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                    self.enemy_koopa_collide_flag = False
コード例 #21
0
class QuestionBlock(CoinBlock):
    # random item block
    MUSHROOM = 'mushroom'
    ONE_UP = '1-up'
    FIRE_FLOWER = 'fire-flower'
    STARMAN = 'starman'

    def __init__(self,
                 x,
                 y,
                 screen,
                 map_group,
                 game_objects,
                 item=MUSHROOM,
                 static_img=None):
        if not static_img:
            images = [
                'images/Question-Block-1.png', 'images/Question-Block-2.png',
                'images/Question-Block-3.png'
            ]
            self.animator = Animate(images)
            initial_image = self.animator.get_image()
        else:
            initial_image = static_img
            self.animator = None
        self.game_objects = game_objects
        if item in (QuestionBlock.MUSHROOM, QuestionBlock.FIRE_FLOWER,
                    QuestionBlock.STARMAN, QuestionBlock.ONE_UP):
            self.item = item
            coins = None
        else:
            self.item = None
            coins = 1
        super(QuestionBlock, self).__init__(x,
                                            y,
                                            initial_image,
                                            screen,
                                            map_group,
                                            coins=coins if coins else 0)
        if self.item:
            self.sound = mixer.Sound('audio/Powerup-Appear.wav')
        self.blank_img = image.load(
            'images/super-mario-empty-block.png')  # force blank image
        self.state['blank'] = False

    @classmethod
    def q_block_from_tmx_obj(cls, obj, screen, map_group, game_objects):
        # creates a question mark box
        item_type = obj.properties.get('item', None)
        if obj.properties.get('invisible', None):
            return cls(obj.x,
                       obj.y,
                       screen,
                       map_group,
                       game_objects,
                       item_type,
                       static_img=obj.image)
        return cls(obj.x, obj.y, screen, map_group, game_objects, item_type)

    def check_hit(self, other):
        points = super(QuestionBlock, self).check_hit(other)
        if self.item and self.state['meta'] == CoinBlock.HIT_STATE:
            obstacles, floor = self.game_objects[
                'collide_objs'], self.game_objects['floors']
            if self.item == QuestionBlock.MUSHROOM and not other.state_info[
                    'big']:
                n_item = Mushroom(self.rect.x,
                                  self.rect.y,
                                  obstacles,
                                  floor,
                                  rise_from=self)
            elif self.item == QuestionBlock.ONE_UP:
                n_item = OneUp(self.rect.x,
                               self.rect.y,
                               obstacles,
                               floor,
                               rise_from=self)
            elif self.item == QuestionBlock.FIRE_FLOWER or self.item == QuestionBlock.MUSHROOM:
                n_item = FireFlower(self.rect.x,
                                    self.rect.y,
                                    obstacles,
                                    floor,
                                    rise_from=self)
            else:
                n_item = StarMan(self.rect.x,
                                 self.rect.y,
                                 obstacles,
                                 floor,
                                 rise_from=self)
            self.game_objects['items'].add(n_item)
            self.map_group.add(n_item)
            self.item = None
            self.state['blank'] = True
            self.sound.play()
        elif points:
            return points

    def update(self):
        # updates the question block
        if not self.state['blank'] and self.animator:
            self.image = self.animator.get_image()
        elif self.state['blank']:
            self.image = self.blank_img
        super(QuestionBlock, self).update()
コード例 #22
0
ファイル: solver.py プロジェクト: deadmau915/Npuzzle
if __name__ == '__main__':

	#~ blocks  = [[0,1,3],[4,2,5],[7,8,6]]
	#~ blocks = [[6,0,5],[8,7,4],[3,2,1]]
	#~ blocks = [[8,6,7],[2,5,4],[1,3,0]]
	blocks = [[2,3,4,8],[1,6,0,12],[5,10,7,11],[9,13,14,15]]
	#~ blocks = [[5,1,8],[2,7,3],[4,0,6]]
	#~ blocks = [[1,2,3,4],[6,10,7,8],[5,0,11,12],[9,13,14,15]]
	initial = Board(blocks)
	
	# this list save all the solution's boards 
	lst = []
	
	if initial.isSolvable():
		solver = Solver(initial)
		for board in solver.solution():
			lst.append(board)			
		# here is where the magic ocurrs
		win = GraphWin("Npuzzle", 800, 800)
		win.setBackground('#FFFFFF')
		A = Animate(initial)		
		for pic in A.getLst():
			pic.exhibit(win)
		for i in range(1, len(lst)):
			A.animation(lst[i])	
		win.getMouse() # pause for click in window
		win.close()
		# here is where the magic ocurrs
	else:
		print "Unsolvable"
コード例 #23
0
ファイル: main.py プロジェクト: ryantangit/Riebot
from weather import Weather
from ranking import Ranking
from tictactoe import TicTacToe
from replit import db
import re

#############
# Ryan Tan, Timothy Wu
# For our own discord server.
# Requires repl to run this program, particular the database
#
################

#Load in the client from the discord api
client = discord.Client()
animate = Animate()
ranking = Ranking()
tictoe = TicTacToe()

emote = "⣿⣯⣿⣟⣟⡼⣿⡼⡿⣷⣿⣿⣿⠽⡟⢋⣿⣿⠘⣼⣷⡟⠻⡿⣷⡼⣝⡿⡾⣿\n⣿⣿⣿⣿⢁⣵⡇⡟⠀⣿⣿⣿⠇⠀⡇⣴⣿⣿⣧⣿⣿⡇⠀⢣⣿⣷⣀⡏⢻⣿\n⣿⣿⠿⣿⣿⣿⠷⠁⠀⠛⠛⠋⠀⠂⠹⠿⠿⠿⠿⠿⠉⠁⠀⠘⠛⠛⠛⠃⢸⣯\n⣿⡇⠀⣄⣀⣀⣈⣁⠈⠉⠃⠀⠀⠀⠀⠀⠀⠀⠀⠠⠎⠈⠀⣀⣁⣀⣀⡠⠈⠉\n⣿⣯⣽⡿⢟⡿⠿⠛⠛⠿⣶⣄⠀⠀⠀⠀⠀⠀⠈⢠⣴⣾⠛⠛⠿⠻⠛⠿⣷⣶\n⣿⣿⣿⠀⠀⠀⣿⡿⣶⣿⣫⠉⠀⠀⠀⠀⠀⠀⠀⠈⠰⣿⠿⠾⣿⡇⠀⠀⢺⣿\n⣿⣿⠻⡀⠀⠀⠙⠏⠒⡻⠃⠀⠀⠀⠀⣀⠀⠀⠀⠀⠀⠐⡓⢚⠟⠁⠀⠀⡾⢫\n⣿⣿⠀⠀⡀⠀⠀⡈⣉⡀⡠⣐⣅⣽⣺⣿⣯⡡⣴⣴⣔⣠⣀⣀⡀⢀⡀⡀⠀⣸\n⣿⣿⣷⣿⣟⣿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢻⢾⣷⣿\n⣿⣿⣟⠫⡾⠟⠫⢾⠯⡻⢟⡽⢶⢿⣿⣿⡛⠕⠎⠻⠝⠪⢖⠝⠟⢫⠾⠜⢿⣿\n⣿⣿⣿⠉⠀⠀⠀⠀⠈⠀⠀⠀⠀⣰⣋⣀⣈⣢⠀⠀⠀⠀⠀⠀⠀⠀⠀⣐⢸⣿\n⣿⣿⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⣿\n⣿⣿⣿⣿⣦⡔⠀⠀⠀⠀⠀⠀⢻⣿⡿⣿⣿⢽⣿⠀⠀⠀⠀⠀⠀⠀⣠⣾⣿⣿\n⣿⣿⣿⣿⣿⣿⣶⣤⣀⠀⠀⠀⠘⠛⢅⣙⣙⠿⠉⠀⠀⠀⢀⣠⣴⣿⣿⣿⣿⣿\n⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣄⣅⠀⠓⠀⠀⣀⣠⣴⣺⣿⣿⣿⣿⣿⣿⣿⣿\n"

riebot_help_msg = "`animate <gif_number>(optional)` - Send out a random(or selected) gif from the collection.\n`animate delete <gif_number>` - Deletes a selected gif from the collection. \n`animate insert <tenor gif url>` - Inserts a gif into the collection.\n`test` - testing\n`weather <zip-code>` - Reports the weather from the zipcode.\n`whotao` - Whotao?"

#This is the response that the bot should have when it is ready/loaded.
@client.event
async def on_ready():
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="the Sounds of Rie"))
  print("We have logged in as {0.user}".format(client))

@client.event
#Check on the message and see how to process it.
コード例 #24
0
 def __init__(self, times, values):
     # Workaround to convert lua tables to lists
     self._a = Animate(list(times.values()), list(values.values()))
コード例 #25
0
class Goomba(Enemy):
    def __init__(self, screen, x, y, player, floor, block, goombas, koopas):
        self.walk_images = [
            'images/GoombaLeftBoot.png', 'images/GoombaRightBoot.png'
        ]
        self.upside_down_images = [
            'images/GoombaUD1.png', 'images/GoombaUD2.png'
        ]
        self.crushed_images = ['images/GoombaCrushed.png']
        self.animator = Animate(self.walk_images)
        image = self.animator.get_image()
        super().__init__(screen, image, x, y, player, floor, block, goombas,
                         koopas)

    def crushed_death_animation(self):
        time = pygame.time.get_ticks()
        # Animate and keep on screen for half a second before killing sprite
        self.animator = Animate(self.crushed_images)
        if abs(time - self.last_frame) > 1000:
            self.player.score += 100
            self.kill()

    def upside_down_death_animation(self):
        time = pygame.time.get_ticks()
        # Animate getting hit (Go up for two seconds)
        if self.death_animation_frame == 0:
            self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_SPEED)
        else:
            self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_SPEED * -1)
        # After two seconds fall down while upside down
        if self.death_animation_frame == 0 and abs(self.last_frame -
                                                   time) > 2000:
            self.animator = Animate(self.upside_down_images)
            self.death_animation_frame += 1
        # Kill off after 10 seconds (Enough to be off screen)
        if abs(self.last_frame - time) > 10000:
            self.player.score += 100
            self.kill()

    def update(self):
        if not self.dead:
            self.goomba_physics()
        else:
            if self.player_enemy_kill is True:
                self.crushed_death_animation()
            elif self.block_enemy_kill is True:
                self.upside_down_death_animation()
            elif self.shell_enemy_kill is True:
                self.upside_down_death_animation()
        self.image = self.animator.get_image()

    def goomba_physics(self):
        self.check_boundary()
        # If no blocks are touching enemy -> Fall Down
        if not self.check_floor() and self.start_movement:
            self.rect.y += (abs(self.ENEMY_DIRECTION) * self.ENEMY_GRAVITY)
            self.rect.x = self.rect.x + (self.ENEMY_DIRECTION *
                                         (self.ENEMY_SPEED - 1))
        if self.check_floor() and self.start_movement:
            self.rect.x = self.rect.x + (self.ENEMY_DIRECTION *
                                         self.ENEMY_SPEED)

        # print('Player ' + str(self.check_player_collision()))
        # print('Block ' + str(self.check_block_collision()))
        # print('Enemy' + str(self.check_friendly_collision()))

        if self.check_collisions():
            # Collides with player
            if self.enemy_player_collide_flag:
                # Enemy dead
                if self.player_enemy_kill:
                    self.dead = True
                    self.last_frame = pygame.time.get_ticks()
                    self.crushed_death_animation()
                else:
                    self.enemy_player_collide_flag = False
            # Collision with map or block
            elif self.enemy_block_collide_flag:
                # Killed by player hitting block
                if self.block_enemy_kill:
                    self.dead = True
                    self.upside_down_death_animation()
                # If colliding with map (i.e. Pipe) change direction
                else:
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                    self.enemy_block_collide_flag = False
            # If colliding with goomba change direction
            elif self.enemy_goomba_collide_flag:
                self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                self.enemy_goomba_collide_flag = False
            # If colliding with koopa
            elif self.enemy_koopa_collide_flag:
                # Colliding with koopa shell thats moving
                if self.shell_enemy_kill:
                    self.dead = True
                    self.upside_down_death_animation()
                # Colliding with koopa enemy or shell
                else:
                    self.rect.x += (self.ENEMY_DIRECTION * self.ENEMY_SPEED)
                    self.enemy_koopa_collide_flag = False
コード例 #26
0
def main():
    """Test the simulation with Mars and its moons."""
    anim = Animate('marsandmoons.csv', 86)
    anim.show(300)
コード例 #27
0
def handleCommand(cmd, scr=True):
    global anim
    global curWorld
    global proofMode
    #strip any comments
    i = cmd.find("//")
    if i >= 0:
        cmd = cmd[:i].strip()

    if anim:
        if scr and cmd:
            print "a>" + cmd
        result = anim.dispatch(cmd)
        if result.startswith("_exit"):
            print " " + result[5:]
            anim = None
        elif result:
            print " " + result
        return 0

    if proofMode:
        if scr and cmd:
            print proofMode.prompt + ">" + cmd
        result = proofMode.dispatch(cmd)
        if result.startswith("_exit"):
            print " " + result[5:]
            proofMode = None
        elif result:
            print result
        return 0

    if cmd == "exit":
        return -1
    elif cmd == "animate":
        anim = Animate(curWorld)
    elif cmd == "proof":
        proofMode = curWorld.ProofMode(curWorld)
    elif cmd.startswith("load"):
        words = parseCommand(cmd)
        for f in words[1:]:
            loadFile(f)
    elif cmd.startswith("print"):
        words = parseCommand(cmd)
        if len(words) == 1:
            print pPrint(curWorld.top)
        else:
            fName = words[1]
            if "." not in fName:
                fName = fName + ".n.out"
            f = open(fName, "w")
            f.write(pPrint(curWorld.top))
            f.close()
            print "Success writing to: " + fName
    elif cmd.startswith("latex"):
        words = parseCommand(cmd)
        if len(words) == 1:
            print lPrint(curWorld.top)
        else:
            fName = words[1]
            if "." not in fName:
                fName = fName + ".tex"
            f = open(fName, "w")
            f.write(lPrint(curWorld.top))
            f.close()
            print "Success writing to: " + fName
    elif cmd.startswith("sh "):
        try:
            subprocess.call(cmd[3:], shell=True)
        except Exception as e:
            print "Error trying to execute '" + cmd[3:] + "': " + str(e)
        else:
            print "Executed " + cmd[3:]
    elif cmd == "**":
        curWorld.err = False
    elif cmd.startswith("*"):
        if curWorld.err:
            return handleCommand(cmd[1:])
    elif cmd == "help":
        print "N v0.09"
        print
        print "Supported commands:"
        print "  help                  print this message"
        print "  exit                  exit n"
        print "  load filenames        load the specified files"
        print "  latex [filename]      output the current formal system as latex"
        print "  print [filename]      output the current formal system in the source format"
        print "  proof                 switch to proof mode"
        print "  animate               switch to animation mode"
        print
        print "  * cmd                 execute cmd if an error has occured"
        print "  **                    reset the error flag"
        print
    elif cmd == "":
        pass
    else:
        print "Unknown command: ", cmd
        return 1

    return 0
コード例 #28
0
class _Expression(object):
	def __init__(self):
		self._emotion = 0 + 0j
		self._anim = None

		self.servos = []
		self.dofs = {}
		self.dof_values = {}
		self.lock = threading.Lock()

		self.empty_config()
		self.load_config()
		self.isEmotion = False

	def get_emotion_complex(self):
		"""
		Returns current emotion as a complex number
		"""
		return self._emotion

	def set_emotion(self, valence=None, arousal=None, r=None, phi=None, degrees=False, anim_time=0):
		self.isEmotion = True

		# TODO: Phi in deg or radians? Internally probably radians
		e = 0 + 0j
		if valence is not None and arousal is not None:
			e = valence + arousal*1j
		elif r is not None and phi is not None:
			if degrees:
				phi = phi * math.pi/180.0
			e = cmath.rect(r, phi)
		else:
			raise RuntimeError("Bad combination of parameters. Either valence and arousal or r and phi need to be provided.")

		# Make sure emotion is restricted to within unity circle.
		if abs(e) > 1.0:
			e = cmath.rect(1.0, cmath.phase(e))

		if anim_time > 0:
			self._anim = Animate([0, anim_time], [self._emotion, e])
		else:
			self._emotion = e

	def set_emotion_val_ar(self, valence, arousal, anim_time=0):
		self.set_emotion(valence=valence, arousal=arousal, anim_time=anim_time)

	def set_emotion_r_phi(self, r, phi, degrees=False, anim_time=0):
		self.set_emotion(r=r, phi=phi, degrees=degrees, anim_time=anim_time)

	def set_dof_values(self, dof_position_values):
		self.isEmotion = False
		for dof in dof_position_values:
		 	dof_position_values[dof] = constrain(dof_position_values[dof], -1.0, 1.0)
		self.dof_values = dof_position_values

	def update(self):
		if self._anim is not None:
			self._emotion = self._anim()
			if self._anim.has_ended():
				self._anim = None

		phi = cmath.phase(self._emotion)
		r = abs(self._emotion)

		# Create a list of dummy values.
		# None indicates that the servo at that index will not be updated.
		servo_pos_us = [None for i in range(16)]

		# Buffer to store all DOF values
		#self.dof_values = {}

		# (1) Calculate DOF positions using phi/r
		# (2) This step also applies overlay functions to the DOFs
		if self.isEmotion:
			for dofname, dof in self.dofs.iteritems():
				self.dof_values[dofname] = dof.calc(phi, r)

		# (3) Update all servos
		for servo in self.servos:
			if servo.pin < 0 or servo.pin > 15:
				continue # Skip invalid pins
			if servo.dofname in self.dof_values:
				servo_pos_us[servo.pin] = servo.dof_to_us(self.dof_values[servo.dofname])

		# TODO: send values to hardware

		with Hardware.lock:
			Hardware.servo_set_all(servo_pos_us)


	def empty_config(self):
		self.servos = []
		self.dofs = {}

	def load_config(self):
		def open_yaml(filename):
			"""Helper function to load YAML files into a dict."""
			try:
				yaml_dict = None
				with open(filename) as f:
					yaml_dict = yaml.load(f, Loader=Loader)
				return yaml_dict
			except IOError:
				raise RuntimeError("Could not open YAML file: %s" % filename)
		def default(x, e, y):
			"""
			Helper function that attempts to read a key from a dict. If the
			specified exception occurs, a default value is returned.
			"""
			try:
				return x()
			except e:
				return y

		pinmap_yaml = open_yaml(_configs["pinmap"])
		limits_yaml = open_yaml(_configs["limits"])
		functions_yaml = open_yaml(_configs["functions"])

		self.empty_config()

		# Create all Servo objects
		# Starts from pinmap, as a servo needs to have a pin associated with it.
		# If DOF not found in limits, default values are assigned.
		for pin, dofname in pinmap_yaml.iteritems():
			dofname = str(dofname) # Force into str

			s = {}
			s["pin"] = pin
			s["dofname"] = dofname
			s["min_range"] = default(lambda: limits_yaml[dofname]["min"], KeyError, None)
			s["mid_pos"] = default(lambda: limits_yaml[dofname]["mid"], KeyError, None)
			s["max_range"] = default(lambda: limits_yaml[dofname]["max"], KeyError, None)

			# Remove all empty values
			s = {k: v for k, v in s.items() if v is not None}

			# Create new servo object from dict
			self.servos.append(Servo(**s))

		# Create all DOF objects
		# Starts from functions YAML
		# If DOF not found in limits, default values are assigned.
		for dofname, params in functions_yaml.iteritems():
			d = {}
			d["name"] = dofname
			d["neutral"] = default(lambda: params.pop("neutral"), KeyError, None)
			d["poly"] = default(lambda: params.pop("poly"), KeyError, None)

			# Remove all empty values
			d = {k: v for k, v in d.items() if v is not None}

			# Create new DOF object from dict, store extra values from YAML
			dof = DOF(**d)
			dof.data = params
			self.dofs[dofname] = dof

		print_info("Loaded %d DOFs, %d servos" % (len(self.servos), len(self.dofs)) )
コード例 #29
0
from animate import Animate
from painter import Painter
import numpy as np

#Paint a random painting
painting = Painter()
painting.generate_n_frames(300)
Animate(painting.frames)
コード例 #30
0
class FireBall(Sprite):
    # sprite for the fireball
    def __init__(self,
                 x,
                 y,
                 norm_images,
                 explode_images,
                 obstacles,
                 floor,
                 goomba,
                 koopa,
                 speed=5):
        self.norm_animator = Animate(norm_images)
        self.explode_animator = Animate(explode_images, repeat=False)
        self.image = self.norm_animator.get_image()
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = x, y
        self.obstacles = obstacles
        self.floor = floor
        self.goomba, self.koopa = goomba, koopa
        self.speed_x = speed
        self.speed_y = speed
        self.active = True
        super(FireBall, self).__init__()

    def check_hit_wall(self):
        # checks if fireball hits wall
        for obs in self.obstacles:
            pts = [
                obs.rect.midleft, obs.rect.midright, obs.rect.bottomleft,
                obs.rect.bottomright
            ]
            for pt in pts:
                if self.rect.collidepoint(pt):
                    self.active = False
                    return
        for flr_rect in self.floor:
            pts = [
                flr_rect.midleft, flr_rect.midright, flr_rect.bottomleft,
                flr_rect.bottomright
            ]
            for pt in pts:
                if self.rect.collidepoint(pt):
                    self.active = False
                    return

    def check_hit_enemies(self):
        # checks if fireball hits enemy
        for g_enemy in self.goomba:
            if collide_rect(self, g_enemy):
                g_enemy.kill()
                self.active = False
                return
        for k_enemy in self.koopa:
            if collide_rect(self, k_enemy):
                k_enemy.kill()
                self.active = False
                return

    def apply_gravity(self):
        # gravity to the fireball
        bounce = False
        for obs in self.obstacles:
            pts = [obs.rect.topleft, obs.rect.midtop, obs.rect.topright]
            for pt in pts:
                if self.rect.collidepoint(pt):
                    bounce = True
                    break
            if bounce:
                break
        if not bounce:
            for flr_rect in self.floor:
                # check if bottom is at the top of the floor rect and that the x pos is within floor area
                if self.rect.bottom >= flr_rect.top and (
                        flr_rect.left < self.rect.center[0] < flr_rect.right):
                    bounce = True
                    break
        if bounce:
            self.speed_y = -abs(
                self.speed_y)  # ensure speed in y-direction is negative
        else:
            self.speed_y += 2  # apply gravity
        self.rect.y += self.speed_y

    def update(self):
        # updates position of fireball
        if self.active:
            self.rect.x += self.speed_x
            self.apply_gravity()
            self.image = self.norm_animator.get_image()
            self.check_hit_wall()
            self.check_hit_enemies()
        elif self.explode_animator.is_animation_done():
            self.kill()
        else:
            self.image = self.explode_animator.get_image()