Beispiel #1
0
    def __init__(self, prohibited=None):
        self.position = (0, 0)
        self.board_width = self.board_height = L
        self.randomize_position(prohibited)

        self.sprite_counter = 0
        self.num_sprites = 4
        self.spritesheet = Spritesheet('Character')
Beispiel #2
0
 def __init__(self):
     super().__init__()
     self.menus = ["Main Menu", "Map Selection", "Help"]
     self.spritesheet = Spritesheet('Character')
     self.num_sprites = 4
     self.sprite_counter = 0
     hat_path = os.path.join(SPRITES_DIR, 'chapeu_magicos.png')
     self.hat = pygame.image.load(hat_path).convert_alpha()
     self.select_sound = pygame.mixer.Sound(sound_path('select.ogg'))
     self.enter_sound = pygame.mixer.Sound(sound_path('enter.ogg'))
Beispiel #3
0
    def __init__(self, **kwargs):
        self.board_width = self.board_height = L
        self.randomize_position()

        self.effect_key = kwargs['key']  # key to define power-up effect
        self.lasting = kwargs['lasting']
        if self.lasting:
            self.duration = kwargs['interval']

        self.sprite_counter = 0
        self.num_sprites = 4
        self.spritesheet = Spritesheet('Powerups')
Beispiel #4
0
class Food:
    def __init__(self, prohibited=None):
        self.position = (0, 0)
        self.board_width = self.board_height = L
        self.randomize_position(prohibited)

        self.sprite_counter = 0
        self.num_sprites = 4
        self.spritesheet = Spritesheet('Character')

    def randomize_position(self, prohibited=None):
        if prohibited is None:
            prohibited = []
        # item position can't override snake's body
        while True:
            self.position = (random.randint(0, self.board_width - 1),
                             random.randint(0, self.board_height - 1))
            if self.position not in prohibited:
                return

    def draw(self, surface: pygame.Surface):
        if self.sprite_counter >= self.num_sprites * UPDATE_CONST:
            self.sprite_counter = 0

        sprite = self.get_sprite()
        pos = tuple((x * PX) for x in self.position)
        surface.blit(sprite, pos)

        self.sprite_counter += 1

    def get_sprite(self):
        frame_name = 'down_{}'.format(self.sprite_counter // UPDATE_CONST)
        sprite = self.spritesheet.parse_sprite(frame_name)
        return sprite
Beispiel #5
0
class PowerUp:
    def __init__(self, **kwargs):
        self.board_width = self.board_height = L
        self.randomize_position()

        self.effect_key = kwargs['key']  # key to define power-up effect
        self.lasting = kwargs['lasting']
        if self.lasting:
            self.duration = kwargs['interval']

        self.sprite_counter = 0
        self.num_sprites = 4
        self.spritesheet = Spritesheet('Powerups')

    def randomize_position(self, prohibited=None):
        if prohibited is None:
            prohibited = []
        while True:
            self.position = (random.randint(0, self.board_width - 1),
                             random.randint(0, self.board_height - 1))
            # item position can't override snake's body
            if self.position not in prohibited:
                return

    def draw(self, surface: pygame.Surface):
        if self.sprite_counter >= self.num_sprites * UPDATE_CONST:
            self.sprite_counter = 0

        sprite = self.get_sprite()
        draw_image(surface, sprite, *self.position)

        self.sprite_counter += 1

    def get_sprite(self):
        # fixme: gambi alert
        i = (not self.effect_key
             ) * self.num_sprites + self.sprite_counter // UPDATE_CONST
        filename = f'Powerups{i}.png'
        sprite = self.spritesheet.parse_sprite(filename)
        return sprite

    def get_effect(self, snake):
        """
        Method to cause the corresponding effect on the snake
        """
        if self.effect_key == 0:
            # increases snake speed by a factor of 2
            snake.update_counter = UPDATE_CONST // 2
            pygame.time.set_timer(STOP_EFFECT, self.duration, True)
        elif self.effect_key == 1:
            snake.reverse()

    def reset_effect(self, snake):
        if self.effect_key == 0:
            snake.update_counter = UPDATE_CONST
Beispiel #6
0
    def __init__(self, prohibited=None, head=None, hd=None):
        self.width = self.height = L
        self.length = 1
        self.update_counter = UPDATE_CONST

        head = self.initial_head(prohibited) if head is None else head
        self.body = [head]

        self.up = (0, -1)
        self.down = (0, 1)
        self.left = (-1, 0)
        self.right = (1, 0)
        d = (self.up, self.down, self.left, self.right)
        self.head_direction = random.choice(d) if hd is None else hd
        self.directions = [self.head_direction]

        self.sprite_counter = 0
        self.num_sprites = 4
        self.spritesheet = Spritesheet('Character')
        self.lost_sound = pygame.mixer.Sound(sound_path('perdeu.ogg'))

        self.last_turn_command = self.head_direction
        self.turns_to_apply = []
Beispiel #7
0
class Snake:
    def __init__(self, prohibited=None, head=None, hd=None):
        self.width = self.height = L
        self.length = 1
        self.update_counter = UPDATE_CONST

        head = self.initial_head(prohibited) if head is None else head
        self.body = [head]

        self.up = (0, -1)
        self.down = (0, 1)
        self.left = (-1, 0)
        self.right = (1, 0)
        d = (self.up, self.down, self.left, self.right)
        self.head_direction = random.choice(d) if hd is None else hd
        self.directions = [self.head_direction]

        self.sprite_counter = 0
        self.num_sprites = 4
        self.spritesheet = Spritesheet('Character')
        self.lost_sound = pygame.mixer.Sound(sound_path('perdeu.ogg'))

        self.last_turn_command = self.head_direction
        self.turns_to_apply = []

    def get_head_position(self):
        return self.body[0]

    def add_turn_command(self, to):
        if (to[0] * -1, to[1] * -1) == self.last_turn_command:
            return
        self.last_turn_command = to
        if len(self.turns_to_apply
               ) < 3:  # limit the "simultaneous" commands to three
            self.turns_to_apply.append(to)

    def move(self, map_prohibited=None):
        """
        :return: has collided?
        """

        if map_prohibited is None:
            map_prohibited = []

        def lose():
            self.lost_sound.play()
            return True

        cur = self.get_head_position()

        # turn
        if self.turns_to_apply:
            self.head_direction = self.turns_to_apply.pop(0)

        x, y = self.head_direction
        new_x, new_y = new = (cur[0] + x, cur[1] + y)

        # checks if snake collided with something inside the map
        if new in map_prohibited:
            return lose()

        # checks if the snake collided with map borders
        if new_x < 0 or new_x >= self.width or new_y >= self.height or new_y < 0:
            return lose()

        # checks if the snake collided with itself
        if new in self.body[3:]:
            return lose()
        else:
            self.body.insert(0, new)
            self.directions.insert(0, self.head_direction)
            if len(self.body) > self.length:
                self.body.pop()
            if len(self.directions) > self.length:
                self.directions.pop()
            return False

    def draw(self, surface: pygame.Surface):
        if self.sprite_counter >= self.num_sprites * self.update_counter:
            self.sprite_counter = 0  # fixme

        for pos, direction in zip(self.body, self.directions):
            pos = tuple((PX * x) for x in pos)  # fixme
            sprite = self.get_sprite(direction)
            surface.blit(sprite, pos)

        self.sprite_counter += 1

    def get_sprite(self, d):
        possible_directions = [{
            'dir': self.__dict__[x],
            'name': x
        } for x in ('up', 'down', 'left', 'right')]
        direction = next(x['name'] for x in possible_directions
                         if x['dir'] == d)
        frame_name = f'{direction}_{self.sprite_counter // self.update_counter}'
        sprite = self.spritesheet.parse_sprite(frame_name)
        return sprite

    def reverse(self):
        tmp = []
        for i, d in enumerate(self.directions):
            if d == self.up:
                tmp.insert(0, self.down)
            elif d == self.left:
                tmp.insert(0, self.right)
            elif d == self.right:
                tmp.insert(0, self.left)
            elif d == self.down:
                tmp.insert(0, self.up)
        self.directions = tmp
        self.head_direction = tmp[0]
        self.body.reverse()

    def initial_head(self, prohibited=None):
        if prohibited is None:
            prohibited = []
        while True:
            head = (random.randint(0, self.width - 1),
                    random.randint(0, self.height - 1))
            if head not in prohibited:
                return head
Beispiel #8
0
class Menu(GameState):
    def __init__(self):
        super().__init__()
        self.menus = ["Main Menu", "Map Selection", "Help"]
        self.spritesheet = Spritesheet('Character')
        self.num_sprites = 4
        self.sprite_counter = 0
        hat_path = os.path.join(SPRITES_DIR, 'chapeu_magicos.png')
        self.hat = pygame.image.load(hat_path).convert_alpha()
        self.select_sound = pygame.mixer.Sound(sound_path('select.ogg'))
        self.enter_sound = pygame.mixer.Sound(sound_path('enter.ogg'))

    def startup(self):
        self.selected = 1
        self.select(self.selected)
        self.update()

    def cleanup(self):
        self.unselect(self.selected)

    def update(self):
        self.set_texts()
        self.set_rects()

    def draw(self, surface: pygame.Surface):
        surface.fill(background_color)

        surface.blit(self.title, self.title_rect)
        surface.blit(self.mapselec, self.mapselec_rect)
        surface.blit(self.help, self.help_rect)
        surface.blit(self.hat, self.hat_rect)

        if self.sprite_counter >= self.num_sprites * UPDATE_CONST:
            self.sprite_counter = 0

        sprite = self.get_sprite()
        surface.blit(sprite, self.animation_rect_right)
        surface.blit(sprite, self.animation_rect_left)

        self.sprite_counter += 1

    def on_key_up(self, e):
        if e.key in [K_DOWN, K_RIGHT]:
            self.down()
            self.select_sound.play()
        elif e.key in [K_UP, K_LEFT]:
            self.up()
            self.select_sound.play()
        elif e.key in [K_RETURN, K_KP_ENTER, K_SPACE]:
            self.next_state = self.unselect(self.selected,
                                            inplace=False).replace(' ', '')
            self.enter_sound.play()
            self.done = True

    def on_mouse_up(self, e):
        pass

    def down(self):
        self.unselect(self.selected)
        self.selected = 1 + (self.selected % (len(self.menus) - 1))
        self.select(self.selected)

    def up(self):
        self.unselect(self.selected)
        self.selected = (self.selected - 2) % (len(self.menus) - 1) + 1
        self.select(self.selected)

    # noinspection DuplicatedCode
    def set_texts(self):
        f1, f2 = (self.fonts[x] for x in ('h1', 'h2'))
        self.title = f1.render(self.menus[0], True, pygame.Color("blue"))
        self.mapselec = f2.render(self.menus[1], True, pygame.Color("red"))
        self.help = f2.render(self.menus[2], True, pygame.Color("yellow"))

    # noinspection DuplicatedCode
    def set_rects(self):
        self.set_texts()

        self.title_center = (self.get_screen_rect().center[0],
                             self.get_screen_rect().center[1] - 30)
        self.mapselec_center = (self.get_screen_rect().center[0],
                                self.get_screen_rect().center[1])
        self.help_center = (self.get_screen_rect().center[0],
                            self.get_screen_rect().center[1] + 20)

        self.title_rect = self.title.get_rect(center=self.title_center)
        self.mapselec_rect = self.mapselec.get_rect(
            center=self.mapselec_center)
        self.help_rect = self.help.get_rect(center=self.help_center)

        self.hat_topleft = (self.get_screen_rect().bottomright[0] - 150,
                            self.get_screen_rect().bottomright[1] - 150)
        self.animation_right = (self.title_rect.right + 20, self.title_rect.y)
        self.animation_left = (self.title_rect.left - 52, self.title_rect.y)

        self.hat_rect = pygame.Rect(self.hat_topleft, (128, 128))
        self.animation_rect_right = pygame.Rect(self.animation_right, (32, 32))
        self.animation_rect_left = pygame.Rect(self.animation_left, (32, 32))

    def select(self, idx, inplace=True):
        selected = '< ' + self.menus[idx] + ' >'
        if inplace:
            self.menus[idx] = selected
        return selected

    def unselect(self, idx, inplace=True):
        unselected = self.menus[idx][2:-2]
        if inplace:
            self.menus[idx] = unselected
        return unselected

    def get_sprite(self):
        frame_name = 'down_{}'.format(self.sprite_counter // UPDATE_CONST)
        sprite = self.spritesheet.parse_sprite(frame_name)
        return sprite