Skip to content

Commit

Permalink
Merge pull request #1 from sam123114/dev
Browse files Browse the repository at this point in the history
Merging dev with master
  • Loading branch information
sam123114 authored Nov 15, 2022
2 parents c9bd910 + 6df8789 commit e570610
Show file tree
Hide file tree
Showing 15 changed files with 2,822 additions and 1,746 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# LolQuizz

This is a project I made for fun. If you have any suggestions or want to update it youself, you can create a issue or a pull request.
16 changes: 16 additions & 0 deletions commands/info.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { SlashCommandBuilder, EmbedBuilder, AttachmentBuilder } = require('discord.js');

module.exports = {
data: new SlashCommandBuilder()
.setName('info')
.setDescription("Used to get more information about the game and the rules"),
async execute(interaction) {
const attachment = new AttachmentBuilder('./images/author_logo.jpg');
const infoEmbed = new EmbedBuilder()
.setTitle('LolQuizz')
.setColor(0xFF0000)
.setDescription('**Rules:**\nLolQuizz is a game in which you will hear the quote of a random champion and the first person to guess the champion wins.\n**Commands:**\n🔸 **/info** Rules and list of command\n🔸 **/start** Start a new game\n🔸 **/stop** End the game')
.setFooter({ text: 'By Sam | イボイノシシ#0878', iconURL: 'attachment://author_logo.jpg' });
interaction.reply({ embeds: [infoEmbed], files: [attachment] });
},
};
35 changes: 35 additions & 0 deletions commands/start.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { SlashCommandBuilder, Integration } = require('discord.js');
const gameManager = require('../managers/game-manager.js');

module.exports = {
data: new SlashCommandBuilder()
.setName('start')
.setDescription("Start a new game of LolQuizz")
.addStringOption(option =>
option.setName('mode')
.setDescription('Used to choose the game mode that you want to play')
.setRequired(true)
.addChoices(
{ name: 'Normal', value: 'normal' }
)
),
async execute(interaction) {
//we want to add the game to the games array
let guildId = interaction.guildId;
let gameInstance = gameManager.getGame(guildId);
if (gameInstance === false) {
gameInstance = gameManager.addGame(guildId, interaction.channel);

//sending embed for game settings
result = gameInstance.getCurrentEmbed();
if (result !== false) {
interaction.reply({ embeds: [result.embed], components: [result.actionRow] });
gameInstance.Message = await interaction.fetchReply();
} else {
interaction.reply({ content: 'An error occured while generating the embed', ephemeral: true });
}
} else {
interaction.reply({ content: 'A game is already in progress in this server', ephemeral: true });
}
},
};
23 changes: 23 additions & 0 deletions commands/stop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { SlashCommandBuilder } = require('discord.js');
const gameManager = require('../managers/game-manager.js');

module.exports = {
data: new SlashCommandBuilder()
.setName('stop')
.setDescription("End the game"),
async execute(interaction) {
//we want to add the game to the games array
let guildId = interaction.guildId;
let gameInstance = gameManager.getGame(guildId);
if (gameInstance !== false) {
gameInstance.stopGame();
gameManager.clearGame(guildId);

interaction.update({ embeds: [result.embed], components: [result.actionRow] });

// interaction.reply({ content: 'The game has been stopped' });
} else {
interaction.reply({ content: 'There is no game currently in progress', ephemeral: true });
}
},
};
26 changes: 26 additions & 0 deletions deploy-commands.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* This is a script used to deploy commands to your discord server
*/
const fs = require('node:fs');
const path = require('node:path');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord.js');
require('dotenv').config();

const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
commands.push(command.data.toJSON());
}

const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);

exports.deployCommands = function (clientId, guildId) {
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log(`Successfully registered application commands for guild ID (${guildId})`))
.catch((err) => console.log(`Failed to deploy application commands on guild ID (${guildId}). Error: ${err.rawError.message}`));
}
61 changes: 61 additions & 0 deletions events/button-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const gameManager = require('../managers/game-manager.js');

module.exports = {
name: 'interactionCreate',
once: false,
async execute(interaction) {
if (!interaction.isButton()) return;

let guildId = interaction.guildId;
let gameInstance = gameManager.getGame(guildId);
if (gameInstance !== false) {
let interactionId = interaction.customId;
let action = interactionId.split("_")[1];

if (gameInstance.State == 'IN_CREATION') {
if (action == 'JOIN') {
gameInstance.addPlayer(interaction.user);
} else if (action == 'LEAVE') {
gameInstance.removePlayer(interaction.user);
} else if (action == 'START') {
if (!interaction.member.voice.channel) {
interaction.reply({ content: 'You need to enter a voice channel in order to start the game', ephemeral: true });
return;
}
if (gameInstance.Players.length === 0) {
interaction.reply({ content: 'There needs to be at least one player in order to start the game', ephemeral: true });
}
gameInstance.startGame(interaction.member.voice.channel);
} else {
interaction.reply({ content: 'An error occured', ephemeral: true });
return;
}
} else if (gameInstance.State == 'IN_PROGRESS') {
if (action == 'REPLAY') {
gameInstance.playCurrent();
} else if (action == 'SKIP') {
gameInstance.nextRound();
} else if (action == 'STOP') {
gameInstance.stopGame();
gameManager.clearGame(guildId);
} else {
interaction.reply({ content: 'An error occured', ephemeral: true });
return;
}
} else {
interaction.reply({ content: 'An error occured', ephemeral: true });
return;
}

//sending embed for game settings
result = gameInstance.getCurrentEmbed();
if (result !== false) {
interaction.update({ embeds: [result.embed], components: result.actionRow ? [result.actionRow] : [], files: result.files ? [result.files] : [] });
} else {
interaction.reply({ content: 'An error occured while generating the embed', ephemeral: true });
}
} else {
interaction.reply({ content: 'No game is currently in progress in this server', ephemeral: true });
}
},
};
20 changes: 20 additions & 0 deletions events/command-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports = {
name: 'interactionCreate',
once: false,
async execute(interaction) {
const client = interaction.client;

if (!interaction.isChatInputCommand()) return;

const command = client.commands.get(interaction.commandName);

if (!command) return;

try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
},
};
35 changes: 35 additions & 0 deletions events/message-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const gameManager = require('../managers/game-manager.js');

module.exports = {
name: 'messageCreate',
once: false,
async execute(msg) {
if (msg.author.bot) {
return;
}
let guildId = msg.guildId;
let gameInstance = gameManager.getGame(guildId);
if (gameInstance !== false && msg.channel.id == gameInstance.Channel.id) {
if (gameInstance.State != 'IN_PROGRESS') {
return;
}

//deleting message
msg.delete();

if (!gameInstance.isPlayer(msg.author)) {
return
}

if (gameInstance.validateResponse(msg.author.id, msg.content)) {
//starting next round
gameInstance.nextRound();

//updating message
result = gameInstance.getCurrentEmbed();

gameInstance.Message.edit({ embeds: [result.embed], components: [result.actionRow] });
}
}
},
};
33 changes: 19 additions & 14 deletions helpers/champion_data_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,22 @@ const { resolve } = require('path');

const dataFilePath = './data/champion_data.json';

exports.updateChampionData = function(lastestVersion) {
try{
const champion_data = ReadFileSync(dataFilePath);
if (champion_data['version'] !== lastestVersion) {
exports.updateChampionData = function (lastestVersion) {
try {
let createOrUpdateFile = false;

if (!fs.existsSync(dataFilePath)) {
//if the file doesn't exist, we want to create it.
createOrUpdateFile = true;
} else {
//if the file does exist, we want to update it if necessary.
const championData = ReadFileSync(dataFilePath);
if (championData.version !== lastestVersion) {
createOrUpdateFile = true;
}
}

if (createOrUpdateFile) {
fetchChampionData(lastestVersion).then(new_champion_data => {
WriteFileSync(dataFilePath, JSON.stringify(new_champion_data));
console.log("Champion data file was updated. New version: " + lastestVersion);
Expand All @@ -25,23 +37,16 @@ exports.getChampions = function () {
return champion_data.data;
}

exports.selectChampionRandomly = function () {
const champion_data = ReadFileSync(dataFilePath);
let champions = Object.keys(champion_data.data);
let champion = champions[Math.floor(Math.random() * Object.keys(champion_data.data).length)];
return champion_data.data[champion];
}

//private functions
const fetchChampionData = function(version) {
const fetchChampionData = function (version) {
return fetch(`http://ddragon.leagueoflegends.com/cdn/${version}/data/en_US/champion.json`).then(res => res.json()).then(json => json).catch(console.error);
}

const ReadFileSync = function(filePath) {
const ReadFileSync = function (filePath) {
const data = fs.readFileSync(filePath);
return JSON.parse(data);
}

const WriteFileSync = function(filePath, jsonString) {
const WriteFileSync = function (filePath, jsonString) {
fs.writeFileSync(filePath, jsonString);
}
Binary file modified images/author_logo.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit e570610

Please sign in to comment.