Ejemplo n.º 1
0
    def __init__(self, window):
        super().__init__(window)
        self.batch = Batch()
        self.menu = 0
        self.main_index = 0
        self.practice_index = 0
        self.config_index = 0
        self.t = 0

        self.background = Sprite(IMAGES['ui']['mainmenu_bg'], -15, -15)
        self.background.opacity = 100
        self.background2 = Sprite(IMAGES['ui']['mainmenu_bg2'], 0, 0, blend_src=774)
        self.left_sprite = Sprite(IMAGES['ui']['mainmenu_left'], 0, 0, batch=self.batch)
        self.left_sprite.opacity = 50

        # Main menu options:
        options_text = ['Start game', 'Practice', 'High scores', 'Config', 'Exit']
        self.main_options_shadow = [Label(text=options_text[i], font_name=MENU_FONT, color=(100, 100, 100, 100), font_size=22, x=199, y=401 - 32*i, batch=self.batch) for i in range(len(options_text))]
        self.main_options = [Label(text=options_text[i], font_name=MENU_FONT, font_size=22, x=200, y=400 - 32*i, batch=self.batch) for i in range(len(options_text))]

        # Practice options:
        options_text = ['Level 1', 'Level 2', 'Level 3', 'Level 4', 'Level 5']
        self.practice_options_shadow = [Label(text=options_text[i], font_name=MENU_FONT, color=(100, 100, 100, 0), font_size=22, x=499, y=401 - 32*i, batch=self.batch) for i in range(len(options_text))]
        self.practice_options = [Label(text=options_text[i], font_name=MENU_FONT, font_size=22, x=500, y=400 - 32*i, color=(255,255,255,0), batch=self.batch) for i in range(len(options_text))]

        # Config options:
        options_text = ['SFX volume', 'BGM volume', 'Controls']
        self.config_options_shadow = [Label(text=options_text[i], font_name=MENU_FONT, color=(100, 100, 100, 0), font_size=22, x=499, y=401 - 32*i, batch=self.batch) for i in range(len(options_text))]
        self.config_options = [Label(text=options_text[i], font_name=MENU_FONT, font_size=22, x=500, y=400 - 32*i, color=(255,255,255,0), batch=self.batch) for i in range(len(options_text))]
Ejemplo n.º 2
0
    def __init__(self, runner):
        super().__init__(runner, width=512, height=512)

        tile = image('tile.png')
        tile.anchor_x = 32
        tile.anchor_y = 32
        self.sprite = Sprite(img=tile, x=0, y=0)
Ejemplo n.º 3
0
    def init(self, **kwargs):
        self.image = load_image(self.image_file)
        self.sprite = Sprite(self.image, self.x, self.y,
                             batch=self.batch, group=self.group)
        self.chunk.objects.append(self)

        clock.schedule_once(self.delete, self.timer)
Ejemplo n.º 4
0
class TemporaryEntity(Entity):
    defaults = {
        'width': 48,
        'height': 48,
    }

    attributes = {
        'image_file': 'app/assets/corpse.png',
        'chunk': None,
        'timer': 60
    }

    def init(self, **kwargs):
        self.image = load_image(self.image_file)
        self.sprite = Sprite(self.image, self.x, self.y,
                             batch=self.batch, group=self.group)
        self.chunk.objects.append(self)

        clock.schedule_once(self.delete, self.timer)

    def delete(self, dt):
        if self in self.chunk.objects:
            self.chunk.objects.remove(self)
        self.sprite.delete()

    def update(self):
        pass

    def draw(self):
        self.sprite.draw()
Ejemplo n.º 5
0
 def resize(self, width, height):
     self._element = list()
     for x in range(width // self._img.width * 2 + 1):
         for y in range(height // self._img.height * 2 + 1):
             sprite = Sprite(self._img, x=x * self._img.width, y = y * self._img.height)
             sprite.scale = 2
             self._element.append(sprite)
Ejemplo n.º 6
0
    def __init__(self, window, bus):
        super().__init__(window, bus)
        self.title = Text('Welcome to',
                          batch=self.batch,
                          x=self.margin,
                          y=(self.window.height // 2) + 100)
        self.title_bold = Text('tabulr',
                               bold=True,
                               batch=self.batch,
                               x=self.margin,
                               y=(self.window.height // 2) + 60)
        self.subtitle = Text(
            'Your schedule, from list to wallpaper. Like magic.',
            size=12,
            batch=self.batch,
            x=self.margin,
            y=self.window.height // 2)
        self.init_sprite(
            'next_button',
            Button('next',
                   self.window,
                   self.batch,
                   x=self.margin,
                   y=(self.window.height // 2) - 100))

        waves = Sprite(image('front-waves.png'), x=0, y=-30, batch=self.batch)
        waves.opacity = 140
        self.elapsed = 0
        self.init_sprite('waves', waves, is_button=False)
Ejemplo n.º 7
0
class GameObject:
    def __init__(self, posx, posy, image, batch=None):
        self.in_opacity = False
        self.x_target = posx
        self.batch = batch
        self.begin = 255
        self.opacity_target = 255
        self.set_ok = False
        self.waiting = False
        if isinstance(image, str):
            self.sprite = Sprite(pyglet.image.load(f"res/{image}"),
                                 batch=self.batch)
        else:
            self.sprite = image
        self.sprite.x = posx
        self.sprite.y = posy
        self.opacity = self.sprite.opacity

    def draw(self):
        self.sprite.draw()

    def replace_bg(self, image):
        self.sprite = Sprite(pyglet.image.load(f"res/bg/{image}"),
                             batch=self.batch)

    def update(self, dt):

        if not self.sprite.x == self.x_target:
            if ceil(self.sprite.x) < self.x_target:
                self.sprite.x += 150 * dt
            if ceil(self.sprite.x) == self.x_target or floor(
                    self.sprite.x) == self.x_target:
                self.sprite.x = self.x_target
                self.set_ok = True
            if floor(self.sprite.x) > self.x_target:
                self.sprite.x -= 150 * dt

        if not self.sprite.opacity == self.opacity_target:
            if ceil(self.sprite.opacity) < self.opacity_target:
                self.sprite.opacity += 150 * dt
            if ceil(self.sprite.opacity) == self.opacity_target or floor(
                    self.sprite.opacity) == self.opacity_target:
                self.sprite.opacity = self.opacity_target
                self.set_ok = True
            if floor(self.sprite.opacity) > self.opacity_target:
                self.sprite.opacity -= 150 * dt

    def set_opacity(self, opacity=255):
        self.sprite.opacity = opacity
        self.opacity_target = opacity

    def animate_opacity(self, opacity=255):
        self.begin = self.sprite.opacity
        self.opacity_target = opacity
        self.set_ok = False

    def animate_x(self, x):
        self.begin = self.sprite.x
        self.x_target = x
        self.set_ok = False
Ejemplo n.º 8
0
    def __init__(self, x, y, dx, dy, goo_batch):
        image = pyglet.image.load(data.filepath('goo.png'))
        self.sequence = pyglet.image.ImageGrid(image, 1, 4)

        self.splat_image = pyglet.image.load(data.filepath('splat.png'))
        self.splat_image.anchor_x = self.splat_image.width / 2

        for sequence_image in self.sequence:
            sequence_image.anchor_x = sequence_image.width / 2
            sequence_image.anchor_y = sequence_image.height / 2

        Sprite.__init__(self, image, batch=goo_batch)
        self.x = self.xpos = x
        self.y = self.ypos = y

        self.speedx = dx
        self.speedy = dy

        self.animation_time = 0
        self.animation_frame = 0
        self.animation_speed = 0.25

        self.splat = False

        self.hitbox = (0, 0, self.splat_image.width, self.splat_image.height)
Ejemplo n.º 9
0
    def seed_handler(self, engine, boundsRect):
        seed_config = self.seed_config
        bounds = (boundsRect.left, boundsRect.top, boundsRect.right,
                  boundsRect.bottom)
        cells = []
        seed_keys = list(seed_config.keys())
        shuffle(seed_keys)
        for key in seed_keys:
            cfg = seed_config[key]
            perlins = self.perlin.perlin_octave_array(bounds[0], bounds[1],
                                                      CHUNK_SIZE, CHUNK_SIZE,
                                                      cfg['freq'],
                                                      cfg['octaves'], 1.0, 16)
            for (oy, pees) in enumerate(perlins):
                for (ox, val) in enumerate(pees):
                    ix = bounds[0] + ox * 16
                    iy = bounds[1] + oy * 16
                    if val > cfg['threshold'] and (
                            cfg['rand_thresh'] == 0
                            or random() > cfg['rand_thresh']):
                        cells.append(
                            BlueprintCell(cfg['class'],
                                          (engine.textures, (ix, iy))))
        image_key = engine.textures.create_background(int(CHUNK_SIZE / 2),
                                                      int(bounds[0] / 2),
                                                      int(bounds[1] / 2))
        bg_sprite = Sprite(engine.textures[image_key], bounds[0], bounds[1])
        bg_sprite.scale = 2
        engine.world.set_bg(bg_sprite, bounds[0], bounds[1])

        return cells
Ejemplo n.º 10
0
    def enemy_spawn(self, dt):

        self.enemy_typeA_spawner -= dt
        self.enemy_typeB_spawner -= dt
        if self.player_is_alive:
            if self.enemy_typeA_spawner <= 0:
                self.enemy_list.append(
                    GameObject(1000,
                               800,
                               Sprite(self.enemy_imgA, batch=self.main_batch),
                               health=2))
                self.enemy_list[-1].vel_x = randint(100, 300) * choice(
                    self.directions)  # last spawned entity in entity list
                self.enemy_list[-1].vel_y = 30

                self.enemy_typeA_spawner += self.enemy_typeA_counter

            if self.enemy_typeB_spawner <= 0:
                self.enemy_list.append(
                    GameObject(600,
                               950,
                               Sprite(self.enemy_imgB, batch=self.main_batch),
                               health=5))
                self.enemy_list[-1].vel_x = randint(100, 300) * choice(
                    self.directions)  # last spawned entity in entity list
                self.enemy_list[-1].vel_y = 30

                self.enemy_typeB_spawner += self.enemy_typeB_counter

        if self.next_wave >= 20:
            self.enemy_typeA_counter -= 0.05
            self.enemy_typeB_counter -= 0.2
            self.next_wave = 0
Ejemplo n.º 11
0
    def __init__(self, x, y, facing=Direction.NORTH):
        self.sprite = Sprite(self.Sprite.faces[facing], x, y)
        self.facing = facing
        self.movement_queue = []
        self.movement_ticks = 0

        self.current_health = self.health
Ejemplo n.º 12
0
    def __init__(self, id, pos, rot, weapon, game):
        self.id = id

        self.pos = pos

        self.rot = rot

        self.weapon = weapon

        self.sprite = Sprite(game.player_images[weapon])
        self.width = self.sprite.width
        self.height = self.sprite.height

        self.hit_box = PLAYER_HIT_BOX.copy()
        self.hit_box.x = pos.x
        self.hit_box.y = pos.y

        self.sprite.image.anchor_x = self.sprite.image.width / 2 - WEAPONS[
            weapon]['img_offset'].x
        self.sprite.image.anchor_y = self.sprite.image.height / 2 - WEAPONS[
            weapon]['img_offset'].y

        self.game = game

        self.health = PLAYER_HEALTH
        self.dead = False
Ejemplo n.º 13
0
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.set_location(400,100)
		self.frame_rate = 1/60.0

		self.episodes = 0
		self.move_count = 0

		self.epsilon = EPSILON

		self.reward = 0
		self.episode_reward = 0
		self.episode_rewards = np.array()

		self.main_batch = pyglet.graphics.Batch()
		backGround = pyglet.graphics.OrderedGroup(0)
		foreGround = pyglet.graphics.OrderedGroup(1)

		backGround_sprite = Sprite(preload_image('backGround.png'), batch=self.main_batch, group=backGround)
		self.backGround = gameObjects(LOW,LOW,backGround_sprite)

		pos = floor((SIZE/2)-(BLACK_ARC_DIAMETER/2))
		blackArc_sprite = Sprite(preload_image('blackArc.png'), batch=self.main_batch, group=foreGround)
		self.blackArc = gameObjects(pos,pos,blackArc_sprite)

		redArc_sprite = Sprite(preload_image('redArc.png'), batch=self.main_batch, group=foreGround)
		self.redArc = gameObjects(LOW,LOW,redArc_sprite)
Ejemplo n.º 14
0
class PreviewWindow(BasePreview):
    colors = ((0, 0, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255))
    rotations = [0, 90, 180, 270]

    def __init__(self, runner):
        super().__init__(runner, width=512, height=512)

        tile = image('tile.png')
        tile.anchor_x = 32
        tile.anchor_y = 32
        self.sprite = Sprite(img=tile, x=0, y=0)

    def draw_tiles(self, pos, bits):
        if bits == 0:
            return

        x, y = pos[-2:]
        self.sprite.x = x * 64 + 32
        self.sprite.y = self.height - y * 64 - 32

        tiles = self.runner.model.get_allowed_tiles(bits)
        self.sprite.opacity = 255 / len(tiles)

        for tile in tiles:
            for direction, adj in enumerate(tile.adj):
                if adj < 1 or self.rotations[direction] == None:
                    continue
                self.sprite.color = self.colors[adj]
                self.sprite.rotation = self.rotations[direction]
                self.sprite.draw()

        if self.debug:
            Label(str(bits), x=self.sprite.x, y=self.sprite.y).draw()
Ejemplo n.º 15
0
 def _draw_overlay(self):
     pattern = SolidColorImagePattern((0, 0, 0, 200))
     overlay_image = pattern.create_image(1000, 1000)
     overlay_image.anchor_x = overlay_image.width / 2
     overlay_image.anchor_y = overlay_image.height / 2
     overlay = Sprite(overlay_image, self.camera.x, self.camera.y)
     overlay.draw()
Ejemplo n.º 16
0
    def __init__(self, runner, tile_size):
        width = runner.model.world_shape[0] * tile_size
        height = runner.model.world_shape[1] * tile_size
        super().__init__(runner, width=width, height=height)

        self.sprite = Sprite(img=runner.model.tiles[0].image)
        self.tile_size = tile_size
Ejemplo n.º 17
0
class GameObject:
    def __init__(self, game, x, y, image):
        self.game = game
        self.x = x
        self.y = y
        self.sprite = Sprite(image,
                             x=x,
                             y=y,
                             batch=self.game.batch,
                             group=G_MAIN_0)

    def draw(self):
        self.sprite.draw()

    def early_update(self, dt):
        pass

    def update(self, dt):
        pass

    def late_update(self, dt):
        self.sprite.position = self.x, self.y

    def destroy(self):
        self.sprite.batch = None
Ejemplo n.º 18
0
 def __init__(self, x, y, width, height, text):
     self._size = win_width, win_height = get_size()
     super().__init__(x, win_height - y, width, height)
     self._width = width
     self._depressed_img = image.load(
         join(path['texture.ui'],
              'widgets.png')).get_region(0, 170, 200, 20)
     self._pressed_img = image.load(join(path['texture.ui'],
                                         'widgets.png')).get_region(
                                             0, 150, 200, 20)
     self._unable_img = image.load(join(path['texture.ui'],
                                        'widgets.png')).get_region(
                                            0, 190, 200, 20)
     self._sprite = Sprite(self._depressed_img, x, win_height - y)
     self._text = text
     self._label = ColorLabel(self._text,
                              color='white',
                              align='center',
                              anchor_x='center',
                              anchor_y='center',
                              x=x + width / 2,
                              y=win_height - y + height / 2 - 2,
                              font_name='minecraftia')
     self._pressed = False
     self._enable = True
Ejemplo n.º 19
0
    def __init__(self, x, y, game):
        self.pos = Vector(x, y)
        self.vel = Vector(0, 0)
        self.acc = Vector(0, 0)

        self.game = game

        self.rot = 0

        self.hit_box = MOB_HIT_BOX.copy()

        self.sprite = Sprite(game.mob_image, batch=game.mob_batch)
        self.width = self.sprite.width
        self.height = self.sprite.height

        self.sprite.image.anchor_x = self.sprite.image.width / 2 - MOB_IMAGE_OFFSET.x
        self.sprite.image.anchor_y = self.sprite.image.height / 2 - MOB_IMAGE_OFFSET.y

        self.sprite.x = x
        self.sprite.y = y

        self.health = MOB_HEALTH

        self.hit_box.x = self.pos.x - self.hit_box.width / 2
        self.hit_box.y = self.pos.y - self.hit_box.height / 2

        self.target = None

        self.q = Queue(self.game)

        self.id = game.new_mob_id()

        self.last_hit = datetime.now()
Ejemplo n.º 20
0
    def on_activate(self):
        super().on_activate()
        if not self.inactive_sprite:
            self.inactive_sprite = Sprite(self.inactive_image,
                                          x=self.viewport.x1,
                                          y=self.viewport.y1,
                                          batch=BATCHES['ui_batch'],
                                          group=GROUPS['button_background'])

        self.inactive_sprite.scale = self.get_scale()
        self.inactive_sprite.opacity = self.opacity
        if self.current_percent == 0:
            image_region = self.active_image.get_region(
                self.active_image.height // 2, self.active_image.height // 2,
                1, 1)
        else:
            image_region = self.active_image.get_region(
                0, 0, self.current_percent * self.active_image.width // 100,
                self.active_image.height)

        if not self.active_sprite:
            self.active_sprite = Sprite(image_region,
                                        x=self.viewport.x1,
                                        y=self.viewport.y1,
                                        batch=BATCHES['ui_batch'],
                                        group=GROUPS['button_text'])
        else:
            self.active_sprite.image = image_region

        self.active_sprite.scale = self.get_scale()
        self.active_sprite.opacity = self.opacity
Ejemplo n.º 21
0
    def __init__(self, x, y, rot, img, weapon, game, main=True, owner=None):
        self.o_pos = Vector(x, y)
        self.prev_pos = Vector(x - 1, y - 1)
        self.pos = Vector(x, y)
        self.vector = Vector(WEAPONS[weapon]["bullet_speed"], 0).rotate(-rot)

        self.weapon = weapon

        self.sprite = Sprite(img, batch=game.bullet_batch)
        self.sprite.update(rotation=rot, scale=WEAPONS[weapon]["bullet_size"])
        self.sprite.image.anchor_x = self.sprite.image.width / 2
        self.sprite.image.anchor_y = self.sprite.image.height / 2

        self.distance = 0

        self.rot = rot

        if main:
            game.o_bullets.append({
                "rot": rot,
                "pos": {
                    "x": x,
                    "y": y
                },
                "weapon": weapon
            })

        self.owner = owner
Ejemplo n.º 22
0
class Inhabitant(object):
    def __init__(self, img, x, y):
        super(Inhabitant, self).__init__()
        register(self)
        self.x, self.y = x, y
        self.pathfinder = None
        self.path = []  # extra copy for custom tumbling or alternative path factories
        self.speed = 0.05
        self.image = img
        self.sprite = Sprite(img, batch=batch)
        self.update()

    def update(self):
        grpos = topo.ground_position(self.x, self.y)
        if grpos:
            x, y = grpos
            self.sprite.set_position(x - 10, y)

    def move(self):
        dx = self.path[0].x - self.x
        dy = self.path[0].y - self.y
        if dx ** 2 + dy ** 2 < 0.01:
            self.path.pop(0)
            if len(self.path) < 1:
                self.pathfinder = None
        else:
            r = math.sqrt(dx ** 2 + dy ** 2)
            dx *= self.speed / r
            dy *= self.speed / r
            self.x += dx
            self.y += dy
            self.update()
Ejemplo n.º 23
0
 def __init__(self, img,
          map=None,
          pos=None,
          stats=None,
          x=0, y=0,
          blend_src=pyglet.gl.GL_SRC_ALPHA,
          blend_dest=pyglet.gl.GL_ONE_MINUS_SRC_ALPHA,
          batch=None,
          group=None,
          usage='dynamic'):
     if stats is None:
         self.stats = Stats(self)
     else:
         self.stats = stats
     self.map = map
     self.pos = pos
     self.blocked = True
     self.oldPos = pos
     self.playerOldPos = None
     self.dead = False
     self.currentPath = []
     Sprite.__init__(self, img,
                     x, y, blend_src,
                     blend_dest, batch,
                     group, usage)
Ejemplo n.º 24
0
    def __init__(self,
                 window,
                 bus,
                 title='Welcome to tabulr',
                 draw_waves=False):
        """
        Initialize the Scene object.
        :param window: Pyglet window object. Must be same throughout application.
        :param bus: Event bus. Used for communicating scene changes to main application thread.
        """
        self.window = window
        self.window_title = title
        self.bus = bus
        self.batch = Batch()
        self.margin = 36
        self.sprites = {}
        self.inputs = []

        # Error message
        self.error_msg = Text('',
                              size=12,
                              bold=True,
                              batch=self.batch,
                              x=self.margin,
                              color=(236, 64, 122, 255))
        self.error_elapsed = 0
        self.error_opacity = 0

        # Waves background
        if draw_waves:
            waves_img = image('side-waves.png')
            waves_img.anchor_x = waves_img.width
            waves = Sprite(waves_img, x=window.width, y=0, batch=self.batch)
            waves.opacity = 160
            self.init_sprite('waves', waves, is_button=False)
Ejemplo n.º 25
0
 def __init__(self):
     width, height = get_size()
     GUI.__init__(self, width, height)
     self._xpbar = Sprite(image.load(join(path['texture.gui'], 'icons.png')).get_region(0, 187, 182, 5),
             x=(width - 364) / 2, y=48)
     self._xpbar.scale_x = 2
     self._xpbar.scale_y = 1.5
Ejemplo n.º 26
0
    def draw_enemy_tanks_remaining(self, game: Game, reset=False):
        if game.game_director.stage is None:
            return

        tank_icon_count = 0
        target_icon_count = game.game_director.stage.active_tanks
        for row in range(0, self.tank_icons.shape[0]):
            for col in range(0, self.tank_icons.shape[1]):
                tank_icon_count += 1
                if tank_icon_count <= target_icon_count:
                    if self.tank_icons[row, col] is None or reset:
                        tank_icon_sprite = Sprite(img=TextureManager.tank_icon,
                                                  x=game.game_map.map_data["pixel_width"]
                                                    + col * constants.UI_TANK_ICON_SIZE
                                                    + col * constants.UI_TANK_ICONS_GAP
                                                    + constants.UI_SIDE_PANEL_SIZE // 2
                                                    - constants.UI_TANK_ICONS_WIDTH // 2,
                                                  y=game.game_map.map_data["pixel_height"]
                                                    - (row * constants.UI_TANK_ICON_SIZE)
                                                    - constants.UI_TANK_ICON_SIZE
                                                    - constants.UI_TANK_ICONS_TOP_PAD,
                                                  batch=self.batch)
                        tank_icon_sprite.scale = 3
                        self.tank_icons[row, col] = tank_icon_sprite
                else:
                    if self.tank_icons[row, col] is not None:
                        self.tank_icons[row, col].delete()
                        self.tank_icons[row, col] = None
Ejemplo n.º 27
0
    def __init__(self,
                 shipTexture,
                 shieldTexture,
                 alienBatch,
                 shipGroup,
                 shieldGroup,
                 x=0,
                 y=0):
        self.ship = Sprite(shipTexture,
                           x=x,
                           y=y,
                           blend_src=770,
                           blend_dest=771,
                           batch=alienBatch,
                           group=shipGroup,
                           usage='dynamic',
                           subpixel=False)
        self.shield = Sprite(shieldTexture,
                             x=x,
                             y=y,
                             blend_src=770,
                             blend_dest=771,
                             batch=alienBatch,
                             group=shieldGroup,
                             usage='dynamic',
                             subpixel=False)

        # Set the physical aspects of the Alien ship
        self.acceleration = np.array((0, 0), dtype=np.float32)
        self.velocity = np.array((0, 0), dtype=np.float32)
        self.position = np.array((x, y), dtype=np.float32)
        self.maxSpeed = 500
Ejemplo n.º 28
0
class Button(Rectangle):
    def __init__(self, x, y, width, height, image=None, caption=None, batch=None, group=None):
        super(Button, self).__init__(x, y, width, height)
        self.batch = batch
        self.group = group
        self.sprite = None
        self.label = None
        if image:
            self.sprite = Sprite(image.get_region(0, 0, self.width, self.height), batch=self.batch, group=self.group)
        if caption:
            self.label = Label(caption, font_name='Arial', font_size=12,
                anchor_x='center', anchor_y='center', color=(255, 255, 255, 255), batch=self.batch,
                group=self.group)
        self.set_position(x, y)
	
    def set_position(self, x, y):
        super(Button, self).set_position(x, y)
        if self.sprite:
            self.sprite.x, self.sprite.y = x, y
        if self.label:
            self.label.x, self.label.y = self.get_center()

    def draw(self):
        if self.sprite:
            self.sprite.draw()
        if self.label:
            self.label.draw()
Ejemplo n.º 29
0
 def _draw_overlay(self):
     pattern = SolidColorImagePattern((0, 0, 0, 200))
     overlay_image = pattern.create_image(1000, 1000)
     overlay_image.anchor_x = overlay_image.width / 2
     overlay_image.anchor_y = overlay_image.height / 2
     overlay = Sprite(overlay_image, self.camera.x, self.camera.y)
     overlay.draw()
Ejemplo n.º 30
0
    def __init__(self,
                 *,
                 player: Player,
                 space: pymunk.Space,
                 ui_batch=None,
                 background_batch=None):
        super().__init__()

        self.player = player
        self.space = space
        self.background_batch = background_batch

        self.danger_sprite = Sprite(img=resources.danger_image,
                                    batch=background_batch,
                                    x=128,
                                    y=128)
        self.danger_sprite.visible = False

        # Internal score modified by the property below
        self._score = 0
        # Show the score
        self.score_label = Label('',
                                 font_name='m5x7',
                                 font_size=48,
                                 x=WIDTH - 10,
                                 y=HEIGHT,
                                 anchor_x='right',
                                 anchor_y='top',
                                 batch=ui_batch)
        # "call" the property setter below
        self.score = self._score
Ejemplo n.º 31
0
class Inhabitant(object):
    def __init__(self, img, x, y):
        super(Inhabitant, self).__init__()
        register(self)
        self.x, self.y = x, y
        self.pathfinder = None
        self.path = [
        ]  # extra copy for custom tumbling or alternative path factories
        self.speed = .05
        self.image = img
        self.sprite = Sprite(img, batch=batch)
        self.update()

    def update(self):
        grpos = topo.ground_position(self.x, self.y)
        if grpos:
            x, y = grpos
            self.sprite.set_position(x - 10, y)

    def move(self):
        dx = self.path[0].x - self.x
        dy = self.path[0].y - self.y
        if dx**2 + dy**2 < .01:
            self.path.pop(0)
            if len(self.path) < 1:
                self.pathfinder = None
        else:
            r = math.sqrt(dx**2 + dy**2)
            dx *= self.speed / r
            dy *= self.speed / r
            self.x += dx
            self.y += dy
            self.update()
Ejemplo n.º 32
0
class SpritePreviewWindow(BasePreview):
    def __init__(self, runner, tile_size):
        width = runner.model.world_shape[0] * tile_size
        height = runner.model.world_shape[1] * tile_size
        super().__init__(runner, width=width, height=height)

        self.sprite = Sprite(img=runner.model.tiles[0].image)
        self.tile_size = tile_size

    def draw_tiles(self, pos, bits):
        if bits == 0:
            return

        x, y = pos[-2:]
        self.sprite.x = x * self.tile_size + self.tile_size / 2
        self.sprite.y = self.height - y * self.tile_size - self.tile_size / 2

        tiles = self.runner.model.get_allowed_tiles(bits)
        self.sprite.opacity = 255 / len(tiles)

        for tile in tiles:
            tile.image.anchor_x = self.tile_size / 2
            tile.image.anchor_y = self.tile_size / 2
            self.sprite.image = tile.image
            self.sprite.rotation = tile.rotation * 90
            self.sprite.draw()

        if self.debug:
            Label(str(bits), x=self.sprite.x, y=self.sprite.y).draw()
Ejemplo n.º 33
0
class Scroll(object):
    def __init__(self, text, pos, batch):
        self.text = text
        x, y = self.pos = pos

        group = OrderedGroup(1)
        self.label = Label(text,
                           font_name=FONT_NAME,
                           font_size=28,
                           color=COLOUR,
                           x=x + 20,
                           y=y + 15,
                           group=group,
                           batch=batch)
        w = self.label.content_width + 40
        self.bg = ScrollBG(x, x + w, y, batch=batch, group=OrderedGroup(0))
        self.left = Sprite(scroll_left, x=x, y=y, group=group, batch=batch)
        self.right = Sprite(scroll_right,
                            x=x + w,
                            y=y,
                            group=group,
                            batch=batch)

    def delete(self):
        self.label.delete()
        self.left.delete()
        self.right.delete()
        self.bg.delete()
Ejemplo n.º 34
0
    def __init__(self,
                 x=0, y=0, map=None,
                 blend_src=pyglet.gl.GL_SRC_ALPHA,
                 blend_dest=pyglet.gl.GL_ONE_MINUS_SRC_ALPHA,
                 pos=None,
                 batch=None,
                 group=None,
                 usage='dynamic',
                 ):
        self.dead = False
        self.charName = 'Player'
        self.charClass = 'Fighter'
        self.map = map
        self.mbox = msgBox()
        img = sheet['class'][79]
        self.stats = Stats(self, Con=18, hpRoll=20)
        self.statuswindow = statusWindow(self, batch, group)

        if pos is None:
            self.pos = Position()
        else:
            self.pos = pos
        Sprite.__init__(self, img,
                        x, y, blend_src,
                        blend_dest, batch,
                        group, usage)
Ejemplo n.º 35
0
class Image(Widget):
    def __init__(self, x, y, image):
        self._size = win_width, win_height = get_size()
        self.sprite = Sprite(image, x, y)
        super().__init__(x, y, image.width, image.height)

    def draw(self):
        self.sprite.draw()
Ejemplo n.º 36
0
    def fire(self):
        """Create a new bullet"""
        bullet = Sprite(images['bullet'], batch=self.bullet_batch)
        
        bullet.x = self.player.x + self.player.width  
        bullet.y = self.player.y + self.player.height / 2 - bullet.height / 2

        self.bullets.append(bullet)
Ejemplo n.º 37
0
 def sprites(self, image, x, y, scale=1.0):
     from pyglet.sprite import Sprite
     for i in range(len(x)):
         sprite = Sprite(image, batch=self._batch)
         sprite.x = x[i]
         sprite.y = y[i]
         sprite.scale = scale
         self._sprites.append(sprite)
Ejemplo n.º 38
0
 def sprites(self, image, x, y, scale=1.0):
     from pyglet.sprite import Sprite
     for i in range(len(x)):
         sprite = Sprite(image, batch=self._batch, group=background)
         sprite.x = x[i]
         sprite.y = y[i]
         sprite.scale = scale
         self._sprites.append(sprite)
Ejemplo n.º 39
0
def players_lives(num_icons, batch=None):
    lives_left = []
    for idx in range(num_icons):
        new_sprite = Sprite(img=resources.get_image('engine_stop'),
                            x=785-idx*30, y=585, batch=batch)
        new_sprite.scale = 0.3
        lives_left.append(new_sprite)
    return lives_left
Ejemplo n.º 40
0
class Game(Window):
    def __init__(self):
        """This is run when the game is created"""
        super(Game, self).__init__()

        # Create the sprites
        self.arch = Sprite(images['arch'], x=50, y=50)
        self.bullet = Sprite(images['bullet'], x=-50, y=-50)

        # A handler that watches the keyboard state
        self.keyboard = key.KeyStateHandler()
        self.set_handlers(self.keyboard)

        # Call update() 60 times a second
        clock.schedule_interval(self.update, 1/60.0)

        # Display the current FPS on screen
        self.fps_display = clock.ClockDisplay()

    def on_draw(self):
        """Clear the window, draw the sprites and display framerate"""
        self.clear()
        self.arch.draw()
        self.bullet.draw()
        self.fps_display.draw()

    def on_mouse_press(self, x, y, button, modifiers):
        """This is run when a mouse button is pressed"""
        if button == mouse.LEFT:
            print "The left mouse button was pressed."
        elif button == mouse.RIGHT:
            print "The right mouse button was pressed."

    def update(self, dt):
        """This is called on every update

        It uses the keyboard input to move the player
        at around 200 pixels per second"""

        if self.keyboard[key.RIGHT]:
            self.arch.x += dt * 200

        if self.keyboard[key.LEFT]:
            self.arch.x -= dt * 200

        if self.keyboard[key.UP]:
            self.arch.y += dt * 200

        if self.keyboard[key.DOWN]:
            self.arch.y -= dt * 200

        # Fire if spce bar pressed
        if self.keyboard[key.SPACE]:
            self.fire()

    def fire(self):
        print "Fire!"
Ejemplo n.º 41
0
    def _draw_action_menu(self):
        pattern = SolidColorImagePattern((0, 0, 150, 200))
        overlay_image = pattern.create_image(1000, 200)
        overlay_image.anchor_x = overlay_image.width / 2
        overlay_image.anchor_y = overlay_image.height + 100
        overlay = Sprite(overlay_image, self.camera.x, self.camera.y)
        overlay.draw()

        self._generate_text()
Ejemplo n.º 42
0
    def enemy(self, dt):
	"""creates enemies """
        enemy = Sprite(images['windows'], batch=self.enemy_batch)

	enemy.y = random.uniform(0, self.width)
	enemy.x = self.width
	enemy.startX = enemy.x
	enemy.startY = enemy.y

	self.win_enemy.append(enemy)	
Ejemplo n.º 43
0
    def background_2(self, dt):
	"""Random stars created in back moving faster"""
	fast_star = Sprite(images['star'], batch=self.fast_star_batch)

	fast_star.y = random.uniform(0, self.height)
	fast_star.x = self.width
	
	fast_star.scale = random.uniform(0.2, 2)

	self.fast_stars.append(fast_star)
Ejemplo n.º 44
0
    def on_draw(self):
        from pyglet.sprite import Sprite

        if not self.initialized:
            self.initialized = True
            self.init_gl()

        width, height = self.get_size()
        x_max = width // 32 + 1
        y_max = height // 32 + 1

        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        gl.glEnable(gl.GL_BLEND)

        fov = towel.FieldOfVision(self.passable.__contains__)
        fov.place_viewer(self.player, self.player_view)
        x, y = self.player

        x_offset = x - x_max // 2
        y_offset = y - y_max // 2

        x_range = range(0, x_max + 1)
        y_range = range(0, y_max + 1)

        self.clear()
        batch = pyglet.graphics.Batch()
        sprites = []

        player_screen_pos = None

        for iy in y_range:
            for ix in x_range:
                p = (ix + x_offset, iy + y_offset)
                image = None
                color = (255, 255, 255)
                if fov.is_visible(p):
                    if p in self.passable:
                       image = self.image_floor 
                    else:
                       image = self.image_wall 
                    self.remembered[p] = image
                else:
                    image = self.remembered.get(p, None)
                    color = (128, 128, 128)
                if image:
                    sprite = Sprite(image, ix*32, iy*32, batch=batch)
                    sprite.color = color
                    sprites.append(sprite)
                if p == self.player:
                    player_screen_pos = (ix*32, iy*32)

        batch.draw()
        if player_screen_pos:
            self.image_player.blit(*player_screen_pos)
        self.invalid = False
Ejemplo n.º 45
0
 def player_icons(self, batch=None):
     self._life_icons = set()
     WIDTH = self.win_size[0]
     HEIGHT = self.win_size[1]
     for idx in range(self._num_lives):
         new_sprite = Sprite(img=resources.get_image('engine_stop'),
                             x=WIDTH - 15 - idx * 30, y=HEIGHT - 15, batch=batch)
         new_sprite.scale = 0.3
         new_sprite.rotation = -90
         self._life_icons.add(new_sprite)
     return self._life_icons
Ejemplo n.º 46
0
    def background_1(self, dt):
	"""create random number of stars at random y co ordinates"""
	#for star in self.star:
	star = Sprite(images['star'], batch=self.star_batch)
	
	star.y = random.uniform(0,self.width-2)
	star.x = self.width 

	star.scale = random.uniform(0.2, 2)
	
	self.stars.append(star) 
Ejemplo n.º 47
0
    def add_button(self, b_type):
        if b_type == "1":
            x = 20
            y = 20
            category = "tower"
            texture = self.w.textures["tower_wood"]
            active = True
            b_price = self.w.game.available_towers[b_type]
        elif b_type == "2":
            x = 20
            y = 20 + self.b_size
            category = "tower"
            texture = self.w.textures["tower_poison"]
            active = True
            b_price = self.w.game.available_towers[b_type]
        elif b_type == "3":
            x = 20
            y = 20 + self.b_size * 2
            category = "tower"
            texture = self.w.textures["tower_splash"]
            active = True
            b_price = self.w.game.available_towers[b_type]
        elif b_type == "4":
            x = 20
            y = 20 + self.b_size * 3
            category = "tower"
            texture = self.w.textures["tower_chain"]
            active = True
            b_price = self.w.game.available_towers[b_type]
        elif b_type == "gold_icon":
            texture = image.load(RES_PATH + 'ui/gold.png')
            texture = center_image(texture)
            x = texture.width + 2
            y = self.w.height - (texture.height + 2)
            category = "ui"
            active = False
            b_price = False
            b_type = "icon"
        else:
            return False

        b_sprite = Sprite(
                        texture,
                        x=x, y=y,
                        batch=self.w.batches["buttons"],
                        group=self.w.ui_group
                    )

        b_sprite.category = category
        b_sprite.b_type = b_type
        b_sprite.active = active
        b_sprite.b_price = b_price
        self.sprites.append(b_sprite)
Ejemplo n.º 48
0
 def __init__(self):
     frames.basicFrame.__init__(self)        
     
     self.background = Sprite(assets.mainMenuBackground,0,0)
     self.background.scale = float(setting.SCREEN_HEIGHT) / self.background.height
     self.playButton = Sprite(assets.mainMenuPlay,0,0)
     self.optionsButton = Sprite(assets.mainMenuOptions,0,0)
     self.playButton.scale = self.optionsButton.scale = self.background.scale
     self.optionsButton.tx = self.optionsButton.x = self.playButton.x = self.playButton.tx = 1385 * self.playButton.scale
     self.playButton.ty = 520 * self.playButton.scale
     self.playButton.y = self.playButton.ty + 2000
     self.optionsButton.ty = 300 * self.optionsButton.scale
     self.optionsButton.y = self.optionsButton.y + 1000
Ejemplo n.º 49
0
    def draw(self):
        if self.xpos > window.width / 2:
            self.x = window.width / 2
        else:
            self.x = self.xpos

        if self.ypos > window.height / 2:
            self.y = window.height / 2
        else:
            self.y = self.ypos

        Sprite.draw(self)

        self.goo_batch.draw()
Ejemplo n.º 50
0
 def value(self, value):
     new = min(self.display_max, value)
     delta = new - self.value
     self._value = value
     while delta > 0:
         sprite = Sprite(self.__class__.icon_img, y=self.y)
         self.icons.append(sprite)
         self.add_sprite(sprite, self.__class__.sprite_group)
         self.x = self.x
         delta -= 1
     while delta < 0:
         sprite = self.icons.pop()
         sprite.delete()
         delta += 1
Ejemplo n.º 51
0
    def __init__(self):
        music_player.next()

        self.start_level()

        music_player.seek(0)
        music_player.play()

        bar_fill_image.width = bar_fill_image.start_width

        image = pyglet.image.load(data.filepath('player.png'))
        self.sequence = pyglet.image.ImageGrid(image, 5, 2)
        self.frame = -2

        for sequence_image in self.sequence:
            sequence_image.anchor_x = sequence_image.width / 2
            sequence_image.anchor_y = sequence_image.height / 2

        Sprite.__init__(self, self.sequence[self.frame], 0, window.height / 2)

        self.hitbox = (10, 2, 38, 30)

        # Start at 1, height - 1
        self.xpos = TILE_SIZE
        self.ypos = TILE_SIZE
        for index, value in enumerate(world_map):
            if value == TILE_PLAYER:
                self.xpos = (index % map_width) * TILE_SIZE
                self.ypos = ((index / map_width) + 1) * TILE_SIZE

        self.speedx = self.speedy = 0

        self.walking = False
        self.walk_speed = 100
        self.walk_damping = 0.1
        self.walk_frame_time = 0
        self.walk_frame_speed = 0.25

        self.goo_batch = pyglet.graphics.Batch()
        self.projectiles = []

        self.shoot_time = 0
        self.shoot_speed = 0.25
        self.shooting = False

        self.bounce_height = 400
        self.bounce_first = None

        self.finished = False
        self.dead = False
Ejemplo n.º 52
0
    def __init__(self):
        """This is run when the game is created"""
        super(Game, self).__init__()

        # Create the sprites
        self.arch = Sprite(images['arch'], x=50, y=50)
        self.bullet = Sprite(images['bullet'], x=-50, y=-50)

        # A handler that watches the keyboard state
        self.keyboard = KeyStateHandler()
        self.set_handlers(self.keyboard)

        # Call update() 60 times a second
        clock.schedule_interval(self.update, 1/60.0)
Ejemplo n.º 53
0
    def __init__(self):
        self.image_opened = image.load(data_file('garbagecan-open.png'))
        self.image_closed = image.load(data_file('garbagecan-closed.png'))
        self.image_lid = image.load(data_file('garbagecan-lid.png'))

        self.image_opened.anchor_x = self.image_opened.width/2
        self.image_opened.anchor_y = self.image_opened.height/2
        self.image_closed.anchor_x = self.image_opened.width/2
        self.image_closed.anchor_y = self.image_opened.height/2

        self.candidateLeaves = {}

        self.opened = True
        self.lid_active = False
        self.can_active = False
        self.fallen = False
        self.can_highlighted = False
        self.lid_highlighted = True

        self.can_rect = Rect(0, 0, self.image_closed)
        self.can_rect.center = (80, 90)

        self.can_sprite = Sprite(self.image_opened)
        self.can_sprite.set_position(self.can_rect.x, self.can_rect.y)

        self.lid_rect = Rect(20, 40, self.image_lid)

        window.game_window.push_handlers(self.on_mouse_release)
        window.game_window.push_handlers(self.on_mouse_press)
        window.game_window.push_handlers(self.on_mouse_drag)
        window.game_window.push_handlers(self.on_mouse_motion)

        events.AddListener(self)
Ejemplo n.º 54
0
 def __init__(self, x, y, hb=None):
     super().__init__()
     cls = self.__class__
     self.rect = primitives.Rect(0, 0, cls.sprite_img.width,
             cls.sprite_img.height)
     self.hb = hb
     self.sprite = Sprite(cls.sprite_img)
     self.add_sprite(self.sprite, cls.sprite_group)
     self.x, self.y = x, y
Ejemplo n.º 55
0
    def __init__(self, index, x, y):
        self.animation = False

        image = tileset[index]

        if image.width > TILE_SIZE:
            self.animation = True
            self.sequence = pyglet.image.ImageGrid(image, 1, image.width / TILE_SIZE)

            self.tile_time = 0
            self.tile_frame = 0
            self.tile_speed = 0.25

            image = self.sequence[self.tile_frame]

        Sprite.__init__(self, image, x, y, batch=map_batch)
        self.xpos = x
        self.ypos = y
Ejemplo n.º 56
0
 def __init__(self, img, x, y):
     super(Inhabitant, self).__init__()
     register(self)
     self.x, self.y = x, y
     self.pathfinder = None
     self.path = []  # extra copy for custom tumbling or alternative path factories
     self.speed = 0.05
     self.image = img
     self.sprite = Sprite(img, batch=batch)
     self.update()
Ejemplo n.º 57
0
 def add_entry(self, title="No title", action=None):
     b_sprite = Sprite(
                     self.w.textures["wall_stone"],
                     x=self.w.width / 2,
                     y=self.w.height / 2 - (32 * len(self.entries)),
                     batch=self.w.batches["mm_buttons"],
                     group=self.w.ui_group
                 )
     # b_sprite.width, b_sprite.height = 3, 1
     x, y = b_sprite.x, b_sprite.y
     b_sprite.rectangle = create_rectangle(x, y, 128, 32)
     b_sprite.action = action
     b_sprite.label = text.Label(
         title, font_name='Soft Elegance',
         font_size=14,
         x=x, y=y,
         anchor_x="center", anchor_y="center"
     )
     self.entries.append(b_sprite)
Ejemplo n.º 58
0
 def on_draw(self):
     self.clear()
     self.background.blit(0, 0)
     self.ships.draw()
     self.rocks.draw()
     self.missiles.draw()
     self.text_lives.draw()
     self.text_score.draw()
     if not self.started:
        self.splash = Sprite(self.splash_img, 200, 125)
        self.splash.draw()
Ejemplo n.º 59
0
class Pawn(object):
    def __init__(self, image):
        self._sprite = Sprite(image)
        self.position = None

    @property
    def opacity(self):
        return self._sprite.opacity

    @opacity.setter
    def opacity(self, value):
        self._sprite.opacity = value

    def render(self):
        self._sprite.draw()

    def set_position(self, position, offset):
        self.position = position
        self._sprite.x = position.x * STREET_GRID_SIZE + offset.x
        self._sprite.y = position.y * STREET_GRID_SIZE + offset.y