繁体   English   中英

阵列中每个玩家的Discord RPG Bot显示ID

[英]Discord RPG Bot display ids for each player in array

我正在尝试学习javascript,以及如何使用discord提供的开发人员api。

我确实相信到目前为止我想要的一切都可以正常工作,但我想创建一个像数据库一样工作的系统。 表中的每个玩家都有唯一的ID密钥。 我不确定在不使用数据库的情况下是否有可能。

[Index.js]

/* Discord API Information */
const Discord = require('discord.js');
const token = '';
const Game = require('./game.js');
const client = new Discord.Client();

let playersName = []; // tracks each player that joins
let currPlayers = 0; //tracker for total players online
let INIT_GAME;
let userJoined = false;
let inBattle = false;

client.on('message', (msg) => {
    if(msg.content === '!join'){

        // Prevents multiple instances of the same person from joining
        for(var x = 0; x < playersName.length; x++){
            if(playersName[x]===msg.author.username){
                return playersName[x];
            }
        }

        currPlayers++;
        userJoined = true;
        playersName.push(msg.author.username);

        //My attempt at having the question im asking
        function convertToID(arr, width) {
            return arr.reduce(function (rows, key, index) {
              return (index % width == 0 ? rows.push([key])
                : rows[rows.length-1].push(key)) && rows;
            }, []);
          }

        console.log(convertToID(playersName,1)); /* Tracks players by ID in developer tools */

        INIT_GAME = new Game(playersName, client, 'bot-testing', currPlayers);
        let myRet = INIT_GAME.startGame();

        const embed = new Discord.RichEmbed()
        .setTitle("Welcome To Era Online")
        .setColor(0xFF0000)
        .addField(`${msg.author.username} has Joined`, myRet);
        msg.channel.send(embed);
        msg.channel.send(`${msg.author} has joined the game.`);
        return;
    }

    if(userJoined == true){
        if(msg.content === '!fight' && (!inBattle)){
            let grabCurrPlayer = msg.author.username;
            msg.channel.send(`${INIT_GAME.initBattle(grabCurrPlayer)}`);
        }

        else if(msg.content === '!leave'){
            let tempLeave = msg.author.username;

            for(var y = 0; y < playersName.length; y++){
                if(playersName[y] == msg.author.username){
                    playersName[y] = [`${playersName[y]} was previously ID: ` + [y]];
                    currPlayers--;
                }
            }
            msg.channel.send([`${tempLeave} has left the server.`]);
            userJoined = false;
        }

        else if(msg.content === '!newgame'){
            msg.channel.send(INIT_GAME.newGame());
        }

        /* Simply checks the bonus damage. command for developer*/
        else if(msg.content === '!bonus'){
            msg.channel.send(INIT_GAME.bonusAttack());
        }  
    }

    /* checks whose currently online. command for developer*/
    if(msg.content === '!online'){
        msg.channel.send(INIT_GAME.getOnline());
    }

});

client.on('ready', () => {
    console.log('Bot is now connected');
});

client.login(token);

[game.js]

class Game {
    constructor(player, client, channelName='bot-testing', playersOnline){
         this.client = client;
         this.channelName = channelName;
         this.currentPlayer = player;   
         this.playersOnline = [];
         this.hitpoints = 120;
         this.damage = '';
         this.chance = 3;
         this.inBattle = false;
         this.online = playersOnline;

        this.monster = [{
            hp: Math.floor(Math.random() * 200),
            temphp: 0,
            damage: 10
        }];
    };

    /* main menu information, players online */
    startGame(){
            for(var x = 0; x < this.currentPlayer.length; x++){
                this.playersOnline.push(this.currentPlayer[x]);
                if(this.playersOnline[x] === this.currentPlayer[x]){
                    return [`Players Online: ${this.online}\n`];
            }
         }
    }

    /* Battle system */
    initBattle(currPlayer){
        this.inBattle = true;
        let npcHP = this.monster[0].hp;
        let numberOfAttacks = 0;
        let totalDamage=0, totalBonusDamage=0;

        while( this.monster[0].hp > 0 ){
            let playerDamage = Math.floor(Math.random() * (npcHP / 4));  
            if(this.bonusAttack() === 2){
                console.log(`Bonus Attack: ${this.bonusAttack()}`);
                console.log(`Regular damage without bonus attack: ${playerDamage}`);
                playerDamage = playerDamage + 2; 
            }
            this.monster[0].hp -= playerDamage;
            this.hitpoints -= this.monster[0].damage;

            console.log('Monster: ' + this.monster[0].hp);
            console.log('Player: ' + this.hitpoints);
            console.log(`${currPlayer} has attacked for ${playerDamage}`);
            console.log(`NPC health: ${this.monster[0].hp}`);   

            if(this.hitpoints <= 0){
                return [`You lost the battle.`];
            }

            this.inBattle = false;
            numberOfAttacks++; 
            totalDamage += playerDamage;
            totalBonusDamage = playerDamage + this.bonusAttack();    
        }
        if(this.monster[0].hp <= 0 && this.inBattle !== true){
            let maxDamage = totalDamage + totalBonusDamage; 
            return [`${currPlayer} has attacked ${numberOfAttacks} times dealing ${totalDamage} + (${totalBonusDamage}) bonus damage for a total of ${maxDamage} damage. The monster is dead.\n
            Your Health: ${this.hitpoints}`];
        } 
        else{
            this.newGame();
            return [`You rejuvenated your hitpoints and are ready for battle. \nType !fight again to start a new battle!`];
        }
    }

    /* bonus attack damage [ 1 in 3 chance ] */
    bonusAttack(bonusDamage){
        let chance = Math.floor(Math.random() * 3);
        return chance === 2 ? bonusDamage = 2 : false;
    }

    /* displays players currently online */
    getOnline(){
        console.log(this.currentPlayer);
        return this.currentPlayer;

    }

    /* refresh stats */
    newGame(){
        this.monster[0].hp = Math.floor(Math.random() * 50);
        this.hitpoints = 150;
    }
}

module.exports = Game;

[我的问题]

在这两个文件中,唯一真正重要的部分是在index.js中,这是有关播放器何时离开的那一行。 所以!离开。

我遇到一个问题,一个玩家输入!leave,两个人都会离开。 那就是我用来修复它的解决方案。

我无法让输入命令的人只清空数组。

例:

人A类型!加入

在线玩家= [PlayerA]

B人类型!加入

在线玩家= [玩家A,玩家B]

玩家A类型!离开

在线玩家= [[],PlayerB]]

它将总是在该位置插入一个空数组。 因此,我要做的只是用用户的先前姓名和他们的数组ID填充该位置。

  1. 我想要的是使它完全从阵列中删除该人并删除该空白点。

  2. 我也想知道是否有可能每次有人输入!join时,我都可以将它们插入一个多维的新数组中,该数组具有每个玩家的ID,这样当我输入!online时,它将显示

[[0,PlayerA],[1,PlayerB]]。 就像一个数据库,如果需要,我可以随时查看它们的索引。

到目前为止,我所拥有的: https : //i.imgur.com/lWrtEtB.png

它们仅在离开后跟踪最后一个索引。 如何使其在线显示球员的当前指数?

使用findIndex()查找名称在数组中的位置。 然后使用splice()方法从数组中删除一个值。 您无需将其用于for循环,因为findIndex将运行类似的循环。

var playerIndex = playersName.findIndex(function(index) {
  return index === tempLeave
})
playersName.splice(playerIndex, 1)

在阅读了问题的第二部分之后,我认为您应该在数组内部创建对象。 一个例子是:

[
  {
   playerName: "Foo",
   id: indexNumber,
   isOnline: true
  },
 {
  playerName: "Bar",
  id: indexNumber,
  isOnline: true
 }
]

当某人加入时,您检查其姓名是否已分配给对象(您可以在此处再次使用findIndex)。 如果不创建新的播放器,则将播放器的isOnline属性更改为true。 我确定这是存储用户信息的最佳方法,但它可能对您有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM