Esempio n. 1
0
def authenticate(credentials):
    """ input: credentials
        output: user or None
    """
    # look up identity service
    identity_service = _get_identity_service(credentials)

    # try to authenticate with the identity service
    auth_result = identity_service.authenticate(credentials)
    if not auth_result:
        return None

    # drop password as it is not needed any more
    credentials.password = auth_result.credentials = auth_result.password = None

    # check if corresponding internal user exists
    iuser = internalusers.check_user(credentials)
    if iuser:
        # if it exists, just give it
        return iuser

    # make internal user corresponding to external one
    group = model.Groups(auth_result.group_name).list()[0]
    user = internalusers.add_user(auth_result,
                                  auth_result.profile,
                                  group=group)

    users = model.Users(username=auth_result.username)
    return users.list()[0]
Esempio n. 2
0
    def __init__(self) -> None:
        super().__init__()

        pg.mixer.pre_init(44100, -16, 4, 2048)

        pg.init()

        self._dim_screen = pg.Surface(self.screen.get_size()).convert_alpha()
        self._dim_screen.fill((0, 0, 0, 180))

        # needs to happen before we make any controllers
        controllers.base.initialize_controller(self._quit)

        # needs to happen after the video mode has been set
        images.initialize_images()

        # needs to happen after a valid mixer is available
        sounds.initialize_sounds()

        self._clock = pg.time.Clock()

        timer = model.Timer(self._clock)
        groups = model.Groups()
        model.initialize(groups, timer)

        self._paused = False
Esempio n. 3
0
    def test_groups_immutable_container(self) -> None:
        groups = model.Groups()

        self.assertIsInstance(groups.walls, Group)
        self.assertIsInstance(groups.all_sprites, LayeredUpdates)

        with self.assertRaises(AttributeError):
            groups.walls = Group()
class InitsTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def test_pass(self) -> None:
        pass
Esempio n. 5
0
def initialize_everything(groups: model.Groups = None,
                          timer: model.Timer = None) -> None:
    if groups is None:
        groups = model.Groups()
    if timer is None:
        timer = MockTimer()

    initialize_pygame()
    model.initialize(groups, timer)
    initialize_controller(None)
    ScreenAccess.initialize()
Esempio n. 6
0
class ModTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()
    ability_data = None

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def test_item_object_bob_motion(self) -> None:
        pistol_item = build_map_object('pistol', Vector2(0, 0))
        time_for_sweep = int(pistol_item._bob_period * 10)

        center = pistol_item.rect.center
        original_center_y = center[1]
        original_center_x = center[0]
        min_center_y = center[1]
        max_center_y = center[1]

        for _ in range(time_for_sweep):
            min_center_y = min(min_center_y, center[1])
            max_center_y = max(max_center_y, center[1])
            self.assertEqual(center[1], original_center_x)

        self.assertEqual(original_center_y, min_center_y)
        self.assertEqual(-original_center_y, max_center_y)

    def test_mod_str_output(self) -> None:
        description = 'banana hammock'
        mod_data = ModData('legs', 'pistol', 'no_image', 'no_image',
                           description)
        hammock_mod = Mod(mod_data)

        self.assertEqual(hammock_mod.description, description)
        self.assertEqual(str(hammock_mod), description)

        mod_data = ModData('legs',
                           'pistol',
                           'no_image',
                           'no_image',
                           description,
                           buffs=[Buffs.DAMAGE],
                           proficiencies=[Proficiencies.STEALTH])
        nice_mod = Mod(mod_data)

        self.assertIn('damage', str(nice_mod))
        self.assertIn('stealth', str(nice_mod))
Esempio n. 7
0
def CreateGroup(name, owner, pictureUrl, players, timeCreated):
    logging.info("Creating group")

    groupID = GenerateUID()

    group = model.Groups(group_id=groupID, key_name=groupID)
    group.group_name = name
    group.group_owner = owner
    group.group_picture_url = pictureUrl
    group.players = players
    group.last_updated = timeCreated
    group.group_created_at = timeCreated
    group.group_hidden = False

    group.put()

    return groupID
Esempio n. 8
0
class WeaponsTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def test_fire_projectile_distance_independent_of_count(self) -> None:
        player = make_player()
        num_updates = 100

        data_dict = load_ability_data_kwargs('shotgun')
        data_dict['projectile_count'] = 1
        ability_data = AbilityData(**data_dict)

        fire_little_bullet = GenericAbility(ability_data)

        fire_little_bullet.use(player)

        self.assertEqual(len(self.groups.bullets), 1)
        bullet = self.groups.bullets.sprites()[0]
        first_pos = Vector2(bullet.pos.x, bullet.pos.y)

        for _ in range(num_updates):
            self.groups.bullets.update()

        one_disp = (bullet.pos - first_pos).length()

        many = 10
        ability_data = ability_data._replace(projectile_count=many)
        fire_little_bullet = GenericAbility(ability_data)

        self.groups.bullets.empty()
        fire_little_bullet.use(player)
        self.assertEqual(len(self.groups.bullets), many)

        bullet = self.groups.bullets.sprites()[0]
        first_pos = Vector2(bullet.pos.x, bullet.pos.y)

        for _ in range(num_updates):
            self.groups.bullets.update()

        many_disp = (bullet.pos - first_pos).length()

        self.assertLess(0.5 * many_disp, one_disp)
Esempio n. 9
0
class LaserTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()
    laser_ability = None

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def test_player_fire_laser_available_after_cooldown_time(self) -> None:
        player = make_player()
        laser_gun = make_item('laser')
        player.inventory.attempt_pickup(laser_gun)
        fire_ability = laser_gun.mod.ability

        self.assertFalse(fire_ability.can_use(player))
        # Initially player can't fire the gun because the cooldown time has
        # not been waited.
        while fire_ability.cooldown_fraction < 1:
            self.timer.current_time += 1
        self.assertFalse(fire_ability.can_use(player))

        self.timer.current_time += 1
        self.assertTrue(fire_ability.can_use(player))

    def test_player_fires_laser_makes_projectile(self) -> None:
        laser_gun, player = self._player_with_ready_laser()

        fire_laser = player.ability_caller(laser_gun.mod.loc)

        self.assertEqual(len(self.groups.bullets), 0)
        fire_laser()
        self.assertEqual(len(self.groups.bullets), 1)

    def test_player_fires_laser_expends_energy(self) -> None:
        laser_gun, player = self._player_with_ready_laser()

        starting_energy = player.energy_source.energy_available

        fire_laser = player.ability_caller(laser_gun.mod.loc)
        fire_laser()
        final_energy = player.energy_source.energy_available

        expected = load_ability_data_kwargs('laser')['energy_required']
        actual = starting_energy - final_energy
        self.assertEqual(actual, expected)

    def test_player_cannot_fire_laser_with_too_low_energy(self) -> None:
        laser_gun, player = self._player_with_ready_laser()

        self.assertTrue(laser_gun.mod.ability.can_use(player))

        all_energy = player.energy_source.energy_available
        player.energy_source.expend_energy(all_energy)

        self.assertFalse(laser_gun.mod.ability.can_use(player))

    def _player_with_ready_laser(self) -> Tuple[items.ItemObject, Player]:
        player = make_player()
        laser_gun = make_item('laser')
        player.inventory.attempt_pickup(laser_gun)
        fire_ability = laser_gun.mod.ability
        while fire_ability.cooldown_fraction < 1:
            self.timer.current_time += 10
        self.timer.current_time += 1
        return laser_gun, player
Esempio n. 10
0
def setUpModule() -> None:
    initialize_pygame()
    ConstructorTest.groups = model.Groups()
    model.initialize(ConstructorTest.groups, MockTimer())
Esempio n. 11
0
class ProjectilesTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def test_projectile_moves_in_direction(self) -> None:
        direction = Vector2(1, 0)
        speed = 100
        basic_data = ProjectileData(True, 10, speed, 100, images.LITTLE_BULLET)

        bullet = SimpleProjectile(Vector2(0, 0), direction, basic_data)

        steps = 100
        for _ in range(steps):
            bullet.update()
        time_elapsed = self.timer.dt * steps

        dx = bullet.pos.x
        dy = bullet.pos.y

        expected_dx = time_elapsed * speed * direction.x
        self.assertLess(abs(expected_dx - dx), time_elapsed * speed / 10)

        expected_dy = time_elapsed * speed * direction.y
        self.assertLess(abs(expected_dy - dy), time_elapsed * speed / 10)

    def test_projectile_dies_after_lifetime_exceeded(self) -> None:
        direction = Vector2(1, 0)
        basic_data = ProjectileData(False, 10, 100, 100, images.LITTLE_BULLET)

        bullet = SimpleProjectile(Vector2(0, 0), direction, basic_data)

        self.assertIn(bullet, self.groups.bullets)

        self.timer.current_time += bullet.max_lifetime + 1

        bullet.update()
        self.assertNotIn(bullet, self.groups.bullets)

    def test_projectile_with_drops_on_kill_instantiates_object(self) -> None:
        lifetime = 10
        dropper_data = ProjectileData(False,
                                      10,
                                      10,
                                      lifetime,
                                      images.LITTLE_BULLET,
                                      drops_on_kill='rock')
        rock_dropper = FancyProjectile(Vector2(0, 0), Vector2(1, 0),
                                       dropper_data)

        self.assertEqual(len(self.groups.items), 0)
        self.timer.current_time += lifetime + 1
        rock_dropper.update()
        self.assertEqual(len(self.groups.items), 1)

    def test_fancy_projectile_rotating_image_changes_width(self) -> None:

        data = ProjectileData(False,
                              10,
                              10,
                              20,
                              'laser_blue.png',
                              rotating_image=True)
        projectile = FancyProjectile(Vector2(0, 0), Vector2(1, 0), data)

        initial_width = projectile.image.get_width()
        self.timer.current_time += 10
        projectile.update()

        final_width = projectile.image.get_width()
        self.assertNotEqual(initial_width, final_width)

    def test_fancy_projectile_angled_image_changes_angle(self) -> None:

        data = ProjectileData(**load_projectile_data_kwargs('laser'))
        assert data.angled_image
        projectile_y = FancyProjectile(Vector2(0, 0), Vector2(0, 1), data)
        projectile_x = FancyProjectile(Vector2(0, 0), Vector2(1, 0), data)

        image_y = projectile_y.image
        image_x = projectile_x.image

        self.assertEqual(image_y.get_width(), image_x.get_height())
        self.assertEqual(image_y.get_height(), image_x.get_width())

    def test_projectile_factory_build(self) -> None:
        basic_data = ProjectileData(True, 10, 100, 100, images.LITTLE_BULLET)
        factory = ProjectileFactory(basic_data)

        self.assertEqual(len(self.groups.all_sprites), 0)

        for k in range(5):
            factory.build(Vector2(0, 0), Vector2(1, 0))
            self.assertEqual(len(self.groups.all_sprites), k + 1)
            self.assertEqual(len(self.groups.enemy_projectiles), k + 1)
            self.assertEqual(len(self.groups.bullets), 0)

    def test_projectile_data_eq(self) -> None:
        rock_data_0 = ProjectileData(**load_projectile_data_kwargs('rock'))
        rock_data_1 = ProjectileData(**load_projectile_data_kwargs('rock'))
        self.assertEqual(rock_data_0, rock_data_1)
Esempio n. 12
0
class HumanoidsTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def test_groups_immutable_container(self) -> None:
        groups = model.Groups()

        self.assertIsInstance(groups.walls, Group)
        self.assertIsInstance(groups.all_sprites, LayeredUpdates)

        with self.assertRaises(AttributeError):
            groups.walls = Group()

    def test_humanoid_increment_health(self) -> None:
        player = make_player()
        max_health = player.status.max_health

        player.status.increment_health(-1)
        self.assertEqual(player.status.health, max_health - 1)
        player.status.increment_health(100)
        self.assertEqual(player.status.health, max_health)
        player.status.increment_health(-max_health - 2)
        self.assertEqual(player.status.health, 0)
        self.assertTrue(player.status.is_dead)

    def test_player_move(self) -> None:
        player = make_player()

        original_pos = Vector2(0, 0)
        self.assertEqual(player.pos, original_pos)

        player.translate_down()
        player.translate_left()
        player.update()
        player.translate_down()
        player.translate_left()
        player.update()

        speed = 56
        expected = Vector2(-speed, speed)
        self.assertEqual(player.pos, expected)

        # velocity set to zero after each update
        player.update()
        self.assertEqual(player.pos, expected)

        # up movement is twice as fast as other moves, so we only do it once.
        player.translate_up()
        player.translate_right()
        player.update()
        player.translate_right()
        player.translate_up()
        player.update()
        self.assertEqual(player.pos, original_pos)

    def test_player_turn(self) -> None:
        player = make_player()

        # start player at origin facing right
        player.pos = (0, 0)
        player.motion.rot = 0

        # +x is to the right of player - no rotation
        player.set_mouse_pos((100, 0))
        player._rotate_towards_cursor()
        self.assertAlmostEqual(player.motion.rot, 0, 1)

        # -y is above player - faces top of screen
        player.set_mouse_pos((0, -100))
        player._rotate_towards_cursor()
        self.assertAlmostEqual(player.motion.rot, 90, 1)

        # +y is above below - faces bottom of screen
        player.set_mouse_pos((0, 100))
        player._rotate_towards_cursor()
        self.assertAlmostEqual(player.motion.rot, 270, 1)

        # -x is left of player
        player.set_mouse_pos((-100, 0))
        player._rotate_towards_cursor()
        self.assertAlmostEqual(player.motion.rot, 180, 1)

    def test_player_move_to_mouse(self) -> None:

        def normalize(pos: Tuple[float, float]) \
                -> Tuple[float, float]:
            x, y = pos
            length = math.sqrt(x**2 + y**2)
            if length == 0:
                return (0.0, 0.0)
            return (x / length, y / length)

        player = make_player()

        # test that the player moves in the same direction as mouse
        possible_positions = [[0, 100, -100]] * 2
        for x, y in product(*possible_positions):
            player.pos = (0, 0)
            player.motion.rot = 0
            player.set_mouse_pos((x, y))
            player.move_towards_mouse()
            player.update()

            # player direction
            p_hat = normalize(player.pos)

            # mouse direction
            m_hat = normalize((x, y))

            self.assertAlmostEqual(p_hat[0], m_hat[0], 8)
            self.assertAlmostEqual(p_hat[1], m_hat[1], 8)

    def test_mouse_too_close(self) -> None:
        # stop moving when you get close to the mouse
        player = make_player()

        player.pos = (0, 0)
        player.motion.rot = 0
        player.set_mouse_pos((1, 1))
        player.move_towards_mouse()
        player.update()

        self.assertEqual(player.pos[0], 0)
        self.assertEqual(player.pos[1], 0)

    def test_player_stop(self) -> None:
        player = make_player()

        original_pos = Vector2(0, 0)
        self.assertEqual(player.pos, original_pos)

        player.translate_down()
        player.translate_left()
        player.motion.stop_x()
        player.update()
        expected = Vector2(0, 28)
        self.assertEqual(player.pos, expected)

        player.translate_down()
        player.translate_left()
        player.motion.stop_y()
        player.update()
        expected = Vector2(-28, 28)
        self.assertEqual(player.pos, expected)

    def test_mob_move_to_player(self) -> None:
        player = make_player()
        mob = make_zombie(player)

        initial_dist = _dist(player.pos, mob.pos)
        mob.update()
        final_dist = _dist(player.pos, mob.pos)

        self.assertLess(final_dist, initial_dist)

    def test_mob_damage_and_death(self) -> None:
        groups = self.groups
        mob = make_zombie()
        mob.status.increment_health(61 - mob.status.max_health)
        mob.status.increment_health(31 - 61)
        mob.status.increment_health(0 - 31)

        self.assertIn(mob, groups.enemies)

        mob.update()
        self.assertNotIn(mob, groups.enemies)

    def test_pickup_stackable_adds_to_active_mods(self) -> None:
        player = make_player()

        player.inventory.attempt_pickup(build_map_object('rock', player.pos))

        self.assertFalse(player.inventory.backpack.slot_occupied(0))

        player.inventory.attempt_pickup(build_map_object('rock', player.pos))
        self.assertFalse(player.inventory.backpack.slot_occupied(0))

    def test_use_ability_at_empty_slot_no_effect(self) -> None:
        player = make_player()

        self.assertEqual(len(self.groups.all_sprites), 1)

        arms_ability_caller = player.ability_caller(ModLocation.ARMS)
        arms_ability_caller()
        self.assertEqual(len(self.groups.all_sprites), 1)

    def test_collide_hit_rect_with_rect(self) -> None:
        player = make_player()
        pos = player.pos

        x = pos.x
        y = pos.y

        wall_sprite = Sprite([self.groups.walls])
        wall_sprite.rect = Rect(x, y, 30, 30)

        self.assertTrue(collide_hit_rect_with_rect(player, wall_sprite))

    def test_x_wall_collisions(self) -> None:
        player = make_player()
        hit_rect = player.motion.hit_rect

        wall_sprite = Sprite([self.groups.walls])

        x = player.pos.x + hit_rect.width / 2 + 1
        y = player.pos.y
        wall_sprite.rect = Rect(x, y, 30, 30)
        self.assertFalse(collide_hit_rect_with_rect(player, wall_sprite))

        player.motion.vel.x = 10
        player.update()
        self.assertFalse(collide_hit_rect_with_rect(player, wall_sprite))
        self.assertEqual(player.motion.vel.x, 0)

    def test_y_wall_collisions(self) -> None:
        player = make_player()
        hit_rect = player.motion.hit_rect

        wall_sprite = Sprite([self.groups.walls])

        x = player.pos.x
        y = player.pos.x + hit_rect.height / 2 + 1
        wall_sprite.rect = Rect(x, y, 30, 30)
        self.assertFalse(collide_hit_rect_with_rect(player, wall_sprite))

        player.motion.vel.y = 10
        player.update()
        self.assertFalse(collide_hit_rect_with_rect(player, wall_sprite))
        self.assertEqual(player.motion.vel.y, 0)

    def test_hit_rect_matches_rect(self) -> None:
        mob = make_zombie()
        self.assertEqual(mob.pos, mob.motion.hit_rect.center)
Esempio n. 13
0
def setUpModule() -> None:
    HumanoidsTest.groups = model.Groups()
    HumanoidsTest.timer = MockTimer()
    initialize_everything(HumanoidsTest.groups, HumanoidsTest.timer)
Esempio n. 14
0
class AbilitiesTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()
    projectile_ability_data: AbilityData = None

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def test_fire_projectile_cannot_shoot_at_first(self) -> None:
        fire_pistol = GenericAbility(self.projectile_ability_data)

        self.assertFalse(fire_pistol.can_use('dummy_arg'))
        self.timer.current_time += self.projectile_ability_data.cool_down_time
        self.assertFalse(fire_pistol.can_use('dummy_arg'))
        self.timer.current_time += 1
        self.assertTrue(fire_pistol.can_use('dummy_arg'))

    def test_fireprojectile_use_instantiates_bullet_and_flash(self) -> None:
        groups = self.groups
        player = make_player()
        fire_pistol = GenericAbility(self.projectile_ability_data)

        self.assertEqual(len(groups.all_sprites), 1)
        fire_pistol.use(player)
        # Check if a MuzzleFlash and Projectile sprite were created
        sprites = groups.all_sprites
        num_bullets = 0
        num_flashes = 0
        num_others = 0
        for sp in sprites:
            if isinstance(sp, Projectile):
                num_bullets += 1
            elif isinstance(sp, MuzzleFlash):
                num_flashes += 1
            else:
                num_others += 1

        self.assertEqual(num_bullets, 1)
        self.assertEqual(num_flashes, 1)
        self.assertEqual(num_others, 1)

    def test_fireprojectile_use_ignores_can_use(self) -> None:
        player = make_player()
        fire_pistol = GenericAbility(self.projectile_ability_data)

        self.assertEqual(len(self.groups.bullets), 0)
        self.assertFalse(fire_pistol.can_use('dummy_arg'))
        fire_pistol.use(player)
        self.assertEqual(len(self.groups.bullets), 1)

    def test_fireprojectile_cannot_use_after_firing(self) -> None:
        player = make_player()
        fire_pistol = GenericAbility(self.projectile_ability_data)
        self.timer.current_time += \
            self.projectile_ability_data.cool_down_time + 1

        self.assertTrue(fire_pistol.can_use('dummy_arg'))
        fire_pistol.use(player)
        self.assertFalse(fire_pistol.can_use('dummy_arg'))

    def test_player_shoot_kickback(self) -> None:
        player = make_player()
        fire_pistol = GenericAbility(self.projectile_ability_data)

        old_vel = (player.motion.vel.x, player.motion.vel.y)
        fire_pistol.use(player)
        new_vel = (player.motion.vel.x, player.motion.vel.y)

        kickback = self.projectile_ability_data.kickback
        expected_vel = (-kickback + old_vel[0], old_vel[1])
        self.assertEqual(new_vel, expected_vel)

    def test_fire_many_bullets(self) -> None:
        player = make_player()

        projectile_count = 15
        ability_data = self.projectile_ability_data._replace(
            projectile_count=projectile_count)
        fire_many = GenericAbility(ability_data)

        self.assertEqual(len(self.groups.bullets), 0)
        fire_many.use(player)
        self.assertEqual(len(self.groups.bullets), projectile_count)

    def test_heal_player_not_damaged(self) -> None:
        player = make_player()
        heal_amount = 10
        data = AbilityData(cool_down_time=300,
                           finite_uses=True,
                           uses_left=3,
                           heal_amount=heal_amount)
        heal = GenericAbility(data)

        max_health = player.status.max_health
        self.assertEqual(player.status.health, max_health)
        self.assertFalse(heal.can_use(player))

        # use implements a heal anyway
        heal.use(player)
        self.assertEqual(player.status.health, max_health)
        self.assertEqual(heal.uses_left, 2)

    def test_heal_player_damaged_to_full(self) -> None:
        player = make_player()
        heal_amount = 10
        data = AbilityData(cool_down_time=300,
                           finite_uses=True,
                           uses_left=3,
                           heal_amount=heal_amount)
        heal = GenericAbility(data)

        max_health = player.status.max_health
        player.status.increment_health(-heal_amount + 2)
        heal.use(player)
        self.assertEqual(player.status.health, max_health)
        self.assertEqual(heal.uses_left, 2)

    def test_heal_player_damaged_correct_amount(self) -> None:
        player = make_player()
        heal_amount = 10
        data = AbilityData(cool_down_time=300,
                           finite_uses=True,
                           uses_left=3,
                           heal_amount=heal_amount)
        heal = GenericAbility(data)

        max_health = player.status.max_health
        player.status.increment_health(-heal_amount - 2)
        heal.use(player)
        self.assertEqual(player.status.health, max_health - 2)
        self.assertEqual(heal.uses_left, 2)

    def test_regenerate_player_energy_correct_amount(self) -> None:
        player = make_player()
        recharge_amount = 15
        data = AbilityData(cool_down_time=300,
                           finite_uses=True,
                           uses_left=2,
                           recharge_amount=recharge_amount)
        recharge = GenericAbility(data)

        source = player.energy_source
        starting_energy = source.max_energy
        energy_expended = 20

        source.expend_energy(energy_expended)
        self.assertEqual(source.energy_available,
                         starting_energy - energy_expended)

        recharge.use(player)
        self.assertEqual(source.energy_available,
                         starting_energy - energy_expended + recharge_amount)
        self.assertEqual(recharge.uses_left, 1)

        recharge.use(player)
        self.assertEqual(source.energy_available, starting_energy)
        self.assertEqual(recharge.uses_left, 0)

    def test_ability_data_equality(self) -> None:

        base_data = AbilityData(cool_down_time=300,
                                finite_uses=True,
                                uses_left=3)
        base_data_2 = AbilityData(cool_down_time=300,
                                  finite_uses=True,
                                  uses_left=3)
        self.assertEqual(base_data, base_data_2)

        base_data = AbilityData(cool_down_time=300,
                                finite_uses=True,
                                uses_left=3)
        base_data_2 = AbilityData(cool_down_time=300,
                                  finite_uses=True,
                                  uses_left=2)
        self.assertEqual(base_data, base_data_2)

        base_data = AbilityData(cool_down_time=301,
                                finite_uses=True,
                                uses_left=3)
        base_data_2 = AbilityData(cool_down_time=300,
                                  finite_uses=True,
                                  uses_left=3)
        self.assertNotEqual(base_data, base_data_2)

        self.assertNotEqual(base_data, 1)
        self.assertNotEqual(1, base_data)

        reg_data = AbilityData(300,
                               heal_amount=10,
                               finite_uses=True,
                               uses_left=1)
        reg_data_2 = AbilityData(300,
                                 heal_amount=10,
                                 finite_uses=True,
                                 uses_left=1)
        self.assertEqual(reg_data, reg_data_2)

        reg_data = AbilityData(301,
                               heal_amount=10,
                               finite_uses=True,
                               uses_left=1)
        reg_data_2 = AbilityData(300,
                                 heal_amount=10,
                                 finite_uses=True,
                                 uses_left=1)
        self.assertNotEqual(reg_data, reg_data_2)

        reg_data = AbilityData(300,
                               heal_amount=10,
                               finite_uses=True,
                               uses_left=1)
        reg_data_2 = AbilityData(300,
                                 heal_amount=11,
                                 finite_uses=True,
                                 uses_left=1)
        self.assertNotEqual(reg_data, reg_data_2)

        reg_data = AbilityData(300,
                               heal_amount=10,
                               finite_uses=True,
                               uses_left=1)
        reg_data_2 = AbilityData(300,
                                 heal_amount=10,
                                 finite_uses=True,
                                 uses_left=2)
        self.assertEqual(reg_data, reg_data_2)

        reg_data = AbilityData(300,
                               heal_amount=10,
                               recharge_amount=1,
                               finite_uses=True,
                               uses_left=1)
        reg_data_2 = AbilityData(300,
                                 heal_amount=10,
                                 finite_uses=True,
                                 uses_left=1)
        self.assertNotEqual(reg_data, reg_data_2)

        proj_ability_data_0 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        proj_ability_data_1 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        self.assertEqual(proj_ability_data_0, proj_ability_data_1)

        proj_ability_data_0 = AbilityData(251,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        proj_ability_data_1 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        self.assertNotEqual(proj_ability_data_0, proj_ability_data_1)

        proj_ability_data_0 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=2,
                                          kickback=200,
                                          spread=5)

        proj_ability_data_1 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        self.assertNotEqual(proj_ability_data_0, proj_ability_data_1)

        proj_ability_data_0 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=201,
                                          spread=5)

        proj_ability_data_1 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        self.assertNotEqual(proj_ability_data_0, proj_ability_data_1)

        proj_ability_data_0 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        proj_ability_data_1 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=6)

        self.assertNotEqual(proj_ability_data_0, proj_ability_data_1)

        proj_ability_data_0 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5,
                                          sound_on_use='a')

        proj_ability_data_1 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5,
                                          sound_on_use='b')

        self.assertNotEqual(proj_ability_data_0, proj_ability_data_1)

        proj_ability_data_0 = AbilityData(250,
                                          projectile_label='bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        proj_ability_data_1 = AbilityData(250,
                                          projectile_label='little_bullet',
                                          projectile_count=1,
                                          kickback=200,
                                          spread=5)

        self.assertNotEqual(proj_ability_data_0, proj_ability_data_1)
Esempio n. 15
0
class ModTest(unittest.TestCase):
    groups = model.Groups()
    timer = MockTimer()

    def tearDown(self) -> None:
        self.groups.empty()
        self.timer.reset()

    def testmake_item_in_groups(self) -> None:
        groups = self.groups

        hp = make_item('healthpack')
        self.assertIn(hp, groups.all_sprites)
        self.assertIn(hp, groups.items)
        self.assertEqual(len(groups.all_sprites), 1)
        self.assertEqual(len(groups.items), 1)

        pistol = make_item('pistol')
        self.assertIn(pistol, groups.all_sprites)
        self.assertIn(pistol, groups.items)
        self.assertEqual(len(groups.all_sprites), 2)
        self.assertEqual(len(groups.items), 2)

        shotgun = make_item('shotgun')
        self.assertIn(shotgun, groups.all_sprites)
        self.assertIn(shotgun, groups.items)
        self.assertEqual(len(groups.all_sprites), 3)
        self.assertEqual(len(groups.items), 3)

    def test_backpack_full(self) -> None:
        player = make_player()
        pistol = make_item('pistol')

        backpack = player.inventory.backpack
        self.assertEqual(len(backpack), backpack.size)
        # TODO (dvirk): You should not be able to add the same object to the
        # backpack more than once.

        for i in range(backpack.size + 1):
            self.assertFalse(backpack.is_full)
            player.inventory.attempt_pickup(pistol)
        self.assertTrue(backpack.is_full)

        # Item not gained since backpack full
        player.inventory.attempt_pickup(pistol)
        self.assertEqual(len(backpack), backpack.size)

    def test_pickup_healthpacks(self) -> None:
        player = make_player()
        hp = make_item('healthpack')

        backpack = player.inventory.backpack

        player.inventory.attempt_pickup(hp)
        # healthpack goes straight to active mods.
        self.assertNotIn(hp.mod, backpack)  # healthpack added to stack.
        active_mods = player.inventory.active_mods
        self.assertIn(hp.mod, active_mods.values())
        self.assertEqual(active_mods[hp.mod.loc].ability.uses_left, 1)

        hp_2 = make_item('healthpack')
        player.inventory.attempt_pickup(hp_2)

        self.assertNotIn(hp_2.mod, backpack)
        self.assertEqual(active_mods[hp.mod.loc].ability.uses_left, 2)

    def test_health_pack_not_used_full_health(self) -> None:
        hp, player = self._player_with_ready_healthpack()

        # health is full
        self.assertFalse(player.status.damaged)
        self.assertFalse(hp.mod.expended)
        use_hp_mod = player.ability_caller(hp.mod.loc)
        use_hp_mod()
        self.assertFalse(hp.mod.expended)

        # health pack doesn't work if health is full
        self.assertIn(hp.mod, player.inventory.active_mods.values())

    def test_health_pack_heals_back_to_full(self) -> None:
        hp, player = self._player_with_ready_healthpack()

        backpack = player.inventory.backpack

        # health pack fills health back up and is gone from active_mods
        player.status.increment_health(-5)
        self.assertTrue(player.status.damaged)

        # Ability is only usable after sufficient time has elapsed.
        use_hp_mod = player.ability_caller(hp.mod.loc)
        use_hp_mod()

        self.assertTrue(hp.mod.expended)
        self.assertEqual(hp.mod.ability.uses_left, 0)
        self.assertNotIn(hp.mod, backpack)
        self.assertFalse(player.status.damaged)
        self.assertEqual(player.status.health, player.status.max_health)

    def _player_with_ready_healthpack(self) -> Tuple[items.ItemObject, Player]:
        player = make_player()
        hp = make_item('healthpack')
        player.inventory.attempt_pickup(hp)
        while hp.mod.ability.cooldown_fraction < 1:
            self.timer.current_time += 100
        self.timer.current_time += 1
        return hp, player

    def test_add_weapons(self) -> None:
        player = make_player()
        shotgun = make_item('shotgun')

        player.inventory.attempt_pickup(shotgun)

        # nothing installed at arms location -> install shotgun
        backpack = player.inventory.backpack
        self.assertNotIn(shotgun.mod, backpack)
        active_mods = player.inventory.active_mods
        arm_mod = active_mods[mods.ModLocation.ARMS]
        self.assertIs(arm_mod, shotgun.mod)

        # adding a second arm mod goes into the backpack
        pistol = make_item('pistol')

        player.inventory.attempt_pickup(pistol)
        self.assertIn(pistol.mod, backpack)
        arm_mod = active_mods[mods.ModLocation.ARMS]
        self.assertIs(arm_mod, shotgun.mod)
        self.assertIn(pistol.mod, backpack)

        # make sure we can swap the pistol with the shotgun
        player.inventory.equip(pistol.mod)
        arm_mod = active_mods[mods.ModLocation.ARMS]
        self.assertEqual(arm_mod, pistol.mod)
        self.assertIn(shotgun.mod, backpack)

    def test_mod_stacking_in_active_mods(self) -> None:
        player = make_player()
        pos = Vector2(0, 0)
        hp = build_map_object('healthpack', pos)

        self.assertNotIn(hp.mod.loc, player.inventory.active_mods)

        player.inventory.attempt_pickup(hp)
        player_mod = player.inventory.active_mods[hp.mod.loc]
        self.assertIs(player_mod, hp.mod)
        self.assertEqual(player_mod.ability.uses_left, 1)

        player.inventory.attempt_pickup(build_map_object('healthpack', pos))
        player_mod = player.inventory.active_mods[hp.mod.loc]
        self.assertEqual(player_mod.ability.uses_left, 2)

        player.inventory.attempt_pickup(build_map_object('healthpack', pos))
        player_mod = player.inventory.active_mods[hp.mod.loc]
        self.assertEqual(player_mod.ability.uses_left, 3)

    def test_mod_stacking_in_backpack(self) -> None:
        player = make_player()
        pos = Vector2(0, 0)

        player.inventory.attempt_pickup(build_map_object('pistol', pos))

        self.assertFalse(player.inventory.backpack.slot_occupied(0))

        player.inventory.attempt_pickup(build_map_object('rock', pos))
        self.assertTrue(player.inventory.backpack.slot_occupied(0))
        self.assertEqual(player.inventory.backpack[0].ability.uses_left, 1)

        player.inventory.attempt_pickup(build_map_object('rock', pos))
        self.assertEqual(player.inventory.backpack[0].ability.uses_left, 2)

        player.inventory.attempt_pickup(build_map_object('rock', pos))
        self.assertEqual(player.inventory.backpack[0].ability.uses_left, 3)

        player.inventory.attempt_pickup(build_map_object('rock', pos))
        self.assertEqual(player.inventory.backpack[0].ability.uses_left, 4)

    def test_pickup_several_items(self) -> None:
        player = make_player()
        pos = Vector2(0, 0)

        laser_gun = build_map_object('laser', pos)
        battery = build_map_object('battery', pos)
        pistol = build_map_object('pistol', pos)
        medpack = build_map_object('healthpack', pos)

        player.inventory.attempt_pickup(laser_gun)
        self.assertIs(laser_gun.mod,
                      player.inventory.active_mods[mods.ModLocation.ARMS])
        player.inventory.attempt_pickup(battery)
        self.assertIs(battery.mod,
                      player.inventory.active_mods[mods.ModLocation.CHEST])
        player.inventory.attempt_pickup(pistol)
        self.assertIn(pistol.mod, player.inventory.backpack)
        self.assertTrue(player.inventory.backpack.slot_occupied(0))
        player.inventory.attempt_pickup(medpack)
        self.assertIn(medpack.mod, player.inventory.backpack)
        self.assertTrue(player.inventory.backpack.slot_occupied(1))

    def test_creation_of_usable_items_from_data(self) -> None:
        player = make_player()
        item_data = items.ItemData(**load_item_data_kwargs('pistol'))
        pistol_ability = AbilityData(**load_ability_data_kwargs('pistol'))

        pistol = items.ItemFromData(item_data, Vector2(0, 0))
        player.inventory.attempt_pickup(pistol)

        self.assertIs(pistol.mod, player.inventory.active_mods[pistol.mod.loc])

        use_pistol = player.ability_caller(mods.ModLocation.ARMS)
        self.timer.current_time += pistol_ability.cool_down_time + 1

        use_pistol()
        self.assertEqual(len(self.groups.bullets), 1)