Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protect function not killing mobs #3563

Open
1 task
weedfqsfd opened this issue Jan 17, 2025 · 0 comments
Open
1 task

Protect function not killing mobs #3563

weedfqsfd opened this issue Jan 17, 2025 · 0 comments
Labels
possible bug Stage1 just created by someone new to the project, we don't know yet if it deserves an implementation / a f

Comments

@weedfqsfd
Copy link

weedfqsfd commented Jan 17, 2025

  • The FAQ doesn't contain a resolution to my issue

Versions

  • mineflayer: 4.25.0
  • server: vanilla/spigot/paper vanilla 1.20.4
  • node: v20.18.1

Detailed description of a problem

My chat controlled minecraft bot won't attack mobs. The protect function is supposed to protect a target and kill surrounding mobs, but it won't kill the mobs. It can kill players.

What did you try yet?

Did you try any method from the API?
Yes, I have looked over the API. There is nothing on attacking mobs.
Did you try any example? Any error from those?
I have not found any any error

Your current code

/*
const mineflayer = require('mineflayer');
const { plugin: Pvp } = require('mineflayer-pvp');
const { pathfinder, Movements, goals } = require('mineflayer-pathfinder');
const { Vec3 } = require('vec3');
const fs = require('fs');

// Create log file for errors and details
const logFile = 'bot_errors.log';
function logError(message) {
  const timestamp = new Date().toISOString();
  fs.appendFileSync(logFile, `[${timestamp}] ERROR: ${message}\n`);
  console.error(`[ERROR] ${message}`);
}

// Create a separate log file for detailed physicTick logging
const detailLogFile = 'bot_details.log';
function logDetail(message) {
  const timestamp = new Date().toISOString();
  fs.appendFileSync(detailLogFile, `[${timestamp}] DETAIL: ${message}\n`);
  console.log(`[DETAIL] ${message}`);
}

// Number of bots to spawn
const numBots = 1;

// Bot configuration
const botConfigs = [];
for (let i = 0; i < numBots; i++) {
  const botName = i === 0 ? 'PvPBot' : `PvPBot${i}`;
  botConfigs.push({ host: 'localhost', port: 25565, username: botName });
}

// Create bots
const bots = botConfigs.map(config => mineflayer.createBot(config));

// Enable debug mode for mineflayer
mineflayer.debug = true;

// Error handling
process.on('uncaughtException', (err) => {
  logError(`Uncaught exception: ${err.stack || err}`);
});
process.on('unhandledRejection', (reason, promise) => {
  logError(`Unhandled rejection: ${reason.stack || reason} from ${promise}`);
});

// Setup bots
bots.forEach((bot, index) => {
  bot.loadPlugin(pathfinder);
  bot.loadPlugin(Pvp);

  bot.setMaxListeners(50);

  bot.on('spawn', () => {
    console.log(`Bot ${bot.username} is ready!`);
    equipBestGear(bot);
  });

bot.on('physicTick', () => {
  const position = bot.entity.position;
  const velocity = bot.entity.velocity;
  const health = bot.health;
  const yaw = bot.entity.yaw;
  const pitch = bot.entity.pitch;

  // Define controlStates
  const controlStates = Object.entries(bot.controlState)
    .filter(([, active]) => active)
    .map(([state]) => state)
    .join(', ');

  const nearestEntity = bot.nearestEntity();
  const entityInfo = nearestEntity ? `Entity Type: ${nearestEntity.type}, Display Name: ${nearestEntity.displayName || 'Unknown'}, Position: ${nearestEntity.position}` : 'No nearby entities';

  const message = `PhysicStick | Position: ${position.toString()} | Velocity: ${velocity.toString()} | Health: ${health} | Yaw: ${yaw.toFixed(2)} | Pitch: ${pitch.toFixed(2)} | Control States: [${controlStates}] | ${entityInfo}`;
  logDetail(message);
});




  bot.on('chat', (username, message) => {
    if (username === bot.username) return;
    console.log(`${username} said to ${bot.username}: ${message}`);

    const args = message.split(' ');

    if (args[0] === '!fight') {
      const targetName = args[1];
      startFight(bot, targetName.toLowerCase() === 'me' ? username : targetName);
    } else if (args[0] === '!stop') {
      bot.chat('Stopping all actions.');
      stopAllActions(bot);
    } else if (args[0] === '!protect') {
      const targetName = args[1];
      startProtection(bot, targetName.toLowerCase() === 'me' ? username : targetName);
    }
  });
});

// Equip best gear
function equipBestGear(bot) {
  try {
    const armorSlots = ['helmet', 'chestplate', 'leggings', 'boots'];
    armorSlots.forEach(slot => {
      const bestArmor = bot.inventory.items().filter(item => item.name.includes(slot))
        .sort((a, b) => b.metadata - a.metadata)[0];
      if (bestArmor) {
        bot.equip(bestArmor, slot, (err) => {
          if (err) logError(`Failed to equip ${slot} on ${bot.username}: ${err}`);
        });
      }
    });

    const bestWeapon = bot.inventory.items().filter(item => item.name.includes('sword') || item.name.includes('axe'))
      .sort((a, b) => b.metadata - a.metadata)[0];
    if (bestWeapon) {
      bot.equip(bestWeapon, 'hand', (err) => {
        if (err) logError(`Failed to equip weapon on ${bot.username}: ${err}`);
      });
    }

    const shield = bot.inventory.items().find(item => item.name.includes('shield'));
    if (shield) {
      bot.equip(shield, 'off-hand', (err) => {
        if (err) logError(`Failed to equip shield on ${bot.username}: ${err}`);
      });
    }
  } catch (err) {
    logError(`Error equipping gear on ${bot.username}: ${err}`);
  }
}

// Stop all actions
function stopAllActions(bot) {
  bot.pvp.stop();
  bot.pathfinder.setGoal(null);
  bot.clearControlStates();
}

function startProtection(bot, targetName) {
  const target = bot.players[targetName]?.entity;

  if (!target || !target.isValid) {
    logError(`Could not find target for protection: ${targetName}`);
    bot.chat(`Could not find the target: ${targetName}`);
    return;
  }

  logDetail(`Starting protection for target: ${targetName}, Position: ${target.position}`);
  const movements = new Movements(bot, require('minecraft-data')(bot.version));
  bot.pathfinder.setMovements(movements);

  const protectionInterval = setInterval(() => {
    if (!target || !target.isValid) {
      logDetail(`Protection target lost: ${targetName}. Stopping protection.`);
      clearInterval(protectionInterval);
      bot.pathfinder.setGoal(null);
      bot.chat(`Stopped protecting ${targetName}.`);
      return;
    }

    bot.pathfinder.setGoal(new goals.GoalFollow(target, 2));
    logDetail(`Following target: ${targetName}, Position: ${target.position}`);

    const hostileMob = bot.nearestEntity(entity => {
      const isHostile = entity.type === 'mob' &&
        entity.displayName &&
        ['Zombie', 'Skeleton', 'Creeper', 'Spider', 'Enderman', 'Witch', 'Slime', 'Magma Cube', 'Phantom', 'Drowned', 'Husk', 'Zombified Piglin', 'Pillager', 'Vindicator', 'Evoker', 'Blaze', 'Ghast', 'Wither Skeleton', 'Stray', 'Silverfish', 'Guardian', 'Elder Guardian', 'Piglin', 'Piglin Brute', 'Warden', 'Zoglin']
          .includes(entity.displayName) &&
        bot.entity.position.distanceTo(entity.position) <= 15;

      if (isHostile) {
        logDetail(`Hostile mob detected: ${entity.displayName}, Position: ${entity.position}`);
      }

      return isHostile;
    });

    if (hostileMob) {
      logDetail(`Attempting to attack hostile mob: ${hostileMob.displayName}, Position: ${hostileMob.position}`);
      bot.lookAt(hostileMob.position.offset(0, hostileMob.height / 2, 0), true, (err) => {
        if (err) {
          logError(`Error looking at hostile mob: ${err}`);
        } else if (hostileMob.isValid) {
          bot.pvp.attack(hostileMob);
          logDetail(`Attacking hostile mob: ${hostileMob.displayName}`);
          bot.chat(`Attacking hostile mob: ${hostileMob.displayName}`);
        } else {
          logDetail(`Hostile mob is no longer valid: ${hostileMob.displayName}`);
        }
      });
    } else {
      logDetail(`No hostile mobs nearby for protection.`);
    }
  }, 500);
}



function startFight(bot, targetName) {
  const target = bot.players[targetName]?.entity;
  if (!target || !target.isValid) {
    bot.chat(`Could not find the target: ${targetName}`);
    return;
  }

  engagePvP(bot, target);
}

function engagePvP(bot, target) {
  const attackInterval = setInterval(() => {
    if (!target || !target.isValid) {
      logDetail(`Target invalid or lost for PvP. Stopping attack.`);
      clearInterval(attackInterval);
      bot.pvp.stop();
      bot.chat(`Target lost or defeated.`);
      return;
    }

    const distance = bot.entity.position.distanceTo(target.position);
    logDetail(`EngagePvP | Target: ${target.displayName}, Distance: ${distance.toFixed(2)}, Position: ${target.position}`);

    if (distance < 3) {
      bot.lookAt(target.position.offset(0, target.height / 2, 0), true, (err) => {
        if (err) {
          logError(`Error looking at target: ${err}`);
        } else {
          logDetail(`Bot is facing target: ${target.displayName}. Initiating attack.`);
          bot.pvp.attack(target);
        }
      });
    } else {
      logDetail(`Target out of range: ${target.displayName}, Distance: ${distance.toFixed(2)}`);
    }
  }, 500);
}
*/

Expected behavior

The protect function should follow the player, kill surrounding mobs and block projectiles

@weedfqsfd weedfqsfd added possible bug Stage1 just created by someone new to the project, we don't know yet if it deserves an implementation / a f labels Jan 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
possible bug Stage1 just created by someone new to the project, we don't know yet if it deserves an implementation / a f
Projects
None yet
Development

No branches or pull requests

1 participant