类型错误:SnakeGame 不是构造函数

时间:2021-01-16 22:17:57

标签: javascript node.js visual-studio-code discord discord.js

我正在尝试为我的不和谐机器人创建一个蛇命令,从我在网上找到但无法在我的代码中实现它的代码中获取 spunot!在控制台日志中,错误是这样的:

TypeError: SnakeGame is not a constructor

代码是这样的:

const Discord = require("discord.js");
const client = new Discord.Client({partials: ["MESSAGE", "CHANNEL", "REACTION"]});

...

//snake (Work in progress)
    const snakeGame = new SnakeGame(client);

    const WIDTH = 15;
    const HEIGHT = 10;
    const gameBoard = [];
    const apple = { x: 1, y: 1 };

    var SnakeGame = class SnakeGame {
        constructor() {
            this.snake = [{ x: 5, y: 5 }];
            this.snakeLength = 1;
            this.score = 0;
            this.gameEmbed = null;
            this.inGame = false;
            for (let y = 0; y < HEIGHT; y++) {
                for (let x = 0; x < WIDTH; x++) {
                    gameBoard[y * WIDTH + x] = "?";
                }
            }
        }

        gameBoardToString() {
            let str = ""
            for (let y = 0; y < HEIGHT; y++) {
                for (let x = 0; x < WIDTH; x++) {
                    if (x == apple.x && y == apple.y) {
                        str += "?";
                        continue;
                    }

                    let flag = true;
                    for (let s = 0; s < this.snake.length; s++) {
                        if (x == this.snake[s].x && y == this.snake[s].y) {
                            str += "?";
                            flag = false;
                        }
                    }

                    if (flag)
                        str += gameBoard[y * WIDTH + x];
                }
                str += "\n";
            }
            return str;
        }

        isLocInSnake(pos) {
            return this.snake.find(sPos => sPos.x == pos.x && sPos.y == pos.y);
        };

        newAppleLoc() {
            let newApplePos = { x: 0, y: 0 };
            do {
                newApplePos = { x: parseInt(Math.random() * WIDTH), y: parseInt(Math.random() * HEIGHT) };
            } while (this.isLocInSnake(newApplePos))

            apple.x = newApplePos.x;
            apple.y = newApplePos.y;
        }

        newGame(msg) {
            if (this.inGame)
                return;

            this.inGame = true;
            this.score = 0;
            this.snakeLength = 1;
            this.snake = [{ x: 5, y: 5 }];
            this.newAppleLoc();
            const embed = new Discord.MessageEmbed()
                .setColor('#03ad03')
                .setTitle('Snake Game')
                .setDescription(this.gameBoardToString())
                .setTimestamp();

            msg.channel.send(embed).then(emsg => {
                this.gameEmbed = emsg;
                this.gameEmbed.react('⬅️');
                this.gameEmbed.react('⬆️');
                this.gameEmbed.react('⬇️');
                this.gameEmbed.react('➡️');

                this.waitForReaction();
            });
        }

        step() {
            if (apple.x == this.snake[0].x && apple.y == this.snake[0].y) {
                this.score += 1;
                this.snakeLength++;
                this.newAppleLoc();
            }

            const editEmbed = new Discord.MessageEmbed()
                .setColor('#03ad03')
                .setTitle('Snake Game')
                .setDescription(this.gameBoardToString())
                .setTimestamp();
            this.gameEmbed.edit(editEmbed);

            this.waitForReaction();
        }

        gameOver() {
            this.inGame = false;
            const editEmbed = new Discord.MessageEmbed()
                .setColor('#03ad03')
                .setTitle('Snake Game')
                .setDescription("GAME OVER!\nSCORE: " + this.score)
                .setTimestamp();
            this.gameEmbed.edit(editEmbed);

            this.gameEmbed.reactions.removeAll()
        }

        filter(reaction, user) {
            return ['⬅️', '⬆️', '⬇️', '➡️'].includes(reaction.emoji.name) && user.id !== this.gameEmbed.author.id;
        }

        waitForReaction() {
            this.gameEmbed.awaitReactions((reaction, user) => this.filter(reaction, user), { max: 1, time: 60000, errors: ['time'] })
                .then(collected => {
                    const reaction = collected.first();

                    const snakeHead = this.snake[0];
                    const nextPos = { x: snakeHead.x, y: snakeHead.y };
                    if (reaction.emoji.name === '⬅️') {
                        let nextX = snakeHead.x - 1;
                        if (nextX < 0)
                            nextX = WIDTH - 1;
                        nextPos.x = nextX;
                    }
                    else if (reaction.emoji.name === '⬆️') {
                        let nextY = snakeHead.y - 1;
                        if (nextY < 0)
                            nextY = HEIGHT - 1;
                        nextPos.y = nextY;
                    }
                    else if (reaction.emoji.name === '⬇️') {
                        let nextY = snakeHead.y + 1;
                        if (nextY >= HEIGHT)
                            nextY = 0;
                        nextPos.y = nextY;
                    }
                    else if (reaction.emoji.name === '➡️') {
                        let nextX = snakeHead.x + 1;
                        if (nextX >= WIDTH)
                            nextX = 0;
                        nextPos.x = nextX;
                    }

                    reaction.users.remove(reaction.users.cache.filter(user => user.id !== this.gameEmbed.author.id).first().id).then(() => {
                        if (this.isLocInSnake(nextPos)) {
                            this.gameOver();
                        }
                        else {
                            this.snake.unshift(nextPos);
                            if (this.snake.length > this.snakeLength)
                                this.snake.pop();

                            this.step();
                        }
                    });
                })
                .catch(collected => {
                    this.gameOver();
                });
        }
    }
    
    if (msg.startsWith(prefix + 'snake')) {
        snakeGame.newGame(msg);
    }

我尝试在任何地方添加 var 和 const 但它仍然不起作用:(( “...”是其他命令,所以 nvm。 谢谢帮忙?

1 个答案:

答案 0 :(得分:0)

您在第一行使用了 SnakeGame 类,但该类在下面几行中定义。
您需要确保先定义该类,然后再使用:

const WIDTH = 15;
const HEIGHT = 10;
const gameBoard = [];
const apple = { x: 1, y: 1 };

//original code: var SnakeGame = class SnakeGame - assigning class to a variable with the same name is pointless, so just define the class
class SnakeGame {// that entire code for the class...}

// creating class instance after the class has been defined
const snakeGame = new SnakeGame(client);