Ejemplo n.º 1
0
class Button(pg.sprite.Sprite):
    button_images = {
        'button': load_image('buttons/button.png'),
        'button_pressed': load_image('buttons/button_pressed.png'),
        'button_play': load_image('buttons/button_play.png'),
        'button_sell': load_image('buttons/button_sell.png'),
        'button_upgrade': load_image('buttons/button_upgrade.png')
    }

    def __init__(self, left_top, size, settings):
        super(Button, self).__init__(settings.all_sprites,
                                     settings.button_sprites)
        self.settings = settings
        self.image = pg.transform.scale(self.button_images['button'], size)
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = left_top

    def update(self, *args, **kwargs) -> None:
        mouse_pos = kwargs.get('mouse_pos', None)
        self.on_pressed_update_image()
        if self.rect.collidepoint(mouse_pos) and pg.mouse.get_pressed(3)[0]:
            self.click()

    def on_pressed_update_image(self):
        pass

    def _change_image(self, base_image, inner_image):
        self.image = pg.transform.scale(base_image, self.rect.size)
        w, h = self.image.get_size()
        tower_img = pg.transform.scale(inner_image,
                                       (int(w * 0.70), int(h * 0.70)))
        self.image.blit(tower_img, (int(w * 0.15), int(h * 0.15)))

    def click(self, *args, **kwargs):
        pass
Ejemplo n.º 2
0
class SplitTower(BaseTower):
    tower_image = [
        load_image('towers/split_tower_lvl1.png'),
        load_image('towers/split_tower_lvl2.png'),
        load_image('towers/split_tower_lvl3.png')
    ]
    tower_shoot_sound = pg.mixer.Sound('data/sounds/split_tower_shoot.WAV')

    def __init__(self, settings, top_left, size):
        super(SplitTower, self).__init__(settings, top_left, size)
        self.targets = settings.split_tower_targets

    def select_enemy_to_shoot(self, enemies) -> object:
        new_enemies = []
        for _ in range(self.targets):
            if not enemies:
                break
            enemy = super(SplitTower, self).select_enemy_to_shoot(enemies)
            enemies.remove(enemy)
            new_enemies.append(enemy)
        self.rotate_to_shooting_enemy(new_enemies[0])
        return new_enemies

    def shoot(self, enemies):
        if not self.attack_cooldown:
            for enemy in enemies:
                Bullet(self.rect.center, enemy, self.damage, self.settings)
            self.attack_cooldown = self.attack_speed
            self.tower_shoot_sound.play()

    def upgrade_stats(self):
        self.targets += 1
        self.damage = int(self.damage * 1.5)
        if self.level == 3:
            self.range += 1
Ejemplo n.º 3
0
 def __init__(self, x, y, move_on_right, *group):
     super().__init__(*group)
     self.right_images = [
         load_image("Bullets/bull_3_0.png", -1),
         load_image("Bullets/bull_3_1.png", -1),
         load_image("Bullets/bull_3_2.png", -1),
         load_image("Bullets/bull_3_3.png", -1),
         load_image("Bullets/bull_3_4.png", -1)
     ]
     self.left_images = [
         pygame.transform.flip(load_image("Bullets/bull_3_0.png", -1), True,
                               False),
         pygame.transform.flip(load_image("Bullets/bull_3_1.png", -1), True,
                               False),
         pygame.transform.flip(load_image("Bullets/bull_3_2.png", -1), True,
                               False),
         pygame.transform.flip(load_image("Bullets/bull_3_3.png", -1), True,
                               False),
         pygame.transform.flip(load_image("Bullets/bull_3_4.png", -1), True,
                               False)
     ]
     if move_on_right:
         self.image = self.right_images[0]
     else:
         self.image = self.left_images[0]
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.t = 0
Ejemplo n.º 4
0
class Bullet(pg.sprite.Sprite):
    bullet_image = {
        'normal_bullet': load_image('towers/normal_bullet.png'),
        'big_bullet': load_image('towers/big_bullet.png')
    }

    def __init__(self, start, enemy, damage, settings):
        super(Bullet, self).__init__(settings.all_sprites,
                                     settings.bullet_sprites)
        self.settings = settings
        self.image = self.bullet_image['big_bullet']
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = start
        self.speed = settings.bullet_speed
        self.damage = damage
        self.x, self.y = start
        self.enemy = enemy

    def update(self, *args, **kwargs) -> None:
        delta_time = kwargs['delta_time']
        if pg.sprite.collide_rect(self, self.enemy):
            self.enemy.hit(self.damage)
            self.kill()
        self._update_unit_vector()
        self.x += self.unit_vector[0] * self.speed * delta_time
        self.y += self.unit_vector[1] * self.speed * delta_time
        self.rect.x = self.x
        self.rect.y = self.y

    def _update_unit_vector(self):
        v = self.enemy.rect.centerx - self.rect.centerx, self.enemy.rect.centery - self.rect.centery
        vm = hypot(*v)
        self.unit_vector = (v[0] / vm, v[1] / vm)
Ejemplo n.º 5
0
class Particle(pygame.sprite.Sprite):
    many_stars = [load_image("star.png")]
    for scale in (5, 10, 20):
        many_stars.append(pygame.transform.scale(many_stars[0],
                                                 (scale, scale)))

    many_hearts = [load_image("heart.png")]
    for scale in (5, 10, 20):
        many_hearts.append(
            pygame.transform.scale(many_hearts[0], (scale, scale)))

    def __init__(self, pos, dx, dy, name):
        super().__init__(all_sprites)
        self.add(particles)
        if name == 'star':
            self.image = random.choice(self.many_stars)
        elif name == 'heart':
            self.image = random.choice(self.many_hearts)
        self.rect = self.image.get_rect()
        self.velocity = [dx, dy]
        self.rect.x, self.rect.y = pos
        self.gravity = GRAVITY

    def update(self):
        self.velocity[1] += self.gravity
        self.rect.x += self.velocity[0]
        self.rect.y += self.velocity[1]
        if not self.rect.colliderect(screen_rect):
            self.kill()
Ejemplo n.º 6
0
 def __init__(self, x, y, *group):
     super().__init__(x, y, "Enemys/Enemy_base.png", *group)
     self.bullet_spawn = 10
     self.t = 0
     self.life = True
     self.running_right = []
     for i in range(8):
         self.running_right.append(
             pygame.transform.scale(
                 load_image("Enemys/Enemy_base_" + str(i) + ".png", -1),
                 (50, 90)))
     self.running_left = []
     for i in range(8):
         x = pygame.transform.scale(
             load_image("Enemys/Enemy_base_" + str(i) + ".png", -1),
             (50, 90))
         self.running_left.append(pygame.transform.flip(x, True, False))
     self.Exp_right = []
     for i in range(8):
         self.Exp_right.append(
             pygame.transform.scale(
                 load_image("Enemys/Enemy_Exp_base_" + str(i) + ".png", -1),
                 (50, 90)))
     self.Exp_left = []
     for i in range(8):
         x = pygame.transform.scale(
             load_image("Enemys/Enemy_Exp_base_" + str(i) + ".png", -1),
             (50, 90))
         self.Exp_left.append(pygame.transform.flip(x, True, False))
Ejemplo n.º 7
0
def start_screen(screen):
    # Размеры переданного экрана
    size = width, height = screen.get_rect().w, screen.get_rect().h
    intro_text = ["2D Гонки", "", "Выберите машину"]

    # Добавляем картинку фона (я заменил на бесплатную картинку)
    fon = pygame.transform.scale(load_image('fon1.jpg'), (width, height))
    # Добавляем её на экран
    screen.blit(fon, (0, 0))
    # Создаём экземпляр шрифта
    font = pygame.font.Font(None, 30)
    text_coord = 50  # Начальная высота надписи
    # Рендерим текст стартового экрана построчно (из-за особенностей pygame)
    # тут я сам не до конца понимаю, поэтому лучше не трогать
    for line in intro_text:
        string_rendered = font.render(line, 1, (0, 0, 0))
        intro_rect = string_rendered.get_rect()
        text_coord += 10
        intro_rect.top = text_coord
        intro_rect.x = width // 2 - intro_rect.w // 2
        text_coord += intro_rect.height
        fon.blit(string_rendered, intro_rect)

    # Создаём спрайты машин и кнопки
    car_sprites = pygame.sprite.Group()
    buttons = pygame.sprite.Group()
    btn = Button((200, 400), 'start_button.png', buttons)

    for i in range(4):
        Car((80 + i * 130, 200), load_image(f'car{i}.png'), car_sprites)

    selected_car = None
    selection_rect = pygame.Rect(
        -10, -10, 1, 1)  # Прямоугольник подсвечивающий выбранную машинку

    while True:
        screen.blit(fon, (0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                for car in car_sprites:
                    # Проверяем на какую машину нажали мышкой и сохраняем выбор
                    if car.rect.collidepoint(event.pos):
                        selected_car = car
                        selection_rect = selected_car.rect
                # Если нажали кнопку и машина выбрана, то возвращаем выбранную машину и начинаем игру
                if btn.button_pressed(event.pos) and selected_car is not None:
                    return selected_car.image

        pygame.draw.rect(screen, (0, 0, 0), selection_rect)
        car_sprites.draw(screen)
        buttons.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)
Ejemplo n.º 8
0
 def __init__(self, x, y, *group):
     super().__init__(x, y, "Glass\glass_0.png", *group)
     self.images = [
         load_image("Floor\Glass\glass_0.png", -1),
         load_image("Floor\Glass\glass_1.png", -1),
         load_image("Floor\Glass\glass_2.png", -1),
         load_image("Floor\Glass\glass_3.png", -1),
         load_image("Floor\Glass\glass_4.png", -1)
     ]
     self.hp = 1000
     self.t = 0
Ejemplo n.º 9
0
 def __init__(self, speed=-5):
     """
     se instancian los atributos que vamos a utilizar en esta clase
     entre ellos imagenes,botones y rectangulo alrededor del sprite para las colisiones
     y por ultimo la velocidad.
     """
     self.image, self.rect = fn.load_image('fondo_kaio.png', -1, -1, -1)
     self.image1, self.rect1 = fn.load_image('fondo_kaio.png', -1, -1, -1)
     self.rect.bottom = var.height
     self.rect1.bottom = var.height
     self.rect1.left = self.rect.right
     self.speed = speed
Ejemplo n.º 10
0
	def __init__(self, root, x, y):
		Weapon.__init__(self, root, x, y)

		self.sprite = load_image("sprites/weapons/scatterguns/0.png")
		self.rect = self.sprite.get_rect()
		self.firingSprite = load_image("sprites/weapons/scatterguns/2.png")

		self.maxAmmo = 6
		self.ammo = self.maxAmmo

		self.refireTime = 0.5
		self.reloadTime = 1

		self.xImageOffset = -8
		self.yImageOffset = -8
Ejemplo n.º 11
0
class NPC:
    NPC_sprite = functions.load_image('friendly.png')

    def __init__(self, x, y, roomObj, text):
        self.dialogue = text
        self.collisionx = x
        self.collisiony = y
        self.width = 48
        self.height = 48
        self.range = 48
        self.roomObj = roomObj

    def update(self):
        self.drawNPC()
        if self.checkPlayerCollision():
            self.roomObj.text = self.dialogue
        else:
            self.roomObj.text = ""

    def checkPlayerCollision(self):
        if functions.objCollision(self, self.roomObj.playerObj):
            return True

    def drawNPC(self):
        pygame.draw.rect(
            Display.DISPLAYSURF, Display.BLUE,
            pygame.Rect(self.collisionx, self.collisiony, self.width,
                        self.height))
        Display.DISPLAYSURF.blit(
            self.NPC_sprite,
            pygame.Rect(self.collisionx, self.collisiony, self.width,
                        self.height))
Ejemplo n.º 12
0
 def __init__(self, *group):
     self.circspos = [(100, 50), (180, 175), (250, 100), (140, 25),
                      (50, 170)]
     self.oldx = 400
     self.oldy = 50
     super().__init__(self.oldx, self.oldy, "Boss/Boss_0.png", *group)
     self.hp = 1000
     self.LeftUpbullet_spawn = 50
     self.LeftDownbullet_spawn = 50
     self.RightUpbullet_spawn = 50
     self.RightDownbullet_spawn = 50
     self.DownLeftbullet_spawn = 50
     self.DownCentbullet_spawn = 50
     self.DownRightbullet_spawn = 50
     self.move = "y+"
     self.t = 0
     self.r = 10
     self.life = True
     self.animations = []
     for i in range(6):
         self.animations.append(
             load_image("Boss/boss_" + str(i) + ".png", -1))
     self.boss_sound = pygame.mixer.Sound("data/Sounds/boss.ogg")
     self.boss_sound.set_volume(0.5)
     self.mustexp = True
Ejemplo n.º 13
0
 def __init__(self, x_pos, v, number):
     super().__init__(main_group, all_sprites)
     self.image = load_image('bird' + str(number) + '.png')
     self.rect = self.image.get_rect()
     self.rect.x = random.randint(x_pos + 150, x_pos + 200)
     self.rect.y = random.randint(280, 310)
     self.v = v
Ejemplo n.º 14
0
 def __init__(self, x, y, speed, *group):
     super().__init__(x, y, False, speed, "bull_2.png", *group)
     self.image = load_image("Bullets/" + "bull_2.png", -1)
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.move = speed
Ejemplo n.º 15
0
 def __init__(self, x, y, name_of_next_level, imgname, *group):
     super().__init__(*group)
     self.image = load_image("Endsoflevels/" + imgname, -1)
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.nextlevel = name_of_next_level
Ejemplo n.º 16
0
def dead_screen(name):
    outro_text = ["Menu", 'Press SPACE to restart']
    screen.fill((0, 0, 0))
    fon = pygame.transform.scale(load_image('gameover.png'), (900, 700))
    screen.blit(fon, (-50, -150))
    font = pygame.font.Font('data/font/PressStart2P.ttf', 25)
    text = font.render(outro_text[1], 1, (100, 255, 100))
    text_x = 170
    text_y = 480
    screen.blit(text, (text_x, text_y))
    restart_button = dead_buttons(250, 50, outro_text[0], 270, 370)
    play_music('dead.mp3')
    high_score(screen)
    dead_group.draw(screen)
    pygame.display.flip()
    #возвращение ранее выбранной карты при рестарте
    if name == 'cactus':
        color = (255, 219, 88)
    elif name == 'tree':
        color = (0, 255, 0)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if restart_button.check_click(event.pos):
                    start_screen()
            if event.type == pygame.KEYDOWN:
                if pygame.key.get_pressed():
                    if event.key == pygame.K_SPACE:
                        game(velocity, bvelocity, color, isJump, JumpCount,
                             running, name)

        pygame.display.flip()
        clock.tick(fps)
Ejemplo n.º 17
0
 def __init__(self, x_pos, v, number, name):
     super().__init__(main_group, all_sprites)
     self.image = load_image(name + str(number) + '.png')
     self.rect = self.image.get_rect()
     self.rect.x = x_pos
     self.rect.y = 310
     self.v = v
Ejemplo n.º 18
0
    def __init__(self, object_group, collider_group, x, y, health, speed):
        super().__init__()
        object_group.add(self)
        self.width = 100
        self.height = 100

        self.image = pygame.transform.scale(
            load_image('Main character (0%).jpg'), (self.width, self.height))
        self.moving_rect = list(self.image.get_rect())
        self.moving_rect[0] = x
        self.moving_rect[1] = y
        self.rect = pygame.Rect(self.moving_rect)
        self.collider = Collider(collider_group,
                                 self,
                                 0,
                                 0,
                                 self.width,
                                 self.height,
                                 trigger=False)

        self.tick = None
        self.health = health
        self.speed = speed
        self.direction_sides = []
        self.blocked_sides = [False, False, False, False]
Ejemplo n.º 19
0
    def __init__(self, player, enemy):
        self.Menu = GUI.Menu(("Engage", "Talk", "Exit"), "Actions", 10)
        ARplugin = None
        sys.path.append("area/default")
        import ARplugin
        self.draw = ARplugin.draw
        self.width = ARplugin.width()
        self.height = ARplugin.height()
        self.grid = []
        self.off = [0, 0]
        self.sprite = functions.load_image(ARplugin.sprite(), False)
        self.temp = pygame.Surface((self.width, self.height))
        self.action = False

        ids = []
        for nme in ARplugin.enemies(enemy):
            bid = functions.bugID()
            while bid in ids:
                bid = functions.bugID()
            string = nme[0] + ".dfile"
            bug = Wbug.bug(string, bid)
            bug.x = nme[1]
            bug.y = nme[2]
            self.grid.append([bug, bug.y])
        del ids

        self.grid.append([player, player.y])

        sys.path.pop()
Ejemplo n.º 20
0
def pause(screen, record):
    size = width, height = screen.get_rect().w, screen.get_rect().h
    image = load_image('pause_fon.jpg')
    intro_text = ["Пауза", "Нажмите Esc, чтобы продолжить"]

    # Создаём экземпляр шрифта
    font = pygame.font.Font(None, 30)
    text_coord = 260  # Начальная высота надписи
    # Рендерим текст стартового экрана построчно (из-за особенностей pygame)
    # тут я сам не до конца понимаю, поэтому лучше не трогать
    for line in intro_text:
        string_rendered = font.render(line, 1, (255, 255, 255))
        intro_rect = string_rendered.get_rect()
        text_coord += 10
        intro_rect.top = text_coord
        intro_rect.x = width // 2 - intro_rect.w // 2
        text_coord += intro_rect.height
        image.blit(string_rendered, intro_rect)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate(record=record)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
        screen.blit(image, (0, 0))
        pygame.display.flip()
Ejemplo n.º 21
0
 def __init__(self, x, y):
     super().__init__(all_sprites_group, lever_group)
     self.image = functions.load_image("lever_sprite.png").convert_alpha()
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.orig = self.image
Ejemplo n.º 22
0
def gameover_screen(screen):
    pygame.mixer.init()
    gayover = pygame.mixer.Sound('data/sounds/gameover1.wav')
    # Размеры переданного экрана
    size = width, height = screen.get_rect().w, screen.get_rect().h
    intro_text = [
        "Game over", "", "Игра окончена",
        "Нажмите любую кнопку чтобы продолжить", "Esc чтобы выйти"
    ]
    image = load_image('gameover.jpg')
    # Создаём экземпляр шрифта
    font = pygame.font.Font(None, 30)
    text_coord = 260  # Начальная высота надписи
    # Рендерим текст стартового экрана построчно (из-за особенностей pygame)
    # тут я сам не до конца понимаю, поэтому лучше не трогать
    for line in intro_text:
        string_rendered = font.render(line, 1, (255, 255, 255))
        intro_rect = string_rendered.get_rect()
        text_coord += 10
        intro_rect.top = text_coord
        intro_rect.x = width // 2 - intro_rect.w // 2
        text_coord += intro_rect.height
        image.blit(string_rendered, intro_rect)
        gayover.play()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            if event.type == pygame.KEYDOWN:
                return event.key != pygame.K_ESCAPE

        screen.blit(image, (0, 0))
        pygame.display.flip()
Ejemplo n.º 23
0
	def __init__(self, root, x, y):
		GameObject.__init__(self, root, x, y)
		
		self.lifeAlarm = 0
		self.direction = 0

		self.sprite = load_image("sprites/projectiles/shots/0.png")
		self.rect = self.sprite.get_rect()
Ejemplo n.º 24
0
 def __init__(self, window, x=10, y=5, mvmt=5):
     self.x = x*64
     self.y = y*64
     self.mvmt = mvmt
     self.window = window
     self.img = load_image('vache.png')
     self.x_action = {1: self.x+self.mvmt, 2: self.x-self.mvmt}
     self.y_action = {1: self.y+self.mvmt, 2: self.y-self.mvmt}
Ejemplo n.º 25
0
 def __init__(self, x=11, y=7, life=1, frames=[]):
     self.x = x*64
     self.y = y*64
     self.life = life
     sheet = load_image('arsene.png')
     size = sheet.get_size()
     self.frames = strip_from_sheet(sheet, (0, 0), (size[0]/3, size[1]/4), 1, 4)
     self.movement = 64
Ejemplo n.º 26
0
class FastTower(BaseTower):
    tower_image = [
        load_image('towers/fast_tower_lvl1.png'),
        load_image('towers/fast_tower_lvl2.png'),
        load_image('towers/fast_tower_lvl3.png')
    ]
    tower_shoot_sound = pg.mixer.Sound('data/sounds/tower_shoot.WAV')

    def shoot(self, enemy):
        if not self.attack_cooldown:
            Bullet(self.rect.center, enemy, self.damage, self.settings)
            self.attack_cooldown = self.attack_speed
            self.tower_shoot_sound.play()

    def upgrade_stats(self):
        self.damage = int(self.damage * 1.2)
        self.attack_speed = self.attack_speed * 0.8
Ejemplo n.º 27
0
def main():
    # construct the argument parse and parse the arguments
    ap = argparse.ArgumentParser()

    ap.add_argument("-d",
                    "--data_dir",
                    required=True,
                    help="Path to the images directory")
    ap.add_argument("-m",
                    "--model_path",
                    required=True,
                    help="Path to the the model")
    ap.add_argument("-i",
                    "--input",
                    type=int,
                    required=True,
                    default=299,
                    help="The input size")
    ap.add_argument("-o",
                    "--output",
                    required=True,
                    help="Path to the output file")

    args = vars(ap.parse_args())
    size = args['input']

    # model
    print("Loading model...")
    subdir = args["model_path"]
    model_path = glob.glob(subdir + '*.h5')[-1]
    model = load_model(model_path)

    # data
    print("Reading data...")
    filenames, _, _ = read_data(args["data_dir"])
    n_files = len(filenames)

    # encoding
    print("Encoding images...")
    index_to_filename = {}
    filename_to_path = {}
    features = np.zeros((n_files, model.output.shape[1]))
    for i in tqdm.tqdm(range(n_files)):
        image_id = extract_image_id(filenames[i])
        index_to_filename[i] = image_id
        filename_to_path[image_id] = filenames[i]
        #print("->", image_id)
        image = load_image(filenames[i], (size, size))
        image = image.reshape((1, ) + image.shape)

        features[i] = np.squeeze(model(image))

    # save transfer values
    np.save(args["output"], features)
    with open("index_to_filename.json", "w") as f:
        json.dump(index_to_filename, f, indent=4, ensure_ascii=False)
    with open("filename_to_path.json", "w") as f:
        json.dump(filename_to_path, f, indent=4, ensure_ascii=False)
Ejemplo n.º 28
0
 def __init__(self, x, y, *group):
     super().__init__(x, y, "Enemys/Enemy_up_0.png", *group)
     self.bullet_spawn = 1000
     self.herowas = False
     self.t = 0
     self.animations = []
     for i in range(4):
         self.animations.append(
             load_image("Enemys/Enemy_up_" + str(i) + ".png", -1))
Ejemplo n.º 29
0
 def __init__(self, x, y, imgname, *group):
     super().__init__(*group)
     self.image = load_image(imgname, -1)
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.oldrunningwasright = True
     self.hp = 100
     self.immortal = False
Ejemplo n.º 30
0
    def __init__(self, pos, _screen, side):

        pygame.sprite.Sprite.__init__(self)
        self.image = functions.load_image("portal.png", "colorkey")
        self.rect = pygame.Rect(pos[0], pos[1] - 20, 32, 50)
        self.screen = _screen
        self.anim_delay = 5
        self.frame = 0
        self.side = side
Ejemplo n.º 31
0
 def __init__(self):
     pygame.init()
     pygame.display.set_icon(
         pygame.transform.scale(functions.load_image(GAME_ICON), (32, 32)))
     pygame.display.set_caption('Python-Game')
     self.playerObj = Player.Player()
     self.audioObj = Audio.GameAudio()
     self.inputObj = Input()
     self._log = logging.getLogger(__name__)
     self._log.debug('Initialized Game')
Ejemplo n.º 32
0
class TerrainObject(pygame.sprite.Sprite):
    object_images = {
        'spruce': load_image('Spruce.png'),
        'grass bush': load_image('Grass bush.png')
    }

    def __init__(self, object_group, collider_group, type, x, y, width, height,
                 speed):
        super().__init__()
        object_group.add(self)
        self.width = width
        self.height = height
        self.type = type
        self.speed = speed

        self.image = pygame.transform.scale(
            TerrainObject.object_images[self.type], (self.width, self.height))
        self.moving_rect = list(self.image.get_rect())
        self.moving_rect[0] = x
        self.moving_rect[1] = y
        self.rect = pygame.Rect(self.moving_rect)

        self.collider = None
        self.setup_collider(collider_group)

    def setup_collider(self, collider_group):
        if self.type == 'spruce':
            stem_width = int(self.width / 3.45)
            stem_depth = int(self.width / 6)
            self.collider = Collider(collider_group,
                                     self, (self.width - stem_width) / 2,
                                     self.height - stem_depth,
                                     stem_width,
                                     stem_depth,
                                     trigger=False)
        elif self.type == 'grass bush':
            bush_base_width = int(self.width / 1.85)
            self.collider = Collider(collider_group,
                                     self, (self.width - bush_base_width) / 2,
                                     self.height,
                                     bush_base_width,
                                     0,
                                     trigger=False)
Ejemplo n.º 33
0
	def __init__(self):
		'''
		@brief Inicializa pygame y fija las características básicas de la pantalla
		'''
		pygame.init()
		self.screen = pygame.display.set_mode((globals.SCREEN_WIDTH, globals.SCREEN_HEIGHT))
		pygame.display.set_caption("Pong in pygame");
		self.closing = functions.load_image("media/closing.png")
		self.game = game.Game()
		self.salir = False
		self.n = 0
		self.clock = pygame.time.Clock()
Ejemplo n.º 34
0
	def __init__(self):
		'''
		@brief Inicializa los componentes basicos del juego
		(fondo, paletas y pelota).
		'''
		self.background = functions.load_image("media/background.png")
		
		#Cargamos los sprite que intervienen en el juego
		
		self.pong_human = Pong()
		self.ball = Ball()
		self.pong_ia = Pong(True)
		self.score_board = Score_Board()
Ejemplo n.º 35
0
    def __init__(self, pos, screen, type):

        pygame.sprite.Sprite.__init__(self)
        ###TYPE OF EXPLOSION
        t = {
            1 : ("ex001.png", (7, 5), 128),
            2 : ("ex002.png", (14, 0), 64)
            }

        self.image = functions.load_image(t[type][0], "alpha")
        self.screen = screen

        self.wh = t[type][2]
        self.maxXY = t[type][1]
        self.rect = pygame.Rect(0, 0, self.wh, self.wh)
        self.rect.center = pos
        self.x = 0
        self.y = 0
Ejemplo n.º 36
0
	def __init__(self, root):
		Character.__init__(self, root)

		self.sprite = load_image("sprites/characters/scoutreds/0.png")

		# The Scout hitbox: left = -6; right = 6; top = -10; bottom = 23
		self.rect = pygame.Rect(self.x - 6, self.y - 10, 12, 33)

		self.xImageOffset = 30
		self.yImageOffset = 40

		self.hp = 100
		self.maxHp = 100

		self.moveSpeed = 200
		
		self.weapon = ScatterGun(self.root, self.x, self.y)
		self.weapon.owner = self

		self.xRectOffset = self.x - self.rect.centerx
		self.yRectOffset = self.y - self.rect.centery
Ejemplo n.º 37
0
    pass

Config.screen_size = (1280,720)
Config.tile_size = 40
Config.wall_thickness = 8
Config.difficulty = EASY

Config.difficulty_multiplier = (10,10,20)
Config.colors = {'black': (0,0,0),
                'white': (255,255,255),
                'red': (255,0,0),
                'fire_color': (255,168,0),
                'wall_color': (73,33,33),
                'text_color': (200,200,200)}
Config.firewall_mode = Config.difficulty > EASY
Config.cell_image = functions.load_image('grass.png')

def main():

    pygame.init()
    screen = pygame.display.set_mode(Config.screen_size)
    pygame.display.set_caption('Maze')

    maze = Maze(Config)
    goal = Goal(maze, Config.tile_size)
    player = Player( (maze.start_cell.x,maze.start_cell.y), Config )


    #Layers are rendered in order of their index
    render_layers = [pygame.sprite.RenderPlain() for i in range(3)]