Skip to content
This repository has been archived by the owner on Dec 9, 2024. It is now read-only.

Commit

Permalink
allow bet on same line
Browse files Browse the repository at this point in the history
  • Loading branch information
sean351 committed Mar 25, 2024
1 parent 84cbb11 commit e0904f2
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 35 deletions.
37 changes: 25 additions & 12 deletions commands/games-sp/blackjack.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,20 @@ module.exports = class BlackjackCommand extends Command {
group: 'games-sp',
memberName: 'blackjack',
description: 'Play a game of blackjack.',
args: [
{
key: 'bet',
prompt: 'How much would you like to bet?',
type: 'integer',
default: 0,
max: (msg) => msg.client.casinoUtils.getBalance(msg.author.id),
}
]
});
}

async run(msg) {
async run(msg, { betAmount }) {
let finalBet;
if (await this.client.casinoUtils.checkChannel(msg.channel.id, msg.client.casinoChannel)) {
return msg.reply('Please use this command in a casino channel.');
}
Expand All @@ -30,8 +40,11 @@ module.exports = class BlackjackCommand extends Command {
event: 'PLAYER_JOINED',
playerId: msg.author.id,
}, 'blackjack');
const betAmount = await msg.client.casinoUtils.waitForBet(msg);
await msg.client.casinoUtils.placeBet(msg, betAmount, id, 'blackjack');
if (betAmount <= 0) {
finalBet = await msg.client.casinoUtils.waitForBet(msg);
}
finalBet = bet;
await msg.client.casinoUtils.placeBet(msg, finalBet, id, 'blackjack');
const deck = msg.client.casinoGames.get(id).data;

const dealerHand = [];
Expand All @@ -44,7 +57,7 @@ module.exports = class BlackjackCommand extends Command {
return msg.say(`Your new token balance is ${await msg.client.dbHelper.getBalance(msg.author.id)}`);
}

await this.playPlayerTurn(msg, deck, playerHand, dealerHand, id, betAmount);
await this.playPlayerTurn(msg, deck, playerHand, dealerHand, id, finalBet);
} catch (error) {
msg.client.botLogger({
embed: msg.client.errorMessage(
Expand All @@ -58,7 +71,7 @@ module.exports = class BlackjackCommand extends Command {
return msg.say('An error occurred during the game. Please try again later.');
}
}
async handleInitialRound(msg, dealerTotal, playerTotal, id, playerId, betAmount) {
async handleInitialRound(msg, dealerTotal, playerTotal, id, playerId, finalBet) {
if (dealerTotal === 21 && playerTotal === 21) { // PUSH
await msg.client.dbHelper.createGameLog({
gameId: id,
Expand All @@ -77,7 +90,7 @@ module.exports = class BlackjackCommand extends Command {
event: 'DEALER_WIN',
playerId: '1'
}, 'blackjack');
await msg.client.casinoUtils.calcWinUpdateBal(msg, 0, betAmount, false);
await msg.client.casinoUtils.calcWinUpdateBal(msg, 0, finalBet, false);
return 'Ouch, the dealer hit blackjack right away! Try again!';
} else if (playerTotal === 21) { // Player BJ
await msg.client.dbHelper.createGameLog({
Expand All @@ -90,12 +103,12 @@ module.exports = class BlackjackCommand extends Command {
event: 'PLAYER_WIN',
playerId: playerId,
}, 'blackjack');
await msg.client.casinoUtils.calcWinUpdateBal(msg, betAmount * 2, betAmount, true);
await msg.client.casinoUtils.calcWinUpdateBal(msg, finalBet * 2, finalBet, true);
return 'Wow, you hit blackjack right away! Lucky you!';
}
return null;
}
async playPlayerTurn(msg, deck, playerHand, dealerHand, gameId, betAmount) {
async playPlayerTurn(msg, deck, playerHand, dealerHand, gameId, finalBet) {
let isPlaying = true;
let canSplit = this.checkSplitPossibility(playerHand);

Expand Down Expand Up @@ -172,19 +185,19 @@ module.exports = class BlackjackCommand extends Command {
if (winner === 'Dealer Wins!') {
// Log dealer win event after confirming outcome
await msg.client.dbHelper.createGameLog({ gameId, event: 'DEALER_WIN', playerId: msg.author.id }, 'blackjack');
await msg.client.casinoUtils.calcWinUpdateBal(msg, false, betAmount, betAmount);
await msg.client.casinoUtils.calcWinUpdateBal(msg, false, finalBet, finalBet);
return msg.reply(`You lost!, your new token balance is ${await msg.client.dbHelper.getBalance(msg.author.id)}`);
} else if (winner === 'You Win!') {
let winAmount;
// Calculate win amount based on bet and blackjack payout (optional)
if (this.calculate(playerHand) === 21 && playerHand.length === 2) { // Check for Blackjack
winAmount = betAmount * 2.5; // Hypothetical 3:2 payout for Blackjack
winAmount = finalBet * 2.5; // Hypothetical 3:2 payout for Blackjack
} else {
winAmount = betAmount; // Hypothetical 1:1 payout for regular win
winAmount = finalBet; // Hypothetical 1:1 payout for regular win
}
// You can optionally add logic here to log a player win event
await msg.client.dbHelper.createGameLog({ gameId, event: 'PLAYER_WIN', playerId: msg.author.id }, 'blackjack');
await msg.client.casinoUtils.calcWinUpdateBal(msg, true, betAmount, winAmount);
await msg.client.casinoUtils.calcWinUpdateBal(msg, true, finalBet, winAmount);
return msg.reply(`You won!, your new token balance is ${await msg.client.dbHelper.getBalance(msg.author.id)}`);
} else if (winner === 'Push!') {
// You can optionally add logic here to log a push event
Expand Down
57 changes: 34 additions & 23 deletions commands/games-sp/roulette.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = class RouletteCommand extends Command {
description: 'Play a game of roulette.',
args: [
{
key: 'bet',
key: 'betType',
prompt: `What betType would you like to place? i.e. ${['straightUp', 'split', 'street', 'corner', 'fiveNumberBet', 'redBlack', 'evenOdd', 'highLow', 'dozens', 'columns', 'red', 'black']}`,
type: 'string',
validate: (bet) => {
Expand All @@ -24,11 +24,19 @@ module.exports = class RouletteCommand extends Command {
}
},
},
{
key: 'betAmount',
prompt: 'How much would you like to bet?',
type: 'integer',
default: 0,
max: (msg) => msg.client.casinoUtils.getBalance(msg.author.id),
},
],
});
}

async run(msg, { bet }) {
async run(msg, { betType, betAmount }) {
let finalBet;
if (await this.client.casinoUtils.checkChannel(msg.channel.id, msg.client.casinoChannel)) {
return msg.reply('Please use this command in a casino channel.');
}
Expand All @@ -46,8 +54,11 @@ module.exports = class RouletteCommand extends Command {
event: 'PLAYER_JOINED',
playerId: msg.author.id,
}, 'roulette');
const betAmount = await msg.client.casinoUtils.waitForBet(msg);
await msg.client.casinoUtils.placeBet(msg, betAmount, id, 'roulette');
if (betAmount <= 0) {
finalBet = await msg.client.casinoUtils.waitForBet(msg);
}
finalBet = betAmount;
await msg.client.casinoUtils.placeBet(msg, finalBet, id, 'roulette');
await msg.client.dbHelper.createGameLog({
gameId: id,
event: 'PLACED_BETS_CLOSED',
Expand All @@ -56,7 +67,7 @@ module.exports = class RouletteCommand extends Command {
msg.say('Bets placed. Game starting...');

// get winnings
const winnings = this.calculateRouletteWinnings(msg, bet, betAmount, 'european');
const winnings = this.calculateRouletteWinnings(msg, betType, finalBet, 'european');
await msg.client.dbHelper.createGameLog({
gameId: id,
event: 'WHEEL_SPUN',
Expand All @@ -77,11 +88,11 @@ module.exports = class RouletteCommand extends Command {
event: 'WINNINGS_DISTRIBUTED',
playerId: msg.author.id,
}, 'roulette');
newBal = await msg.client.casinoUtils.calcWinUpdateBal(msg, true, betAmount, winnings)
newBal = await msg.client.casinoUtils.calcWinUpdateBal(msg, true, finalBet, winnings)
resultMessage = `Congratulations! You won ${winnings} on your ${bet} bet.`;
newBal ? resultMessage += ` Your new token balance is ${newBal}.` : resultMessage = 'Error updating balance';
} else {
newBal = await msg.client.casinoUtils.calcWinUpdateBal(msg, false, betAmount, winnings);
newBal = await msg.client.casinoUtils.calcWinUpdateBal(msg, false, finalBet, winnings);
resultMessage = `Sorry, you didn't win this round.`;
newBal ? resultMessage += ` Your new token balance is ${newBal}.` : resultMessage = 'Error updating balance'
}
Expand All @@ -107,7 +118,7 @@ module.exports = class RouletteCommand extends Command {
}
}

calculateRouletteWinnings(msg, betType, betAmount, rouletteVariant) {
calculateRouletteWinnings(msg, betType, finalBet, rouletteVariant) {
const payouts = this.getPayouts(rouletteVariant); // Function to retrieve payouts based on variant

// Check if the bet type exists
Expand All @@ -121,68 +132,68 @@ module.exports = class RouletteCommand extends Command {
let winnings = 0;
switch (betType) {
case 'straightUp':
winnings = betAmount * payouts[betType] ** (winningNumber === betAmount); // Direct number match using exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** (winningNumber === finalBet); // Direct number match using exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'split':
winnings = betAmount * payouts[betType] ** ([betAmount - 1, betAmount + 1].includes(winningNumber)); // Adjacent numbers, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** ([finalBet - 1, finalBet + 1].includes(winningNumber)); // Adjacent numbers, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'street':
const streetStart = Math.floor((betAmount - 1) / 3) * 3 + 1; // Calculate street starting number
winnings = betAmount * payouts[betType] ** ([streetStart, streetStart + 1, streetStart + 2].includes(winningNumber)); // Numbers in the street, exponentiation for boolean conversion
const streetStart = Math.floor((finalBet - 1) / 3) * 3 + 1; // Calculate street starting number
winnings = finalBet * payouts[betType] ** ([streetStart, streetStart + 1, streetStart + 2].includes(winningNumber)); // Numbers in the street, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'corner':
const cornerRow = Math.floor((betAmount - 1) / 4); // Calculate corner row
const cornerCol = (betAmount - 1) % 4; // Calculate corner column
const cornerRow = Math.floor((finalBet - 1) / 4); // Calculate corner row
const cornerCol = (finalBet - 1) % 4; // Calculate corner column
const cornerNumbers = [
cornerRow * 4 + cornerCol + 1,
cornerRow * 4 + cornerCol + 2,
(cornerRow + 1) * 4 + cornerCol + 1,
(cornerRow + 1) * 4 + cornerCol + 2,
];
winnings = betAmount * payouts[betType] ** (cornerNumbers.includes(winningNumber)); // Numbers in the corner, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** (cornerNumbers.includes(winningNumber)); // Numbers in the corner, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'fiveNumberBet': // American Roulette only
if (rouletteVariant !== 'american') {
throw new Error('Five Number Bet is only available in American Roulette');
}
winnings = betAmount * payouts[betType] * ([0, 0o0, 1, 2, 3].includes(winningNumber));
winnings = finalBet * payouts[betType] * ([0, 0o0, 1, 2, 3].includes(winningNumber));
msg.say(`The winning number is ${winningNumber}`);
break;
case 'redBlack':
const winningColor = winningNumber === 0 ? 'green' : (winningNumber % 2 === 0 ? 'black' : 'red');
winnings = betAmount * payouts[betType] ** (winningColor === betAmount); // Color match, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** (winningColor === finalBet); // Color match, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber} ${winningColor}`);
break;
case 'black':
winnings = betAmount * payouts[betType] ** (winningNumber === 0); // Zero match, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** (winningNumber === 0); // Zero match, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'red':
winnings = betAmount * payouts[betType] ** (winningNumber !== 0 && winningNumber % 2 !== 0); // Red match, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** (winningNumber !== 0 && winningNumber % 2 !== 0); // Red match, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'evenOdd':
winnings = betAmount * payouts[betType] ** ((winningNumber % 2 === 0 && betAmount === 'even') || (winningNumber % 2 !== 0 && betAmount === 'odd')); // Even/odd match, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** ((winningNumber % 2 === 0 && finalBet === 'even') || (winningNumber % 2 !== 0 && finalBet === 'odd')); // Even/odd match, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'highLow':
const highLowBoundary = 18;
winnings = betAmount * payouts[betType] ** ((winningNumber >= highLowBoundary && betAmount === 'high') || (winningNumber < highLowBoundary && betAmount === 'low')); // High/low match, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** ((winningNumber >= highLowBoundary && finalBet === 'high') || (winningNumber < highLowBoundary && finalBet === 'low')); // High/low match, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'dozens':
const dozen = Math.ceil(winningNumber / 12);
winnings = betAmount * payouts[betType] ** (dozen === betAmount); // Dozen match, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** (dozen === finalBet); // Dozen match, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
case 'columns':
const column = Math.ceil(betAmount / 3);
const columnNumbers = [column, column + 3, column + 6];
winnings = betAmount * payouts[betType] ** (columnNumbers.includes(winningNumber)); // Column match, exponentiation for boolean conversion
winnings = finalBet * payouts[betType] ** (columnNumbers.includes(winningNumber)); // Column match, exponentiation for boolean conversion
msg.say(`The winning number is ${winningNumber}`);
break;
default:
Expand Down
71 changes: 71 additions & 0 deletions util/casinoUtils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const Jimp = require('jimp');
const fs = require('fs/promises');

module.exports = class CasinoUtils {
constructor() {
Expand Down Expand Up @@ -106,4 +108,73 @@ module.exports = class CasinoUtils {
validateRouletteBet(betInput) {
return this.validRouletteBets.includes(betInput);
}

getImagePath(value) {
return `./assets/images/deck/${value}.png`;
}

async combineImagesToFile(imagePaths, outputWidth = 200, outputHeight = 200) {
if (!imagePaths || imagePaths.length === 0) {
throw new Error('No image paths provided');
}

try {
// Read all images using Promise.all for efficiency
const images = await Promise.all(imagePaths.map(async (imagePath) => {
try {
return await Jimp.read(imagePath);
} catch (error) {
console.error(`Error reading image: ${imagePath}`, error);
// Optionally handle individual image reading errors (e.g., return null)
return null;
}
}));

// Filter out any images that failed to read (if applicable)
const validImages = images.filter(image => image !== null);
if (validImages.length === 0) {
// Handle the case where no images were successfully read
console.error('No valid images found.');
return null;
}

// Calculate total width based on desired output width per image
const totalWidth = validImages.length * outputWidth;

// Get maximum image height based on valid images and aspect ratio preservation
const maxHeight = Math.max(...validImages.map(image => {
const aspectRatio = image.bitmap.width / image.bitmap.height;
return outputHeight * aspectRatio;
}));

// Create a new Jimp image with desired format (e.g., PNG)
const combinedImage = new Jimp(totalWidth, maxHeight, (mime) => mime.png());

let currentX = 0;
for (const image of validImages) {
// Resize image to fit output dimensions while maintaining aspect ratio
const aspectRatio = image.bitmap.width / image.bitmap.height;
const resizeWidth = Math.min(outputWidth, image.bitmap.width);
const resizeHeight = Math.min(outputHeight, aspectRatio * outputWidth);
await image.resize(resizeWidth, resizeHeight);

// Composite image onto combinedImage
await combinedImage.composite(image, currentX, 0);

// Update currentX for next image placement
currentX += outputWidth;
}

// Generate a unique filename for the combined image
const filename = `combined.png`;

// Write the combined image to a temporary file
await combinedImage.writeAsync(filename);

return filename; // Return the filename of the combined image
} catch (error) {
console.error('Error combining images:', error);
return null;
}
}
}

0 comments on commit e0904f2

Please sign in to comment.