Skip to content

Commit

Permalink
feat: improve coin command randomness and response
Browse files Browse the repository at this point in the history
  • Loading branch information
Guilhermeasper committed Mar 30, 2024
1 parent 586983f commit 61b083f
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 7 deletions.
95 changes: 88 additions & 7 deletions src/bot/commands/slashCommands/coin.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,103 @@
import { SlashCommandBuilder, AttachmentBuilder } from 'discord.js';
import {
SlashCommandBuilder,
AttachmentBuilder,
Embed,
EmbedBuilder,
} from 'discord.js';

import { SlashCommand } from '@marquinhos/types';
import { FlipCoinResult, SlashCommand } from '@marquinhos/types';
import { sleep } from '@marquinhos/utils/sleep';

export const coin: SlashCommand = {
command: new SlashCommandBuilder()
.setName('moeda')
.setDescription('Tiro cara ou coroa numa moeda semi-viciada.'),
execute: async (interaction) => {
const result = ['Cara', 'Coroa'][Math.floor(Math.random() * 2)];
await interaction.deferReply();
await interaction.followUp('Lançando a moeda... 🪙');

const flipCoinResult = await flipCoin();

if (flipCoinResult.result === null) {
return interaction.reply({
content: 'A moeda caiu no ralo e não consegui ver o resultado.',
ephemeral: true,
});
}

const attachment = new AttachmentBuilder(
`./src/resources/images/coin_${result}.png`,
{ name: 'result.png' }
`./src/resources/images/coin_${flipCoinResult.result}.png`
);

const coinEmbed = buildEmbed(
interaction.client.baseEmbed(),
flipCoinResult
);

interaction.reply({
await interaction.editReply({
content: '',
embeds: [coinEmbed],
files: [attachment],
content: `${result}!`,
});
},
cooldown: 10,
};

async function flipCoin(): Promise<FlipCoinResult> {
const randomTime = Math.floor(Math.random() * 5000);
let finalResult = null;
let heads = 0;
let tails = 0;
let count = 0;
let timeEnd = 0;

const timeStart = Date.now();
while (true) {
const result = ['Cara', 'Coroa'][Math.floor(Math.random() * 2)];
result === 'Cara' ? heads++ : tails++;

count++;
if (Date.now() - timeStart > randomTime) {
timeEnd = Date.now();
finalResult = result;
break;
}
await sleep(0);
}
const elapsedTime = timeEnd - timeStart;

return { result: finalResult, heads, tails, count, elapsedTime };
}

function buildEmbed(
baseEmbed: EmbedBuilder,
flipCoinResult: FlipCoinResult
): EmbedBuilder {
return baseEmbed
.setTimestamp()
.setTitle(`Deu ${flipCoinResult.result}!`)
.setDescription(
`A moeda caiu após ${(flipCoinResult.elapsedTime / 1000).toFixed(
2
)}s. Foram feitas ${flipCoinResult.count} tentativas.`
)
.addFields(
{
name: 'Cara',
value: `${flipCoinResult.heads}x | ${(
(flipCoinResult.heads / flipCoinResult.count) *
100
).toFixed(2)}%`,
inline: true,
},
{
name: 'Coroa',
value: `${flipCoinResult.tails}x | ${(
(flipCoinResult.tails / flipCoinResult.count) *
100
).toFixed(2)}%`,
inline: true,
}
)
.setThumbnail(`attachment://coin_${flipCoinResult.result}.png`);
}
9 changes: 9 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,14 @@ export type BalanceChangeStatus = {
validAmount: boolean;
};

export type FlipCoinResult = {
result: string;
heads: number;
tails: number;
count: number;
elapsedTime: number;
};

export interface IBalance extends mongoose.Document {
userId: string;
guildId: string;
Expand Down Expand Up @@ -156,6 +164,7 @@ declare module 'discord.js' {
commands: Collection<string, Command>;
cooldowns: Collection<string, number>;
secretChannels: Collection<string, SecretChannelData>;
baseEmbed: () => EmbedBuilder;
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/utils/sleep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

0 comments on commit 61b083f

Please sign in to comment.