Skip to content

Instantly share code, notes, and snippets.

@dipamsen
Last active October 13, 2023 07:19
Show Gist options
  • Save dipamsen/2b80d411ffdafc94ae710f7bcc21e274 to your computer and use it in GitHub Desktop.
Save dipamsen/2b80d411ffdafc94ae710f7bcc21e274 to your computer and use it in GitHub Desktop.
Number guessing game in Discord.js using Slash Commands
import { SlashCommandBuilder } from "discord.js";
import { gameInfo } from "./startgame.js";
export const data = new SlashCommandBuilder()
.setName("guess")
.setDescription("Guess a number between 1 and 100")
.addIntegerOption((option) =>
option.setName("number").setDescription("Your guess").setRequired(true)
);
export async function execute(interaction) {
if (!gameInfo.game) {
await interaction.reply(
"No game is in progress! Use /startgame to start one."
);
return;
}
const guess = interaction.options.getInteger("number");
const result = gameInfo.game.guess(guess);
await interaction.reply(result);
if (gameInfo.game.number === guess) {
gameInfo.game = null;
}
}
import { SlashCommandBuilder } from "discord.js";
export const data = new SlashCommandBuilder()
.setName("startgame")
.setDescription("Start a number guessing game");
// needs to be an object so that it stores state across imports/exports
// stores global state
export const gameInfo = {
// stores a single game object, can be modified to an Array/Map to store
// multiple games at a time (eg. for multiple guilds)
game: null,
};
export async function execute(interaction) {
if (gameInfo.game) {
await interaction.reply("A game is already in progress!");
return;
}
await interaction.reply(
"Let's start a number guessing game! I'm thinking of a number between 1 and 100. What's your guess? (/guess)"
);
gameInfo.game = new NumberGuesser();
}
// A better organisation would be to extract out all the game stuff to a different file outside `commands/` and import them in here.
export class NumberGuesser {
constructor() {
this.number = Math.floor(Math.random() * 100) + 1;
this.guesses = 0;
}
guess(n) {
this.guesses++;
if (n < this.number) {
return "Your guess is too low!";
} else if (n > this.number) {
return "Your guess is too high!";
} else {
return `You got it in ${this.guesses} guesses!`;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment