import { world, system, Vector } from '@minecraft/server'
import { Vec3 } from "Vec3"

const blockTags = [
    "minecraft:andesite",
    "minecraft:bedrock",
    "minecraft:brick_block",
    "minecraft:cobblestone",
    "minecraft:cobblestone_wall",
    "minecraft:diorite",
    "minecraft:double_stone_block_slab",
    "minecraft:dripstone_block",
    "minecraft:granite",
    "minecraft:mossy_cobblestone",
    "minecraft:polished_andesite",
    "minecraft:polished_diorite",
    "minecraft:polished_granite",
    "minecraft:stone",
    "minecraft:stone_block_slab",
    "minecraft:stone_button",
    "minecraft:stone_pressure_plate",
    "minecraft:stone_stairs",
    "minecraft:coal_ore",
    "minecraft:deepslate_coal_ore",
    "minecraft:deepslate_diamond_ore",
    "minecraft:deepslate_emerald_ore",
    "minecraft:deepslate_gold_ore",
    "minecraft:deepslate_iron_ore",
    "minecraft:deepslate_redstone_ore",
    "minecraft:diamond_ore",
    "minecraft:emerald_ore",
    "minecraft:gold_ore",
    "minecraft:iron_ore",
    "minecraft:lapis_ore",
    "minecraft:lit_deepslate_redstone_ore",
    "minecraft:lit_redstone_ore",
    "minecraft:obsidian",
    "minecraft:raw_gold_block",
    "minecraft:raw_iron_block",
    "minecraft:redstone_ore",
    "minecraft:grass",
    "minecraft:grass_block",
    "minecraft:grass_path",
    "minecraft:dirt",
    "minecraft:dirt_with_roots",
    "minecraft:farmland",
    "minecraft:grass_block",
    "minecraft:moss_block",
    "minecraft:mud",
    "minecraft:muddy_mangrove_roots",
    "minecraft:mycelium",
    "minecraft:podzol",
    "minecraft:gravel",
    "minecraft:suspicious_gravel"
];

//EVENTS

//This prevents world crash
system.beforeEvents.watchdogTerminate.subscribe(data => {
    data.cancel = true;
});

//Define house spawnpoint to set an Orc Raid timer
world.afterEvents.playerInteractWithBlock.subscribe((event) => {
    const player = event.player;
    const block = event.block

    if (block.typeId !== `minecraft:bed`) return;

    const { dimension, location } = block
    const entities = world.getDimension(player.dimension.id).getEntities({ location: { x: location.x + 0.5, y: location.y + 0.5, z: location.z + 0.5 }, maxDistance: 2, type: `ch:raid_house_timer` })[0];
    if (entities === undefined) {
        dimension.spawnEntity(`ch:raid_house_timer`, { x: location.x + 0.5, y: location.y + 0.5, z: location.z + 0.5 });
    }
});

//3D Items in Ground
world.afterEvents.entitySpawn.subscribe(({ entity }) => {
    const { typeId } = entity

    if (entity.isValid() == false || typeId !== `minecraft:item`) return;

    const itemStack = entity?.getComponent('item')?.itemStack

    if (!itemStack.typeId.includes(`ch:`)) return;

    const dimension = entity?.dimension
    const location = entity?.location
    const player = dimension?.getPlayers({ closest: 1, location })[0];
    const vel = entity?.getVelocity()
    const velMultiplier = 2
    const playerRot = player?.getRotation()
    const playerVel = player?.getVelocity();

    function setEntity(itemGround, itemStack) {
        itemGround.setRotation({ x: playerRot.x, y: playerRot.y })
        itemGround.applyImpulse({ x: (vel.x * velMultiplier) + (playerVel.x * velMultiplier * 2), y: vel.y * velMultiplier, z: (vel.z * velMultiplier) + (playerVel.z * velMultiplier * 2) })
        entity?.remove();
        const event = world.afterEvents.playerInteractWithEntity.subscribe((data) => {
            const player = data.player;
            const interactedEntity = data.target;
            const interactedPosition = interactedEntity.location;
            const itemGroundPosition = itemGround.location;

            if (interactedPosition.x !== itemGroundPosition.x || interactedPosition.y !== itemGroundPosition.y || interactedPosition.z !== itemGroundPosition.z) return;

            const inv = player.getComponent("minecraft:inventory")?.container
            inv.addItem(itemStack);
            interactedEntity.remove();
            world.afterEvents.playerInteractWithEntity.unsubscribe(event);
        })
    };
    function setEntity2(itemGround, itemStack) {
        itemGround.setRotation({ x: playerRot.x, y: playerRot.y });
        itemGround.applyImpulse({ x: (vel.x * velMultiplier) + (playerVel.x * velMultiplier * 2), y: vel.y * velMultiplier * 2, z: (vel.z * velMultiplier) + (playerVel.z * velMultiplier * 2) })
        entity?.remove();
        const event = world.afterEvents.playerInteractWithEntity.subscribe((data) => {
            const player = data.player;
            const interactedEntity = data.target;
            if (interactedEntity.typeId === itemGround.typeId) {
                const inv = player.getComponent("minecraft:inventory")?.container
                inv.addItem(itemStack);
                interactedEntity?.remove();
                world.afterEvents.playerInteractWithEntity.unsubscribe(event);
            }
        })
    }

    if (itemStack.typeId === "ch:soulless_knight_sword") {
        const itemGround = dimension.spawnEntity(`ch:sk_sword_ground`, { x: location.x, y: location.y + 0.5, z: location.z })
        setEntity(itemGround, itemStack)
    };

    if (itemStack.typeId === "ch:buffed_soulless_knight_sword") {
        const itemGround = dimension.spawnEntity(`ch:buffed_sk_sword_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:soulless_knight_chestplate") {
        const itemGround = dimension.spawnEntity(`ch:sk_chestplate_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:buffed_soulless_knight_chestplate") {
        const itemGround = dimension.spawnEntity(`ch:buffed_sk_chestplate_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:bardiche") {
        const itemGround = dimension.spawnEntity(`ch:bardiche_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity2(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:buffed_bardiche") {
        const itemGround = dimension.spawnEntity(`ch:buffed_bardiche_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity2(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:orc_cannon") {
        const itemGround = dimension.spawnEntity(`ch:orc_cannon_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:buffed_orc_cannon") {
        const itemGround = dimension.spawnEntity(`ch:buffed_orc_cannon_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:wand") {
        const itemGround = dimension.spawnEntity(`ch:orc_wand_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity2(itemGround, itemStack)
    }

    if (itemStack.typeId === "ch:buffed_wand") {
        const itemGround = dimension.spawnEntity(`ch:buffed_orc_wand_ground`, { x: location.x, y: location.y + 0.5, z: location.z });
        setEntity(itemGround, itemStack)
    }
});

//Show UI on join
world.afterEvents.playerSpawn.subscribe((data) => {
    if (data.player.isValid()) {
        system.runTimeout(() => {
            if (data.player.hasTag('dark_soul_curse')) {
                data.player.onScreenDisplay.setTitle(`dark_soul_curse;`)
            };
            //Charging UI System
            system.runTimeout(() => {
                //Evil Mana
                system.runInterval(() => {
                    const score = world.scoreboard.getObjective('evil_mana')?.getScore(data.player);

                    if (score < 625 && score > 0 && data.player.hasTag('evil_mana') && !data.player.hasTag('getting_evil_mana')) {
                        data.player.onScreenDisplay.setTitle(`evil_mana;${100 - (score / 625) * 100}`)
                    }
                }, 10);

                //Bardiche Charge Atttack Cooldown
                system.runInterval(() => {
                    const score = world.scoreboard.getObjective('bardiche_cooldown')?.getScore(data.player);

                    if (score < 250 && score > 0 && data.player.hasTag('bardiche')) {
                        data.player.onScreenDisplay.setTitle(`bardiche_cooldown${100 - (score / 250) * 100}`)
                    }
                }, 20)
            }, 50)
        }, 100)
    }
});
//on Tick
system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const inv = player.getComponent("minecraft:inventory")?.container;
        const mainHand = player.getComponent("minecraft:equippable")?.getEquipmentSlot(`Mainhand`).getItem();

        //Equip Weapon System
        for (let i = 0; i < 36; i++) {
            const item = inv.getItem(i);

            if (!item || (item.typeId !== `ch:bardiche` && item.typeId !== `ch:buffed_bardiche`)) continue;

            const bardicheScore = world.scoreboard.getObjective('bardiche');

            if (mainHand?.typeId === "ch:bardiche" || mainHand?.typeId === "ch:buffed_bardiche") {
                hasWeapon(player, bardicheScore, item);
                break;
            }

            if ((mainHand?.typeId !== "ch:bardiche" && mainHand?.typeId !== "ch:buffed_bardiche") || mainHand === undefined) {
                hasNotWeapon(player, bardicheScore, item);
                break;
            }

        };

        for (let i = 0; i < 36; i++) {
            const item = inv.getItem(i)

            if (!item || (item.typeId !== `ch:soulless_knight_sword` && item.typeId !== `ch:buffed_soulless_knight_sword`)) continue;

            const skSwordScore = world.scoreboard.getObjective('sk_sword');

            if (mainHand?.typeId === "ch:soulless_knight_sword" || mainHand?.typeId === "ch:buffed_soulless_knight_sword") {
                const item = player.getComponent("minecraft:equippable")?.getEquipmentSlot(`Mainhand`).getItem();
                hasWeapon(player, skSwordScore, item);

                //Jump Attack
                const jumpState = player.getDynamicProperty(`jump_state`) ?? 0;

                if (jumpState != 4 && (player.isOnGround || player.isInWater || player.isClimbing)) {
                    player.setDynamicProperty(`jump_state`, 0)
                };

                if (!player.matches({ gameMode: `creative` }) && !player.matches({ gameMode: `spectator` }) && !player.hasTag(`sk_sword_cant_attack`)) {
                    if (jumpState == 0 && player.isJumping && !player.isInWater && !player.isClimbing) {
                        player.setDynamicProperty(`jump_state`, 1);
                        system.runTimeout(() => {
                            const jumpState = player.getDynamicProperty(`jump_state`) ?? 0;
                            if (jumpState < 3) {
                                player.setDynamicProperty(`jump_state`, 3);
                            }
                        }, 10)
                    };
                    if (jumpState == 0 && !player.isOnGround && !player.isJumping) {
                        player.setDynamicProperty(`jump_state`, 3);
                    }
                    if (jumpState == 1 && !player.isJumping) {
                        player.setDynamicProperty(`jump_state`, 2);
                    };
                    if (jumpState == 2 && player.isJumping) {
                        player.setDynamicProperty(`jump_state`, 3);

                        const playerVel = Math.sqrt(Math.pow(player.getVelocity().x, 2) + Math.pow(player.getVelocity().z, 2));
                        player.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, (playerVel * 3), 1.1);
                        world.playSound(`mob.soulless_knight.jump`, { x: player.location.x, y: player.location.y, z: player.location.z })

                        system.runTimeout(() => {
                            player.playAnimation(`animation.soulless_knight_sword.jump_attack`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.is_on_ground || query.is_in_water`, controller: `jump_attack` });
                            player.setDynamicProperty(`jump_state`, 4)
                        }, 3)
                    };
                    if (jumpState == 4 && (player.isOnGround || player.isInWater || player.isClimbing)) {
                        if (player.isOnGround) {
                            const block = player.dimension.getBlock({ x: player.location.x, y: player.location.y - 1, z: player.location.z }).typeId;

                            player.playAnimation(`animation.soulless_knight_sword.jump_attack_damage`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished || query.is_in_water`, controller: `jump_attack` });
                            world.playSound(`mob.attack.greatsword_ground_impact`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            world.playSound(`mob.attack.greatsword_impact`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            player.addEffect(`slowness`, 12, { amplifier: 3, showParticles: false });

                            if (blockTags.includes(block)) {
                                player.spawnParticle(`ch:ground_explosion_no_local`, player.location);
                            };
                            darkSoulDamage(player, item);
                            stopingAttack(player, item);
                        };
                        if (player.isInWater || player.isClimbing) {
                            player.setDynamicProperty(`jump_state`, 0);
                            player.playAnimation(`animation.none`, { nextState: `none`, blendOutTime: 0, controller: `jump_attack` });
                        }
                    }
                }
                break;
            }

            if ((mainHand?.typeId !== "ch:soulless_knight_sword" && mainHand?.typeId !== "ch:buffed_soulless_knight_sword") || mainHand === undefined) {
                player.setDynamicProperty(`jump_state`, 3);
                hasNotWeapon(player, skSwordScore, item);
                break;
            }

        };
        break;
    }
}, 1);

function hasWeapon(player, score, item) {
    const scoreNum = score?.getScore(player);

    for (const entity of player.dimension.getEntities({ families: [`weapon_backward`], closest: 1, scoreOptions: [{ objective: score.displayName, minScore: scoreNum, maxScore: scoreNum }] })) {
        entity?.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 1 air`);
        entity?.runCommandAsync(`ride ${player.name} stop_riding`)
        if (item.typeId.includes(`buffed_`)) {
            entity?.addTag(`buffed`);
        }
        if (!item.typeId.includes(`buffed_`)) {
            entity?.removeTag(`buffed`);
        };

        if (score.displayName === `bardiche`) {
            const skSwordScore = world.scoreboard.getObjective('sk_sword')?.getScore(player);
            const entity2 = entity?.dimension.getEntities({ families: [`weapon_backward`], closest: 1, scoreOptions: [{ objective: `sk_sword`, minScore: skSwordScore, maxScore: skSwordScore }] })[0]
            const entity2Seat = entity2?.getProperty(`ch:seat_pos`)

            if (entity2?.getComponent("minecraft:riding")?.entityRidingOn && entity2Seat == 0) {
                entity?.setProperty(`ch:seat_pos`, 1)
                entity2?.setProperty(`ch:seat_pos`, 0)
            }
        };
        if (score.displayName === `sk_sword`) {
            const bardicheScore = world.scoreboard.getObjective('bardiche')?.getScore(player);
            const entity2 = entity?.dimension.getEntities({ families: [`weapon_backward`], closest: 1, scoreOptions: [{ objective: `bardiche`, minScore: bardicheScore, maxScore: bardicheScore }] })[0]
            const entity2Seat = entity2?.getProperty(`ch:seat_pos`)

            if (entity2?.getComponent("minecraft:riding")?.entityRidingOn && entity2Seat == 0) {
                entity?.setProperty(`ch:seat_pos`, 1)
                entity2?.setProperty(`ch:seat_pos`, 0)
            }
        }
        break;
    }
};
function hasNotWeapon(player, score, item) {
    const scoreNum = score?.getScore(player);

    for (const entity of player.dimension.getEntities({ families: [`weapon_backward`], closest: 1, scoreOptions: [{ objective: score?.displayName, minScore: scoreNum, maxScore: scoreNum }] })) {
        entity?.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 1 ${item.typeId}`);
        entity?.triggerEvent(`minecraft:ride_event`);
        entity?.runCommandAsync(`ride @s start_riding ${player.name} teleport_rider`)

        if (item.typeId.includes(`buffed_`)) {
            entity?.addTag(`buffed`);
            entity?.runCommandAsync(`enchant @s sharpness 1`)
        }
        if (!item.typeId.includes(`buffed_`)) {
            entity?.removeTag(`buffed`);
        };

        const zVec = player.getViewDirection();
        const xVec = Vec3(zVec.z, 0, -zVec.x).normalized;
        const locationX = Vec3.multiply(xVec, 0.42426);
        const xPos = entity.location.x - locationX.x - player.getHeadLocation().x;
        const yPos = entity.location.y - locationX.y - player.getHeadLocation().y;
        const zPos = entity.location.z - locationX.z - player.getHeadLocation().z;
        const distance = Math.sqrt(Math.pow(xPos, 2) + Math.pow(yPos, 2) + Math.pow(zPos, 2));

        if (distance < 0.5) {
            entity?.setProperty(`ch:seat_pos`, 0)
        };
        if (distance > 0.5) {
            entity?.setProperty(`ch:seat_pos`, 1)
        };
        if (score.displayName === `bardiche`) {
            if ((item.typeId !== `ch:bardiche` && item.typeId !== `ch:buffed_bardiche`)) {
                entity?.remove();
                player.onScreenDisplay.setTitle(`hide_bardiche_cooldown`)
                player.removeTag(`bardiche`)
            }
        };
        if (score.displayName === `sk_sword`) {
            if ((item.typeId !== `ch:soulless_knight_sword` && item.typeId !== `ch:buffed_soulless_knight_sword`)) {
                entity?.remove();
                player.removeTag(`sk_sword_jump_attack`)
                player.removeTag(`soulless_knight_sword`)
            }
        }
        break;
    }
};

//Weapon Use
world.afterEvents.itemUse.subscribe((data) => {
    const item = data.itemStack;
    const player = data.source;

    if (!item.typeId.startsWith(`ch:`)) return;

    //Bardiche
    if (item.typeId === `ch:bardiche` || item.typeId === `ch:buffed_bardiche`) {

        const bardicheCooldown = world.scoreboard.getObjective(`bardiche_cooldown`);

        //Charge Attack
        if (player.isSneaking && player.isOnGround && !player.isInWater && !player.hasTag(`bardiche_attacking`) && !player.hasTag(`bardiche_charge_attack`) && bardicheCooldown?.getScore(player) < 1) {
            player.addEffect(`slowness`, 34, { amplifier: 5, showParticles: false });
            player.playAnimation(`animation.captain_orc_bardiche.charge_attack`, { nextState: `none`, stopExpression: `query.any_animation_finished`, blendOutTime: 0, controller: `controller_name` });
            world.playSound(`mob.attack.man_scream`, { x: player.location.x, y: player.location.y, z: player.location.z });
            world.playSound(`mob.attack.fast_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
            player.addTag(`bardiche_charge_attack`);
            bardicheCooldown.setScore(player, 250);

            system.runTimeout(() => {
                const interval = system.runInterval(() => {
                    const playerVel = Math.sqrt(Math.pow(player.getVelocity().x, 2) + Math.pow(player.getVelocity().z, 2));
                    const playerDir = player.getViewDirection();
                    const equipment = player.getComponent("minecraft:equippable");
                    const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();
                    const sharpness = item.getComponent("enchantable").getEnchantment(`sharpness`)?.level ?? 0

                    if (!item.typeId.includes(`buffed_`)) {
                        let newItem = damageItem(player, item);
                        if (mainHand?.typeId === item?.typeId) {
                            const fireAspect = item.getComponent("enchantable").getEnchantment(`fire_aspect`)?.level ?? 0

                            if (mainHand?.typeId === item?.typeId && fireAspect != 0) {
                                for (const entity of player.dimension.getEntities({ location: Vector.add(Vector.multiply(player.getViewDirection(), 2), player.location), maxDistance: 2, excludeNames: [player.name] })) {
                                    entity?.setOnFire(fireAspect * 4, true)
                                }
                            };
                            equipment.setEquipment(`Mainhand`, newItem);
                            player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2.5 run damage @e[name=!${player.name}, family=!despawn,r=2.5] ${sharpness + 4} entity_attack entity @s`);
                            player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2 run tp @e[name=!${player.name}, r=2,family=!despawn,family=!inanimate,family=!projectile,type=!fishing_hook,type=!arrow,c=1] ^ ^0.5 ^2 true`);
                            player.applyKnockback(playerDir.x, playerDir.z, (playerVel * 1.5 + 0.05), -0.5);
                        }
                        if (!newItem) {
                            world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
                        }
                    }
                    if (item.typeId.includes(`buffed_`)) {
                        player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2 run tp @e[name=!${player.name}, r=2,family=!despawn,family=!inanimate,family=!projectile,type=!fishing_hook,type=!arrow,c=1] ^ ^0.5 ^2 true`);
                        player.applyKnockback(playerDir.x, playerDir.z, (playerVel * 1.5 + 0.05), -0.5);
                        player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2.5 run damage @e[name=!${player.name}, family=!despawn,r=2.5] 8 entity_attack entity @s`)
                    }
                }, 1)
                system.runTimeout(() => {
                    system.clearRun(interval);
                    system.runTimeout(() => {
                        const equipment = player.getComponent("minecraft:equippable");
                        const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();
                        if (mainHand?.typeId === item?.typeId) {
                            player.runCommandAsync(`summon ch:bardiche_knockback_attack ^ ^0.5 ^2`);
                            world.playSound(`mob.attack.long_sword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                        }

                        system.runTimeout(() => {
                            world.playSound(`mob.captain_orc.break`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            player.removeTag(`bardiche_charge_attack`);
                            return;
                        }, 28.466)
                    }, 4.8)
                }, 27.4)
            }, 35)
        };
        //Basic Attack
        if (!player.isSneaking && !player.hasTag(`bardiche_charge_attack`)) {
            player.addTag(`bardiche_attacking`);
            const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;

            if (attackState == 0 && !player.hasTag(`bardiche_cant_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 1);
                player.playAnimation(`animation.captain_orc_bardiche.attack1`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });

                system.runTimeout(() => {
                    normalDamage(player, item);
                    system.runTimeout(() => {
                        const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;
                        if (attackState == 1) {
                            stopingAttack(player, item);
                        }
                    }, 12.6)
                }, 8.2);
            };
            if (attackState == 1 && !player.hasTag(`bardiche_cant_attack`) && player.hasTag(`bardiche_done_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 2);

                player.removeTag(`bardiche_done_attack`);
                player.playAnimation(`animation.captain_orc_bardiche.attack2`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });

                system.runTimeout(() => {
                    normalDamage(player, item);
                    system.runTimeout(() => {
                        const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;
                        if (attackState == 2) {
                            stopingAttack(player, item);
                        }
                    }, 11.8)
                }, 9)
            };
            if (attackState == 2 && !player.hasTag(`bardiche_cant_attack`) && player.hasTag(`bardiche_done_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 3);
                player.removeTag(`bardiche_done_attack`);
                player.playAnimation(`animation.captain_orc_bardiche.attack3`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });

                system.runTimeout(() => {
                    normalDamage(player, item);
                    system.runTimeout(() => {
                        const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;
                        if (attackState == 3) {
                            stopingAttack(player, item);
                        }
                    }, 11.8)
                }, 9)
            };
            if (attackState == 3 && !player.hasTag(`bardiche_cant_attack`) && player.hasTag(`bardiche_done_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 4);
                player.removeTag(`bardiche_done_attack`);
                player.playAnimation(`animation.captain_orc_bardiche.attack4`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                system.runTimeout(() => {
                    verticalDamage(player, item);
                    system.runTimeout(() => {
                        stopingAttack(player, item);
                    }, 17.666)
                }, 14);
            };
            return;
        }
    };
    //Soulless Sword
    if (item.typeId === `ch:soulless_knight_sword` || item.typeId === `ch:buffed_soulless_knight_sword`) {
        const selectedSlot = world.scoreboard.getObjective(`sk_sword_ability`);
        const chargeAttack = world.scoreboard.getObjective(`sk_sword_charge`);
        const cooldown = world.scoreboard.getObjective(`sk_sword_cooldown`);
        const jumpAttack = player.getDynamicProperty(`jump_state`) ?? 0;
        const equipment = player.getComponent("minecraft:equippable");

        //Change slot selection
        if (player.isSneaking) {
            if (selectedSlot?.getScore(player) == 2) {
                selectedSlot?.setScore(player, 0);
                player.onScreenDisplay.setTitle(`sk_sword_ability;${selectedSlot?.getScore(player)}`);
                return;
            };
            if (selectedSlot?.getScore(player) < 2) {
                selectedSlot?.addScore(player, 1);
                player.onScreenDisplay.setTitle(`sk_sword_ability;${selectedSlot?.getScore(player)}`);
            }
        };
        //Abilities
        if (!player.isSneaking && (jumpAttack == 0 || jumpAttack == 3)) {
            //Basic attack
            if (selectedSlot?.getScore(player) == 0 && cooldown?.getScore(player) < 1) {
                player.addTag(`soulless_knight_sword_attacking`);
                const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;

                if (attackState == 0 && !player.hasTag(`sk_sword_cant_attack`)) {
                    player.setDynamicProperty(`sk_sword_attack_state`, 1);
                    player.playAnimation(`animation.soulless_knight_sword.attack1`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    player.addEffect(`slowness`, 25, { amplifier: 3, showParticles: false });

                    system.runTimeout(() => {
                        normalDamage(player, item);
                        system.runTimeout(() => {
                            const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;
                            if (attackState == 1) {
                                stopingAttack(player, item);
                            }
                        }, 10)
                    }, 15);
                };
                if ((attackState == 1 || attackState == 3) && !player.hasTag(`sk_sword_cant_attack`) && player.hasTag(`sk_sword_done_attack`)) {
                    player.setDynamicProperty(`sk_sword_attack_state`, 2);

                    player.removeTag(`sk_sword_done_attack`);
                    player.playAnimation(`animation.soulless_knight_sword.attack2`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    player.addEffect(`slowness`, 25, { amplifier: 3, showParticles: false });

                    system.runTimeout(() => {
                        normalDamage(player, item);
                        system.runTimeout(() => {
                            const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;
                            if (attackState == 2) {
                                stopingAttack(player, item);
                            }
                        }, 10)
                    }, 15)
                };
                if (attackState == 2 && !player.hasTag(`sk_sword_cant_attack`) && player.hasTag(`sk_sword_done_attack`)) {
                    player.setDynamicProperty(`sk_sword_attack_state`, 3);
                    player.removeTag(`sk_sword_done_attack`);
                    player.playAnimation(`animation.soulless_knight_sword.attack1_again`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    player.addEffect(`slowness`, 25, { amplifier: 3, showParticles: false });

                    system.runTimeout(() => {
                        normalDamage(player, item);
                        system.runTimeout(() => {
                            const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;
                            if (attackState == 3) {
                                stopingAttack(player, item);
                            }
                        }, 10)
                    }, 15)
                }
            };
            //Dodge
            if (selectedSlot?.getScore(player) == 1 && !player.hasTag(`soulless_knight_sword_attacking`) && player.isOnGround && chargeAttack?.getScore(player) < 1 && cooldown?.getScore(player) < 1) {
                const playerVel = Math.sqrt(Math.pow(player.getVelocity().x, 2) + Math.pow(player.getVelocity().z, 2));
                cooldown?.setScore(player, 25);
                player.playAnimation(`animation.soulless_knight_sword.dash`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                world.playSound(`mob.attack.greatsword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                if (!item.typeId.includes(`buffed_`)) {
                    player.applyKnockback(player.getVelocity().x, player.getVelocity().z, (playerVel * 15), (playerVel * 1.5))
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.applyKnockback(player.getVelocity().x, player.getVelocity().z, (playerVel * 25), (playerVel * 2.5))
                }
            };
            //Charge
            if (selectedSlot?.getScore(player) == 2 && !player.hasTag(`sk_sword_cant_attack`)) {
                player.addTag(`soulless_knight_sword_charge`);
                player.playAnimation(`animation.soulless_knight_sword.charge_attack`, { nextState: `none`, blendOutTime: 0, stopExpression: `!query.is_using_item` });
                player.addEffect(`slowness`, 12, { amplifier: 3, showParticles: false });

                const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                    system.clearRun(timeOut);
                    world.afterEvents.itemReleaseUse.unsubscribe(event);
                });

                const timeOut = system.runTimeout(() => {
                    const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                        system.clearRun(interval);
                        player.playAnimation(`animation.soulless_knight_sword.charge_attack_damage`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished` });

                        system.runTimeout(() => {
                            world.playSound(`mob.attack.greatsword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            world.playSound(`mob.attack.greatsword_heavy_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            darkSoulDamage(player, item);
                            stopingAttack(player, item);
                        }, 2);
                        world.afterEvents.itemReleaseUse.unsubscribe(event);
                    });
                    const interval = system.runInterval(() => {
                        const mainHand = equipment?.getEquipmentSlot(`Mainhand`).getItem();
                        if (mainHand?.typeId === item?.typeId) {
                            if (!item.typeId.includes(`buffed_`)) {
                                player.applyDamage(2, { cause: `magic` });
                            };
                            player.addEffect(`slowness`, 5, { amplifier: 3, showParticles: false });
                            chargeAttack?.addScore(player, 1);
                            darkSoulParticles(player, chargeAttack);
                            return;
                        };
                        system.clearRun(interval);
                        stopingAttack(player, item);
                        world.afterEvents.itemReleaseUse.unsubscribe(event);
                    }, 4)
                }, 5)
            };
        };
        //Dark Soul on Jump Attack
        if (jumpAttack == 4 && !player.isClimbing && !player.isInWater) {
            const interval = system.runInterval(() => {
                const mainHand = equipment?.getEquipmentSlot(`Mainhand`).getItem();
                if (mainHand?.typeId === item?.typeId && !player.isClimbing && !player.isInWater && !player.isOnGround) {
                    if (!item.typeId.includes(`buffed_`)) {
                        player.applyDamage(2, { cause: `magic` });
                    };
                    chargeAttack?.addScore(player, 1);
                    if (player.isOnGround || player.isInWater) {
                        system.clearRun(interval);
                    };
                    darkSoulParticles(player, chargeAttack);
                    return;
                };
                system.clearRun(interval);
                stopingAttack(player, item);
                world.afterEvents.itemReleaseUse.unsubscribe(event);
            }, 4);
            const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                system.clearRun(interval);
                world.afterEvents.itemReleaseUse.unsubscribe(event);
            });
        }
    };
    //Orc Cannon
    if (item.typeId === `ch:orc_cannon` || item.typeId === `ch:buffed_orc_cannon`) {
        const cooldown = player.getDynamicProperty(`cannonCooldown`) ?? 0;
        const multishot = item.getComponent("enchantable").getEnchantment(`multishot`)?.level ?? 0

        if (cooldown == 0) {
            player.addEffect(`slowness`, 40, { amplifier: 5, showParticles: false });
            world.playSound(`mob.cannoneer_orc.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z });
            player.playAnimation(`animation.orc_cannon.shoot`, { nextState: `none`, blendOutTime: 0, });
            player.runCommandAsync(`clear @s ch:orc_cannon 0 1`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^0.8`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^0.4`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^-0.4`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^-0.8`);
            player.runCommandAsync(`particle ch:orc_cannon_item_smoke ^-0.5 ^1.4 ^0.4`);

            if (!item.typeId.includes(`buffed_`)) {
                player.runCommandAsync(`summon ch:orc_cannon_destroyed ^-0.5 ^1.4 ^ ~-90 ~`);
                world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
            };

            player.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, -5, 0.3);

            const projectile = player.dimension.spawnEntity(`ch:bomb`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
            projectile.triggerEvent(`minecraft:player_shoot_event`);
            projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 1.6));
            item.getComponent("cooldown")?.startCooldown(player);

            if (multishot != 0) {
                const projectile2 = player.dimension.spawnEntity(`ch:bomb`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                projectile2.triggerEvent(`minecraft:player_shoot_event`);
                projectile2.setRotation({ x: player.getRotation().x, y: player.getRotation().y - 40 })
                projectile2.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 1.6), projectile2.getViewDirection()));

                const projectile3 = player.dimension.spawnEntity(`ch:bomb`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                projectile3.triggerEvent(`minecraft:player_shoot_event`);
                projectile3.setRotation({ x: player.getRotation().x, y: player.getRotation().y + 40 })
                projectile3.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 1.6), projectile3.getViewDirection()));
            }

            player.setDynamicProperty(`cannonCooldown`, 1);

            system.runTimeout(() => {
                player.setDynamicProperty(`cannonCooldown`, 0)
            }, 40)
        }
    };
    //Magic Wand
    if (item.typeId === `ch:wand` || item.typeId === `ch:buffed_wand`) {
        const hasEvilMana = world.scoreboard.getObjective(`has_evil_mana`)?.getScore(player) ?? 0
        const selectedSlot = world.scoreboard.getObjective(`evil_mana_spell`);
        const evilMana = world.scoreboard.getObjective(`evil_mana`);
        const cooldown = player.getDynamicProperty(`wandCooldown`) ?? 0

        if (hasEvilMana == 0) {
            player.sendMessage({ rawtext: [{ translate: `translation.message.no_mana_warning` }] })
        };
        //Change slot
        if (hasEvilMana == 1 && player.isSneaking) {
            if (selectedSlot?.getScore(player) == 6) {
                selectedSlot.setScore(player, 1);
                player.onScreenDisplay.setTitle(`evil_mana_spell;${selectedSlot?.getScore(player)}`)
            } else if (selectedSlot?.getScore(player) < 6) {
                selectedSlot.addScore(player, 1);
                player.onScreenDisplay.setTitle(`evil_mana_spell;${selectedSlot?.getScore(player)}`)
            }
        };
        //Abilities
        if (hasEvilMana == 1 && !player.isSneaking && cooldown == 0) {
            //Shoot
            if (selectedSlot?.getScore(player) == 1 && evilMana?.getScore(player) <= 536) {
                world.playSound(`mob.mage_orc.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.playAnimation(`animation.orc_wand.shoot`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });

                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 89);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 44);
                    }
                };

                const projectile = player.dimension.spawnEntity(`ch:energy_shoot`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                projectile.triggerEvent(`minecraft:player_shoot_event`);
                projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 1));
                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 10)
            };
            //Ground enegry
            if (selectedSlot?.getScore(player) == 2 && evilMana?.getScore(player) <= 417) {
                const entities = player.dimension.getEntities({ location: player.location, maxDistance: 20, excludeTypes: [`minecraft:arrow`, `minecraft:item`, `minecraft:xp_orb`, `minecraft:fishing_hook`, `minecraft:snowball`, `minecraft:fireball`, `minecraft:trident`], excludeFamilies: [`inanimate`, `despawn`, `projectile`], excludeNames: [player.name], excludeTags: [`creative`] });
                world.playSound(`mob.mage_orc.wand_hit2`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.playAnimation(`animation.orc_wand.ground_energy`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });

                for (const entity of entities) {
                    entity.dimension.spawnEntity(`ch:ground_energy_player`, entity.location);
                    if (!player.matches({ gameMode: `creative` })) {
                        evilMana.addScore(player, 208);
                        if (!item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 208);
                        };
                        if (item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 156);
                        }
                    }
                };
                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 20)
            };
            //Teleport
            if (selectedSlot?.getScore(player) == 3 && evilMana?.getScore(player) <= 417) {
                world.playSound(`mob.mage_orc.wand_hit2`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.playAnimation(`animation.orc_wand.ground_energy`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                world.getDimension(player.dimension.id).spawnParticle(`ch:magic_pentagram`, player.location);
                world.getDimension(player.dimension.id).spawnParticle(`ch:magic_disappear`, player.location);
                world.playSound(`mob.mage_orc.teleport`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.runCommandAsync(`spreadplayers ~ ~ 20 30 @s`);
                player.runCommandAsync(`tp @s ~ ~-0.5 ~`);
                player.runCommandAsync(`playsound mob.mage_orc.teleport @a ~ ~ ~ 9`);
                player.runCommandAsync(`particle ch:magic_pentagram ~ ~-0.5 ~`);
                player.runCommandAsync(`particle ch:magic_appear ~ ~ ~`);
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });

                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 208);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 156);
                    }
                };

                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 30)
            };
            //Energy orbs
            if (selectedSlot?.getScore(player) == 4 && evilMana?.getScore(player) <= 255) {
                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 307);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 208);
                    }
                };

                player.playAnimation(`animation.orc_wand.summon_balls`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished` });
                world.playSound(`mob.mage_orc.summon_balls`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^1 ^ ^`);
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^-1 ^ ^`);
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^1 ^ ^-1`);
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^-1 ^ ^-1`);

                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 40)
            };
            //lifesteal
            if (selectedSlot?.getScore(player) == 5 && evilMana?.getScore(player) <= 255) {
                const entities = player.dimension.getEntities({ location: player.location, maxDistance: 20, excludeTypes: [`minecraft:arrow`, `minecraft:item`, `minecraft:xp_orb`, `minecraft:fishing_hook`, `minecraft:snowball`, `minecraft:fireball`, `minecraft:trident`], excludeFamilies: [`inanimate`, `despawn`, `projectile`], excludeNames: [player.name], excludeTags: [`creative`] })[0];

                if (entities !== undefined) {
                    player.playAnimation(`animation.orc_wand.healing`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    world.playSound(`mob.mage_orc.wand_start_healing_shoot`, { x: player.location.x, y: player.location.y, z: player.location.z });
                    player.addEffect(`slowness`, 60, { amplifier: 2, showParticles: false });
                    const particleEntity = player.dimension.spawnEntity(`ch:lifesteal_summon_projectile`, player.location);

                    if (!player.matches({ gameMode: `creative` })) {
                        if (!item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 400);
                        };
                        if (item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 312);
                        }
                    };

                    const interval = system.runInterval(() => {
                        const projectile = player.dimension.spawnEntity(`ch:lifesteal_projectile_player`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                        projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 1));
                        particleEntity.teleport(player.location, { rotation: { x: player.getRotation().x, y: player.getRotation().y } })
                    }, 4)

                    player.setDynamicProperty(`wandCooldown`, 1);

                    system.runTimeout(() => {
                        player.setDynamicProperty(`wandCooldown`, 0);
                        system.clearRun(interval)
                    }, 40)
                }
            };
            //Shields
            if (selectedSlot?.getScore(player) == 6 && evilMana?.getScore(player) <= 85) {
                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 540);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 400);
                    }
                };
                player.playAnimation(`animation.orc_wand.ground_energy`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                world.playSound(`mob.mage_orc.wand_hit2`, { x: player.location.x, y: player.location.y, z: player.location.z });
                world.playSound(`mob.mage_orc.shield_activate`, { x: player.location.x, y: player.location.y, z: player.location.z });
                const shieldEntity = player.dimension.spawnEntity(`ch:shields_player`, player.location);
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });
                player.addEffect(`resistance`, 140, { amplifier: 255, showParticles: false });

                const interval = system.runInterval(() => {
                    shieldEntity.teleport(player.location)
                }, 4)

                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0);
                    system.clearRun(interval)
                }, 20)
            }
        }
    };
    //Automatic Crossbow
    if (item.typeId === `ch:automatic_crossbow`) {
        const inv = player.getComponent("inventory").container;
        const equipment = player.getComponent("minecraft:equippable");
        const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();

        let arrowFound = false;
        for (let i = 0; i < 36; i++) {
            const arrow = inv.getItem(i);
            const offHand = equipment.getEquipmentSlot(`Offhand`)?.getItem();

            if ((arrow?.typeId === `minecraft:arrow` || offHand?.typeId === `minecraft:arrow`) && arrowFound == false) {
                arrowFound = true;
                let newItem = damageItem(player, item);
                let arrowAmount = arrow?.amount ?? 0
                let arrowAmount2 = offHand?.amount ?? 0
                arrowAmount--
                arrowAmount2--
                if (mainHand?.typeId === item?.typeId && ((arrow?.amount >= 1 && arrowAmount >= 1) || (offHand?.amount >= 1 && arrowAmount2 >= 1))) {
                    const multishot = item.getComponent("enchantable").getEnchantment(`multishot`)?.level ?? 0

                    const interval = system.runInterval(() => {
                        const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();
                        const offHand = equipment.getEquipmentSlot(`Offhand`)?.getItem();
                        const arrow = inv.getItem(i);
                        const playerRot = player.getRotation()

                        if (arrow?.amount >= 1) {
                            function eachProjectile(projectile) {      
                                projectile.triggerEvent(`minecraft:entity_spawned`);
                                projectile.setProperty(`ch:rotation_y`, playerRot.y);
                                projectile.setProperty(`ch:rotation_x`, playerRot.x);
                                
                                let block = projectile.dimension.getBlock({x: projectile.location.x, y: projectile.location.y - 1, z: projectile.location.z});
                                system.runTimeout(() => {
                                    const interval = system.runInterval(() => {
                                        if (projectile.isValid() == true && block.permutation.matches(`minecraft:air`)) {
                                            const VectorSpeed = Vec3(projectile.getVelocity().x, 0, projectile.getVelocity().z);
                                            const horizontalSpeed = Vec3.magnitude(VectorSpeed)
                                            const verticalSpeed = projectile.getVelocity().y;
                                            projectile.setProperty(`ch:rotation_x`, Math.min(-verticalSpeed * 60, 90));
                                            block = projectile.dimension.getBlock({x: projectile.location.x, y: projectile.location.y - 2, z: projectile.location.z});

                                            if (horizontalSpeed < 1 && verticalSpeed == 0) {
                                                system.clearRun(interval)
                                            }
                                        } else {
                                            system.clearRun(interval)
                                        }
                                    }, 2)
                                }, 2)
                            };

                            if (multishot == 0) {
                                item.getComponent("cooldown").startCooldown(player);
                                world.playSound(`crossbow.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z })

                                const projectile = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                projectile.setRotation({ x: playerRot.x, y: playerRot.y });
                                projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 2));
                                eachProjectile(projectile);

                                if (!player.matches({ gameMode: `creative` })) {
                                    if (mainHand?.typeId === item?.typeId && (arrow !== undefined && arrowAmount >= 0) || (offHand !== undefined && offHand?.typeId === `minecraft:arrow` && arrowAmount2 >= 0)) {
                                        player.runCommandAsync(`clear @s arrow -1 1`);
                                        system.clearRun(interval);
                                        equipment.setEquipment(`Mainhand`, newItem);
                                    }
                                };
                                if (mainHand?.typeId !== item?.typeId || (arrow === undefined || arrowAmount == 0 && (offHand === undefined || offHand?.typeId !== `minecraft:arrow` || arrowAmount2 == 0))) {
                                    system.clearRun(interval);
                                    world.afterEvents.itemReleaseUse.unsubscribe(event)
                                }
                            };
                            if (multishot != 0) {
                                if ((arrow.amount >= 3 && arrowAmount >= 3) || (offHand?.amount >= 3 && arrowAmount2 >= 3)) {

                                    item.getComponent("cooldown").startCooldown(player);
                                    world.playSound(`crossbow.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z })

                                    const projectile = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                    projectile.setRotation({ x: playerRot.x, y: playerRot.y });
                                    projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 2));
                                    eachProjectile(projectile);

                                    const projectile2 = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                    projectile2.setRotation({ x: playerRot.x, y: playerRot.y - 40 });
                                    projectile2.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 2), projectile2.getViewDirection()));
                                    eachProjectile(projectile2);

                                    const projectile3 = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                    projectile3.setRotation({ x: playerRot.x, y: playerRot.y + 40 });
                                    projectile3.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 2), projectile3.getViewDirection()));
                                    eachProjectile(projectile3);

                                    if (!player.matches({ gameMode: `creative` })) {
                                        if (mainHand?.typeId === item?.typeId) {
                                            if (mainHand?.typeId === item?.typeId && (arrow !== undefined && arrowAmount >= 3) || (offHand !== undefined && offHand?.typeId === `minecraft:arrow` && arrowAmount2 >= 3)) {
                                                player.runCommandAsync(`clear @s arrow -1 3`);
                                                system.clearRun(interval);
                                                equipment.setEquipment(`Mainhand`, newItem);
                                            }
                                        };
                                    };
                                    if (mainHand?.typeId !== item?.typeId || (arrow === undefined || arrowAmount < 3 && (offHand === undefined || offHand?.typeId !== `minecraft:arrow` || arrowAmount2 < 3))) {
                                        system.clearRun(interval);
                                        world.afterEvents.itemReleaseUse.unsubscribe(event)
                                    };
                                }
                            }
                        }
                    }, 5);
                    const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                        system.clearRun(interval);
                        world.afterEvents.itemReleaseUse.unsubscribe(event);
                    });
                }
                if (!newItem) {
                    world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
                }
                break;
            }
        }
    };
});
world.afterEvents.playerInteractWithEntity.subscribe((data) => {
    const item = data.itemStack;
    const player = data.player;

    if (!item || !item.typeId.startsWith(`ch:`)) return;

    //Bardiche
    if (item.typeId === `ch:bardiche` || item.typeId === `ch:buffed_bardiche`) {

        const bardicheCooldown = world.scoreboard.getObjective(`bardiche_cooldown`);

        //Charge Attack
        if (player.isSneaking && player.isOnGround && !player.isInWater && !player.hasTag(`bardiche_attacking`) && !player.hasTag(`bardiche_charge_attack`) && bardicheCooldown?.getScore(player) < 1) {
            player.addEffect(`slowness`, 34, { amplifier: 5, showParticles: false });
            player.playAnimation(`animation.captain_orc_bardiche.charge_attack`, { nextState: `none`, stopExpression: `query.any_animation_finished`, blendOutTime: 0, controller: `controller_name` });
            world.playSound(`mob.attack.man_scream`, { x: player.location.x, y: player.location.y, z: player.location.z });
            world.playSound(`mob.attack.fast_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
            player.addTag(`bardiche_charge_attack`);
            bardicheCooldown.setScore(player, 250);

            system.runTimeout(() => {
                const interval = system.runInterval(() => {
                    const playerVel = Math.sqrt(Math.pow(player.getVelocity().x, 2) + Math.pow(player.getVelocity().z, 2));
                    const playerDir = player.getViewDirection();
                    const equipment = player.getComponent("minecraft:equippable");
                    const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();
                    const sharpness = item.getComponent("enchantable").getEnchantment(`sharpness`)?.level ?? 0

                    if (!item.typeId.includes(`buffed_`)) {
                        let newItem = damageItem(player, item);
                        if (mainHand?.typeId === item?.typeId) {
                            const fireAspect = item.getComponent("enchantable").getEnchantment(`fire_aspect`)?.level ?? 0

                            if (mainHand?.typeId === item?.typeId && fireAspect != 0) {
                                for (const entity of player.dimension.getEntities({ location: Vector.add(Vector.multiply(player.getViewDirection(), 2), player.location), maxDistance: 2, excludeNames: [player.name] })) {
                                    entity?.setOnFire(fireAspect * 4, true)
                                }
                            };
                            equipment.setEquipment(`Mainhand`, newItem);
                            player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2.5 run damage @e[name=!${player.name}, family=!despawn,r=2.5] ${sharpness + 4} entity_attack entity @s`);
                            player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2 run tp @e[name=!${player.name}, r=2,family=!despawn,family=!inanimate,family=!projectile,type=!fishing_hook,type=!arrow,c=1] ^ ^0.5 ^2 true`);
                            player.applyKnockback(playerDir.x, playerDir.z, (playerVel * 1.5 + 0.05), -0.5);
                        }
                        if (!newItem) {
                            world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
                        }
                    }
                    if (item.typeId.includes(`buffed_`)) {
                        player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2 run tp @e[name=!${player.name}, r=2,family=!despawn,family=!inanimate,family=!projectile,type=!fishing_hook,type=!arrow,c=1] ^ ^0.5 ^2 true`);
                        player.applyKnockback(playerDir.x, playerDir.z, (playerVel * 1.5 + 0.05), -0.5);
                        player.runCommandAsync(`execute as @s positioned ^ ^0.5 ^2.5 run damage @e[name=!${player.name}, family=!despawn,r=2.5] 8 entity_attack entity @s`)
                    }
                }, 1)
                system.runTimeout(() => {
                    system.clearRun(interval);
                    system.runTimeout(() => {
                        const equipment = player.getComponent("minecraft:equippable");
                        const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();
                        if (mainHand?.typeId === item?.typeId) {
                            player.runCommandAsync(`summon ch:bardiche_knockback_attack ^ ^0.5 ^2`);
                            world.playSound(`mob.attack.long_sword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                        }

                        system.runTimeout(() => {
                            world.playSound(`mob.captain_orc.break`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            player.removeTag(`bardiche_charge_attack`);
                            return;
                        }, 28.466)
                    }, 4.8)
                }, 27.4)
            }, 35)
        };
        //Basic Attack
        if (!player.isSneaking && !player.hasTag(`bardiche_charge_attack`)) {
            player.addTag(`bardiche_attacking`);
            const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;

            if (attackState == 0 && !player.hasTag(`bardiche_cant_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 1);
                player.playAnimation(`animation.captain_orc_bardiche.attack1`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });

                system.runTimeout(() => {
                    normalDamage(player, item);
                    system.runTimeout(() => {
                        const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;
                        if (attackState == 1) {
                            stopingAttack(player, item);
                        }
                    }, 12.6)
                }, 8.2);
            };
            if (attackState == 1 && !player.hasTag(`bardiche_cant_attack`) && player.hasTag(`bardiche_done_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 2);

                player.removeTag(`bardiche_done_attack`);
                player.playAnimation(`animation.captain_orc_bardiche.attack2`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });

                system.runTimeout(() => {
                    normalDamage(player, item);
                    system.runTimeout(() => {
                        const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;
                        if (attackState == 2) {
                            stopingAttack(player, item);
                        }
                    }, 11.8)
                }, 9)
            };
            if (attackState == 2 && !player.hasTag(`bardiche_cant_attack`) && player.hasTag(`bardiche_done_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 3);
                player.removeTag(`bardiche_done_attack`);
                player.playAnimation(`animation.captain_orc_bardiche.attack3`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });

                system.runTimeout(() => {
                    normalDamage(player, item);
                    system.runTimeout(() => {
                        const attackState = player.getDynamicProperty(`bardiche_attack_state`) ?? 0;
                        if (attackState == 3) {
                            stopingAttack(player, item);
                        }
                    }, 11.8)
                }, 9)
            };
            if (attackState == 3 && !player.hasTag(`bardiche_cant_attack`) && player.hasTag(`bardiche_done_attack`)) {
                player.setDynamicProperty(`bardiche_attack_state`, 4);
                player.removeTag(`bardiche_done_attack`);
                player.playAnimation(`animation.captain_orc_bardiche.attack4`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                system.runTimeout(() => {
                    verticalDamage(player, item);
                    system.runTimeout(() => {
                        stopingAttack(player, item);
                    }, 17.666)
                }, 14);
            };
            return;
        }
    };
    //Soulless Sword
    if (item.typeId === `ch:soulless_knight_sword` || item.typeId === `ch:buffed_soulless_knight_sword`) {
        const selectedSlot = world.scoreboard.getObjective(`sk_sword_ability`);
        const chargeAttack = world.scoreboard.getObjective(`sk_sword_charge`);
        const cooldown = world.scoreboard.getObjective(`sk_sword_cooldown`);
        const jumpAttack = player.getDynamicProperty(`jump_state`) ?? 0;
        const equipment = player.getComponent("minecraft:equippable");

        //Change slot selection
        if (player.isSneaking) {
            if (selectedSlot?.getScore(player) == 2) {
                selectedSlot?.setScore(player, 0);
                player.onScreenDisplay.setTitle(`sk_sword_ability;${selectedSlot?.getScore(player)}`);
                return;
            };
            if (selectedSlot?.getScore(player) < 2) {
                selectedSlot?.addScore(player, 1);
                player.onScreenDisplay.setTitle(`sk_sword_ability;${selectedSlot?.getScore(player)}`);
            }
        };
        //Abilities
        if (!player.isSneaking && (jumpAttack == 0 || jumpAttack == 3)) {
            //Basic attack
            if (selectedSlot?.getScore(player) == 0 && cooldown?.getScore(player) < 1) {
                player.addTag(`soulless_knight_sword_attacking`);
                const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;

                if (attackState == 0 && !player.hasTag(`sk_sword_cant_attack`)) {
                    player.setDynamicProperty(`sk_sword_attack_state`, 1);
                    player.playAnimation(`animation.soulless_knight_sword.attack1`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    player.addEffect(`slowness`, 25, { amplifier: 3, showParticles: false });

                    system.runTimeout(() => {
                        normalDamage(player, item);
                        system.runTimeout(() => {
                            const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;
                            if (attackState == 1) {
                                stopingAttack(player, item);
                            }
                        }, 10)
                    }, 15);
                };
                if ((attackState == 1 || attackState == 3) && !player.hasTag(`sk_sword_cant_attack`) && player.hasTag(`sk_sword_done_attack`)) {
                    player.setDynamicProperty(`sk_sword_attack_state`, 2);

                    player.removeTag(`sk_sword_done_attack`);
                    player.playAnimation(`animation.soulless_knight_sword.attack2`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    player.addEffect(`slowness`, 25, { amplifier: 3, showParticles: false });

                    system.runTimeout(() => {
                        normalDamage(player, item);
                        system.runTimeout(() => {
                            const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;
                            if (attackState == 2) {
                                stopingAttack(player, item);
                            }
                        }, 10)
                    }, 15)
                };
                if (attackState == 2 && !player.hasTag(`sk_sword_cant_attack`) && player.hasTag(`sk_sword_done_attack`)) {
                    player.setDynamicProperty(`sk_sword_attack_state`, 3);
                    player.removeTag(`sk_sword_done_attack`);
                    player.playAnimation(`animation.soulless_knight_sword.attack1_again`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    player.addEffect(`slowness`, 25, { amplifier: 3, showParticles: false });

                    system.runTimeout(() => {
                        normalDamage(player, item);
                        system.runTimeout(() => {
                            const attackState = player.getDynamicProperty(`sk_sword_attack_state`) ?? 0;
                            if (attackState == 3) {
                                stopingAttack(player, item);
                            }
                        }, 10)
                    }, 15)
                }
            };
            //Dodge
            if (selectedSlot?.getScore(player) == 1 && !player.hasTag(`soulless_knight_sword_attacking`) && player.isOnGround && chargeAttack?.getScore(player) < 1 && cooldown?.getScore(player) < 1) {
                const playerVel = Math.sqrt(Math.pow(player.getVelocity().x, 2) + Math.pow(player.getVelocity().z, 2));
                cooldown?.setScore(player, 25);
                player.playAnimation(`animation.soulless_knight_sword.dash`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                world.playSound(`mob.attack.greatsword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                if (!item.typeId.includes(`buffed_`)) {
                    player.applyKnockback(player.getVelocity().x, player.getVelocity().z, (playerVel * 15), (playerVel * 1.5))
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.applyKnockback(player.getVelocity().x, player.getVelocity().z, (playerVel * 25), (playerVel * 2.5))
                }
            };
            //Charge
            if (selectedSlot?.getScore(player) == 2 && !player.hasTag(`sk_sword_cant_attack`)) {
                player.addTag(`soulless_knight_sword_charge`);
                player.playAnimation(`animation.soulless_knight_sword.charge_attack`, { nextState: `none`, blendOutTime: 0, stopExpression: `!query.is_using_item` });
                player.addEffect(`slowness`, 12, { amplifier: 3, showParticles: false });

                const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                    system.clearRun(timeOut);
                    world.afterEvents.itemReleaseUse.unsubscribe(event);
                });

                const timeOut = system.runTimeout(() => {
                    const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                        system.clearRun(interval);
                        player.playAnimation(`animation.soulless_knight_sword.charge_attack_damage`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished` });

                        system.runTimeout(() => {
                            world.playSound(`mob.attack.greatsword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            world.playSound(`mob.attack.greatsword_heavy_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            darkSoulDamage(player, item);
                            stopingAttack(player, item);
                        }, 2);
                        world.afterEvents.itemReleaseUse.unsubscribe(event);
                    });
                    const interval = system.runInterval(() => {
                        const mainHand = equipment?.getEquipmentSlot(`Mainhand`).getItem();
                        if (mainHand?.typeId === item?.typeId) {
                            if (!item.typeId.includes(`buffed_`)) {
                                player.applyDamage(2, { cause: `magic` });
                            };
                            player.addEffect(`slowness`, 5, { amplifier: 3, showParticles: false });
                            chargeAttack?.addScore(player, 1);
                            darkSoulParticles(player, chargeAttack);
                            return;
                        };
                        system.clearRun(interval);
                        stopingAttack(player, item);
                        world.afterEvents.itemReleaseUse.unsubscribe(event);
                    }, 4)
                }, 5)
            };
        };
        //Dark Soul on Jump Attack
        if (jumpAttack == 4 && !player.isClimbing && !player.isInWater) {
            const interval = system.runInterval(() => {
                const mainHand = equipment?.getEquipmentSlot(`Mainhand`).getItem();
                if (mainHand?.typeId === item?.typeId && !player.isClimbing && !player.isInWater && !player.isOnGround) {
                    if (!item.typeId.includes(`buffed_`)) {
                        player.applyDamage(2, { cause: `magic` });
                    };
                    chargeAttack?.addScore(player, 1);
                    if (player.isOnGround || player.isInWater) {
                        system.clearRun(interval);
                    };
                    darkSoulParticles(player, chargeAttack);
                    return;
                };
                system.clearRun(interval);
                stopingAttack(player, item);
                world.afterEvents.itemReleaseUse.unsubscribe(event);
            }, 4);
            const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                system.clearRun(interval);
                world.afterEvents.itemReleaseUse.unsubscribe(event);
            });
        }
    };
    //Orc Cannon
    if (item.typeId === `ch:orc_cannon` || item.typeId === `ch:buffed_orc_cannon`) {
        const cooldown = player.getDynamicProperty(`cannonCooldown`) ?? 0;
        const multishot = item.getComponent("enchantable").getEnchantment(`multishot`)?.level ?? 0

        if (cooldown == 0) {
            player.addEffect(`slowness`, 40, { amplifier: 5, showParticles: false });
            world.playSound(`mob.cannoneer_orc.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z });
            player.playAnimation(`animation.orc_cannon.shoot`, { nextState: `none`, blendOutTime: 0, });
            player.runCommandAsync(`clear @s ch:orc_cannon 0 1`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^0.8`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^0.4`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^-0.4`);
            player.runCommandAsync(`particle ch:orc_cannon_destroy ^-0.5 ^1.4 ^-0.8`);
            player.runCommandAsync(`particle ch:orc_cannon_item_smoke ^-0.5 ^1.4 ^0.4`);

            if (!item.typeId.includes(`buffed_`)) {
                player.runCommandAsync(`summon ch:orc_cannon_destroyed ^-0.5 ^1.4 ^ ~-90 ~`);
                world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
            };

            player.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, -5, 0.3);

            const projectile = player.dimension.spawnEntity(`ch:bomb`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
            projectile.triggerEvent(`minecraft:player_shoot_event`);
            projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 1.6));
            item.getComponent("cooldown")?.startCooldown(player);

            if (multishot != 0) {
                const projectile2 = player.dimension.spawnEntity(`ch:bomb`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                projectile2.triggerEvent(`minecraft:player_shoot_event`);
                projectile2.setRotation({ x: player.getRotation().x, y: player.getRotation().y - 40 })
                projectile2.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 1.6), projectile2.getViewDirection()));

                const projectile3 = player.dimension.spawnEntity(`ch:bomb`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                projectile3.triggerEvent(`minecraft:player_shoot_event`);
                projectile3.setRotation({ x: player.getRotation().x, y: player.getRotation().y + 40 })
                projectile3.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 1.6), projectile3.getViewDirection()));
            }

            player.setDynamicProperty(`cannonCooldown`, 1);

            system.runTimeout(() => {
                player.setDynamicProperty(`cannonCooldown`, 0)
            }, 40)
        }
    };
    //Magic Wand
    if (item.typeId === `ch:wand` || item.typeId === `ch:buffed_wand`) {
        const hasEvilMana = world.scoreboard.getObjective(`has_evil_mana`)?.getScore(player) ?? 0
        const selectedSlot = world.scoreboard.getObjective(`evil_mana_spell`);
        const evilMana = world.scoreboard.getObjective(`evil_mana`);
        const cooldown = player.getDynamicProperty(`wandCooldown`) ?? 0

        if (evilMana == 0) {
            player.sendMessage({ rawtext: [{ translate: `translation.message.no_mana_warning` }] })
        };
        //Change slot
        if (hasEvilMana == 1 && player.isSneaking) {
            if (selectedSlot?.getScore(player) == 6) {
                selectedSlot.setScore(player, 1);
                player.onScreenDisplay.setTitle(`evil_mana_spell;${selectedSlot?.getScore(player)}`)
            } else if (selectedSlot?.getScore(player) < 6) {
                selectedSlot.addScore(player, 1);
                player.onScreenDisplay.setTitle(`evil_mana_spell;${selectedSlot?.getScore(player)}`)
            }
        };
        //Abilities
        if (hasEvilMana == 1 && !player.isSneaking && cooldown == 0) {
            //Shoot
            if (selectedSlot?.getScore(player) == 1 && evilMana?.getScore(player) <= 536) {
                world.playSound(`mob.mage_orc.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.playAnimation(`animation.orc_wand.shoot`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });

                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 89);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 44);
                    }
                };

                const projectile = player.dimension.spawnEntity(`ch:energy_shoot`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                projectile.triggerEvent(`minecraft:player_shoot_event`);
                projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 1));
                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 10)
            };
            //Ground enegry
            if (selectedSlot?.getScore(player) == 2 && evilMana?.getScore(player) <= 417) {
                const entities = player.dimension.getEntities({ location: player.location, maxDistance: 20, excludeTypes: [`minecraft:arrow`, `minecraft:item`, `minecraft:xp_orb`, `minecraft:fishing_hook`, `minecraft:snowball`, `minecraft:fireball`, `minecraft:trident`], excludeFamilies: [`inanimate`, `despawn`, `projectile`], excludeNames: [player.name], excludeTags: [`creative`] });
                world.playSound(`mob.mage_orc.wand_hit2`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.playAnimation(`animation.orc_wand.ground_energy`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });

                for (const entity of entities) {
                    entity.dimension.spawnEntity(`ch:ground_energy_player`, entity.location);
                    if (!player.matches({ gameMode: `creative` })) {
                        evilMana.addScore(player, 208);
                        if (!item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 208);
                        };
                        if (item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 156);
                        }
                    }
                };
                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 20)
            };
            //Teleport
            if (selectedSlot?.getScore(player) == 3 && evilMana?.getScore(player) <= 417) {
                world.playSound(`mob.mage_orc.wand_hit2`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.playAnimation(`animation.orc_wand.ground_energy`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                world.getDimension(player.dimension.id).spawnParticle(`ch:magic_pentagram`, player.location);
                world.getDimension(player.dimension.id).spawnParticle(`ch:magic_disappear`, player.location);
                world.playSound(`mob.mage_orc.teleport`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.runCommandAsync(`spreadplayers ~ ~ 20 30 @s`);
                player.runCommandAsync(`tp @s ~ ~-0.5 ~`);
                player.runCommandAsync(`playsound mob.mage_orc.teleport @a ~ ~ ~ 9`);
                player.runCommandAsync(`particle ch:magic_pentagram ~ ~-0.5 ~`);
                player.runCommandAsync(`particle ch:magic_appear ~ ~ ~`);
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });

                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 208);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 156);
                    }
                };

                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 30)
            };
            //Energy orbs
            if (selectedSlot?.getScore(player) == 4 && evilMana?.getScore(player) <= 255) {
                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 307);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 208);
                    }
                };

                player.playAnimation(`animation.orc_wand.summon_balls`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished` });
                world.playSound(`mob.mage_orc.summon_balls`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^1 ^ ^`);
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^-1 ^ ^`);
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^1 ^ ^-1`);
                player.runCommandAsync(`execute as @s at @s anchored eyes run summon ch:electric_ball_player ^-1 ^ ^-1`);

                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0)
                }, 40)
            };
            //lifesteal
            if (selectedSlot?.getScore(player) == 5 && evilMana?.getScore(player) <= 255) {
                const entities = player.dimension.getEntities({ location: player.location, maxDistance: 20, excludeTypes: [`minecraft:arrow`, `minecraft:item`, `minecraft:xp_orb`, `minecraft:fishing_hook`, `minecraft:snowball`, `minecraft:fireball`, `minecraft:trident`], excludeFamilies: [`inanimate`, `despawn`, `projectile`], excludeNames: [player.name], excludeTags: [`creative`] })[0];

                if (entities !== undefined) {
                    player.playAnimation(`animation.orc_wand.healing`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                    world.playSound(`mob.mage_orc.wand_start_healing_shoot`, { x: player.location.x, y: player.location.y, z: player.location.z });
                    player.addEffect(`slowness`, 60, { amplifier: 2, showParticles: false });
                    const particleEntity = player.dimension.spawnEntity(`ch:lifesteal_summon_projectile`, player.location);

                    if (!player.matches({ gameMode: `creative` })) {
                        if (!item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 400);
                        };
                        if (item.typeId.includes(`buffed_`)) {
                            evilMana.addScore(player, 312);
                        }
                    };

                    const interval = system.runInterval(() => {
                        const projectile = player.dimension.spawnEntity(`ch:lifesteal_projectile_player`, Vector.add(Vector.multiply(player.getViewDirection(), 1.2), { x: player.location.x, y: player.location.y + 1.5, z: player.location.z }));
                        projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 1));
                        particleEntity.teleport(player.location, { rotation: { x: player.getRotation().x, y: player.getRotation().y } })
                    }, 4)

                    player.setDynamicProperty(`wandCooldown`, 1);

                    system.runTimeout(() => {
                        player.setDynamicProperty(`wandCooldown`, 0);
                        system.clearRun(interval)
                    }, 40)
                }
            };
            //Shields
            if (selectedSlot?.getScore(player) == 6 && evilMana?.getScore(player) <= 85) {
                if (!player.matches({ gameMode: `creative` })) {
                    if (!item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 540);
                    };
                    if (item.typeId.includes(`buffed_`)) {
                        evilMana.addScore(player, 400);
                    }
                };
                player.playAnimation(`animation.orc_wand.ground_energy`, { nextState: `none`, blendOutTime: 0, stopExpression: `query.any_animation_finished`, controller: `controller_name` });
                world.playSound(`mob.mage_orc.wand_hit2`, { x: player.location.x, y: player.location.y, z: player.location.z });
                world.playSound(`mob.mage_orc.shield_activate`, { x: player.location.x, y: player.location.y, z: player.location.z });
                const shieldEntity = player.dimension.spawnEntity(`ch:shields_player`, player.location);
                player.addEffect(`slowness`, 20, { amplifier: 2, showParticles: false });
                player.addEffect(`resistance`, 140, { amplifier: 255, showParticles: false });

                const interval = system.runInterval(() => {
                    shieldEntity.teleport(player.location)
                }, 4)

                player.setDynamicProperty(`wandCooldown`, 1);

                system.runTimeout(() => {
                    player.setDynamicProperty(`wandCooldown`, 0);
                    system.clearRun(interval)
                }, 20)
            }
        }
    };
    //Automatic Crossbow
    if (item.typeId === `ch:automatic_crossbow`) {
        const inv = player.getComponent("inventory").container;
        const equipment = player.getComponent("minecraft:equippable");
        const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();

        let arrowFound = false;
        for (let i = 0; i < 36; i++) {
            const arrow = inv.getItem(i);
            const offHand = equipment.getEquipmentSlot(`Offhand`)?.getItem();

            if ((arrow?.typeId === `minecraft:arrow` || offHand?.typeId === `minecraft:arrow`) && arrowFound == false) {
                arrowFound = true;
                let newItem = damageItem(player, item);
                let arrowAmount = arrow?.amount ?? 0
                let arrowAmount2 = offHand?.amount ?? 0
                arrowAmount--
                arrowAmount2--
                if (mainHand?.typeId === item?.typeId && ((arrow?.amount >= 1 && arrowAmount >= 1) || (offHand?.amount >= 1 && arrowAmount2 >= 1))) {
                    const multishot = item.getComponent("enchantable").getEnchantment(`multishot`)?.level ?? 0

                    const interval = system.runInterval(() => {
                        const mainHand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem();
                        const offHand = equipment.getEquipmentSlot(`Offhand`)?.getItem();
                        const arrow = inv.getItem(i);
                        const playerRot = player.getRotation()

                        if (arrow?.amount >= 1) {
                            function eachProjectile(projectile) {      
                                projectile.triggerEvent(`minecraft:entity_spawned`);
                                projectile.setProperty(`ch:rotation_y`, playerRot.y);
                                projectile.setProperty(`ch:rotation_x`, playerRot.x);
                                
                                let block = projectile.dimension.getBlock({x: projectile.location.x, y: projectile.location.y - 1, z: projectile.location.z});
                                system.runTimeout(() => {
                                    const interval = system.runInterval(() => {
                                        if (projectile.isValid() == true && block.permutation.matches(`minecraft:air`)) {
                                            const VectorSpeed = Vec3(projectile.getVelocity().x, 0, projectile.getVelocity().z);
                                            const horizontalSpeed = Vec3.magnitude(VectorSpeed)
                                            const verticalSpeed = projectile.getVelocity().y;
                                            projectile.setProperty(`ch:rotation_x`, Math.min(-verticalSpeed * 60, 90));
                                            block = projectile.dimension.getBlock({x: projectile.location.x, y: projectile.location.y - 2, z: projectile.location.z});

                                            if (horizontalSpeed < 1 && verticalSpeed == 0) {
                                                system.clearRun(interval)
                                            }
                                        } else {
                                            system.clearRun(interval)
                                        }
                                    }, 2)
                                }, 2)
                            };

                            if (multishot == 0) {
                                item.getComponent("cooldown").startCooldown(player);
                                world.playSound(`crossbow.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z })

                                const projectile = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                projectile.setRotation({ x: playerRot.x, y: playerRot.y });
                                projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 2));
                                eachProjectile(projectile);

                                if (!player.matches({ gameMode: `creative` })) {
                                    if (mainHand?.typeId === item?.typeId && (arrow !== undefined && arrowAmount >= 0) || (offHand !== undefined && offHand?.typeId === `minecraft:arrow` && arrowAmount2 >= 0)) {
                                        player.runCommandAsync(`clear @s arrow -1 1`);
                                        system.clearRun(interval);
                                        equipment.setEquipment(`Mainhand`, newItem);
                                    }
                                };
                                if (mainHand?.typeId !== item?.typeId || (arrow === undefined || arrowAmount == 0 && (offHand === undefined || offHand?.typeId !== `minecraft:arrow` || arrowAmount2 == 0))) {
                                    system.clearRun(interval);
                                    world.afterEvents.itemReleaseUse.unsubscribe(event)
                                }
                            };
                            if (multishot != 0) {
                                if ((arrow.amount >= 3 && arrowAmount >= 3) || (offHand?.amount >= 3 && arrowAmount2 >= 3)) {

                                    item.getComponent("cooldown").startCooldown(player);
                                    world.playSound(`crossbow.shoot`, { x: player.location.x, y: player.location.y, z: player.location.z })

                                    const projectile = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                    projectile.setRotation({ x: playerRot.x, y: playerRot.y });
                                    projectile.applyImpulse(Vector.multiply(player.getViewDirection(), 2));
                                    eachProjectile(projectile);

                                    const projectile2 = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                    projectile2.setRotation({ x: playerRot.x, y: playerRot.y - 40 });
                                    projectile2.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 2), projectile2.getViewDirection()));
                                    eachProjectile(projectile2);

                                    const projectile3 = player.dimension.spawnEntity(`ch:automatic_crossbow_arrow`, Vector.add(Vector.multiply(player.getViewDirection(), 1), { x: player.location.x, y: player.location.y + 1.4, z: player.location.z }));
                                    projectile3.setRotation({ x: playerRot.x, y: playerRot.y + 40 });
                                    projectile3.applyImpulse(Vector.add(Vector.multiply(player.getViewDirection(), 2), projectile3.getViewDirection()));
                                    eachProjectile(projectile3);

                                    if (!player.matches({ gameMode: `creative` })) {
                                        if (mainHand?.typeId === item?.typeId) {
                                            if (mainHand?.typeId === item?.typeId && (arrow !== undefined && arrowAmount >= 3) || (offHand !== undefined && offHand?.typeId === `minecraft:arrow` && arrowAmount2 >= 3)) {
                                                player.runCommandAsync(`clear @s arrow -1 3`);
                                                system.clearRun(interval);
                                                equipment.setEquipment(`Mainhand`, newItem);
                                            }
                                        };
                                    };
                                    if (mainHand?.typeId !== item?.typeId || (arrow === undefined || arrowAmount < 3 && (offHand === undefined || offHand?.typeId !== `minecraft:arrow` || arrowAmount2 < 3))) {
                                        system.clearRun(interval);
                                        world.afterEvents.itemReleaseUse.unsubscribe(event)
                                    };
                                }
                            }
                        }
                    }, 5);
                    const event = world.afterEvents.itemReleaseUse.subscribe(() => {
                        system.clearRun(interval);
                        world.afterEvents.itemReleaseUse.unsubscribe(event);
                    });
                }
                if (!newItem) {
                    world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
                }
                break;
            }
        }
    };
});

function normalDamage(player, item) {
    const equipment = player.getComponent("minecraft:equippable");
    const mainHand = equipment?.getEquipmentSlot(`Mainhand`).getItem();
    const sharpness = item.getComponent("enchantable").getEnchantment(`sharpness`)?.level ?? 0
    const fireAspect = item.getComponent("enchantable").getEnchantment(`fire_aspect`)?.level ?? 0
    const knockback = item.getComponent("enchantable").getEnchantment(`knockback`)?.level ?? 0

    if (mainHand?.typeId === item?.typeId && (fireAspect != 0 || knockback != 0)) {
        for (const entity of player.dimension.getEntities({ excludeFamilies: [`despawn`], excludeTypes: [`minecraft:item`, `minecraft:arrow`, `minecraft:xp_orb`], location: Vector.add(Vector.multiply(player.getViewDirection(), 2), player.location), maxDistance: 2, excludeNames: [player.name] })) {
            if (fireAspect != 0) {
                entity?.setOnFire(fireAspect * 4, true)
            };
            if (knockback != 0) {
                entity?.applyKnockback(player?.getViewDirection().x, player?.getViewDirection().z, knockback, 0.5)
            }
        }
    };
    if (item.typeId === `ch:bardiche` || item.typeId === `ch:buffed_bardiche`) {
        player.addTag(`bardiche_done_attack`)

        if (!item.typeId.includes(`buffed_`)) {
            let newItem = damageItem(player, item);
            if (mainHand?.typeId === item?.typeId) {
                equipment.setEquipment(`Mainhand`, newItem);
                world.playSound(`mob.attack.long_sword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.runCommandAsync(`camerashake add @a[r=6] 1 0.2 positional`);
                player.runCommandAsync(`execute as @s positioned ^ ^1 ^2 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=2] ${sharpness + 9} entity_attack entity @s`);
                return;
            }
            if (!newItem) {
                world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
            }
        };
        if (item.typeId.includes(`buffed_`)) {
            if (mainHand?.typeId === item?.typeId) {
                world.playSound(`mob.attack.long_sword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
                player.runCommandAsync(`camerashake add @a[r=6] 1 0.2 positional`);
                player.runCommandAsync(`execute as @s positioned ^ ^1 ^2 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=2] ${sharpness + 18} entity_attack entity @s`)
            }
        }
    };
    if (item.typeId === `ch:soulless_knight_sword` || item.typeId === `ch:buffed_soulless_knight_sword`) {
        player.addTag(`sk_sword_done_attack`);
        if (mainHand?.typeId === item?.typeId) {
            world.playSound(`mob.attack.greatsword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
            player.runCommandAsync(`camerashake add @a[r=5] 1 0.3 positional`);
            if (!item.typeId.includes(`buffed_`)) {
                player.runCommandAsync(`execute as @s positioned ^ ^1 ^2 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=2] ${sharpness + 21} entity_attack entity @s`)
            };
            if (item.typeId.includes(`buffed_`)) {
                player.runCommandAsync(`execute as @s positioned ^ ^1 ^2 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=2] ${sharpness + 40} entity_attack entity @s`)
            }
        }
    }
};
function verticalDamage(player, item) {
    const block = player.dimension.getBlock({ x: player.location.x, y: player.location.y - 1, z: player.location.z }).typeId;
    const equipment = player.getComponent("minecraft:equippable");
    const mainHand = equipment?.getEquipmentSlot(`Mainhand`).getItem();
    const sharpness = item.getComponent("enchantable").getEnchantment(`sharpness`)?.level ?? 0
    const fireAspect = item.getComponent("enchantable").getEnchantment(`fire_aspect`)?.level ?? 0

    if (mainHand?.typeId === item?.typeId && fireAspect != 0) {
        for (const entity of player.dimension.getEntities({ location: Vector.add(Vector.multiply(player.getViewDirection(), 2), player.location), maxDistance: 2, excludeNames: [player.name] })) {
            entity?.setOnFire(fireAspect * 4, true)
        }
    };
    if (!item.typeId.includes(`buffed_`)) {
        let newItem = damageItem(player, item);
        if (mainHand?.typeId === item?.typeId) {
            equipment.setEquipment(`Mainhand`, newItem);
            world.playSound(`mob.attack.long_sword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
            world.playSound(`mob.attack.greatsword_impact`, { x: player.location.x, y: player.location.y, z: player.location.z });
            world.playSound(`mob.attack.greatsword_ground_impact`, { x: player.location.x, y: player.location.y, z: player.location.z });
            player.runCommandAsync(`camerashake add @a[r=6] 1 0.4 positional`);
            player.runCommandAsync(`execute as @s positioned ^ ^1 ^2 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=2] ${sharpness + 11} entity_attack entity @s`);
            if (blockTags.includes(block)) {
                const playerDir = new Vector(player.getViewDirection().x * 2, player.getViewDirection().y, player.getViewDirection().z * 2)
                world.getDimension(player.dimension.id).spawnParticle('ch:ground_explosion_no_local', Vector.add(playerDir, player.location));
            };
        }
        if (!newItem) {
            world.playSound(`random.break`, { x: player.location.x, y: player.location.y, z: player.location.z })
        }
    };
    if (item.typeId.includes(`buffed_`)) {
        if (mainHand?.typeId === item?.typeId) {
            world.playSound(`mob.attack.long_sword_whoosh`, { x: player.location.x, y: player.location.y, z: player.location.z });
            world.playSound(`mob.attack.greatsword_impact`, { x: player.location.x, y: player.location.y, z: player.location.z });
            world.playSound(`mob.attack.greatsword_ground_impact`, { x: player.location.x, y: player.location.y, z: player.location.z });
            player.runCommandAsync(`camerashake add @a[r=6] 1 0.4 positional`);
            player.runCommandAsync(`execute as @s positioned ^ ^1 ^2 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=2] ${sharpness + 22} entity_attack entity @s`);
            if (blockTags.includes(block)) {
                const playerDir = new Vector(player.getViewDirection().x * 2, player.getViewDirection().y, player.getViewDirection().z * 2)
                world.getDimension(player.dimension.id).spawnParticle('ch:ground_explosion_no_local', Vector.add(playerDir, player.location));
            }
        }
    };
};
function stopingAttack(player, item) {
    if (item.typeId === `ch:bardiche` || item.typeId === `ch:buffed_bardiche`) {
        player.addTag(`bardiche_cant_attack`);
        system.runTimeout(() => {
            player.setDynamicProperty(`bardiche_attack_state`, 0);
            player.removeTag(`bardiche_attacking`);
            player.removeTag(`bardiche_cant_attack`);
            player.removeTag(`bardiche_done_attack`);
            world.playSound(`mob.captain_orc.break`, { x: player.location.x, y: player.location.y, z: player.location.z });
            return;
        }, 3.366)
    };
    if (item.typeId === `ch:soulless_knight_sword` || item.typeId === `ch:buffed_soulless_knight_sword`) {
        player.addTag(`sk_sword_cant_attack`);
        system.runTimeout(() => {
            player.setDynamicProperty(`sk_sword_attack_state`, 0);
            player.removeTag(`soulless_knight_sword_attacking`);
            player.removeTag(`sk_sword_cant_attack`);
            player.removeTag(`sk_sword_done_attack`);
            player.removeTag(`soulless_knight_sword_charge`);
            return;
        }, 11)
    }
};
function darkSoulDamage(player, item) {
    const chargeAttack = world.scoreboard.getObjective(`sk_sword_charge`);
    const jumpAttack = player.getDynamicProperty(`jump_state`) ?? 0;
    const equipment = player.getComponent("minecraft:equippable");
    const mainHand = equipment?.getEquipmentSlot(`Mainhand`).getItem();
    const sharpness = item.getComponent("enchantable").getEnchantment(`sharpness`)?.level ?? 0
    const fireAspect = item.getComponent("enchantable").getEnchantment(`fire_aspect`)?.level ?? 0
    const knockback = item.getComponent("enchantable").getEnchantment(`knockback`)?.level ?? 0

    player.runCommandAsync(`camerashake add @a[r=5] 1 0.4 positional`);
    if (jumpAttack == 0 || 3) {
        if (mainHand?.typeId === item?.typeId) {
            if (mainHand?.typeId === item?.typeId && (fireAspect != 0 || knockback != 0)) {
                for (const entity of player.dimension.getEntities({ excludeFamilies: [`despawn`], excludeTypes: [`minecraft:item`, `minecraft:arrow`, `minecraft:xp_orb`], location: Vector.add(Vector.multiply(player.getViewDirection(), 2), player.location), maxDistance: 2, excludeNames: [player.name] })) {
                    if (fireAspect != 0) {
                        entity?.setOnFire(fireAspect * 4, true)
                    };
                    if (knockback != 0) {
                        entity?.applyKnockback(player?.getViewDirection().x, player?.getViewDirection().z, knockback, 0.5)
                    }
                }
            };
            if (chargeAttack?.getScore(player) < 4) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 17} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 17} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 34} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 34} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, 0);
            };
            if (chargeAttack?.getScore(player) >= 4 && chargeAttack?.getScore(player) < 7) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 22} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 22} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 39} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 39} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, 0);
            };
            if (chargeAttack?.getScore(player) >= 7 && chargeAttack?.getScore(player) < 11) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 27} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 27} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 44} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 44} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, 0);
            };
            if (chargeAttack?.getScore(player) >= 11) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 32} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 32} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^1.5 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 50} entity_attack entity @s`)
                    player.runCommandAsync(`execute as @s positioned ^ ^1 ^3 run damage @e[name=!${player.name}, family=!despawn,type=!item,r=1.5] ${sharpness + 50} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, 0);
            };
        };
    };
    if (jumpAttack == 4) {
        if (mainHand?.typeId === item?.typeId) {
            if (mainHand?.typeId === item?.typeId && (fireAspect != 0 || knockback != 0)) {
                for (const entity of player.dimension.getEntities({ excludeFamilies: [`despawn`], excludeTypes: [`minecraft:item`, `minecraft:arrow`], location: player.location, maxDistance: 3, excludeNames: [player.name] })) {
                    if (fireAspect != 0) {
                        entity?.setOnFire(fireAspect * 4, true)
                    };
                    if (knockback != 0) {
                        entity?.applyKnockback(entity?.getViewDirection().x, entity?.getViewDirection().z, -knockback, 0.5)
                    }
                }
            };
            if (chargeAttack?.getScore(player) < 4) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 28} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 34} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, -1);
            };
            if (chargeAttack?.getScore(player) >= 4 && chargeAttack?.getScore(player) < 7) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 31} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 39} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, -1);
            };
            if (chargeAttack?.getScore(player) >= 7 && chargeAttack?.getScore(player) < 11) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 34} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 44} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, -1);
            };
            if (chargeAttack?.getScore(player) >= 11) {
                if (!item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 37} entity_attack entity @s`)
                };
                if (item.typeId.includes(`buffed_`)) {
                    player.runCommandAsync(`execute as @s run damage @e[name=!${player.name}, family=!despawn,type=!item,r=3] ${sharpness + 50} entity_attack entity @s`)
                };
                chargeAttack.setScore(player, -1);
            };
        }
        player.setDynamicProperty(`jump_state`, 0);
    };
    return;
};
function darkSoulParticles(player, chargeAttack) {
    if (chargeAttack?.getScore(player) == 4 || chargeAttack?.getScore(player) == 7 || chargeAttack?.getScore(player) == 11) {
        player.spawnParticle(`ch:dark_soul_player_charge_next_phase`, { x: player.location.x, y: player.location.y + 1.5, z: player.location.z })
    };
    if (chargeAttack?.getScore(player) < 4) {
        const playerDir = new Vector(player.getViewDirection().x * -0.1, player.getViewDirection().y + 1, player.getViewDirection().z * -0.1)
        world.getDimension(player.dimension.id).spawnParticle('ch:dark_soul_player_charge0', Vector.add(playerDir, player.location));
        world.playSound(`mob.soulless_knight.dark_soul_effect_ambient`, { x: player.location.x, y: player.location.y, z: player.location.z }, { volume: 0.2 });
    };
    if (chargeAttack?.getScore(player) >= 4 && chargeAttack?.getScore(player) < 7) {
        const playerDir = new Vector(player.getViewDirection().x * -0.1, player.getViewDirection().y + 1, player.getViewDirection().z * -0.1)
        world.getDimension(player.dimension.id).spawnParticle('ch:dark_soul_player_charge1', Vector.add(playerDir, player.location));
        world.playSound(`mob.soulless_knight.dark_soul_effect_ambient`, { x: player.location.x, y: player.location.y, z: player.location.z }, { volume: 0.4 });
    };
    if (chargeAttack?.getScore(player) >= 7 && chargeAttack?.getScore(player) < 11) {
        const playerDir = new Vector(player.getViewDirection().x * -0.1, player.getViewDirection().y + 1, player.getViewDirection().z * -0.1)
        world.getDimension(player.dimension.id).spawnParticle('ch:dark_soul_player_charge2', Vector.add(playerDir, player.location));
        world.playSound(`mob.soulless_knight.dark_soul_effect_ambient`, { x: player.location.x, y: player.location.y, z: player.location.z }, { volume: 0.6 });
    }
    if (chargeAttack?.getScore(player) >= 11) {
        const playerDir = new Vector(player.getViewDirection().x * -0.1, player.getViewDirection().y + 1, player.getViewDirection().z * -0.1)
        world.getDimension(player.dimension.id).spawnParticle('ch:dark_soul_player_charge3', Vector.add(playerDir, player.location));
        world.playSound(`mob.soulless_knight.dark_soul_effect_ambient`, { x: player.location.x, y: player.location.y, z: player.location.z }, { volume: 3 });
    }
};
function damageItem(player, item) {
    if (!player.matches({ gameMode: `creative` })) {
        const durabilityComponent = item.getComponent("durability")
        const unbreaking = item.getComponent("enchantable").getEnchantment(`unbreaking`)?.level ?? 0

        if (durabilityComponent.damage == durabilityComponent.maxDurability) {
            return
        }
        durabilityComponent.damage += Number(Math.round(Math.random() * 100) <= durabilityComponent.getDamageChance(unbreaking))
        return item
    };
    if (player.matches({ gameMode: `creative` })) {
        return item
    }
};

//For Entities

//Practice Dummy Hurt system
world.afterEvents.entityHurt.subscribe(({ damage, hurtEntity }) => {
    //Event by AxelPvz2030
    if (hurtEntity?.typeId !== `ch:practice_dummy_ch`) return;

    const { dimension, location } = hurtEntity
    dimension.spawnEntity(`ch:practice_dummy_damage_indicator`, { x: location.x, y: location.y + 1.5, z: location.z }).nameTag = `§4${Math.floor(damage)}§r`

});
//Break Jail
world.afterEvents.entityHitEntity.subscribe((data) => {
    const player = data.damagingEntity;
    const jail = data.hitEntity;

    if (player.typeId !== `minecraft:player` || jail.typeId !== `ch:jail`) return;

    const hits = jail.getProperty(`ch:hits`) ?? 0;
    const state = jail.getProperty(`ch:state`) ?? 0;
    const trapped = jail.getProperty(`ch:trapped`) ?? false;

    if (player.matches({ gameMode: `creative` })) {
        jail.triggerEvent(`minecraft:despawn_event_event`)
    } else if (hits == 5 && state == 0 && trapped == true) {
        jail.triggerEvent(`minecraft:destroyed_event`)
    } else if (hits == 5 && state == 0 && trapped == false) {
        jail.triggerEvent(`minecraft:despawn_event_event`)
    } else if (state != 0) {
        jail.triggerEvent(`minecraft:despawn_event_event`);
    } else if (trapped == true) {
        jail.triggerEvent(`minecraft:hit_count_event`)
    }
});
//Entities Functions
system.afterEvents.scriptEventReceive.subscribe((data) => {
    const { id, sourceEntity, message, sourceBlock } = data;
    function damage(entity, normalDamage, buffedDamage) {
        if (!sourceEntity.hasTag(`buffed`)) {
            entity.applyDamage(normalDamage, { cause: `entityAttack` })
        };
        if (sourceEntity.hasTag(`buffed`)) {
            entity.applyDamage(buffedDamage, { cause: `entityAttack` })
        }
    };

    if (id === `ch:little_orc_sensor`) {
        if (sourceEntity.typeId === `ch:cannoneer_orc`) {
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == false) {
                    system.clearRun(interval);
                };
                const variant = sourceEntity?.getComponent("variant")?.value;
                const littleOrcNear = sourceEntity?.getProperty(`ch:little_orc_near`) ?? false
                if (variant == 0 && sourceEntity.target !== undefined) {
                    const littleOrc = sourceEntity.dimension.getEntities({ location: sourceEntity.location, maxDistance: 2, closest: 1, type: `ch:little_orc`, excludeTags: [`bucket`, `crossbow`] })[0];
                    if (littleOrc !== undefined) {
                        sourceEntity.setProperty(`ch:little_orc_near`, true);
                        system.clearRun(interval);
                    }
                };
                if (variant != 0 || sourceEntity.target === undefined || littleOrcNear == false || sourceEntity?.isValid() == false) {
                    system.clearRun(interval);
                }
            }, 3)
        }
    };
    if (id === `ch:has_rider`) {
        if (sourceEntity.typeId === `ch:cannoneer_orc`) {
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == true) {
                    const rider = sourceEntity?.getComponent("minecraft:rideable")?.getRiders()[0];

                    if (rider !== undefined) {
                        const riderHealth = rider?.getComponent("health").currentValue ?? 0;
                        sourceEntity?.setProperty(`ch:little_orc_near`, true);

                        if (riderHealth == 0) {
                            sourceEntity?.triggerEvent(`minecraft:not_charged_event`);
                            sourceEntity?.setProperty(`ch:buffed_rider`, false);
                            sourceEntity?.setProperty(`ch:little_orc_near`, false);
                            system.clearRun(interval)
                        };
                        if (rider.hasTag(`buffed`)) {
                            sourceEntity?.setProperty(`ch:buffed_rider`, true)
                        };
                        if (!rider.hasTag(`buffed`)) {
                            sourceEntity?.setProperty(`ch:buffed_rider`, false)
                        }
                    } else {
                        sourceEntity?.triggerEvent(`minecraft:not_charged_event`);
                        sourceEntity?.setProperty(`ch:buffed_rider`, false);
                        sourceEntity?.setProperty(`ch:little_orc_near`, false);
                        system.clearRun(interval)
                    }
                } else {
                    system.clearRun(interval)
                }
            }, 3)
        };
        if (sourceEntity.typeId === `ch:adult_orc`) {
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == true) {
                    const rider = sourceEntity?.getComponent("minecraft:rideable").getRiders()[0];
                    if (rider !== undefined) {
                        const riderHealth = rider?.getComponent("health").currentValue ?? 0;

                        if (riderHealth == 0) {
                            sourceEntity?.setProperty(`ch:buffed_rider`, false);
                            system.clearRun(interval)
                        };
                        if (rider.hasTag(`buffed`)) {
                            sourceEntity?.setProperty(`ch:buffed_rider`, true)
                        };
                        if (!rider.hasTag(`buffed`)) {
                            sourceEntity?.setProperty(`ch:buffed_rider`, false)
                        }
                    } else {
                        sourceEntity?.setProperty(`ch:buffed_rider`, false);
                        system.clearRun(interval)
                    }
                } else {
                    system.clearRun(interval)
                }
            }, 3)
        }
    };
    if (id === `ch:has_target`) {
        let target;
        target = sourceEntity.target;
        if (sourceEntity.typeId === `ch:adult_orc` || sourceEntity.typeId === `ch:little_orc`) {
            if (target?.typeId === `minecraft:villager_v2`) {
                const interval = system.runInterval(() => {
                    const sourceEntity = data.sourceEntity;
                    target = sourceEntity.target;
                    if (target?.typeId !== `minecraft:villager_v2` || target === undefined || sourceEntity?.isValid() == false || sourceEntity.hasTag(`bucket`)) {
                        system.clearRun(interval)
                    };
                    const nearVillager = sourceEntity?.dimension.getEntities({ location: sourceEntity.location, maxDistance: 2, closest: 1, type: `minecraft:villager_v2` })[0];
                    const cooldown = sourceEntity.getDynamicProperty(`cooldown`) ?? 0;
                    if (nearVillager !== undefined && cooldown == 0) {
                        sourceEntity?.setDynamicProperty(`cooldown`, 1);
                        const jailedVillager = nearVillager?.dimension.spawnEntity(`ch:slave_villager`, nearVillager.location);
                        jailedVillager?.triggerEvent(`minecraft:jail_event`);
                        world.playSound(`mob.slave_villager.open_handcuffs`, { x: jailedVillager.location.x, y: jailedVillager.location.y, z: jailedVillager.location.z })
                        nearVillager?.remove();
                        system.runTimeout(() => {
                            sourceEntity?.setDynamicProperty(`cooldown`, 0)
                        }, 15)
                    }
                }, 3)
            };
            if (sourceEntity?.typeId === `ch:little_orc`) {
                if (target?.typeId !== `minecraft:villager_v2` && target?.typeId !== `ch:practice_dummy_ch`) {
                    sourceEntity?.triggerEvent(`minecraft:can_have_bomb_or_not_event`)
                }
            }
        };
        if (sourceEntity.typeId === `ch:captain_orc`) {
            let health;
            sourceEntity.setDynamicProperty(`cooldown`, 0);
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == false) {
                    system.clearRun(interval)
                } else {
                    health = sourceEntity?.getComponent("health")?.currentValue ?? 0
                    target = sourceEntity.target;
                };
                if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                    system.clearRun(interval)
                }
            }, 5)
            const timeOut = system.runTimeout(() => {
                system.clearRun(interval);
                const interval2 = system.runInterval(() => {
                    if (sourceEntity?.isValid() == true) {
                        health = sourceEntity?.getComponent("health")?.currentValue ?? 0;
                        if (health >= 2) {
                            target = sourceEntity?.target;
                        };
                        const targetHealth = target?.getComponent("health").currentValue ?? 0;
                        if (targetHealth == 0 && target === undefined || health < 2) {
                            const timeOut = system.runTimeout(() => {
                                const cooldown = sourceEntity?.getDynamicProperty(`cooldown`) ?? 0;
                                if (target === undefined && cooldown == 0) {
                                    sourceEntity.setDynamicProperty(`cooldown`, 1);
                                    world.playSound(`mob.captain_orc.laught`, { x: sourceEntity?.location.x, y: sourceEntity?.location.y, z: sourceEntity?.location.z });
                                    system.clearRun(interval2);
                                }
                            }, 26);
                            if (health < 2) {
                                system.clearRun(interval2);
                                system.clearRun(timeOut);
                            };
                        };
                    } else {
                        system.clearRun(interval2)
                    }
                }, 5);
                if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                    system.runTimeout(() => {
                        if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                            system.clearRun(interval2)
                        }
                    }, 4)
                }
            }, 400);
            if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                system.clearRun(interval);
                system.clearRun(timeOut);
            }
        };
        if (sourceEntity.typeId === `ch:soulless_knight`) {
            if (message === `noTarget`) {
                const interval = system.runInterval(() => {
                    if (sourceEntity?.isValid() == true) {
                        target = sourceEntity.target;
                        const player = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 30, type: `minecraft:player`, closest: 1 })[0];
                        if (sourceEntity?.isValid() == true && player === undefined && target === undefined) {
                            sourceEntity?.addEffect(`instant_health`, 10, { amplifier: 0, showParticles: false })
                        } else if (target !== undefined || sourceEntity?.isValid() == false) {
                            system.clearRun(interval)
                        }
                    } else {
                        system.clearRun(interval)
                    }
                }, 5)
            } else {
                sourceEntity?.removeEffect(`instant_health`);
                let health;
                sourceEntity.setDynamicProperty(`cooldown`, 0);
                const interval = system.runInterval(() => {
                    if (sourceEntity?.isValid() == false) {
                        system.clearRun(interval)
                    } else {
                        health = sourceEntity?.getComponent("health")?.currentValue ?? 0
                        target = sourceEntity.target;
                    };
                    if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                        system.clearRun(interval)
                    }
                }, 5);
                const timeOut = system.runTimeout(() => {
                    system.clearRun(interval);
                    const interval2 = system.runInterval(() => {
                        if (sourceEntity?.isValid() == true) {
                            health = sourceEntity?.getComponent("health")?.currentValue ?? 0;
                            if (health >= 2) {
                                target = sourceEntity?.target;
                            };
                            const targetHealth = target?.getComponent("health").currentValue ?? 0;
                            if (targetHealth == 0 && target === undefined || health < 2) {
                                const timeOut = system.runTimeout(() => {
                                    const cooldown = sourceEntity?.getDynamicProperty(`cooldown`) ?? 0;
                                    if (target === undefined && cooldown == 0) {
                                        sourceEntity?.setDynamicProperty(`cooldown`, 1);
                                        sourceEntity?.triggerEvent(`minecraft:celebrate_victory_event`);
                                        system.clearRun(interval2);
                                    }
                                }, 26);
                                if (health < 2) {
                                    system.clearRun(interval2);
                                    system.clearRun(timeOut);
                                }
                            }
                        } else {
                            system.clearRun(interval)
                        }
                    }, 5);
                    if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                        system.runTimeout(() => {
                            if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                                system.clearRun(interval2);
                            }
                        }, 4)
                    }
                }, 1200);
                if (target === undefined || health < 2 || sourceEntity?.isValid() == false) {
                    system.clearRun(interval);
                    system.clearRun(timeOut)
                }
            }
        }
    };
    if (id === `ch:strong_attack`) {
        function knockback() {
            function damage(entity) {
                if (!sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(4, { cause: `entityAttack` })
                };
                if (sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(8, { cause: `entityAttack` })
                }
            };
            const entityDir = new Vector(sourceEntity.getViewDirection().x * X, sourceEntity.getViewDirection().y * Y, sourceEntity.getViewDirection().z * Z);
            const loc = new Vector(sourceEntity.location.x, sourceEntity.location.y + 0.1, sourceEntity.location.z)
            const location = Vector.add(entityDir, loc);
            const entities = sourceEntity.dimension.getEntities({ location: location, maxDistance: 2, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
            world.getDimension(sourceEntity.dimension.id).spawnParticle(`ch:ground_stomp`, location);
            world.playSound(`mob.captain_orc.stomp`, location);
            entities.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                    entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * 1.5, y: 0.2, z: sourceEntity?.getViewDirection().z * 1.5 });
                    damage(entity)
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(sourceEntity?.getViewDirection().x, sourceEntity?.getViewDirection().z, 1.5, 0.2);
                    damage(entity)
                }
            })
        };
        let X = 0;
        let Y = 0;
        let Z = 0;
        system.runTimeout(() => {
            X = 1;
            Z = 1;
            knockback();
            system.runTimeout(() => {
                X = 2;
                Z = 2;
                knockback();
                system.runTimeout(() => {
                    X = 3;
                    Z = 3;
                    knockback();
                    system.runTimeout(() => {
                        X = 4;
                        Z = 4;
                        knockback();
                    }, 4)
                }, 4)
            }, 4)
        }, 2)
    };
    if (id === `ch:jumpComboAttack`) {
        function damage(entity) {
            if (!sourceEntity.hasTag(`buffed`)) {
                entity.applyDamage(8, { cause: `entityAttack` })
            };
            if (sourceEntity.hasTag(`buffed`)) {
                entity.applyDamage(14, { cause: `entityAttack` })
            }
        };
        if (message == "up") {
            const location = Vector.multiply(sourceEntity.getViewDirection(), 1.2);

            const entities = sourceEntity?.dimension.getEntities({ location: Vector.add(location, sourceEntity.location), excludeTypes: [sourceEntity.typeId], maxDistance: 3, excludeFamilies: [`inanimate`, `despawn`] });
            entities?.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                    entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * 1.5, y: 1.1, z: sourceEntity?.getViewDirection().z * 1.5 });
                    damage(entity)
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(sourceEntity?.getViewDirection().x, sourceEntity?.getViewDirection().z, 2, 1.1);
                    damage(entity)
                }
            })
        };
        if (message == "down") {
            const location = Vector.multiply(sourceEntity?.getViewDirection(), 1.5);

            const entities = sourceEntity?.dimension.getEntities({ location: Vector.add(location, sourceEntity.location), excludeTypes: [sourceEntity.typeId], maxDistance: 3, excludeFamilies: [`inanimate`, `despawn`] });
            entities?.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                    entity.applyImpulse({ x: sourceEntity.getViewDirection().x * 2, y: -1.1, z: sourceEntity.getViewDirection().z * 2 });
                    damage(entity)
                };
                if (entity.typeId === `minecraft:player`) {
                    entity.applyKnockback(sourceEntity.getViewDirection().x, sourceEntity.getViewDirection().z, 2, -1.1);
                    damage(entity)
                }
            })
        }
    };
    if (id === `ch:jumpAttack`) {
        function knockback(coordinates) {
            function damage(entity) {
                if (!sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(4, { cause: `entityAttack` })
                };
                if (sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(8, { cause: `entityAttack` })
                }
            };
            coordinates.forEach((coords) => {
                const location = new Vector(sourceEntity.location.x + coords.x, sourceEntity.location.y + coords.y, sourceEntity.location.z + coords.z);
                const entities = sourceEntity.dimension.getEntities({ location: location, maxDistance: 2, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
                world.getDimension(sourceEntity.dimension.id).spawnParticle(`ch:ground_stomp`, location);
                world.playSound(`mob.captain_orc.stomp`, location);
                entities.forEach((entity) => {
                    if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                        entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * 0.7, y: 0.6, z: sourceEntity?.getViewDirection().z * 0.7 });
                        damage(entity)
                    };
                    if (entity?.typeId === `minecraft:player`) {
                        entity.applyKnockback(sourceEntity?.getViewDirection().x, sourceEntity?.getViewDirection().z, 1.5, 0.9);
                        damage(entity)
                    }
                })
            })
        };
        system.runTimeout(() => {
            const coordinates = [
                { x: 0, y: 0.1, z: -3 },
                { x: 3, y: 0.1, z: 2 },
                { x: 3, y: 0.1, z: 3 },
                { x: 1, y: 0.1, z: -3 },
                { x: 3, y: 0.1, z: 0 },
                { x: -3, y: 0.1, z: 1 },
                { x: -3, y: 0.1, z: 0 },
                { x: -3, y: 0.1, z: -1 },
                { x: -2, y: 0.1, z: -2 },
                { x: 0, y: 0.1, z: 3 },
                { x: 1, y: 0.1, z: 3 }
            ];
            knockback(coordinates);
            system.runTimeout(() => {
                const coordinates = [
                    { x: 0, y: 0.1, z: 4 },
                    { x: 1, y: 0.1, z: 4 },
                    { x: -2, y: 0.1, z: -4 },
                    { x: -3, y: 0.1, z: 3 },
                    { x: -3, y: 0.1, z: 4 },
                    { x: 4, y: 0.1, z: -2 },
                    { x: 4, y: 0.1, z: -1 }
                ];
                knockback(coordinates);
                system.runTimeout(() => {
                    const coordinates = [
                        { x: 1, y: 0.1, z: 5 },
                        { x: 0, y: 0.1, z: -5 },
                        { x: -1, y: 0.1, z: -5 },
                        { x: 4, y: 0.1, z: 4 },
                        { x: 5, y: 0.1, z: 3 },
                        { x: 5, y: 0.1, z: 2 },
                        { x: -4, y: 0.1, z: 0 },
                        { x: -4, y: 0.1, z: 1 },
                        { x: -5, y: 0.1, z: -1 }
                    ];
                    knockback(coordinates);
                }, 4);
            }, 4)
        }, 4)
    };
    if (id === `ch:littleOrcOnRide`) {
        const interval = system.runInterval(() => {
            if (sourceEntity?.isValid() == false) {
                system.clearRun(interval)
            } else {
                const rideEntity = sourceEntity?.getComponent("riding")
                let ride;
                if (rideEntity !== undefined) {
                    ride = rideEntity?.entityRidingOn;
                    const rideProp = sourceEntity?.getProperty(`ch:ride_entity`)

                    if (ride?.typeId === `ch:adult_orc` && rideProp != 1) {
                        sourceEntity?.triggerEvent(`minecraft:is_riding_event`);
                        sourceEntity?.setProperty(`ch:ride_entity`, 1);
                    };
                    if (ride?.typeId === `ch:cannoneer_orc` && rideProp != 2) {
                        sourceEntity?.setProperty(`ch:ride_entity`, 2);
                    };
                    if ((ride?.typeId !== `ch:adult_orc` && ride?.typeId !== `ch:cannoneer_orc`) || ride === undefined || sourceEntity?.isValid() == false) {
                        sourceEntity?.setProperty(`ch:ride_entity`, 0);
                        sourceEntity?.triggerEvent(`minecraft:not_riding_event`);
                        system.clearRun(interval)
                    }
                } else {
                    sourceEntity?.setProperty(`ch:ride_entity`, 0);
                    sourceEntity?.triggerEvent(`minecraft:not_riding_event`);
                    system.clearRun(interval)
                }
            }
        }, 5)
    };
    if (id === `ch:captainOrcKnockback`) {
        if (message === `roar`) {
            function damage(entity) {
                if (!sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(6, { cause: `entityAttack` })
                };
                if (sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(10, { cause: `entityAttack` })
                }
            };
            const entities = sourceEntity.dimension.getEntities({ location: sourceEntity.location, maxDistance: 3, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
            entities.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                    entity.applyImpulse({ x: entity?.getViewDirection().x * -1.5, y: 0.2, z: entity?.getViewDirection().z * -1.5 });
                    damage(entity)
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(entity?.getViewDirection().x, entity?.getViewDirection().z, -1.5, 0.2);
                    damage(entity)
                }
            })
        };
        if (message !== `roar` && message !== `vertical` && message !== `stomp`) {
            function damage(entity) {
                if (!sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(11, { cause: `entityAttack` })
                };
                if (sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(20, { cause: `entityAttack` })
                }
            };
            const entityDir = new Vector(sourceEntity.getViewDirection().x * message, sourceEntity.getViewDirection().y * message, sourceEntity.getViewDirection().z * message);
            const location = Vector.add(entityDir, sourceEntity.location);
            const entities = sourceEntity?.dimension.getEntities({ location: location, maxDistance: 3, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
            entities.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                    entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * 1.5, y: 0.5, z: sourceEntity?.getViewDirection().z * 1.5 });
                    damage(entity)
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(sourceEntity?.getViewDirection().x, sourceEntity?.getViewDirection().z, 3, 0.5);
                    damage(entity)
                }
            })
        };
        if (message === `vertical`) {
            function damage(entity) {
                if (!sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(11, { cause: `entityAttack` })
                };
                if (sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(20, { cause: `entityAttack` })
                }
            };
            const entityDir = new Vector(sourceEntity.getViewDirection().x * 1, sourceEntity.getViewDirection().y * 1, sourceEntity.getViewDirection().z * 1);
            const location = Vector.add(entityDir, sourceEntity.location);
            const entities = sourceEntity?.dimension.getEntities({ location: location, maxDistance: 3, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
            entities.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                    entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * 0.6, y: 1, z: sourceEntity?.getViewDirection().z * 0.6 });
                    damage(entity)
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(sourceEntity?.getViewDirection().x, sourceEntity?.getViewDirection().z, 0.6, 1);
                    damage(entity)
                }
            })
        };
        if (message === `stomp`) {
            function damage(entity) {
                if (!sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(6, { cause: `entityAttack` })
                };
                if (sourceEntity.hasTag(`buffed`)) {
                    entity.applyDamage(10, { cause: `entityAttack` })
                }
            };
            const entities = sourceEntity.dimension.getEntities({ location: sourceEntity.location, maxDistance: 5, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
            entities.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`] }))) {
                    entity.applyImpulse({ x: entity?.getViewDirection().x * -3, y: 0.2, z: entity?.getViewDirection().z * -3 });
                    damage(entity)
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(entity?.getViewDirection().x, entity?.getViewDirection().z, -7, 0.6);
                    damage(entity)
                }
            })
        };
    };
    if (id === `ch:captainOrcSurround`) {
        const interval = system.runInterval(() => {
            const target = sourceEntity?.target;
            const variant = sourceEntity?.getComponent("variant")?.value;

            if (sourceEntity?.isValid() == true && variant == 3 && target !== undefined) {
                angle(sourceEntity, target);
            } else {
                system.clearRun(interval)
            }
        }, 1)
    }
    if (id === `ch:onDeathState`) {
        const health = sourceEntity?.getComponent("health");

        health.setCurrentValue(1)
    };
    if (id === `ch:avoid`) {
        const [horizontalForce, verticalForce] = message.split(' ');

        const horizontalForceNum = parseFloat(horizontalForce);
        const verticalForceNum = parseFloat(verticalForce);

        if (!isNaN(horizontalForceNum) && !isNaN(verticalForceNum)) {
            sourceEntity?.applyImpulse({ x: sourceEntity.getViewDirection().x * horizontalForceNum, y: verticalForceNum, z: sourceEntity.getViewDirection().z * horizontalForceNum })
        }
    };
    if (id === `ch:avoidLocal`) {
        const split = message.split(' ');
        const localCoords = { x: parseFloat(split[0]), y: parseFloat(split[1]), z: parseFloat(split[2]) };

        const zVec = sourceEntity?.getViewDirection();
        const xVec = Vec3(zVec.z, 0, -zVec.x).normalized;
        const yVec = Vec3.cross(zVec, xVec).normalized;

        // Calcular el impulso en cada eje basado en las coordenadas locales
        const impulseX = { x: xVec.x * localCoords.x, y: xVec.y * localCoords.x, z: xVec.z * localCoords.x };
        const impulseY = { x: yVec.x * localCoords.y, y: yVec.y * localCoords.y, z: yVec.z * localCoords.y };
        const impulseZ = { x: zVec.x * localCoords.z, y: zVec.y * localCoords.z, z: zVec.z * localCoords.z };

        // Sumar los impulsos para obtener el impulso total
        const totalImpulse = { x: impulseX.x + impulseY.x + impulseZ.x, y: localCoords.y, z: impulseX.z + impulseY.z + impulseZ.z };

        // Aplicar el impulso total a la entidad
        sourceEntity?.applyImpulse(totalImpulse);
    };
    if (id === `ch:knockbackDamage`) {
        const [distance, horizontalForce, verticalForce, normalDamage, buffedDamage] = message.split(' ');

        // Convert the text to number
        const distanceNum = parseFloat(distance);
        const horizontalForceNum = parseFloat(horizontalForce);
        const verticalForceNum = parseFloat(verticalForce);
        const normalDamageNum = parseFloat(normalDamage);
        const buffedDamageNum = parseFloat(buffedDamage);

        if (!isNaN(distanceNum) && !isNaN(horizontalForceNum) && !isNaN(verticalForceNum) && !isNaN(normalDamageNum) && !isNaN(buffedDamageNum)) {
            const entityDir = new Vector(sourceEntity.getViewDirection().x * distanceNum, sourceEntity.getViewDirection().y * distanceNum, sourceEntity.getViewDirection().z * distanceNum);
            const entities = sourceEntity?.dimension.getEntities({ location: Vector.add(entityDir, sourceEntity?.location), maxDistance: 3, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
            entities.forEach((entity) => {
                if (sourceEntity?.matches({ families: [`orc`] })) {
                    if (entity?.typeId !== `minecraft:player` && (entity?.matches({ excludeFamilies: [`orc`] }) || entity?.matches({ families: [`little_orc`], excludeTags: [`riding`] }))) {
                        entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * horizontalForceNum, y: verticalForceNum, z: sourceEntity?.getViewDirection().z * horizontalForceNum });
                        damage(entity, normalDamageNum, buffedDamageNum)
                    };
                } else {
                    if (entity?.typeId !== `minecraft:player`) {
                        entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * horizontalForceNum, y: verticalForceNum, z: sourceEntity?.getViewDirection().z * horizontalForceNum });
                        damage(entity, normalDamageNum, buffedDamageNum)
                    };
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(sourceEntity?.getViewDirection().x, sourceEntity?.getViewDirection().z, horizontalForceNum, verticalForceNum);
                    damage(entity, normalDamageNum, buffedDamageNum)
                }
            })
        }
    };
    if (id === `ch:knockbackDamageRadius`) {
        function damage(entity) {
            if (!sourceEntity.hasTag(`buffed`)) {
                entity.applyDamage(normalDamage, { cause: `entityAttack` })
            };
            if (sourceEntity.hasTag(`buffed`)) {
                entity.applyDamage(buffedDamage, { cause: `entityAttack` })
            }
        };

        const [radiusMessage, horizontalForce, verticalForce, normalDamageMessage, buffedDamageMessage] = message.split(' ');

        const radius = parseFloat(radiusMessage);
        const horizontalForceNum = parseFloat(horizontalForce);
        const verticalForceNum = parseFloat(verticalForce);
        const normalDamage = parseFloat(normalDamageMessage);
        const buffedDamage = parseFloat(buffedDamageMessage);

        if (sourceEntity?.typeId === `ch:soulless_knight`) {
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == true) {
                    knockback()
                } else {
                    system.clearRun(interval)
                }
            }, 1);
            system.runTimeout(() => {
                if (sourceEntity?.isValid() == true) {
                    system.clearRun(interval)
                }
            }, 106.766)

        };
        function knockback() {
            const entities = sourceEntity.dimension.getEntities({ location: sourceEntity?.location, maxDistance: radius, excludeTypes: [sourceEntity.typeId], excludeFamilies: [`inanimate`, `despawn`] });
            entities.forEach((entity) => {
                if (entity?.typeId !== `minecraft:player`) {
                    entity.applyImpulse({ x: sourceEntity?.getViewDirection().x * horizontalForceNum, y: verticalForceNum, z: sourceEntity?.getViewDirection().z * horizontalForceNum });
                    damage(entity)
                };
                if (entity?.typeId === `minecraft:player`) {
                    entity.applyKnockback(sourceEntity?.getViewDirection().x, sourceEntity?.getViewDirection().z, horizontalForceNum, verticalForceNum);
                    damage(entity)
                }
            })
        };
    };
    if (id === `ch:can_dust`) {
        const block = sourceEntity?.dimension.getBlock({ x: sourceEntity?.location.x, y: sourceEntity?.location.y - 1, z: sourceEntity?.location.z }).typeId;

        if (blockTags.includes(block)) {
            sourceEntity?.setProperty(`ch:can_dust`, true);
            system.runTimeout(() => {
                let canDust;
                if (sourceEntity?.isValid() == true) {
                    canDust = sourceEntity?.getProperty(`ch:can_dust`) ?? false
                };
                if ((canDust == true || canDust === undefined) && sourceEntity?.isValid() == true) {
                    sourceEntity?.setProperty(`ch:can_dust`, false)
                }
            }, 100)
        }
    };
    if (id === `ch:nearVillagerSensor`) {
        const interval = system.runInterval(() => {
            if (sourceEntity?.isValid() == true) {
                const entities = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 40, type: `minecraft:villager_v2` })[0];
                const inVillage = sourceEntity?.getProperty(`ch:in_village`) ?? false;

                if (entities === undefined || inVillage == false || sourceEntity?.isInWater || sourceEntity?.getComponent("riding")) {
                    sourceEntity?.setProperty(`ch:near_villager`, false);
                    system.clearRun(interval)
                } else {
                    sourceEntity?.setProperty(`ch:near_villager`, true)
                }
            } else {
                system.clearRun(interval)
            }
        }, 5)
    };
    if (id === `ch:backToThrone`) {
        const timeOut = system.runTimeout(() => {
            const attackState = sourceEntity?.getProperty(`ch:attack_state`) ?? `none`;
            const throne = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 30, type: `ch:orc_throne` })[0];
            const target = sourceEntity?.target;

            if (attackState == `none` && throne !== undefined && (!target || target === undefined)) {
                sourceEntity?.triggerEvent(`minecraft:back_to_throne_event`);
                system.clearRun(interval)
            }
        }, 1200);
        const interval = system.runInterval(() => {
            if (sourceEntity?.isValid() == false) {
                system.clearRun(timeOut);
                system.clearRun(interval)
            };
            if (sourceEntity?.isValid() == true) {
                const target = sourceEntity?.target;
                if (target && target !== undefined) {
                    system.clearRun(timeOut);
                    system.clearRun(interval)
                }
            }
        }, 20)
    };
    if (id === `ch:generateShields`) {
        sourceEntity?.runCommandAsync(`tag @e[family=orc, r=40] remove shield_break`)
        const interval = system.runInterval(() => {
            if (sourceEntity.isValid() == false) {
                system.clearRun(interval)
            };
            if (sourceEntity.isValid() == true) {
                const orcs = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 34, families: [`orc`], excludeTags: [`shield_break`], excludeTypes: [`ch:mage_orc`] });
                const mage = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 30, type: `ch:mage_orc`, closest: 1 })[0];
                const attackState = mage?.getProperty(`ch:attack_state`) ?? `none`
                angle(sourceEntity, mage);
                distance(sourceEntity, mage);

                orcs.forEach((orc) => {
                    const shieldGenerator = orc?.dimension.getEntities({ location: orc?.location, maxDistance: 30, type: `ch:shield_generator` })[0];

                    if (shieldGenerator !== undefined) {
                        orc?.setProperty(`ch:shield`, true);
                        angle(orc, shieldGenerator);
                        distance(orc, shieldGenerator);
                    };
                    if (shieldGenerator === undefined || orc.hasTag(`shield_break`)) {
                        orc?.setProperty(`ch:shield`, false);
                    }
                });
                if (mage === undefined || (attackState != `shielding` && attackState != `shields` && attackState != `shields_shoot`) || !orcs || orcs.length == 0) {
                    mage?.triggerEvent(`minecraft:force_stop_shielding_event`);
                    sourceEntity?.runCommandAsync(`stopsound @a mob.mage_orc.shield_loop`);
                    world.playSound(`mob.mage_orc.shield_orb_destroy`, { x: sourceEntity?.location.x, y: sourceEntity?.location.y, z: sourceEntity?.location.z });
                    sourceEntity?.runCommandAsync(`event entity @e[family=orc, r=40] minecraft:stop_shield_event`)
                    system.clearRun(interval);
                    system.runTimeout(() => {
                        sourceEntity?.remove();
                    }, 1)
                }
            }
        }, 1)
    };
    if (id === `ch:jailTrapped`) {
        const interval = system.runInterval(() => {
            if (sourceEntity?.isValid() == false) {
                system.clearRun(interval)
            } else {
                const jail = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 2, type: `ch:jail`, closest: 1 })[0];
                const isTrapped = jail?.getProperty(`ch:trapped`) ?? false;
                const state = jail?.getProperty(`ch:state`) ?? 0;

                if (isTrapped == false || state != 0 || !sourceEntity?.hasTag(`trapped`)) {
                    system.clearRun(interval)
                } else {
                    sourceEntity?.teleport(jail?.location);
                }
            }
        }, 5)
    };
    if (id === `ch:findBell`) {
        getBlock();
        async function getBlock() {
            const blockFound = await GetBlockInRadius(
                { x: sourceEntity?.location.x, y: sourceEntity?.location.y, z: sourceEntity?.location.z },
                "minecraft:bell",
                5,
                world.getDimension(sourceEntity?.dimension.id)
            );
            if (blockFound) {
                if (sourceEntity.isValid() == true) {
                    sourceEntity?.setProperty(`ch:bell`, true)
                }
            }
        }
    };
    if (id === `ch:soulless_knight`) {
        const [messages, numMessage] = message.split(' ');
        const num = parseFloat(numMessage);
        if (messages === `nearPlayerSensor`) {
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == true) {
                    const player = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 50, type: `minecraft:player`, closest: 1 })[0];
                    const variant = sourceEntity?.getComponent("variant")?.value ?? 0;
                    const isTamed = sourceEntity?.getComponent("isTamed");
                    const target = sourceEntity?.target;
                    const health = sourceEntity?.getComponent("health").currentValue;

                    if (player !== undefined) {
                        sourceEntity?.setProperty(`ch:player_near`, true)
                    };
                    if (num == 1) {
                        if (player === undefined || variant == 1 || isTamed || !target || health <= 1100) {
                            sourceEntity?.setProperty(`ch:player_near`, false)
                        }
                    };
                    if (num == 2) {
                        if (player === undefined || variant == 1 || isTamed || !target || health > 1100) {
                            sourceEntity?.setProperty(`ch:player_near`, false)
                        }
                    }
                } else {
                    system.clearRun(interval)
                }
            }, 5)
        }
    };
    if (id === `ch:target_altitude`) {
        function targetFunc() {
            target = sourceEntity?.target;
            const distance = Math.round(target?.location.y - sourceEntity?.location.y);
            const targetAltitudeProp = sourceEntity?.getProperty(`ch:target_altitude`) ?? false;

            if (condition === `greaterOrEqual`) {
                if (sourceEntity?.typeId === `ch:soulless_knight`) {
                    const targetDistance = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 20, closest: 1, type: target.typeId })[0];
                    if (distance >= neededDistance && targetDistance !== undefined) {
                        sourceEntity?.setProperty(`ch:target_altitude`, true)
                    } else if (distance < neededDistance && targetAltitudeProp == true && targetDistance !== undefined) {
                        sourceEntity?.setProperty(`ch:target_altitude`, false)
                    }
                }
            };
        }
        let target;
        const [condition, distanceMessage] = message.split(' ');
        const neededDistance = parseFloat(distanceMessage);

        const interval = system.runInterval(() => {
            if (sourceEntity?.isValid() == true) {
                if (target !== undefined) {
                    targetFunc();
                } else {
                    system.clearRun(interval)
                }
            } else {
                system.clearRun(interval)
            }
        }, 5)
    };
    if (id === `ch:isTargetQuantity`) {
        const mobQuantity = parseFloat(message);
        const interval = system.runInterval(() => {
            if (sourceEntity?.isValid() == true) {
                const target = sourceEntity?.target;
                if (target !== undefined) {
                    let targetQuantity = 0;
                    const targetQuantityProp = sourceEntity?.getProperty(`ch:target_quantity`) ?? false;
                    const variant = sourceEntity?.getComponent("variant").value;
                    const entities = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 20, excludeTypes: [`minecraft:item`, `minecraft:xp`, `minecraft:arrow`, `minecraft:trident`], excludeFamilies: [`despawn`, `inanimate`, `projectile`] });
                    entities.forEach((entity) => {
                        const target = entity?.target;

                        if (target !== undefined) {
                            if (target.typeId === `ch:soulless_knight`) {
                                targetQuantity = targetQuantity + 1
                            } else return;
                        } else return;
                    });
                    if (targetQuantity >= mobQuantity) {
                        sourceEntity?.setProperty(`ch:target_quantity`, true);
                        if (variant == 19 && !sourceEntity?.isInWater && !sourceEntity?.hasTag(`dk_explosion_cooldown`)) {
                            sourceEntity?.triggerEvent(`minecraft:phase2_area_explosion_event`)
                        }
                    } else if (targetQuantity < mobQuantity && targetQuantityProp == true) {
                        sourceEntity?.setProperty(`ch:target_quantity`, false)
                    }
                } else {
                    system.clearRun(interval)
                }
            } else {
                system.clearRun(interval)
            }
        }, 5)
    };
    if (id === `ch:killInanimateMounts`) {
        const rideEntity = sourceEntity?.getComponent("riding");
        if (rideEntity !== undefined) {
            const ride = rideEntity?.entityRidingOn;

            if (ride.typeId === `minecraft:boat` || ride.typeId === `minecraft:minecart`) {
                ride.kill()
            }
        } else return;
    };
    if (id === 'ch:structures') {
        const [structure, type] = message.split(' ');
        const ignoredBlockTypes = ['minecraft:air', 'minecraft:acacia_log', 'minecraft:birch_log', 'minecraft:cherry_log', 'minecraft:spruce_log', 'minecraft:oak_log', 'minecraft:dark_oak_log', 'ch:birch_stake', 'ch:cherry_stake', 'ch:spruce_stake', 'ch:oak_stake', 'ch:dark_oak_stake', 'minecraft:acacia_leaves', 'minecraft:birch_leaves', 'minecraft:oak_leaves', 'minecraft:dark_oak_leaves', 'minecraft:cherry_leaves', 'minecraft:spruce_leaves', 'minecraft:acacia_slab', 'minecraft:birch_slab', 'minecraft:oak_slab', 'minecraft:dark_oak_slab', 'minecraft:cherry_slab', 'minecraft:spruce_slab', 'minecraft:wooden_slab', 'minecraft:spruce_trapdoor', 'minecraft:trapdoor', 'minecraft:dark_oak_trapdoor', 'minecraft:birch_trapdoor', 'minecraft:cherry_trapdoor', 'minecraft:cherry_leaves', 'minecraft:pink_petals', 'minecraft:vine', 'minecraft:tallgrass', 'minecraft:birch_planks', 'minecraft:cherry_planks', 'minecraft:spruce_planks', 'minecraft:oak_planks', 'minecraft:dark_oak_planks', 'minecraft:snow', 'minecraft:snow_layer', 'minecraft:powder_snow', 'minecraft:birch_stairs', 'minecraft:cherry_stairs', 'minecraft:spruce_stairs', 'minecraft:oak_stairs', 'minecraft:dark_oak_stairs', 'minecraft:stone_block_slab', 'minecraft:blackstone_slab', 'minecraft:cobblestone', 'minecraft:birch_fence', 'minecraft:cherry_fence', 'minecraft:spruce_fence', 'minecraft:oak_fence', 'minecraft:dark_oak_fence', 'minecraft:double_plant', 'minecraft:red_flower', 'minecraft:yellow_flower', 'ch:thatched_roof', 'ch:thatched_block', 'minecraft:birch_slab', 'minecraft:cherry_slab', 'minecraft:spruce_slab', 'minecraft:oak_slab', 'minecraft:dark_oak_slab', 'minecraft:birch_wood', 'minecraft:cherry_wood', 'minecraft:spruce_wood', 'minecraft:oak_wood', 'minecraft:dark_oak_wood', 'minecraft:stripped_birch_wood', 'minecraft:stripped_cherry_wood', 'minecraft:stripped_spruce_wood', 'minecraft:stripped_oak_wood', 'minecraft:stripped_dark_oak_wood'];

        if (structure === 'orc_camp' && type === 'walls') {
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == true) {
                    const player = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 50, closest: 1, type: `minecraft:player` })[0];
                    if (player !== undefined) {
                        system.clearRun(interval);

                        const sourceX = sourceEntity?.location.x;
                        const sourceY = sourceEntity?.location.y;
                        const sourceZ = sourceEntity?.location.z;

                        const specificCoordinates = [
                            { x: sourceX + 1, y: 0, z: sourceZ + 11 },
                            { x: sourceX - 2, y: 0, z: sourceZ + 11 },
                            { x: sourceX + 1, y: 0, z: sourceZ - 13 },
                            { x: sourceX - 2, y: 0, z: sourceZ - 13 },
                            { x: sourceX + 2, y: 0, z: sourceZ + 10 },
                            { x: sourceX - 3, y: 0, z: sourceZ + 10 },
                            { x: sourceX + 4, y: 0, z: sourceZ + 10 },
                            { x: sourceX + 5, y: 0, z: sourceZ + 9 },
                            { x: sourceX + 6, y: 0, z: sourceZ + 8 },
                            { x: sourceX + 7, y: 0, z: sourceZ + 8 },
                            { x: sourceX + 8, y: 0, z: sourceZ + 7 },
                            { x: sourceX + 9, y: 0, z: sourceZ + 6 },
                            { x: sourceX + 10, y: 0, z: sourceZ + 5 },
                            { x: sourceX + 10, y: 0, z: sourceZ + 4 },
                            { x: sourceX + 11, y: 0, z: sourceZ + 3 },
                            { x: sourceX + 11, y: 0, z: sourceZ - 5 },
                            { x: sourceX + 10, y: 0, z: sourceZ - 6 },
                            { x: sourceX + 10, y: 0, z: sourceZ - 7 },
                            { x: sourceX + 9, y: 0, z: sourceZ - 8 },
                            { x: sourceX + 8, y: 0, z: sourceZ - 9 },
                            { x: sourceX + 7, y: 0, z: sourceZ - 10 },
                            { x: sourceX + 6, y: 0, z: sourceZ - 10 },
                            { x: sourceX + 5, y: 0, z: sourceZ - 11 },
                            { x: sourceX + 4, y: 0, z: sourceZ - 12 },
                            { x: sourceX + 3, y: 0, z: sourceZ - 12 },
                            { x: sourceX + 2, y: 0, z: sourceZ - 12 },
                            { x: sourceX - 3, y: 0, z: sourceZ - 12 },
                            { x: sourceX - 4, y: 0, z: sourceZ - 12 },
                            { x: sourceX - 5, y: 0, z: sourceZ - 12 },
                            { x: sourceX - 6, y: 0, z: sourceZ - 11 },
                            { x: sourceX - 7, y: 0, z: sourceZ - 11 },
                            { x: sourceX - 8, y: 0, z: sourceZ - 10 },
                            { x: sourceX - 9, y: 0, z: sourceZ - 9 },
                            { x: sourceX - 10, y: 0, z: sourceZ - 8 },
                            { x: sourceX - 10, y: 0, z: sourceZ - 7 },
                            { x: sourceX - 11, y: 0, z: sourceZ - 6 },
                            { x: sourceX - 11, y: 0, z: sourceZ - 5 },
                            { x: sourceX - 11, y: 0, z: sourceZ - 4 },
                            { x: sourceX - 11, y: 0, z: sourceZ - 3 },
                            { x: sourceX - 11, y: 0, z: sourceZ - 2 },
                            { x: sourceX - 12, y: 0, z: sourceZ - 1 },
                            { x: sourceX - 12, y: 0, z: sourceZ - 0 },
                            { x: sourceX - 12, y: 0, z: sourceZ + 1 },
                            { x: sourceX - 11, y: 0, z: sourceZ + 2 },
                            { x: sourceX - 11, y: 0, z: sourceZ + 3 },
                            { x: sourceX - 11, y: 0, z: sourceZ + 4 },
                            { x: sourceX - 11, y: 0, z: sourceZ + 5 },
                            { x: sourceX - 10, y: 0, z: sourceZ + 6 },
                            { x: sourceX - 9, y: 0, z: sourceZ + 7 },
                            { x: sourceX - 8, y: 0, z: sourceZ + 8 },
                            { x: sourceX - 7, y: 0, z: sourceZ + 9 },
                            { x: sourceX - 6, y: 0, z: sourceZ + 9 },
                            { x: sourceX - 5, y: 0, z: sourceZ + 10 },
                            { x: sourceX - 4, y: 0, z: sourceZ + 10 },
                            { x: sourceX - 3, y: 0, z: sourceZ + 10 },
                        ];
                        for (let coords of specificCoordinates) {
                            let blockY = sourceY + 20;
                            const tag = sourceEntity?.getTags()[0];

                            for (let yOffset = sourceY + 20; yOffset >= sourceY - 20; yOffset--) {
                                const block = sourceEntity.dimension.getBlock({ x: coords.x, y: yOffset, z: coords.z });
                                if (block && !ignoredBlockTypes.includes(block.typeId)) {
                                    blockY = block.location.y;
                                    break;
                                }
                            };
                            if (((coords.x === sourceX + 1) && (coords.z === sourceZ + 11)) || ((coords.x === sourceX - 2) && (coords.z === sourceZ + 11))) {
                                sourceEntity?.runCommand(`structure load "mystructure:orcs_update/camp/${tag}/orc_camp_stake_banner_${tag}" ${coords.x} ${blockY} ${coords.z} 180_degrees`);
                            } else if (((coords.x === sourceX + 1) && (coords.z === sourceZ - 13)) || ((coords.x === sourceX - 2) && (coords.z === sourceZ - 13))) {
                                sourceEntity?.runCommand(`structure load "mystructure:orcs_update/camp/${tag}/orc_camp_stake_banner_${tag}" ${coords.x} ${blockY} ${coords.z - 1}`);
                            } else {
                                const randomNumber = Math.floor(Math.random() * 4) + 1;
                                sourceEntity?.runCommand(`structure load "mystructure:orcs_update/camp/${tag}/orc_camp_stake${randomNumber}_${tag}" ${coords.x} ${blockY} ${coords.z}`);
                            }
                        };
                        sourceEntity?.remove()
                    }
                } else {
                    system.clearRun(interval)
                }
            }, 5)
        };
        if (structure === `orc_village` && type === `walls`) {
            const interval = system.runInterval(() => {
                if (sourceEntity?.isValid() == true) {
                    const player = sourceEntity?.dimension.getEntities({ location: sourceEntity?.location, maxDistance: 60, closest: 1, type: `minecraft:player` })[0];
                    if (player !== undefined) {
                        system.clearRun(interval);

                        const sourceX = sourceEntity?.location.x;
                        const sourceY = sourceEntity?.location.y;
                        const sourceZ = sourceEntity?.location.z;

                        const specificCoordinates = [
                            //Walls
                            { x: sourceX, y: 0, z: sourceZ - 37 }, //0
                            { x: sourceX - 1, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 2, y: 0, z: sourceZ - 37 },
                            { x: sourceX - 3, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 4, y: 0, z: sourceZ - 37 },
                            { x: sourceX - 5, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 7, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 9, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 11, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 12, y: 0, z: sourceZ - 35 },
                            { x: sourceX - 13, y: 0, z: sourceZ - 34 }, //10
                            { x: sourceX - 14, y: 0, z: sourceZ - 35 },
                            { x: sourceX - 14, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 15, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 16, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 16, y: 0, z: sourceZ - 37 },
                            { x: sourceX - 17, y: 0, z: sourceZ - 37 },
                            { x: sourceX - 17, y: 0, z: sourceZ - 38 },
                            { x: sourceX - 18, y: 0, z: sourceZ - 38 },
                            { x: sourceX - 18, y: 0, z: sourceZ - 39 },
                            { x: sourceX - 19, y: 0, z: sourceZ - 38 }, //20
                            { x: sourceX - 20, y: 0, z: sourceZ - 39 },
                            { x: sourceX - 21, y: 0, z: sourceZ - 40 },
                            { x: sourceX - 22, y: 0, z: sourceZ - 39 },
                            { x: sourceX - 23, y: 0, z: sourceZ - 40 },
                            { x: sourceX - 24, y: 0, z: sourceZ - 39 },
                            { x: sourceX - 24, y: 0, z: sourceZ - 38 },
                            { x: sourceX - 25, y: 0, z: sourceZ - 38 },
                            { x: sourceX - 25, y: 0, z: sourceZ - 37 },
                            { x: sourceX - 26, y: 0, z: sourceZ - 37 },
                            { x: sourceX - 27, y: 0, z: sourceZ - 37 }, //30
                            { x: sourceX - 27, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 28, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 28, y: 0, z: sourceZ - 35 },
                            { x: sourceX - 29, y: 0, z: sourceZ - 36 },
                            { x: sourceX - 29, y: 0, z: sourceZ - 35 },
                            { x: sourceX - 30, y: 0, z: sourceZ - 35 },
                            { x: sourceX - 31, y: 0, z: sourceZ - 35 },
                            { x: sourceX - 32, y: 0, z: sourceZ - 34 },
                            { x: sourceX - 32, y: 0, z: sourceZ - 33 },
                            { x: sourceX - 33, y: 0, z: sourceZ - 33 }, //40
                            { x: sourceX - 33, y: 0, z: sourceZ - 32 },
                            { x: sourceX - 34, y: 0, z: sourceZ - 32 },
                            { x: sourceX - 34, y: 0, z: sourceZ - 31 },
                            { x: sourceX - 35, y: 0, z: sourceZ - 31 },
                            { x: sourceX - 35, y: 0, z: sourceZ - 30 },
                            { x: sourceX - 36, y: 0, z: sourceZ - 29 },
                            { x: sourceX - 36, y: 0, z: sourceZ - 28 },
                            { x: sourceX - 37, y: 0, z: sourceZ - 28 },
                            { x: sourceX - 37, y: 0, z: sourceZ - 27 },
                            { x: sourceX - 38, y: 0, z: sourceZ - 27 }, //50
                            { x: sourceX - 38, y: 0, z: sourceZ - 26 },
                            { x: sourceX - 39, y: 0, z: sourceZ - 26 },
                            { x: sourceX - 39, y: 0, z: sourceZ - 25 },
                            { x: sourceX - 40, y: 0, z: sourceZ - 25 },
                            { x: sourceX + 1, y: 0, z: sourceZ - 36 },
                            { x: sourceX + 2, y: 0, z: sourceZ - 37 },
                            { x: sourceX + 3, y: 0, z: sourceZ - 36 },
                            { x: sourceX + 4, y: 0, z: sourceZ - 37 },
                            { x: sourceX + 5, y: 0, z: sourceZ - 36 },
                            { x: sourceX + 6, y: 0, z: sourceZ - 35 }, //60
                            { x: sourceX + 7, y: 0, z: sourceZ - 36 },
                            { x: sourceX + 8, y: 0, z: sourceZ - 35 },
                            { x: sourceX + 9, y: 0, z: sourceZ - 36 },
                            { x: sourceX + 10, y: 0, z: sourceZ - 35 },
                            { x: sourceX + 11, y: 0, z: sourceZ - 34 },
                            { x: sourceX + 12, y: 0, z: sourceZ - 35 },
                            { x: sourceX + 13, y: 0, z: sourceZ - 34 },
                            { x: sourceX + 14, y: 0, z: sourceZ - 33 },
                            { x: sourceX + 15, y: 0, z: sourceZ - 32 },
                            { x: sourceX + 16, y: 0, z: sourceZ - 33 }, //70
                            { x: sourceX + 17, y: 0, z: sourceZ - 32 },
                            { x: sourceX + 18, y: 0, z: sourceZ - 33 },
                            { x: sourceX + 19, y: 0, z: sourceZ - 32 },
                            { x: sourceX + 20, y: 0, z: sourceZ - 31 },
                            { x: sourceX + 21, y: 0, z: sourceZ - 32 },
                            { x: sourceX + 22, y: 0, z: sourceZ - 31 },
                            { x: sourceX + 23, y: 0, z: sourceZ - 30 },
                            { x: sourceX + 24, y: 0, z: sourceZ - 31 },
                            { x: sourceX + 25, y: 0, z: sourceZ - 30 },
                            { x: sourceX + 26, y: 0, z: sourceZ - 29 }, //80
                            { x: sourceX + 27, y: 0, z: sourceZ - 28 },
                            { x: sourceX + 28, y: 0, z: sourceZ - 28 },
                            { x: sourceX + 29, y: 0, z: sourceZ - 27 },
                            { x: sourceX + 30, y: 0, z: sourceZ - 27 },
                            { x: sourceX + 31, y: 0, z: sourceZ - 26 },
                            { x: sourceX + 32, y: 0, z: sourceZ - 25 },
                            { x: sourceX + 32, y: 0, z: sourceZ - 24 },
                            { x: sourceX + 33, y: 0, z: sourceZ - 23 },
                            { x: sourceX + 34, y: 0, z: sourceZ - 22 },
                            { x: sourceX + 33, y: 0, z: sourceZ - 21 }, //90
                            { x: sourceX + 34, y: 0, z: sourceZ - 20 },
                            { x: sourceX + 35, y: 0, z: sourceZ - 19 },
                            { x: sourceX + 34, y: 0, z: sourceZ - 18 },
                            { x: sourceX + 35, y: 0, z: sourceZ - 17 },
                            { x: sourceX + 34, y: 0, z: sourceZ - 16 },
                            { x: sourceX + 35, y: 0, z: sourceZ - 15 },
                            { x: sourceX + 34, y: 0, z: sourceZ - 14 },
                            { x: sourceX + 33, y: 0, z: sourceZ - 13 },
                            { x: sourceX + 34, y: 0, z: sourceZ - 12 },
                            { x: sourceX + 33, y: 0, z: sourceZ - 11 }, //100
                            { x: sourceX + 34, y: 0, z: sourceZ - 10 },
                            { x: sourceX + 33, y: 0, z: sourceZ - 9 },
                            { x: sourceX + 32, y: 0, z: sourceZ - 8 },
                            { x: sourceX + 33, y: 0, z: sourceZ - 7 },
                            { x: sourceX + 32, y: 0, z: sourceZ - 6 },
                            { x: sourceX + 32, y: 0, z: sourceZ - 4 },
                            { x: sourceX + 32, y: 0, z: sourceZ - 2 },
                            { x: sourceX + 32, y: 0, z: sourceZ },
                            { x: sourceX + 33, y: 0, z: sourceZ + 1 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 2 }, //110
                            { x: sourceX + 33, y: 0, z: sourceZ + 3 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 4 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 5 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 6 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 7 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 8 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 9 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 10 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 11 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 12 }, //120
                            { x: sourceX + 33, y: 0, z: sourceZ + 13 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 14 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 15 },
                            { x: sourceX + 34, y: 0, z: sourceZ + 16 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 17 },
                            { x: sourceX + 34, y: 0, z: sourceZ + 18 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 19 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 20 },
                            { x: sourceX + 33, y: 0, z: sourceZ + 21 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 22 }, //130
                            { x: sourceX + 33, y: 0, z: sourceZ + 23 },
                            { x: sourceX + 32, y: 0, z: sourceZ + 24 },
                            { x: sourceX + 31, y: 0, z: sourceZ + 24 },
                            { x: sourceX + 31, y: 0, z: sourceZ + 25 },
                            { x: sourceX + 30, y: 0, z: sourceZ + 25 },
                            { x: sourceX + 30, y: 0, z: sourceZ + 26 },
                            { x: sourceX + 29, y: 0, z: sourceZ + 26 },
                            { x: sourceX + 28, y: 0, z: sourceZ + 26 },
                            { x: sourceX + 27, y: 0, z: sourceZ + 26 },
                            { x: sourceX + 26, y: 0, z: sourceZ + 26 }, //140
                            { x: sourceX + 26, y: 0, z: sourceZ + 27 },
                            { x: sourceX + 25, y: 0, z: sourceZ + 27 },
                            { x: sourceX + 24, y: 0, z: sourceZ + 27 },
                            { x: sourceX + 24, y: 0, z: sourceZ + 28 },
                            { x: sourceX + 23, y: 0, z: sourceZ + 28 },
                            { x: sourceX + 22, y: 0, z: sourceZ + 28 },
                            { x: sourceX + 22, y: 0, z: sourceZ + 29 },
                            { x: sourceX + 21, y: 0, z: sourceZ + 29 },
                            { x: sourceX + 21, y: 0, z: sourceZ + 30 },
                            { x: sourceX - 49, y: 0, z: sourceZ }, //150
                            { x: sourceX - 49, y: 0, z: sourceZ - 1 },
                            { x: sourceX - 48, y: 0, z: sourceZ - 2 },
                            { x: sourceX - 49, y: 0, z: sourceZ - 3 },
                            { x: sourceX - 48, y: 0, z: sourceZ - 4 },
                            { x: sourceX - 48, y: 0, z: sourceZ - 5 },
                            { x: sourceX - 47, y: 0, z: sourceZ - 6 },
                            { x: sourceX - 47, y: 0, z: sourceZ - 7 },
                            { x: sourceX - 48, y: 0, z: sourceZ + 1 },
                            { x: sourceX - 49, y: 0, z: sourceZ + 2 },
                            { x: sourceX - 49, y: 0, z: sourceZ + 3 }, //160
                            { x: sourceX - 48, y: 0, z: sourceZ + 4 },
                            { x: sourceX - 48, y: 0, z: sourceZ + 5 },
                            { x: sourceX - 49, y: 0, z: sourceZ + 6 },
                            { x: sourceX - 48, y: 0, z: sourceZ + 7 },
                            { x: sourceX - 49, y: 0, z: sourceZ + 8 },
                            { x: sourceX - 49, y: 0, z: sourceZ + 9 },
                            { x: sourceX - 48, y: 0, z: sourceZ + 10 },
                            { x: sourceX - 49, y: 0, z: sourceZ + 11 },
                            { x: sourceX - 48, y: 0, z: sourceZ + 12 },
                            { x: sourceX - 49, y: 0, z: sourceZ + 13 }, //170
                            { x: sourceX - 49, y: 0, z: sourceZ + 14 },
                            { x: sourceX - 48, y: 0, z: sourceZ + 15 },
                            { x: sourceX - 47, y: 0, z: sourceZ + 16 },
                            { x: sourceX - 46, y: 0, z: sourceZ + 16 },
                            { x: sourceX - 46, y: 0, z: sourceZ + 17 },
                            { x: sourceX - 45, y: 0, z: sourceZ + 17 },
                            { x: sourceX - 45, y: 0, z: sourceZ + 18 },
                            { x: sourceX - 44, y: 0, z: sourceZ + 18 },
                            { x: sourceX - 44, y: 0, z: sourceZ + 19 },
                            { x: sourceX - 43, y: 0, z: sourceZ + 20 }, //180
                            { x: sourceX - 42, y: 0, z: sourceZ + 20 },
                            { x: sourceX - 42, y: 0, z: sourceZ + 21 },
                            { x: sourceX - 41, y: 0, z: sourceZ + 21 },
                            { x: sourceX - 41, y: 0, z: sourceZ + 22 },
                            { x: sourceX - 40, y: 0, z: sourceZ + 22 },
                            { x: sourceX - 39, y: 0, z: sourceZ + 22 },
                            { x: sourceX - 39, y: 0, z: sourceZ + 23 },
                            { x: sourceX - 38, y: 0, z: sourceZ + 23 },
                            { x: sourceX - 37, y: 0, z: sourceZ + 23 },
                            { x: sourceX - 37, y: 0, z: sourceZ + 24 }, //190
                            { x: sourceX - 36, y: 0, z: sourceZ + 24 },
                            { x: sourceX - 36, y: 0, z: sourceZ + 25 },
                            { x: sourceX - 37, y: 0, z: sourceZ + 26 },
                            { x: sourceX - 36, y: 0, z: sourceZ + 27 },
                            { x: sourceX - 37, y: 0, z: sourceZ + 28 },
                            { x: sourceX - 36, y: 0, z: sourceZ + 29 },
                            { x: sourceX - 35, y: 0, z: sourceZ + 30 },
                            { x: sourceX - 34, y: 0, z: sourceZ + 31 },
                            { x: sourceX - 35, y: 0, z: sourceZ + 32 },
                            { x: sourceX - 34, y: 0, z: sourceZ + 33 }, //200
                            { x: sourceX - 34, y: 0, z: sourceZ + 34 },
                            { x: sourceX - 33, y: 0, z: sourceZ + 35 },
                            { x: sourceX - 34, y: 0, z: sourceZ + 36 },
                            { x: sourceX - 33, y: 0, z: sourceZ + 37 },
                            { x: sourceX - 34, y: 0, z: sourceZ + 38 },
                            { x: sourceX - 33, y: 0, z: sourceZ + 39 },
                            { x: sourceX - 32, y: 0, z: sourceZ + 39 },
                            { x: sourceX - 32, y: 0, z: sourceZ + 40 },
                            { x: sourceX - 31, y: 0, z: sourceZ + 40 },
                            { x: sourceX - 31, y: 0, z: sourceZ + 41 }, //210
                            { x: sourceX - 30, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 29, y: 0, z: sourceZ + 41 },
                            { x: sourceX - 28, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 27, y: 0, z: sourceZ + 41 },
                            { x: sourceX - 26, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 25, y: 0, z: sourceZ + 43 },
                            { x: sourceX - 24, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 23, y: 0, z: sourceZ + 43 },
                            { x: sourceX - 22, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 21, y: 0, z: sourceZ + 43 }, //220
                            { x: sourceX - 20, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 19, y: 0, z: sourceZ + 43 },
                            { x: sourceX - 18, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 17, y: 0, z: sourceZ + 43 },
                            { x: sourceX - 16, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 17, y: 0, z: sourceZ + 41 },
                            { x: sourceX - 16, y: 0, z: sourceZ + 42 },
                            { x: sourceX - 15, y: 0, z: sourceZ + 41 },
                            { x: sourceX - 14, y: 0, z: sourceZ + 40 },
                            { x: sourceX - 13, y: 0, z: sourceZ + 40 }, //230
                            { x: sourceX - 12, y: 0, z: sourceZ + 39 },
                            { x: sourceX - 11, y: 0, z: sourceZ + 38 },
                            { x: sourceX - 9, y: 0, z: sourceZ + 38 },
                            { x: sourceX - 7, y: 0, z: sourceZ + 38 },
                            { x: sourceX - 5, y: 0, z: sourceZ + 38 },
                            { x: sourceX - 4, y: 0, z: sourceZ + 39 },
                            { x: sourceX - 3, y: 0, z: sourceZ + 38 },
                            { x: sourceX - 2, y: 0, z: sourceZ + 38 },
                            { x: sourceX - 1, y: 0, z: sourceZ + 37 },
                            { x: sourceX, y: 0, z: sourceZ + 37 }, //240
                            //Structures
                            { x: sourceX - 33, y: 0, z: sourceZ + 9 }, //Mage orc house
                            { x: sourceX - 48, y: 0, z: sourceZ - 25 }, //Village entrance1
                            { x: sourceX - 3, y: 0, z: sourceZ + 28 }, //Village entrance2

                            { x: sourceX - 18, y: 0, z: sourceZ + 24 }, //little orc house
                            { x: sourceX - 23, y: 0, z: sourceZ + 33 }, //little orc house 90
                            { x: sourceX - 35, y: 0, z: sourceZ + 23 }, //little orc house 180
                            { x: sourceX - 32, y: 0, z: sourceZ + 32 }, //little orc house2

                            { x: sourceX + 10, y: 0, z: sourceZ + 6 }, //Adult orc house
                            { x: sourceX + 20, y: 0, z: sourceZ - 2 }, //Adult orc house
                            { x: sourceX + 20, y: 0, z: sourceZ + 14 }, //Adult orc house

                            { x: sourceX - 26, y: 0, z: sourceZ - 27 }, //Village forge

                            { x: sourceX - 8, y: 0, z: sourceZ - 33 }, //Tower
                            { x: sourceX + 32, y: 0, z: sourceZ - 7 }, //Tower 90
                            { x: sourceX - 3, y: 0, z: sourceZ + 37 }, //Tower 180

                            { x: sourceX + 10, y: 0, z: sourceZ - 28 }, //Armery

                            { x: sourceX + 28, y: 0, z: sourceZ - 22 }, //Training fence
                            { x: sourceX + 27, y: 0, z: sourceZ - 14 }, //Training fence2
                            { x: sourceX + 25, y: 0, z: sourceZ - 8 }, //Training fence3

                            { x: sourceX - 9, y: 0, z: sourceZ - 17 }, //Torch
                            { x: sourceX - 23, y: 0, z: sourceZ - 13 }, //Torch
                            { x: sourceX - 41, y: 0, z: sourceZ - 5 }, //Torch
                            { x: sourceX - 13, y: 0, z: sourceZ + 20 }, //Torch
                            { x: sourceX - 23, y: 0, z: sourceZ + 19 }, //Torch
                            { x: sourceX + 11, y: 0, z: sourceZ + 26 }, //Torch
                            { x: sourceX + 26, y: 0, z: sourceZ + 11 }, //Torch

                            { x: sourceX + 4, y: 0, z: sourceZ - 21 }, //Bomb box
                            { x: sourceX + 4, y: 0, z: sourceZ - 22 }, //Bomb box
                            { x: sourceX + 5, y: 0, z: sourceZ - 22 }, //Bomb box
                            { x: sourceX + 6, y: 0, z: sourceZ - 26 }, //Bomb box
                            { x: sourceX + 11, y: 0, z: sourceZ - 24 }, //Bomb box
                            { x: sourceX + 17, y: 0, z: sourceZ - 22 }, //Bomb box
                            { x: sourceX + 24, y: 0, z: sourceZ - 21 }, //Bomb box
                            { x: sourceX + 21, y: 0, z: sourceZ - 8 }, //Bomb box
                        ];
                        const structureNames = [
                            "orc_village_mage_house",
                            "orc_village_entrance",
                            "orc_village_entrance2",
                            "little_orc_house",
                            "little_orc_house_90",
                            "little_orc_house_180",
                            "little_orc_house2",
                            "adult_orc_house",
                            "adult_orc_house",
                            "adult_orc_house",
                            "orc_village_forge",
                            "orc_village_tower",
                            "orc_village_tower",
                            "orc_village_tower",
                            "orc_village_armery",
                            "training_fence1",
                            "training_fence2",
                            "training_fence3",
                            "orc_village_torch",
                            "orc_village_torch",
                            "orc_village_torch",
                            "orc_village_torch",
                            "orc_village_torch",
                            "orc_village_torch",
                            "orc_village_torch"
                        ];
                        const structuresOffset = [
                            { x: -12, y: -3, z: -17 }, //Mage house
                            { x: 3, y: -3, z: 10 }, //Entrance1
                            { x: 10, y: -3, z: 3 }, //Entrance2
                            { x: -4, y: -3, z: -4 }, //Little Orc House
                            { x: -4, y: -3, z: -4 }, //Little Orc House 90
                            { x: -4, y: -3, z: -4 }, //Little Orc House 180
                            { x: -4, y: -3, z: -4 }, //Little Orc House2
                            { x: -5, y: -3, z: -5 }, //Adult Orc House
                            { x: -5, y: -3, z: -5 }, //Adult Orc House
                            { x: -5, y: -3, z: -5 }, //Adult Orc House
                            { x: -10, y: -3, z: -10 }, //Forge
                            { x: -3, y: -3, z: -3 }, //Tower
                            { x: -3, y: -3, z: -3 }, //Tower 90
                            { x: -3, y: -3, z: 0 }, //Tower 180
                            { x: -15, y: -3, z: -7 }, //Armery
                            { x: -2, y: -3, z: -1 }, //Training fence
                            { x: -2, y: -3, z: -1 }, //Training fence
                            { x: -2, y: -3, z: -1 }, //Training fence
                            { x: -1, y: -3, z: -1 }, //Torch
                            { x: -1, y: -3, z: -1 }, //Torch
                            { x: -1, y: -3, z: -1 }, //Torch
                            { x: -1, y: -3, z: -1 }, //Torch
                            { x: -1, y: -3, z: -1 }, //Torch
                            { x: -1, y: -3, z: -1 }, //Torch
                            { x: -1, y: -3, z: -1 }, //Torch
                        ];

                        let count = 0;
                        specificCoordinates.forEach((coords) => {
                            let blockY = 0;

                            for (let yOffset = sourceY + 20; yOffset >= sourceY - 20; yOffset--) {
                                const block = sourceEntity.dimension.getBlock({ x: coords.x, y: yOffset, z: coords.z });
                                if (block && !ignoredBlockTypes.includes(block.typeId)) {
                                    blockY = block.location.y;
                                    break;
                                };
                                if (yOffset === sourceY - 20) {
                                    break;
                                }
                            };
                            if (blockY > 0) {
                                const tag = sourceEntity?.getTags()[0];
                                if (count < 242) {
                                    const randomNumber = Math.floor(Math.random() * 4) + 1;
                                    const randomNumber2 = Math.floor(Math.random() * 2) + 1;

                                    const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/orc_village_wall${randomNumber2}_${tag}`);
                                    world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x, y: blockY - randomNumber, z: coords.z })
                                    count++
                                };
                                if (count >= 242) {
                                    const structureName = structureNames[count - 242];
                                    const offset = structuresOffset[count - 242];
                                    count++
                                    if (count === 244 || count === 245 || (count >= 246 && count <= 252) || count === 255 || count === 256 || count === 258 || count === 259 || count === 260 || count >= 266) {
                                        if (count === 244 || count === 245) {
                                            const modifiedStructureName = structureName.replace('orc_village_', '').toString();

                                            const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                            const structure2 = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${modifiedStructureName}_build_${tag}`);

                                            const randomNumber = Math.random();

                                            if (randomNumber < 0.5) {
                                                world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x, y: blockY + offset.y, z: coords.z });
                                            } else {
                                                world.structureManager.place(structure2, sourceEntity.dimension, { x: coords.x, y: blockY + offset.y, z: coords.z });
                                            }
                                        };
                                        if (count >= 246 && count <= 252) {
                                            const modifiedStructureName = structureName.replace('orc_', '').toString();

                                            const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                            const structure2 = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${modifiedStructureName}_build_${tag}`);

                                            const randomNumber = Math.random();

                                            if (randomNumber < 0.5) {
                                                world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x, y: blockY + offset.y, z: coords.z });
                                            } else {
                                                world.structureManager.place(structure2, sourceEntity.dimension, { x: coords.x, y: blockY + offset.y, z: coords.z });
                                            }
                                        };
                                        if (count === 255) {
                                            const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                            world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x, y: blockY + offset.y, z: coords.z }, { rotation: "Rotate90" })
                                        };
                                        if (count === 256) {
                                            const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                            world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x, y: blockY + offset.y, z: coords.z }, { rotation: "Rotate180" })
                                        };
                                        if (count === 258) {
                                            const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                            world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x + offset.x, y: blockY + offset.y, z: coords.z + offset.z })

                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x - 3, y: blockY + 5, z: coords.z + 2 }).setRotation({ x: 0, y: 25 });
                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x - 6, y: blockY + 5, z: coords.z + 2 }).setRotation({ x: 0, y: 25 });
                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x, y: blockY + 5, z: coords.z + 4 }).setRotation({ x: 0, y: 115 });
                                            const entity = world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:little_orc`, { x: coords.x - 1, y: blockY + 5, z: coords.z + 4 });
                                            entity.triggerEvent(`minecraft:spawned_naturally_event`)
                                        };
                                        if (count === 259) {
                                            const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                            world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x + offset.x, y: blockY + offset.y, z: coords.z + offset.z })

                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x - 2, y: blockY + 5, z: coords.z - 1 }).setRotation({ x: 0, y: 115 });
                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x + 5, y: blockY + 5, z: coords.z - 2 }).setRotation({ x: 0, y: 115 });
                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x + 4, y: blockY + 5, z: coords.z + 2 }).setRotation({ x: 0, y: 90 });
                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x - 1, y: blockY + 5, z: coords.z + 3 }).setRotation({ x: 0, y: 90 });
                                            const entity = world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:little_orc`, { x: coords.x - 2, y: blockY + 5, z: coords.z + 3 });
                                            entity.triggerEvent(`minecraft:spawned_naturally_event`)
                                        };
                                        if (count === 260) {
                                            const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                            world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x + offset.x, y: blockY + offset.y, z: coords.z + offset.z })

                                            world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:practice_dummy_ch`, { x: coords.x + 1, y: blockY + 5, z: coords.z - 2 }).setRotation({ x: 0, y: 90 });
                                            const entity = world.getDimension(sourceEntity?.dimension.id).spawnEntity(`ch:little_orc`, { x: coords.x - 5, y: blockY + 5, z: coords.z });
                                            entity.triggerEvent(`minecraft:spawned_naturally_event`)
                                        };
                                        if (count >= 266) {
                                            sourceEntity?.runCommandAsync(`setblock ${coords.x} ${blockY + 1} ${coords.z} ch:bomb_box`);
                                        }
                                    } else {
                                        const structure = world.structureManager.get(`mystructure:orcs_update/orc_village/${tag}/${structureName}_${tag}`);
                                        world.structureManager.place(structure, sourceEntity.dimension, { x: coords.x + offset.x, y: blockY + offset.y, z: coords.z + offset.z })
                                    }
                                }
                            } else {
                                count++
                            }
                        });
                        sourceEntity?.runCommandAsync(`tickingarea remove orc_village`);
                        sourceEntity?.runCommandAsync(`tellraw @a[r=100] { "rawtext": [ { "translate": "translation.message.generation_finished" } ] }`);
                        sourceEntity?.runCommandAsync(`kill @e[type=item]`)
                        system.runTimeout(() => {
                            sourceEntity?.remove()
                        }, 2)
                    }
                } else {
                    system.clearRun(interval)
                }
            }, 5)
        }
    };
    if (id === `ch:red_paint_block`) {
        condition();
        async function redPaintBlockCondition(block) {
            if ((!block.north(1).hasTag(`red_paint_ground`) || !block.south(1).hasTag(`red_paint_ground`) || !block.west(1).hasTag(`red_paint_ground`) || !block.east(1).hasTag(`red_paint_ground`) || !block.north(2).west(1).hasTag(`red_paint_ground`) || !block.north(2).west(2).hasTag(`red_paint_ground`) || !block.north(1).west(2).hasTag(`red_paint_ground`) || !block.north(2).east(1).hasTag(`red_paint_ground`) || !block.north(2).east(2).hasTag(`red_paint_ground`) || !block.north(1).east(2).hasTag(`red_paint_ground`) || !block.south(2).west(1).hasTag(`red_paint_ground`) || !block.south(2).west(2).hasTag(`red_paint_ground`) || !block.south(1).west(2).hasTag(`red_paint_ground`) || !block.south(2).east(1).hasTag(`red_paint_ground`) || !block.south(2).east(2).hasTag(`red_paint_ground`) || !block.south(1).east(2).hasTag(`red_paint_ground`) || !block.north(3).hasTag(`red_paint_ground`) || !block.north(4).hasTag(`red_paint_ground`) || !block.north(5).hasTag(`red_paint_ground`) || !block.south(3).hasTag(`red_paint_ground`) || !block.south(4).hasTag(`red_paint_ground`) || !block.south(5).hasTag(`red_paint_ground`) || !block.east(3).hasTag(`red_paint_ground`) || !block.east(4).hasTag(`red_paint_ground`) || !block.east(5).hasTag(`red_paint_ground`) || !block.west(3).hasTag(`red_paint_ground`) || !block.west(4).hasTag(`red_paint_ground`) || !block.west(5).hasTag(`red_paint_ground`) || !block.north(5).west(1).hasTag(`red_paint_ground`) || !block.north(5).west(2).hasTag(`red_paint_ground`) || !block.north(5).east(1).hasTag(`red_paint_ground`) || !block.north(5).east(2).hasTag(`red_paint_ground`) || !block.south(5).west(1).hasTag(`red_paint_ground`) || !block.south(5).west(2).hasTag(`red_paint_ground`) || !block.south(5).east(1).hasTag(`red_paint_ground`) || !block.south(5).east(2).hasTag(`red_paint_ground`) || !block.west(5).north(1).hasTag(`red_paint_ground`) || !block.west(5).north(2).hasTag(`red_paint_ground`) || !block.west(5).south(1).hasTag(`red_paint_ground`) || !block.west(5).south(2).hasTag(`red_paint_ground`) || !block.east(5).north(1).hasTag(`red_paint_ground`) || !block.east(5).north(2).hasTag(`red_paint_ground`) || !block.east(5).south(1).hasTag(`red_paint_ground`) || !block.east(5).south(2).hasTag(`red_paint_ground`) || !block.north(3).west(3).hasTag(`red_paint_ground`) || !block.north(4).west(3).hasTag(`red_paint_ground`) || !block.north(4).west(4).hasTag(`red_paint_ground`) || !block.north(3).west(4).hasTag(`red_paint_ground`) || !block.north(5).west(5).hasTag(`red_paint_ground`) || !block.north(3).east(3).hasTag(`red_paint_ground`) || !block.north(4).east(3).hasTag(`red_paint_ground`) || !block.north(4).east(4).hasTag(`red_paint_ground`) || !block.north(3).east(4).hasTag(`red_paint_ground`) || !block.north(5).east(5).hasTag(`red_paint_ground`) || !block.south(3).west(3).hasTag(`red_paint_ground`) || !block.south(4).west(3).hasTag(`red_paint_ground`) || !block.south(4).west(4).hasTag(`red_paint_ground`) || !block.south(3).west(4).hasTag(`red_paint_ground`) || !block.south(5).west(5).hasTag(`red_paint_ground`) || !block.south(3).east(3).hasTag(`red_paint_ground`) || !block.south(4).east(3).hasTag(`red_paint_ground`) || !block.south(4).east(4).hasTag(`red_paint_ground`) || !block.south(3).east(4).hasTag(`red_paint_ground`) || !block.south(5).east(5).hasTag(`red_paint_ground`)) || (block.north(2).typeId != `minecraft:air` || block.south(2).typeId != `minecraft:air` || block.east(2).typeId != `minecraft:air` || block.west(2).typeId != `minecraft:air` || block.north(1).west(1).typeId != `minecraft:air` || block.north(1).east(1).typeId != `minecraft:air` || block.south(1).west(1).typeId != `minecraft:air` || block.south(1).east(1).typeId != `minecraft:air` || block.north(3).west(1).typeId != `minecraft:air` || block.north(3).west(2).typeId != `minecraft:air` || block.north(4).west(1).typeId != `minecraft:air` || block.north(4).west(2).typeId != `minecraft:air` || block.north(3).east(1).typeId != `minecraft:air` || block.north(3).east(2).typeId != `minecraft:air` || block.north(4).east(1).typeId != `minecraft:air` || block.north(4).east(2).typeId != `minecraft:air` || block.south(3).west(1).typeId != `minecraft:air` || block.south(3).west(2).typeId != `minecraft:air` || block.south(4).west(1).typeId != `minecraft:air` || block.south(4).west(2).typeId != `minecraft:air` || block.south(3).east(1).typeId != `minecraft:air` || block.south(3).east(2).typeId != `minecraft:air` || block.south(4).east(1).typeId != `minecraft:air` || block.south(4).east(2).typeId != `minecraft:air` || block.west(3).north(1).typeId != `minecraft:air` || block.west(3).north(2).typeId != `minecraft:air` || block.west(4).north(1).typeId != `minecraft:air` || block.west(4).north(2).typeId != `minecraft:air` || block.west(3).south(1).typeId != `minecraft:air` || block.west(3).south(2).typeId != `minecraft:air` || block.west(4).south(1).typeId != `minecraft:air` || block.west(4).south(2).typeId != `minecraft:air` || block.east(3).north(1).typeId != `minecraft:air` || block.east(3).north(2).typeId != `minecraft:air` || block.east(4).north(1).typeId != `minecraft:air` || block.east(4).north(2).typeId != `minecraft:air` || block.east(3).south(1).typeId != `minecraft:air` || block.east(3).south(2).typeId != `minecraft:air` || block.east(4).south(1).typeId != `minecraft:air` || block.east(4).south(2).typeId != `minecraft:air` || block.north(5).west(3).typeId != `minecraft:air` || block.north(5).west(4).typeId != `minecraft:air` || block.north(3).west(5).typeId != `minecraft:air` || block.north(4).west(5).typeId != `minecraft:air` || block.north(5).east(3).typeId != `minecraft:air` || block.north(5).east(4).typeId != `minecraft:air` || block.north(3).east(5).typeId != `minecraft:air` || block.north(4).east(5).typeId != `minecraft:air` || block.south(6).hasTag(`red_paint_ground`) || block.south(5).west(3).typeId != `minecraft:air` || block.south(5).west(4).typeId != `minecraft:air` || block.south(3).west(5).typeId != `minecraft:air` || block.south(4).west(5).typeId != `minecraft:air` || block.south(5).east(3).typeId != `minecraft:air` || block.south(5).east(4).typeId != `minecraft:air` || block.south(3).east(5).typeId != `minecraft:air` || block.south(4).east(5).typeId != `minecraft:air`) || (block.north(6).hasTag(`red_paint_ground`) || block.north(6).west(1).hasTag(`red_paint_ground`) || block.north(6).west(2).hasTag(`red_paint_ground`) || block.north(6).west(3).hasTag(`red_paint_ground`) || block.north(6).west(4).hasTag(`red_paint_ground`) || block.north(6).west(5).hasTag(`red_paint_ground`) || block.north(6).west(6).hasTag(`red_paint_ground`) || block.north(6).east(1).hasTag(`red_paint_ground`) || block.north(6).east(2).hasTag(`red_paint_ground`) || block.north(6).east(3).hasTag(`red_paint_ground`) || block.north(6).east(4).hasTag(`red_paint_ground`) || block.north(6).east(5).hasTag(`red_paint_ground`) || block.north(6).east(6).hasTag(`red_paint_ground`) || block.south(6).west(1).hasTag(`red_paint_ground`) || block.south(6).west(2).hasTag(`red_paint_ground`) || block.south(6).west(3).hasTag(`red_paint_ground`) || block.south(6).west(4).hasTag(`red_paint_ground`) || block.south(6).west(5).hasTag(`red_paint_ground`) || block.south(6).west(6).hasTag(`red_paint_ground`) || block.south(6).east(1).hasTag(`red_paint_ground`) || block.south(6).east(2).hasTag(`red_paint_ground`) || block.south(6).east(3).hasTag(`red_paint_ground`) || block.south(6).east(4).hasTag(`red_paint_ground`) || block.south(6).east(5).hasTag(`red_paint_ground`) || block.south(6).east(6).hasTag(`red_paint_ground`) || block.west(6).hasTag(`red_paint_ground`) || block.west(6).north(1).hasTag(`red_paint_ground`) || block.west(6).north(2).hasTag(`red_paint_ground`) || block.west(6).north(3).hasTag(`red_paint_ground`) || block.west(6).north(4).hasTag(`red_paint_ground`) || block.west(6).north(5).hasTag(`red_paint_ground`) || block.west(6).north(6).hasTag(`red_paint_ground`) || block.west(6).south(1).hasTag(`red_paint_ground`) || block.west(6).south(2).hasTag(`red_paint_ground`) || block.west(6).south(3).hasTag(`red_paint_ground`) || block.west(6).south(4).hasTag(`red_paint_ground`) || block.west(6).south(5).hasTag(`red_paint_ground`) || block.west(6).south(6).hasTag(`red_paint_ground`) || block.east(6).hasTag(`red_paint_ground`) || block.east(6).north(1).hasTag(`red_paint_ground`) || block.east(6).north(2).hasTag(`red_paint_ground`) || block.east(6).north(3).hasTag(`red_paint_ground`) || block.east(6).north(4).hasTag(`red_paint_ground`) || block.east(6).north(5).hasTag(`red_paint_ground`) || block.east(6).north(6).hasTag(`red_paint_ground`) || block.east(6).south(1).hasTag(`red_paint_ground`) || block.east(6).south(2).hasTag(`red_paint_ground`) || block.east(6).south(3).hasTag(`red_paint_ground`) || block.east(6).south(4).hasTag(`red_paint_ground`) || block.east(6).south(5).hasTag(`red_paint_ground`) || block.east(6).south(6).hasTag(`red_paint_ground`))) { return; } else { return true; }
        }
        async function condition() {
            const condition = await redPaintBlockCondition(sourceBlock);

            if (condition === true) {
                const player = sourceBlock?.dimension.getPlayers({location: sourceBlock?.location, maxDistance: 7, closest: 1, tags: [`rpb_interact`]})[0];
                const blockState = sourceBlock?.permutation.getState(`ch:xp_level`);
                const blockState2 = sourceBlock?.permutation.getState(`ch:xp_level2`);
                const clickState = player?.getDynamicProperty(`clickState`) ?? 0;

                if (clickState == 0 && player !== undefined) {
                    player.removeTag(`rpb_interact`);
                    player.setDynamicProperty(`clickState`, 1);

                    if (blockState < 15) {
                        sourceBlock?.setPermutation(sourceBlock?.permutation.withState(`ch:xp_level`, blockState + 1));
                        player?.addLevels(-1);
                        player?.applyDamage(2, { cause: `magic` });
                        world.playSound(`random.fizz`, { x: player.location.x, y: player.location.y, z: player.location.z });
                        world.getDimension(player.dimension.id).spawnParticle(`ch:red_paint_ground_interact`, { x: player.location.x, y: player.location.y + 0.5, z: player.location.z });
                    }

                    if (blockState == 15) {
                        if (blockState2 < 7) {
                            sourceBlock?.setPermutation(sourceBlock?.permutation.withState(`ch:xp_level2`, blockState2 + 1));
                            player.addLevels(-1);
                            player.applyDamage(2, { cause: `magic` });
                            world.playSound(`random.fizz`, { x: player.location.x, y: player.location.y, z: player.location.z });
                            world.getDimension(player.dimension.id).spawnParticle(`ch:red_paint_ground_interact`, { x: player.location.x, y: player.location.y + 0.5, z: player.location.z });
                        };
                        if (blockState2 == 7) {
                            toGreen(sourceBlock)
                        }
                    }
                    system.runTimeout(() => {
                        player.setDynamicProperty(`clickState`, 0)
                    }, 10)
                }
            }
        }
    }
});
function toGreen(block) {
    const functionBlock = system.runInterval(() => {
        const blockState2 = block.permutation.getState(`ch:xp_level2`);

        const blockStateNorth = block.north(1).permutation.getState(`ch:xp_level2`);
        const blockStateSouth = block.south(1).permutation.getState(`ch:xp_level2`);
        const blockStateWest = block.west(1).permutation.getState(`ch:xp_level2`);
        const blockStateEast = block.east(1).permutation.getState(`ch:xp_level2`);

        const blockStateNortWest = block.north(1).west(1).permutation.getState(`ch:xp_level2`);
        const blockStateNortEast = block.north(1).east(1).permutation.getState(`ch:xp_level2`);
        const blockStateSouthWest = block.south(1).west(1).permutation.getState(`ch:xp_level2`);
        const blockStateSouthEast = block.south(1).east(1).permutation.getState(`ch:xp_level2`);

        if (!block.permutation.matches(`ch:red_paint_ground`) || blockState2 < 7 || ((blockStateNorth == 7 || !block.north(1).hasTag(`red_paint_ground`)) && (blockStateSouth == 7 || !block.south(1).hasTag(`red_paint_ground`)) && (blockStateEast == 7 || !block.east(1).hasTag(`red_paint_ground`)) && (blockStateWest == 7 || !block.west(1).hasTag(`red_paint_ground`)) && (blockStateNortWest == 7 || !block.north(1).west(1).hasTag(`red_paint_ground`)) && (blockStateNortEast == 7 || !block.north(1).east(1).hasTag(`red_paint_ground`)) && (blockStateSouthWest == 7 || !block.south(1).west(1).hasTag(`red_paint_ground`)) && (blockStateSouthEast == 7 || !block.south(1).east(1).hasTag(`red_paint_ground`)))) system.clearRun(functionBlock);

        if (blockStateNorth < 7) {
            const blockNorth = block.north(1);
            toGreen(blockNorth);
            blockNorth.setPermutation(blockNorth.permutation.withState(`ch:xp_level2`, 7));
            system.clearRun(functionBlock)
        };
        if (blockStateSouth < 7) {
            const blockSouth = block.south(1);
            toGreen(blockSouth);
            blockSouth.setPermutation(blockSouth.permutation.withState(`ch:xp_level2`, 7));
            system.clearRun(functionBlock)
        };
        if (blockStateWest < 7) {
            const blockWest = block.west(1);
            toGreen(blockWest);
            blockWest.setPermutation(blockWest.permutation.withState(`ch:xp_level2`, 7));
            system.clearRun(functionBlock)
        };
        if (blockStateEast < 7) {
            const blockEast = block.east(1);
            toGreen(blockEast);
            blockEast.setPermutation(blockEast.permutation.withState(`ch:xp_level2`, 7));
            system.clearRun(functionBlock)
        };
        if (blockStateNortWest < 7) {
            const blockNortWest = block.north(1).west(1);
            toGreen(blockNortWest);
            blockNortWest.setPermutation(blockNortWest.permutation.withState(`ch:xp_level2`, 7));
            system.clearRun(functionBlock)
        };
        if (blockStateNortEast < 7) {
            const blockNortEast = block.north(1).east(1);
            toGreen(blockNortEast);
            blockNortEast.setPermutation(blockNortEast.permutation.withState(`ch:xp_level2`, 7));
            system.clearRun(functionBlock)
        };
        if (blockStateSouthWest < 7) {
            const blockSouthWest = block.south(1).west(1);
            toGreen(blockSouthWest);
            blockSouthWest.setPermutation(blockSouthWest.permutation.withState(`ch:xp_level2`, 7));
            system.clearRun(functionBlock)
        };
        if (blockStateSouthEast < 7) {
            const blockSouthEast = block.south(1).east(1);
            blockSouthEast.setPermutation(blockSouthEast.permutation.withState(`ch:xp_level2`, 7));
            toGreen(blockSouthEast);
            system.clearRun(functionBlock)
        };
    }, 1)
};
async function GetBlockInRadius(center, blockTypeId, radius, dimension) {
    const topRight = { x: center.x + radius, y: center.y + radius, z: center.z + radius };
    const bottomLeft = { x: center.x - radius, y: center.y - radius, z: center.z - radius };
    for (let y = bottomLeft.y; y <= topRight.y; y++) {
        for (let x = bottomLeft.x; x <= topRight.x; x++) {
            for (let z = bottomLeft.z; z <= topRight.z; z++) {
                const location = { x: x, y: y, z: z };
                const isLocationInRadius = Vector.distance(location, center) <= radius;
                if (isLocationInRadius) {
                    let blockAtLocation;
                    try {
                        blockAtLocation = dimension.getBlock(location);
                    } catch (e) { }
                    if (blockAtLocation !== undefined) {
                        if (blockAtLocation.typeId === blockTypeId) {
                            return blockAtLocation;
                        }
                    }
                }
            }
        }
    }
};
function angle(entity, entity2) {
    const locX = entity2?.location.x - entity?.location.x;
    const locY = entity2?.location.y - entity?.location.y;
    const locZ = entity2?.location.z - entity?.location.z;

    const hicks = Math.sqrt(Math.pow(locX, 2) + Math.pow(locZ, 2));
    const hypotenusa = Math.sqrt(Math.pow(hicks, 2) + Math.pow(locY, 2));
    const angle = -Math.sign(locY) * (Math.acos(hicks / hypotenusa) * 180 / Math.PI);

    const rotation = Math.atan2(-locZ, -locX) * 180 / Math.PI;

    entity?.setProperty(`ch:angle`, angle);
    entity?.setProperty(`ch:rotation`, rotation)
};
function distance(entity, entity2) {
    const locX = entity2?.location.x - entity?.location.x;
    const locY = entity2?.location.y - entity?.location.y + 0.5;
    const locZ = entity2?.location.z - entity?.location.z;

    let distance;

    if (entity?.typeId === `ch:shield_generator`) {
        distance = (Math.sqrt(Math.pow(locX, 2) + Math.pow(locY, 2) + Math.pow(locZ, 2))) * 0.6
    } else {
        distance = Math.sqrt(Math.pow(locX, 2) + Math.pow(locY, 2) + Math.pow(locZ, 2))
    };

    entity.setProperty(`ch:distance`, distance)
};