Untitled

 avatar
unknown
plain_text
2 years ago
10 kB
3
Indexable
// Import necessary modules and dependencies
const { CommandInteraction, EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js');
const fs = require('fs');
const path = require('path');
// Build the correct file path to 'players.json' using the '__dirname' variable
const playersFilePath = path.join(__dirname, '..', '..', 'data', 'players.json');
// Read 'players.json' file and parse its contents
const playerData = JSON.parse(fs.readFileSync(playersFilePath, 'utf8'));
const { abcdefg } = require('./db.js');
const { initiateDuel, getMax, checkResults, updateMovesOnCd } = require('./glogic.js'); // Assuming you have implemented the duel logic in gamelogic.js
const cards = require('../fun/cards.js'); // Import the cards data from 'cards.js'

// Duel command handler
module.exports = {
    name: 'duel',
    description: 'Challenge someone to a duel!',
  async execute(client, message, args, interaction) {
   // const collector = message.createMessageComponentCollector({ idle: 30000 });

     // collector.on('collect', async (i) => {
      //  console.log('Collector event - Button clicked:', i.customId);
    try {
      console.log('Duel command executed.');
      const author = message.author.id;
     const opponent = args[0].trim();
      console.log(opponent);
      // Verify that 'cards' property exists for both author and opponent
    if (!playerData[author]?.cards) {
      throw new Error('author players do not have cards.');
    }
      if (!playerData[opponent]?.cards) {
        message.channel.send('Opponent did not register yet');
      throw new Error('seggs players do not have cards.');
    }
      

      // Other code for retrieving card data and deck information similar to the previous implementation
// Get the cards of the author and the opponent
const authorCards = playerData[author]?.cards?.name || [];
const opponentCards = playerData[opponent]?.cards?.name || [];
      
      console.log('authorCardsData:', authorCards);
      console.log('opponentCardsData:', opponentCards);

const authorUserName = playerData[author]?.name;
const opponentUserName = playerData[opponent]?.name;
            console.log('authorCardsData:', authorUserName);
      console.log('opponentCardsData:', opponentUserName);
      
      // Set initial HP for the duel
      let authorHP = 100;
      let opponentHP = 100;

      // Array to store battle logs
      const battleLogs = [];
   

     
    // Function to get the moves of a specific card
  function getCardMoves(cardName) {
    const card = cards[cardName];
    if (card && card.moves) {
      // Check for cooldown status and handle it accordingly
      card.moves.forEach(move => {
        if (!move.onCd || move.onCd <= 0) {
          move.onCd = 0; // Set cooldown to 0 if it's not already set or expired
        } else {
          move.onCd -= 10000; // Decrease the cooldown by 10000 milliseconds (10 seconds) during each iteration
        }
      });
      return card.moves;
    }
    return null; // Return null if the card is not found in the 'cards' data
  }

  // Function to send the duel status as an embed with buttons and wait for user response
  async function sendDuelStatus() {
    // Get the moves of each card for the author and the opponent
    const authorMoves = authorCards.map(cardName => getCardMoves(cardName));
    const opponentMoves = opponentCards.map(cardName => getCardMoves(cardName));

    // Send the duel status as a message embed
    const embed = generateDuelStatusEmbed(author, authorCards, authorHP, opponent, opponentCards, opponentHP, battleLogs);
    const messageResponse = await message.channel.send({ embeds: [embed], components: [getDuelActionRow()] });

    // Wait for the player to select an action using buttons
    const filter = i => i.user.id === message.author.id && i.customId.startsWith('action_');
    const collector = messageResponse.createMessageComponentCollector({ filter, time: 30000 });

    return new Promise(resolve => {
      collector.on('collect', async (interaction) => {
        console.log('Player action:', interaction.customId);

        // Handle the player's chosen action
        if (interaction.customId === 'action_attack') {
          // Handle attack action
          // Calculate the damage and update opponent's HP
          const damage = getMax(20, 20); // Change the damage calculation as per your game rules
          opponentHP -= damage;
          battleLogs.push(`${message.author.username} attacks for ${damage} damage!`);
        } else if (interaction.customId === 'action_dodge') {
          // Handle dodge action
          // Implement dodge logic as per your game rules
          // For example, reduce incoming damage or increase player's defense for a turn
          battleLogs.push(`${message.author.username} dodges the attack!`);
        } else if (interaction.customId.startsWith('action_ability_')) {
          // Handle ability action
          // Extract the ability index from the customId and use it to perform the corresponding ability
          const abilityIndex = parseInt(interaction.customId.split('_')[2], 10);
          // Implement ability logic based on your game's abilities
          // For example, deal extra damage, heal, apply status effects, etc.
          const ability = authorAbilities[abilityIndex];
          const abilityDamage = getMax(15, 30); // Change the ability damage calculation as per your game rules
          opponentHP -= abilityDamage;
          battleLogs.push(`${message.author.username} uses ${ability.name} for ${abilityDamage} damage!`);
        }

        // Check if the duel has ended (i.e., one of the players' HP is <= 0)
        const result = checkResults(authorHP, opponentHP);
        console.log('Duel result:', result);
        updateMovesOnCd(authorMoves);
        updateMovesOnCd(opponentMoves);

        if (result) {
          // Duel has ended, display the final result
          battleLogs.push(result);
          const finalEmbed = generateDuelStatusEmbed(author, authorCards, authorHP, opponent, opponentCards, opponentHP, battleLogs);
          message.channel.send({ embeds: [finalEmbed] });
          collector.stop();
          resolve(); // Resolve the promise to indicate the end of the duel loop
        } else {
          // Update the duel status as the duel continues
          const updatedEmbed = generateDuelStatusEmbed(author, authorCards, authorHP, opponent, opponentCards, opponentHP, battleLogs);
          interaction.update({ embeds: [updatedEmbed], components: [getDuelActionRow()] });
        }
      });

      collector.on('end', (collected, reason) => {
        if (reason === 'time') {
          // Handle timeout (player took too long to respond)
          console.log('Player response timed out.');
          message.channel.send('You took too long to respond. The duel has ended.');
          collector.stop();
          resolve(); // Resolve the promise to indicate the end of the duel loop
        }
      });
    });
  }

  // Start the duel loop
  while (authorHP > 0 && opponentHP > 0) {
    console.log('Duel loop iteration:', { authorHP, opponentHP });
    await sendDuelStatus();
  }
} catch (error) {
  console.error('Error executing duel command:', error);
  message.reply({
    content: 'An error occurred while processing the duel command. Please try again later.',
    ephemeral: true,
  });
}
    

  /*  // Send the duel status as a message embed
    const embed = generateDuelStatusEmbed(author, authorCards, authorHP, opponent, opponentCards, opponentHP, battleLogs);
    const messageResponse = await message.channel.send({ embeds: [embed], components: [getDuelActionRow()] });

    // Wait for the player to select an action using buttons
    const filter = i => i.user.id === message.author.id && i.customId.startsWith('action_');
    const collector = messageResponse.createMessageComponentCollector({ filter, time: 30000 });

    collector.on('collect', async (interaction) => {
      console.log('Player action:', interaction.customId); */
 
  },
}; 
// Function to generate the duel action row with buttons
function getDuelActionRow() {
  const row = new ActionRowBuilder()
    .addComponents(
      new ButtonBuilder()
        .setCustomId('action_attack')
        .setLabel('Attack')
        .setStyle('Danger'),
      new ButtonBuilder()
        .setCustomId('action_dodge')
        .setLabel('Dodge')
        .setStyle('Danger')
    );

  // Add ability buttons based on the player's abilities
  // For example:
  // for (let i = 0; i < authorAbilities.length; i++) {
  //   row.addComponents(
  //     new MessageButton()
  //       .setCustomId(`ability_${i}`)
  //       .setLabel(authorAbilities[i].name)
  //       .setStyle('PRIMARY')
  //   );
  // }

  return row;
}

// Function to generate the duel status message embed
function generateDuelStatusEmbed(author, authorCards, authorUserName, opponentUserName, opponentCards, authorHP,  opponent, opponentHP, battleLogs) {
  // Generate the embed content based on the game state and battle logs
  // You can customize the appearance and information displayed in the embed
  // For example, showing player card stats, health bars, etc.
  const embed = new EmbedBuilder()
    .setTitle('Duel Status')
    .setDescription('The duel is ongoing!')
     .addFields(
      { name: `${authorUserName}'s Deck`, value: `${authorCards.join(', ')}`, inline: true },
      { name: `${opponentUserName}'s Deck`, value: `${opponentCards.join(', ')}`, inline: true },
      { name: `${authorUserName}'s HP`, value: authorHP.toString(), inline: true },
      { name: `${opponentUserName}'s HP`, value: opponentHP.toString(), inline: true },
    );

   // Add battle logs only if they are not empty
  if (battleLogs.length > 0) {
    embed.addFields({ name: 'Battle Logs', value: battleLogs.join('\n'), inline: true });
  } else {
    embed.addFields({ name: 'Battle Logs', value: 'No battle logs yet.', inline: true });
  }

  return embed;
}

Editor is loading...