Discord RPG bot在数组中显示每个播放器的ID



我正在尝试学习JavaScript以及如何使用Discord提供的开发人员API。

我确实相信到目前为止我想要的一切都可以正常工作,除了我想创建一个像数据库的工作原理一样。桌上的每个播放器都有一个唯一的ID密钥。我不确定如果不使用DB。

是否可以使用。

[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中,在谈到玩家何时离开的行中。所以!离开。

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

我无法让它仅用于键入该命令的人。

示例:

人一种类型!加入

玩家在线= [Playera]

Person B类型!加入

玩家在线= [Playera,PlayerB]

玩家A类型!离开

玩家在线= [[],playerb]

它始终将一个空数组插入现场。所以我所做的就是将用户上一个名称及其数组ID填充。

  1. 我想要的是,以便它完全删除了该人的数组并删除了空地。

  2. 我也想知道是否有可能每次有人类型!加入!我都可以将它们插入一个具有多维的新数组中,并为每个播放器具有ID,以便当我输入时!在线,它将显示

[[[0,playera],[1,playerb]]。就像一个数据库一样,如果需要,我总是可以看到他们的索引。

到目前为止我拥有的东西:https://i.stack.imgur.com/c1ggn.png

它仅在离开后跟踪最后一个索引。如何使其显示在线玩家的当前索引?

使用FindIndex()在数组中找到名称的位置。然后使用splice()方法从数组中删除值。您无需将其用于循环,因为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。我确定这是存储用户信息的最佳方法,但它可能对您有用。

最新更新