def actionGamepad(self, pad, time, menu, enemy):
        ## Ir derecha
        if self.keyMap["right"] == pad.get_hat(0) and (not self.cdAction):
            if self.orientacion == 0:
                if not sprite.collide_mask(self, enemy):
                    self.avanzar(time)
                else:
                    self.avanzar(0)
            else:
                self.defender(time)
        ## Ir Izquierda
        if self.keyMap["left"] == pad.get_hat(0) and (not self.cdAction):
            if self.orientacion == 4:
                if not sprite.collide_mask(self, enemy):
                    self.avanzar(time)
                else:
                    self.avanzar(0)
            else:
                self.defender(time)
        ## Saltar
        if self.keyMap["up"] == pad.get_hat(0) and (not self.cdAction
                                                    and not self.cdSalto):
            self.saltar()

        if self.keyMap["up"] == pad.get_hat(
                0) and self.keyMap["right"] == pad.get_hat(0):
            if self.orientacion == 0:
                self.avanzar(time)
            else:
                self.defender(time)

        if self.keyMap["up"] == pad.get_hat(
                0) and self.keyMap["left"] == pad.get_hat(0):
            if self.orientacion == 4:
                self.avanzar(time)
            else:
                self.defender(time)

        if menu == 0:
            ## AtaqueDebil
            if pad.get_button(self.keyMap["weakAttack"]) and not self.cdAction:
                if self.cdSalto:
                    a = 1
                    #self.ataqueSalto()
                elif not self.cdSalto and self.keyMap["down"] == pad.get_hat(
                        0):
                    self.ataqueBajo()
                else:
                    self.ataqueDebil(enemy)
            ## AtaqueFuerte
            if pad.get_button(
                    self.keyMap["strongAttack"]) and not self.cdAction:
                if self.cdSalto:
                    a = 1
                    #self.ataqueSalto()
                elif not self.cdSalto and self.keyMap["down"] == pad.get_hat(
                        0):
                    self.ataqueBajo()
                else:
                    self.ataqueFuerte(enemy)
    def actionKeyboard(self, keys, time, menu, enemy):
        ## Ir derecha
        if keys[self.keyMap["right"]] and (not self.cdAction):
            if self.orientacion == 0:
                if not sprite.collide_mask(self, enemy):
                    self.avanzar(time)
                else:
                    self.avanzar(0)
            else:
                self.defender(time)
        ## Ir Izquierda
        if keys[self.keyMap["left"]] and (not self.cdAction):
            if self.orientacion == 4:
                if not sprite.collide_mask(self, enemy):
                    self.avanzar(time)
                else:
                    self.avanzar(0)
            else:
                self.defender(time)
        ## Saltar
        if keys[self.keyMap["up"]] and (not self.cdAction
                                        and not self.cdSalto):
            self.saltar()

        if keys[self.keyMap["up"]] and keys[self.keyMap["right"]]:
            if self.orientacion == 0:
                self.avanzar(time)
            else:
                self.defender(time)

        if keys[self.keyMap["up"]] and keys[self.keyMap["left"]]:
            if self.orientacion == 4:
                self.avanzar(time)
            else:
                self.defender(time)

        if menu == 0:
            ## AtaqueDebil
            if keys[self.keyMap["weakAttack"]] and not self.cdAction:
                if self.cdSalto:
                    a = 1
                    #self.ataqueSalto()
                elif not self.cdSalto and keys[self.keyMap["down"]]:
                    self.ataqueBajo()
                else:
                    self.ataqueDebil(enemy)
            ## AtaqueFuerte
            if keys[self.keyMap["strongAttack"]] and not self.cdAction:
                if self.cdSalto:
                    a = 1
                    #self.ataqueSalto()
                elif not self.cdSalto and keys[self.keyMap["down"]]:
                    self.ataqueBajo()
                else:
                    self.ataqueFuerte(enemy)
Exemple #3
0
def _do_collide(sprite, group):
    """
    Use mask based collision detection
    """
    global LAST_COLLISON_HIT
    # Test if we still collide with the last hit
    if LAST_COLLISON_HIT and collide_mask(sprite, LAST_COLLISON_HIT):
        return True
    
    for sp in group:
        if collide_mask(sprite, sp):
            LAST_COLLISON_HIT = sp
            return True
    return False
Exemple #4
0
def _do_collide(sprite, group):
    """
    Use mask based collision detection
    """
    global LAST_COLLISON_HIT
    # Test if we still collide with the last hit
    if LAST_COLLISON_HIT and collide_mask(sprite, LAST_COLLISON_HIT):
        return True

    for sp in group:
        if collide_mask(sprite, sp):
            LAST_COLLISON_HIT = sp
            return True
    return False
Exemple #5
0
    def updete(self):  # Функция проверки столкновений
        global damage_take, boss, spawn_boss
        for el in tiles_group:
            if collide_rect(self, el) and el.type in ['wall', 'box']:
                self.rect.x = beforex
                self.rect.y = beforey
        for en in enemy_group:
            if collide_rect(self, en):
                if self.health > 0:
                    self.health -= 1

                break
        if spawn_boss:
            if collide_mask(self, boss):
                if self.health > 0 and damage_take:
                    self.health -= 5
                damage_take = False
            else:
                self.take_damage(boss, 60)

        for f in fruit_group:
            if collide_rect(self, f):
                if self.health < 100:
                    self.health += 5
                f.kill()
 def update(self, player) -> bool:
     """ Update the enemy's health point."""
     for bullet in player.bullets.copy():
         if collide_mask(self, bullet):
             self.hit_point -= player.power
             player.bullets.remove(bullet)
     return self.hit_point <= 0
Exemple #7
0
def detect_collisions(entity: GameEntity, collide_with: Iterable[str], any_one=False):
    """
    Detect collisions with the entities with the given names in collide_with.
    If any_one is true, returns only the first collision detected
    Returns a list of pairs of obstacle object and the collision points.
    """
    collide_names = frozenset(collide_with)
    # filter to entities to collide with specified by collide_with
    collide_entities = [
        e for e in entity.world.entities.values() if e.name in collide_names
    ]

    collisions = []
    for obstacle in collide_entities:
        collide_rel = sprite.collide_mask(entity, obstacle)
        if collide_rel is None:
            # no collision: skip
            continue

        # compute collision point offset by entity rect top left pt.
        collide_pt = Vector2(entity.rect.left, entity.rect.top) + Vector2(collide_rel)
        # record collision
        collisions.append((obstacle, collide_pt))
        # return first collision detected
        if any_one:
            return [collisions[0]]
    return collisions
Exemple #8
0
def _do_collide(sprite, group):
    """
    Use mask based collision detection
    """
    for sp in group:
        if collide_mask(sprite, sp):
            return True
    return False
Exemple #9
0
def colli_kill_both(l, r):
    # testfunction for collision callbacks
    if (sprite.collide_mask(l, r) != None):
        l.destroy()
        r.destroy()
        return True
    else:
        return False
Exemple #10
0
 def update(self, player: PlayerSprite, screen: Surface):
     # enemies need reference to other enemies and the player
     self._enemies.update(player, self._enemies, screen)
     hit = sprite.groupcollide(
         self._enemies, player._weapon._bullets, False, True, lambda sp1,
         sp2: not sp1._data.invulnerable and sprite.collide_mask(sp1, sp2))
     for enemy in hit:
         enemy.take_damage(player._damage)
Exemple #11
0
def _do_collide(sprite, group):
    """
    Use mask based collision detection
    """
    for sp in group:
        if collide_mask(sprite, sp):
            return True
    return False
Exemple #12
0
 def eating(self):
     for x in range(len(map.FOODS)):
         if collide_mask(self, map.FOODS[x]):
             map.FOODS.pop(x).kill()
             self.score += 100
             if len(map.FOODS) == 0:
                 self.is_win = True
             break
Exemple #13
0
 def get_energy(self):
     energizers = map.ENERGIZERS
     for x in range(len(energizers)):
         if collide_mask(self, energizers[x]):
             energizers.pop(x).kill()
             self.score += 100
             self.is_invincible = True
             break
Exemple #14
0
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface):
        if (self._data.health <= 0):
            self.kill()
            enemies.remove(self)
        try:

            for enemy in enemies:
                if sprite.collide_circle(self, enemy) and enemy != self:
                    distance = math.hypot((enemy.rect.x - self.rect.x),
                                          (enemy.rect.y - self.rect.y))

                    if (distance < 400):
                        target_direction = Vector2(
                            (self.rect.x - enemy.rect.x),
                            (self.rect.y - enemy.rect.y))
                        target_direction.scale_to_length(self._data.vel *
                                                         0.001)
                        self.rect.x += target_direction.x
                        self.rect.y += target_direction.y

                # Delete enemy when it comes into contact with player
            if sprite.collide_mask(
                    player, self) is not None and not player.invulnerable:
                player.take_damage(1)
                self.kill()
                enemies.remove(self)

                # Type 2 enemy specification
                # Auto fire towards player at a given rate

            n = time.get_ticks()

            if (self._charging) <= 1000:
                self._charging = n - self._start
                self._pstart = time.get_ticks()
                target_direction = Vector2(-self.rect.x + player.rect.x,
                                           -self.rect.y + player.rect.y)
                target_direction.scale_to_length(self._data.vel * 2)
                self.rect.x += target_direction.x
                self.rect.y += target_direction.y
            elif (self._charging > 1000):
                self._pausing = time.get_ticks() - self._pstart

            if (self._pausing) > 550:
                self._charging = 0
                self._pausing = 0
                self._start = time.get_ticks()

            screen_rect = screen.get_rect()

            self.rect.clamp_ip(screen_rect)

            self._data.pos = Vector2(self.rect.center)

            self._calc_rotation(player)

        except ValueError:
            return
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface):
        if self._data.health <= 0:
            self.dead = True
            self.kill()

        if sprite.collide_mask(player,
                               self) is not None and not player.invulnerable:
            player.take_damage(1.5)
            self.take_damage(50)

        state = self._data.state
        if state is BossState.MOVEDOWN:
            target_direction = Vector2(0, 1)
            self._data.attack_speed = 2000
            self._calc_rotation(player)
            self.image.set_alpha(255)
            self._data.vel = 6
            self._weapon.fire(player, self._data.attack_speed, 10, self.rect)
            self._weapon.update()
            self.invulnerable_start = time.get_ticks()

        elif state is BossState.MOVEUP:
            target_direction = Vector2(0, -1)
            self._data.attack_speed = 2000
            self._calc_rotation(player)
            self.image.set_alpha(255)
            self._data.vel = 6
            self._weapon.fire(player, self._data.attack_speed, 10, self.rect)
            self._weapon.update()
            self.invulnerable_start = time.get_ticks()

        elif state is BossState.TRANSITION:
            target_direction = Vector2(0, 0)
            self._weapon = self.temp_weapon
            self._weapon.spawn()
            self._data.invulnerable = True
            self.image.set_alpha(100)
            self._set_enraged_image(ResourceContainer())

        elif state is BossState.ENRAGED:
            self._data.invulnerable = False
            target_direction = player._data.pos - self._data.pos
            target_direction = self._avoid_player(player, target_direction)
            self._data.attack_speed = 900
            self._calc_rotation(player)
            self.image.set_alpha(255)
            self._data.vel = 7
            self._weapon.fire(player, self._data.attack_speed, 20, self.rect,
                              3)
            self._weapon.update()

        if target_direction.length() != 0:
            target_direction.scale_to_length(self._data.vel)
        screen_rect = screen.get_rect()
        self._data.pos += target_direction
        self.rect = self.image.get_rect(center=self._data.pos)
        self.rect.clamp_ip(screen_rect)
Exemple #16
0
 def _calculate_box(self, tag, node, horizontal):
     if math.floor(node[0].rect.width / 2.0) <= self._min_box_size and \
     math.floor(node[0].rect.height / 2.0) <= self._min_box_size:
         return
     
     node[2] = False
     created = False
     
     if (horizontal or math.floor(node[0].rect.height / 2.0) <= self._min_box_size) \
     and math.floor(node[0].rect.width / 2.0) >= self._min_box_size:
         horizontal = False
         nw1 = math.floor(node[0].rect.width / 2.0)
         nw2 = node[0].rect.width - nw1
         nh1 = nh2 = node[0].rect.height
         b1x = node[0].rect.x
         b2x = node[0].rect.x + nw1
         b1y = b2y = node[0].rect.y
         created = True               
     elif math.floor(node[0].rect.height / 2.0) >= self._min_box_size:
         horizontal = True
         nw1 = nw2 = node[0].rect.width
         nh1 = math.floor(node[0].rect.height / 2.0)
         nh2 = node[0].rect.height - nh1
         b1x = b2x = node[0].rect.x
         b1y = node[0].rect.y
         b2y = node[0].rect.y + nh1
         created = True
     
     if created:
         box1 = Box(b1x, b1y, nw1, nh1)
         box2 = Box(b2x, b2y, nw2, nh2)
         
         if collide_mask(box1, tag):  
             child_node = [box1, [], True]
             self._node_index.append(box1)
             node[1].append(child_node)
             self._calculate_box(tag, child_node, horizontal)
             
         if collide_mask(box2, tag):    
             child_node = [box2, [], True]
             self._node_index.append(box2)
             node[1].append(child_node)
             self._calculate_box(tag, child_node, horizontal)
    def ataqueFuerte(self, playerObjective):
        """El ataque fuerte se caracteriza por inflingir mayor daño pero requerir más tiempo de ejecución.
        Durante el ataque no se podrá efectuar ninguna acción.
        """

        self.state = "ataqueFuerte"
        self.current_hframe = 0
        self.vulnerable = True
        self.golpeando = True
        self.cdAction = 40
        if sprite.collide_mask(self, playerObjective):
            playerObjective.getHurt(12)
Exemple #18
0
    def update(self, player: PlayerSprite, enemies: Group,
               screen: Surface) -> None:

        if self._data.health <= 0:
            self.kill()

        # self._bullets.update()
        rand_pos_x = random.randint(player._data.pos.x + 50, WINDOW_WIDTH)
        rand_pos_y = random.randint(player._data.pos.y + 50, WINDOW_HEIGHT)

        # Delete enemy when it comes into contact with player
        if sprite.collide_mask(player,
                               self) is not None and not player.invulnerable:
            player.take_damage(1)
            self._data.health -= 30

        state = self._data.state
        if state is BossState.CHARGE:
            target_direction = player._data.pos - self._data.pos
            if target_direction != 0:
                target_direction.scale_to_length(self._data.vel * 3)
            self._data.vel = 5
            self._data.attack_speed = 150
            self._calc_rotation(player)
            self._data.pos += target_direction

        elif state is BossState.STATIONARY:
            target_direction = Vector2(0, 0)
            self._data.attack_speed = 15000
            self._calc_rotation(player)
            self._data.pos += target_direction

        elif state is BossState.TELEPORT:
            self._data.attack_speed = 0
            self._data.vel = 5
            self._calc_rotation(player)
            self._data.pos.x = rand_pos_x
            self._data.pos.y = rand_pos_y

        screen_rect = screen.get_rect()

        self.rect = self.image.get_rect(center=self._data.pos)
        self.rect.clamp_ip(screen_rect)

        if state is BossState.TELEPORT:
            self._weapon.fire(player, self._data.attack_speed, 15, self.rect,
                              4)
        else:
            self._weapon.fire(player, self._data.attack_speed, 15, self.rect,
                              2)

        self._weapon.update()
Exemple #19
0
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface):
        if (self._data.health <= 0):
            self.kill()
            enemies.remove(self)
        rand_pos_x = random.randint(40, WINDOW_WIDTH / 2)

        rand_pos_y = random.randint(40, WINDOW_HEIGHT / 2)

        for enemy in enemies:
            if sprite.collide_circle(self, enemy) and enemy != self:
                distance = math.hypot((enemy.rect.x - self.rect.x),
                                      (enemy.rect.y - self.rect.y))
                if (distance < 400):
                    target_direction = Vector2((self.rect.x - enemy.rect.x),
                                               (self.rect.y - enemy.rect.y))
                    target_direction.scale_to_length(self._data.vel * 0.001)
                    self.rect.x += target_direction.x
                    self.rect.y += target_direction.y
        # Delete enemy when it comes into contact with player
        if sprite.collide_mask(player,
                               self) is not None and not player.invulnerable:
            player.take_damage(1)
            self.kill()
            enemies.remove(self)

        n = time.get_ticks()
        if (n - self.weapon.prev_shot) > 2000 and not self._moved:
            self.rect.x = rand_pos_x
            self.rect.y = rand_pos_y
            self._moved = True

        elif (n - self.weapon.prev_shot) > 3000 and self._moved:

            if self._weapon.fire(player, self._data.attack_speed, 15,
                                 self.rect):
                self._moved = False

        else:
            self.rect.x = self.rect.x
            self.rect.y = self.rect.y

        screen_rect = screen.get_rect()

        self.rect.clamp_ip(screen_rect)

        self._data.pos = Vector2(self.rect.center)

        self._calc_rotation(player)
        self._weapon.update()
Exemple #20
0
    def update(self, dt: float, events: List[pygame.event.Event], pressed_keys: Sequence[bool]) -> None:
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    self.moving = True
                    self.move_start = pygame.time.get_ticks()
                    self.velocity[0] = clamp(self.velocity[0], Player.START_MOVE_SPEED, Player.MAX_MOVE_SPEED)
                if event.key == pygame.K_LEFT:
                    self.moving = True
                    self.move_start = pygame.time.get_ticks()
                    self.velocity[0] = clamp(self.velocity[0], -Player.MAX_MOVE_SPEED, -Player.START_MOVE_SPEED)
                if event.key == pygame.K_DOWN:
                    self.moving = True
                    self.move_start = pygame.time.get_ticks()
                    self.velocity[1] = clamp(self.velocity[1], Player.START_MOVE_SPEED, Player.MAX_MOVE_SPEED)
                if event.key == pygame.K_UP:
                    self.moving = True
                    self.move_start = pygame.time.get_ticks()
                    self.velocity[1] = clamp(self.velocity[1], -Player.MAX_MOVE_SPEED, -Player.START_MOVE_SPEED)

        if pressed_keys[pygame.K_RIGHT]:
            self.velocity[0] += Player.MOVE_ACCEL * dt
        if pressed_keys[pygame.K_LEFT]:
            self.velocity[0] -= Player.MOVE_ACCEL * dt
        if pressed_keys[pygame.K_DOWN]:
            self.velocity[1] += Player.MOVE_ACCEL * dt
        if pressed_keys[pygame.K_UP]:
            self.velocity[1] -= Player.MOVE_ACCEL * dt

        if not any(pressed_keys[key] for key in DIRECTION_KEYS):
            self.velocity /= (2 / dt)
            self.moving = False
            self.move_start = None

        self.velocity[0] = clamp(self.velocity[0], -Player.MAX_MOVE_SPEED, Player.MAX_MOVE_SPEED)
        self.velocity[1] = clamp(self.velocity[1], -Player.MAX_MOVE_SPEED, Player.MAX_MOVE_SPEED)

        self.move()

        if self.left < 0 or self.right > WINDOW_WIDTH:
            self.velocity[0] = -self.velocity[0]
        if self.top < 0 or self.bottom > WINDOW_HEIGHT:
            self.velocity[1] = -self.velocity[1]

        self.colliding = any(
            bool(collide_mask(self, enemy))
            for enemy in state.enemies
        )
Exemple #21
0
    def shoot(self):
        """If cannon can be fired, fires cannon.
        
        Otherwise creates bullet moving from player's center along player's direction
        as long as options.max_player_bullets won't be exeeded
        """
        
        if collide_mask(self.player, self.ion_field):
            return

        if self.cannon.start_transition(Cannon.FIRING):
            return        
        
        if len(self.player_bullets) < opt.max_player_bullets:
            new_bullet = Bullet(opt.bullet_filename, opt.bullet_speed, 
                                self.player.get_rect().center, self.player.get_direction())
            self.player_bullets.add(new_bullet)
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface) -> None:

        if self._data.health <= 0:
            self.kill()

        # Delete enemy when it comes into contact with player
        if sprite.collide_mask(player, self) is not None and not player.invulnerable:
            player.take_damage(3)
            self.take_damage(100)

        state = self._data.state
        if state is BossState.RETURN:
            target_direction = self._data._initial_spawn - self._data.pos
            self._data.invulnerable = True
            self._data.attack_speed = 10000
            self._spin()
            self.image.set_alpha(100)

        elif state is BossState.STATIONARY:
            target_direction = Vector2(0, 0)
            self._data.invulnerable = True
            self._data.attack_speed = 1500
            self._calc_rotation(player)
            self.image.set_alpha(100)
            self._data.vel = 5

        elif state is BossState.ROAM:
            target_direction = player._data.pos - self._data.pos
            target_direction = self._avoid_player(player, target_direction)
            self._data.attack_speed = 200
            self._data.invulnerable = False
            self._calc_rotation(player)
            self.image.set_alpha(255)
            self._data.vel = 5

        screen_rect = screen.get_rect()

        if target_direction.length() != 0:
            target_direction.scale_to_length(self._data.vel)

        self._data.pos += target_direction
        self.rect = self.image.get_rect(center=self._data.pos)
        self.rect.clamp_ip(screen_rect)

        self._weapon.fire(player, self._data.attack_speed, 15, self.rect)
        self._weapon.update()
    def ataqueDebil(self, playerObjective):
        """El ataque débil se caracteriza por ser más flojo pero más rápido. Esto en nuestro juego se traduce
        en que el daño será menor pero la cd del golpe también.
        Durante el ataque no se podrá efectuar ninguna acción.
        """

        self.state = "ataqueDebil"
        self.vulnerable = True
        self.golpeando = True
        if self.ataque != 2:
            self.ataque += 1
            self.cdAction = 10
            if sprite.collide_mask(self, playerObjective):
                playerObjective.getHurt(5)
        else:
            self.ataque = 0
            self.cdAction = 30
Exemple #24
0
    def shoot(self):
        """If cannon can be fired, fires cannon.
        
        Otherwise creates bullet moving from player's center along player's direction
        as long as options.max_player_bullets won't be exeeded
        """

        if collide_mask(self.player, self.ion_field):
            return

        if self.cannon.start_transition(Cannon.FIRING):
            return

        if len(self.player_bullets) < opt.max_player_bullets:
            new_bullet = Bullet(opt.bullet_filename, opt.bullet_speed,
                                self.player.get_rect().center,
                                self.player.get_direction())
            self.player_bullets.add(new_bullet)
Exemple #25
0
    def collide(self, group):
        if self.sprite.maskDirty:
            self.sprite.maskDirty = False
            AVRSprite.spriteLock.acquire()
            self.sprite.mask = mask.from_surface(self.transformedSurface)
            AVRSprite.spriteLock.release()

        sprites = sprite.spritecollide(self.sprite, group.group, False)
        results = []
        for s in sprites:
            if s == self.sprite:
                continue
            if s.maskDirty:
                s.maskDirty = False
                AVRSprite.spriteLock.acquire()
                s.mask = mask.from_surface(s.AVRSprite.transformedSurface)
                AVRSprite.spriteLock.release()
            if sprite.collide_mask(self.sprite, s) != None:
                results.append(s.AVRSprite.handle)
        return results
	def collide(self, group):
		if self.sprite.maskDirty:
			self.sprite.maskDirty = False
			AVRSprite.spriteLock.acquire()
			self.sprite.mask = mask.from_surface(self.transformedSurface)
			AVRSprite.spriteLock.release()
		
		sprites = sprite.spritecollide(self.sprite, group.group, False)
		results = []
		for s in sprites:
			if s == self.sprite:
				continue
			if s.maskDirty:
				s.maskDirty = False
				AVRSprite.spriteLock.acquire()
				s.mask = mask.from_surface(s.AVRSprite.transformedSurface)
				AVRSprite.spriteLock.release()
			if sprite.collide_mask(self.sprite, s) != None:
				results.append(s.AVRSprite.handle)
		return results
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface):
        if(self._data.health <= 0):
            self.kill()
            enemies.remove(self)

        for enemy in enemies:
            # Check for nearby enemies to avoid collision
            if sprite.collide_circle(self, enemy) and enemy != self:
                distance = math.hypot(
                    (enemy.rect.x - self.rect.x), (enemy.rect.y - self.rect.y))

                if (distance < 400):
                    target_direction = Vector2(
                        (self.rect.x - enemy.rect.x), (self.rect.y - enemy.rect.y))
                    target_direction.scale_to_length(
                        self._data.vel * 0.001)
                    self.rect.x += target_direction.x
                    self.rect.y += target_direction.y

        target_direction = Vector2(
            - self.rect.x + player.rect.x + random.randrange(0, 30),
            - self.rect.y + player.rect.y + random.randrange(0, 30))
        target_direction.scale_to_length(self._data.vel * 0.7)

        # Delete enemy when it comes into contact with player
        if sprite.collide_mask(player, self) is not None and not player.invulnerable:
            player.take_damage(1)
            self.kill()
            enemies.remove(self)

        self.rect.x += target_direction.x
        self.rect.y += target_direction.y

        screen_rect = screen.get_rect()

        self.rect.clamp_ip(screen_rect)

        self._data.pos = Vector2(self.rect.center)

        self._calc_rotation(player)
Exemple #28
0
 def check_collision_obstacle(self, dog, obstacle):
     if collide_mask(dog, obstacle):
         if self.x < obstacle.x <= self.x + self.width and self.y == 430:
             self.keep_scrolling = False
             self.x = (obstacle.rect.x - self.width)
             self.rect.x = (obstacle.rect.x - self.width)
         elif obstacle.x < self.x < obstacle.x + obstacle.width and self.y == 430:
             self.keep_scrolling = False
             self.x = obstacle.x + obstacle.width
             self.rect.x = obstacle.x + obstacle.width
         elif self.y + self.height <= obstacle.y + (obstacle.height / 2):
             self.keep_scrolling = True
             self.y = (obstacle.y - self.height)
             self.rect.y = (obstacle.y - self.height)
         elif self.x + 100 < obstacle.x and not self.is_jump:
             self.keep_scrolling = True
             self.y = 430
             self.rect.y = 430
         elif self.x > obstacle.x + obstacle.width and not self.is_jump:
             self.keep_scrolling = True
             self.y = 430
             self.rect.y = 430
    def start(self):
        self.clock = pygame.time.Clock()
        if self.server:
            _thread.start_new_thread(self.start_server, ())
        self.buffer = []
        self.flag = 0
        self.flagrem = 0
        no = 0
        temp = True
        self.scoreA = 0
        self.scoreB = 0
        self.reward = 0
        effect = pygame.mixer.Sound('Sounds/button-16-1.wav')
        while self.carryOn:
            if self.pause:
                continue
            '''
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.carryOn = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_x:
                        self.close()
            '''

            inputs = False
            '''
            keys = pygame.key.get_pressed()
            if keys[pygame.K_w]:
                self.paddleA.moveUp(5)
                inputs=True
            if keys[pygame.K_s]:
                self.paddleA.moveDown(5)
                inputs=True
            if keys[pygame.K_UP]:
                self.paddleA.moveUp(5)
                inputs=True
            if keys[pygame.K_DOWN]:
                self.paddleA.moveDown(5)
                inputs=True
            '''

            ## It can be changed to if after training but not while training
            while self.server and self.conti == 0 and not inputs:  ## This while is to be converted to if as the latency is low but for debugging its been set to wait till a input is got
                while len(self.buffer) != 0:
                    if self.pause:
                        break
                    if self.debug: print("Search started for input")
                    if (
                            time.time() - self.buffer[0][1]
                    ) <= 1.5:  ## For being sure that it matches up with frame rate but may have to be reduced as there might be a lag in the server requests
                        if self.buffer[0][0] == '1':
                            self.paddleA.moveUp(5)
                            inputs = True
                        else:
                            self.paddleA.moveDown(5)
                            inputs = True
                        self.buffer = []
                    else:
                        del self.buffer[0]
            if self.conti == 1:
                self.paddleA.AI(self.ball.posi())

            self.paddleB.AI(self.ball.posi())
            self.new_feed = False
            self.all_sprites_list.update()

            if self.ball.rect.x >= 690 and self.flag == 0:
                effect.play()
                self.scoreA += 1
                self.reward += 1
                self.ball.velocity[0] = -abs(self.ball.velocity[0])
                if abs(self.ball.velocity[0]) < 1:
                    self.ball.velocity[0] = randint(-5, -1)
                self.flag = 1

            if self.ball.rect.x <= 0 and self.flag == 0:
                effect.play()
                self.scoreB += 1
                self.reward -= 1
                self.ball.velocity[0] = abs(self.ball.velocity[0])
                if abs(self.ball.velocity[0]) < 1:
                    self.ball.velocity[0] = randint(1, 5)
                self.flag = 1
            if self.ball.rect.y >= 489 and self.flagrem == 0:
                effect.play()
                self.ball.velocity[1] = -1 * abs(self.ball.velocity[1])
                self.flagrem = 1
            if self.ball.rect.y <= 1 and self.flagrem == 0:
                effect.play()
                self.ball.velocity[1] = abs(self.ball.velocity[1])
                self.flagrem = 1
            if ((collide_mask(self.ball, self.paddleA)
                 or collide_mask(self.ball, self.paddleB)) and self.flag == 0):
                effect.play()
                self.ball.bounce()
                self.flag = 1
                if self.debug: print(no, "ITS happeneing now")
                no += 1
            if self.ball.rect.x > 11 and self.ball.rect.x < 679:
                self.flag = 0

            if self.ball.rect.y > 10 and self.ball.rect.y < 480:
                self.flagrem = 0

            self.screen.fill(self.BLACK)
            self.all_sprites_list.draw(self.screen)
            if self.ball.rect.x < 10 or self.ball.rect.x > 680 or self.ball.rect.y < 10 or self.ball.rect.y > 490:
                if self.debug: print(self.ball.rect.x, self.ball.rect.y)

            ###Feed for the net###
            self.feedinp = np.array(pygame.PixelArray(self.screen),
                                    dtype=np.uint8)
            self.feedinp = self.feedinp.T
            self.feed = self.feedinp.reshape([500, 700, 1])
            ##this can be used for screen capturing
            self.new_feed = True
            if self.render:
                cv2.imshow('hello', cv2.resize(self.feed, (70, 50)))
                cv2.waitKey(1)
            ######################

            pygame.draw.line(self.screen, self.WHITE, [349, 0], [349, 500], 5)
            font = pygame.font.Font(None, 74)
            text = font.render(str(self.scoreA), 1, self.WHITE)
            self.screen.blit(text, (250, 10))
            text = font.render(str(self.scoreB), 1, self.WHITE)
            self.screen.blit(text, (420, 10))

            #pygame.display.flip()

            if self.debug:
                if not self.render:
                    cv2.imshow("Hello", np.array(self.feed, dtype=np.uint8))
                    cv2.waitKey(1)
                    if temp:
                        print(self.feed.shape)
                        print(np.array(self.feed, dtype=np.uint8).sum())
                        temp = False

            if self.sync:
                self.clock.tick(
                    60
                )  ## Varing this gives acceptable amount of performance to the environments
Exemple #30
0
    def collisions(self):
        """Handles collisions
        """

        player = self.player
        enemy = self.enemy
        shield = self.shield
        hbullet = self.hbullet
        cannon = self.cannon
        ion_field = self.ion_field
        player_bullets = self.player_bullets
        
        #player with homing bullet
        if collide_mask(player, hbullet) and not collide_mask(player, ion_field):
            self.kill_player()
        
        #player with enemy base
        if collide_mask(player, enemy):
            #if base in moving phase, give player energy
            if enemy.get_state_number() == EnemyBase.MOVING:
                self.manager.give_energy(opt.energy_from_enemy)
            #if base in spinning or shooting phase, kill player
            elif enemy.get_state_number() == EnemyBase.SPINNING:
                self.kill_player()
            elif enemy.get_state_number() == EnemyBase.SHOOTING:
                self.kill_player()
                
        #player with cell
        #-hitting a cell will bounce the player a bit to the left
        #-if the player hit the cell twice in a short enough span,
        # the cell is eaten and the player gets energy
        #-in case of multiple collisions, deal with cell closest to player's center
        #
        #TODO: This still isn't quite right.
        #Should be able to eat top/bottom rows with diagonal movement.
        #(vertical movement should still move player all the way left)
        pc_collides = spritecollide(player, shield, False, collide_mask)
        center_cell = self.find_centermost_cell(pc_collides)
        if center_cell is not None:
            player.rect.right = center_cell.rect.left - opt.cell_bounceback
            
            if not center_cell.marked:
                center_cell.mark()
            elif shield.can_eat():
                center_cell.kill()
                self.manager.give_energy(opt.energy_from_cell)
                self.manager.add_score(opt.score_cell_eat)
                shield.start_delay(opt.frames_to_eat_cell)
            
        #player with cannon
        if collide_mask(player, cannon):
            #if in deactivated phase, try spending required energy to activate
            if (cannon.get_state_number() == Cannon.DEACTIVATED and 
                self.manager.spend_energy(opt.cannon_energy_cost)):
                cannon.start_standby()
            #if in firing phase, kill player
            if cannon.get_state_number() == Cannon.FIRING:
                self.kill_player()
            #if in returning phase, give energy and deactivate cannon
            if cannon.get_state_number() == Cannon.RETURNING:
                cannon.start_transition(Cannon.DEACTIVATED)
                self.manager.give_energy(opt.energy_from_cannon)
                
        #cannon with cell
        #kill one cell and reverse cannon direction
        #assuming this is only possible if cannon in firing state
        if cannon.get_state_number() == Cannon.FIRING:
            cannon_collides = spritecollide(cannon, shield, False, collide_mask)
            if len(cannon_collides) > 0:
                cannon_collides[0].kill()
                self.manager.add_score(opt.score_cell_shoot)
                cannon.start_transition(Cannon.RETURNING)
            
        #cannon with enemy base -- only if cannon in firing state
        #give points corresponding to enemy state and end level
        #if enemy base is in shooting state, player also gets a life
        if cannon.get_state_number() == Cannon.FIRING and collide_mask(cannon, enemy):
            if enemy.get_state_number() == EnemyBase.MOVING:
                self.manager.add_score(opt.score_mover_destroy)
            elif enemy.get_state_number() == EnemyBase.SPINNING:
                self.manager.add_score(opt.score_spinner_destroy)
            elif enemy.get_state_number() == EnemyBase.SHOOTING:
                self.manager.add_score(opt.score_shooter_destroy)
                self.manager.give_life()
            self.end_level()
        
        #player's bullet with cell
        #kill player bullet but remove cells in a cross pattern
        #if somehow one bullet hits multiple cells one is arbitrarily selected
        bc_collides = groupcollide(player_bullets, shield, True, False, collide_mask)
        for current_bullet in bc_collides.keys():
            self.manager.add_score(opt.score_cell_shoot)
            shield.remove_cross(bc_collides[current_bullet][0])
Exemple #31
0
            # Start the work
            if event.unicode == " ":
                started = not started
            if event.unicode in ["1", "2", "3", "4", "5"]:
                fps = int(event.unicode) * 60

        if event.type == pygame.MOUSEBUTTONDOWN:
            # Draw walls
            if event.button == 1 and not started:
                mouse_pos = pygame.mouse.get_pos()
                new_wall = Wall(
                    mouse_pos[0] - (mouse_pos[0] % SPRITE_WIDTH),
                    mouse_pos[1] - (mouse_pos[1] % SPRITE_HEIGHT)
                )

                if sprite.collide_mask(new_wall, irobot) is None:
                    new_wall.render(background)
                    walls.add(new_wall)
                else:
                    print("Error while adding new wall")

            # Move irobot
            if event.button == 3 and not started:
                    mouse_pos = pygame.mouse.get_pos()
                    posx = mouse_pos[0] - irobot.rect[0] - irobot.rect[2] / 2
                    posy = mouse_pos[1] - irobot.rect[1] - irobot.rect[3] / 2
                    old_rect = irobot.rect
                    irobot.rect = irobot.rect.move(posx, posy)
                    if sprite.spritecollideany(irobot, walls,
                                               sprite.collide_mask):
                        irobot.rect = old_rect
Exemple #32
0
def collide_rect_mask(left, right):
    return 1 if collide_rect(left, right) and collide_mask(left, right) else 0
Exemple #33
0
    def run(self):
        self.setup()
        self.running = introGame(self.screen, self.data,
                                 self.database.getProfile())

        add_rumput = True
        add_keris = True
        add_bambu = True
        while self.running:
            events = self.core.events()
            if events["type"]["quit"]:
                self.running = False
                break
            elif events["type"]["keydown"]:
                if events["keys"]["space"] or events["keys"]["up"]:
                    self.player.jump_up()

            #=== Move position ===#
            boundary_values = [0, self.grass_position[-1]]
            self.player.update(
                boundary_values,
                float(
                    self.clock.tick(self.config.parse["settings"]["frame"]) /
                    1000))
            self.tanah_position[0] = -(
                (-self.tanah_position[0] + self.speed) % self.tanah_diff)
            self.grass_position[0] = -(
                (-self.grass_position[0] + self.speed) % self.grass_diff)

            #=== Move rumput object ===#
            for rumput in self.rumputGroup:
                rumput.rect.left -= self.config.parse["settings"]["speed"]
                if rumput.rect.left < 4 and rumput.rect.left > 0 and add_rumput:
                    if len(self.rumputGroup) > 50: continue
                    else:
                        image = self.data["textures"][
                            "rumput" + str(random.randint(1, 6))]
                        self.rumputGroup.add(
                            Rumput(image, [
                                random.randint(self.config.getRect.width,
                                               3000),
                                self.config.getRect.height * 0.80
                            ]))
                elif rumput.rect.right < 0:
                    if len(self.rumputGroup) > 50:
                        self.rumputGroup.remove(rumput)
                    else:
                        self.rumputGroup.remove(rumput)
                        image = self.data["textures"][
                            "rumput" + str(random.randint(1, 6))]
                        self.rumputGroup.add(
                            Rumput(image, [
                                random.randint(self.config.getRect.width,
                                               3000),
                                self.config.getRect.height * 0.80
                            ]))

            #=== Move keris object ===#
            for keris in self.kerisGroup:
                keris.rect.left -= self.config.parse["settings"]["speed"]
                #=== Check object to object ===#
                if collide_mask(self.player, keris) and not keris.is_used:
                    keris.is_used = True
                    self.kerisGroup.remove(keris)
                    add_keris = True
                    self.health.add_value()
                    if self.score.add_score():
                        self.running = False
                        break

                if keris.rect.left < 4 and keris.rect.left > 0 and add_keris:
                    if self.health.revalue():
                        self.running = False
                        break
                    keris = Keris(self.data["anim"]["keris"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    keris.rect.bottom += random.randint(
                        10, self.config.getRect.height - 130)
                    self.kerisGroup.add(keris)
                    add_keris = False

                elif add_keris and keris.is_used:
                    if random.randint(0, 1) == 1:
                        for _ in range(random.randint(1, 2)):
                            keris = Keris(self.data["anim"]["keris"], [
                                random.randint(self.config.getRect.width,
                                               self.config.getRect.width * 2),
                                10
                            ])
                            keris.rect.bottom += random.randint(
                                10, self.config.getRect.height - 130)
                            self.kerisGroup.add(keris)
                    else:
                        keris = Keris(self.data["anim"]["keris"], [
                            random.randint(self.config.getRect.width,
                                           self.config.getRect.width * 2), 10
                        ])
                        keris.rect.bottom += random.randint(
                            10, self.config.getRect.height - 130)
                        self.kerisGroup.add(keris)
                    add_keris = False
                elif keris.rect.right < 0:
                    self.health.revalue()
                    self.kerisGroup.remove(keris)
                    keris = Keris(self.data["anim"]["keris"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    keris.rect.bottom += random.randint(
                        10, self.config.getRect.height - 130)
                    self.kerisGroup.add(keris)

            for bambuEnemy in self.bambuGroup:
                bambuEnemy.rect.left -= self.config.parse["settings"]["speed"]
                if collide_mask(self.player,
                                bambuEnemy) and not bambuEnemy.is_used:
                    bambuEnemy.is_used = True
                    add_bambu = True
                    self.health.revalue()
                    self.score.rescore()

                if bambuEnemy.rect.left < 4 and bambuEnemy.rect.left > 0 and add_bambu:
                    bambu = Bambu(self.data["other"]["bambu"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    bambu.rect.bottom += self.config.getRect.height * 0.78
                    self.bambuGroup.add(bambu)
                    add_bambu = False

                elif bambuEnemy.rect.right < 0:
                    self.bambuGroup.remove(bambuEnemy)
                    bambu = Bambu(self.data["other"]["bambu"], [
                        random.randint(self.config.getRect.width,
                                       self.config.getRect.width * 2), 10
                    ])
                    bambu.rect.bottom += self.config.getRect.height * 0.78
                    self.bambuGroup.add(bambu)

            #=== Screen display ===#
            self.screen.blit(self.BACKGROUND, (0, 0))
            self.rumputGroup.draw(self.screen)
            self.screen.blit(self.tanah, self.tanah_position)
            self.screen.blit(self.grass, self.grass_position)
            self.bambuGroup.draw(self.screen)
            self.health.draw(self.screen)
            self.kerisGroup.draw(self.screen)
            self.player.draw(self.screen)
            self.score.draw(self.screen)

            #=== Check ===#
            if self.score.check():
                self.running = False
            elif self.health.check():
                self.running = False
            self.clock.tick(self.config.parse["settings"]["frame"])
            update()
        self.logs.warning("Menyimpan score")
        self.database.updateScore(self.score.getScore)
        self.logs.warning("Menutup game...")
        pygame.quit()
    def update(self, player: PlayerSprite, enemies: Group, screen: Surface):

        if(self._data.health <= 0):
            self.kill()
            enemies.remove(self)

        # Check for nearby enemies, only move in certain case
        for enemy in enemies:
            if sprite.collide_circle(self, enemy) and enemy != self:
                distance = math.hypot(
                    (enemy.rect.x - self.rect.x), (enemy.rect.y - self.rect.y))

                if (distance < 400):
                    target_direction = Vector2(
                        (self.rect.x - enemy.rect.x), (self.rect.y - enemy.rect.y))
                    target_direction.scale_to_length(
                        self._data.vel * 0.001)
                    self.rect.x += target_direction.x
                    self.rect.y += target_direction.y

        # Type 2 enemy backs away from player
        distance = math.hypot(
            (player.rect.x - self.rect.x), (player.rect.y - self.rect.y))
        if (distance > 550):
            self._data._stopMoving = False

        # Enemy moves toward player given that they are either type 1 or sufficiently far enough from player
        if not self._data._stopMoving:
            target_direction = Vector2(
                - self.rect.x + player.rect.x + random.randrange(0, 30), - self.rect.y + player.rect.y + random.randrange(0, 30))
            target_direction.scale_to_length(self._data.vel * 0.9)

        # Delete enemy when it comes into contact with player
        if sprite.collide_mask(player, self) is not None and not player.invulnerable:
            player.take_damage(1)
            self.kill()
            enemies.remove(self)

        # Stop moving towards player at a certain distance
        if sprite.collide_circle(self, player):
            self._data._stopMoving = True
            distance = math.hypot(
                (player.rect.x-self.rect.x), (player.rect.y - self.rect.y))
            # Move back if in danger zone
            if(distance < 550):
                target_direction = Vector2(
                    (self.rect.x - player.rect.x), (self.rect.y - player.rect.y))
                target_direction.scale_to_length(self._data.vel * 1.01)
                self.rect.x += target_direction.x
                self.rect.y += target_direction.y

        # All other cases are given movement data here
        if self._data._stopMoving is False:
            self.rect.x += target_direction.x
            self.rect.y += target_direction.y

        screen_rect = screen.get_rect()

        self.rect.clamp_ip(screen_rect)

        self._data.pos = Vector2(self.rect.center)

        self._calc_rotation(player)

        self._weapon.fire(player, self._data.attack_speed,
                          15, self.rect, 550)
        self._weapon.update(player, screen)
Exemple #35
0
    def check_collisions(self):
        for bullet in self.bullets.sprites():
            if bullet.pos[0] > SCREEN_SIZE[0] or bullet.pos[1] > SCREEN_SIZE[
                    1] or (bullet.pos < 0).any():
                bullet.kill()
            # С каким из астероидов имеется столкновение?
            hits = [ast for ast in self.asteroids if collide_mask(bullet, ast)]
            if hits:
                for asteroid in hits:
                    fragments = asteroid.explode(
                    )  # Разбиваем астероид на осколки
                    self.score += 1
                    asteroid.kill()
                    self.asteroids.add(fragments)
                if bullet.type == "explosive":
                    self.explosions.add(bullet.explode())
                bullet.kill()

            hits = spritecollide(bullet, self.enemies, False)
            if hits:
                for enemy in hits:
                    if not enemy.damage():  # У врага осталось 0 HP
                        self.score += enemy.score_gain
                        enemy.kill()
                if bullet.type == "explosive":
                    self.explosions.add(bullet.explode())
                bullet.kill()

        for en_bullet in self.enemy_bullets.sprites():
            if en_bullet.pos[0] > SCREEN_SIZE[0] or en_bullet.pos[
                    1] > SCREEN_SIZE[1] or (en_bullet.pos < 0).any():
                en_bullet.kill()

            hits = [
                ast for ast in self.asteroids if collide_mask(en_bullet, ast)
            ]
            if hits:
                for asteroid in hits:
                    fragments = asteroid.explode(
                    )  # Разбиваем астероид на осколки
                    asteroid.kill()
                    self.asteroids.add(*fragments)
                en_bullet.kill()

            if collide_mask(en_bullet, self.starship):
                if self.boosters_timeouts[
                        "Shield"] == 0 and self.starship.damage_animation_timeout == 0:
                    return self.starship.damage()

        for explosion in self.explosions.sprites():
            hits = spritecollide(explosion, self.asteroids, dokill=True)
            self.score += len(hits)
            spritecollide(explosion, self.enemy_bullets, dokill=True)
            hits = spritecollide(explosion, self.enemies, dokill=False)
            if hits:
                for enemy in hits:
                    if not enemy.damage(1 / 16):  # У врага осталось 0 HP
                        self.score += enemy.score_gain
                        enemy.kill()
            spritecollide(explosion, self.boosters, dokill=True)

        # Столкновение астероидов и игрока
        # Индекс астероида, столкнувшегося с игроком
        hits = [
            ast for ast in self.asteroids if collide_mask(self.starship, ast)
        ]
        if hits:  # Если столкновение было...
            # Если бустер "Щит" активен
            if self.boosters_timeouts["Shield"] > 0:
                [ast.kill() for ast in hits]
            elif self.starship.damage_animation_timeout != 0:
                pass
            else:
                return self.starship.damage()
        return False
Exemple #36
0
def collide_rect_mask(left, right):
    return 1 if collide_rect(left, right) and collide_mask(left, right) else 0
Exemple #37
0
 def check_collision_finish(self, dog, finish):
     if collide_mask(dog, finish):
         print("IS COLLIDING")
 def collide2():
     collide_mask(tag_cool, tag_aero)