feat: gambling (coinflip & slots)
This commit is contained in:
parent
543a5a951c
commit
1cae171748
38 changed files with 5631 additions and 1 deletions
491
website/src/lib/components/self/games/Coinflip.svelte
Normal file
491
website/src/lib/components/self/games/Coinflip.svelte
Normal file
|
|
@ -0,0 +1,491 @@
|
|||
<script lang="ts">
|
||||
// https://github.com/gre/bezier-easing
|
||||
// BezierEasing - use bezier curve for transition easing function
|
||||
// by Gaëtan Renaudeau 2014 - 2015 – MIT License
|
||||
|
||||
// These values are established by empiricism with tests (tradeoff: performance VS precision)
|
||||
const NEWTON_ITERATIONS = 4;
|
||||
const NEWTON_MIN_SLOPE = 0.001;
|
||||
const SUBDIVISION_PRECISION = 0.0000001;
|
||||
const SUBDIVISION_MAX_ITERATIONS = 10;
|
||||
|
||||
const kSplineTableSize = 11;
|
||||
const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
|
||||
|
||||
const float32ArraySupported = typeof Float32Array === 'function';
|
||||
|
||||
function A(aA1: number, aA2: number) {
|
||||
return 1.0 - 3.0 * aA2 + 3.0 * aA1;
|
||||
}
|
||||
function B(aA1: number, aA2: number) {
|
||||
return 3.0 * aA2 - 6.0 * aA1;
|
||||
}
|
||||
function C(aA1: number) {
|
||||
return 3.0 * aA1;
|
||||
}
|
||||
|
||||
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
|
||||
function calcBezier(aT: number, aA1: number, aA2: number) {
|
||||
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
|
||||
}
|
||||
|
||||
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
|
||||
function getSlope(aT: number, aA1: number, aA2: number) {
|
||||
return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
|
||||
}
|
||||
|
||||
function binarySubdivide(aX: number, aA: number, aB: number, mX1: number, mX2: number) {
|
||||
let currentX,
|
||||
currentT,
|
||||
i = 0;
|
||||
do {
|
||||
currentT = aA + (aB - aA) / 2.0;
|
||||
currentX = calcBezier(currentT, mX1, mX2) - aX;
|
||||
if (currentX > 0.0) {
|
||||
aB = currentT;
|
||||
} else {
|
||||
aA = currentT;
|
||||
}
|
||||
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
|
||||
return currentT;
|
||||
}
|
||||
|
||||
function newtonRaphsonIterate(aX: number, aGuessT: number, mX1: number, mX2: number) {
|
||||
for (let i = 0; i < NEWTON_ITERATIONS; ++i) {
|
||||
const currentSlope = getSlope(aGuessT, mX1, mX2);
|
||||
if (currentSlope === 0.0) {
|
||||
return aGuessT;
|
||||
}
|
||||
const currentX = calcBezier(aGuessT, mX1, mX2) - aX;
|
||||
aGuessT -= currentX / currentSlope;
|
||||
}
|
||||
return aGuessT;
|
||||
}
|
||||
|
||||
function LinearEasing(x: number) {
|
||||
return x;
|
||||
}
|
||||
|
||||
function bezier(mX1: number, mY1: number, mX2: number, mY2: number): (x: number) => number {
|
||||
if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) {
|
||||
throw new Error('bezier x values must be in [0, 1] range');
|
||||
}
|
||||
|
||||
if (mX1 === mY1 && mX2 === mY2) {
|
||||
return LinearEasing;
|
||||
}
|
||||
|
||||
// Precompute samples table
|
||||
const sampleValues: Float32Array | number[] = float32ArraySupported
|
||||
? new Float32Array(kSplineTableSize)
|
||||
: new Array(kSplineTableSize);
|
||||
for (let i = 0; i < kSplineTableSize; ++i) {
|
||||
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
|
||||
}
|
||||
|
||||
function getTForX(aX: number) {
|
||||
let intervalStart = 0.0;
|
||||
let currentSample = 1;
|
||||
const lastSample = kSplineTableSize - 1;
|
||||
|
||||
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
|
||||
intervalStart += kSampleStepSize;
|
||||
}
|
||||
--currentSample;
|
||||
|
||||
// Interpolate to provide an initial guess for t
|
||||
const dist =
|
||||
(aX - sampleValues[currentSample]) /
|
||||
(sampleValues[currentSample + 1] - sampleValues[currentSample]);
|
||||
const guessForT = intervalStart + dist * kSampleStepSize;
|
||||
|
||||
const initialSlope = getSlope(guessForT, mX1, mX2);
|
||||
if (initialSlope >= NEWTON_MIN_SLOPE) {
|
||||
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
|
||||
} else if (initialSlope === 0.0) {
|
||||
return guessForT;
|
||||
} else {
|
||||
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
|
||||
}
|
||||
}
|
||||
|
||||
return function BezierEasing(x: number) {
|
||||
// Because JavaScript number are imprecise, we should guarantee the extremes are right.
|
||||
if (x === 0 || x === 1) {
|
||||
return x;
|
||||
}
|
||||
return calcBezier(getTForX(x), mY1, mY2);
|
||||
};
|
||||
}
|
||||
|
||||
function getNormalizedTimeForProgress(
|
||||
targetProgress: number,
|
||||
easingFunction: (t: number) => number,
|
||||
tolerance = 0.0001,
|
||||
maxIterations = 100
|
||||
): number {
|
||||
if (targetProgress <= 0) return 0;
|
||||
if (targetProgress >= 1) return 1;
|
||||
|
||||
let minT = 0;
|
||||
let maxT = 1;
|
||||
let t = 0.5;
|
||||
|
||||
for (let i = 0; i < maxIterations; i++) {
|
||||
const currentProgress = easingFunction(t);
|
||||
const error = currentProgress - targetProgress;
|
||||
|
||||
if (Math.abs(error) < tolerance) {
|
||||
return t;
|
||||
}
|
||||
|
||||
if (error < 0) {
|
||||
minT = t;
|
||||
} else {
|
||||
maxT = t;
|
||||
}
|
||||
t = (minT + maxT) / 2;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
// --- End of bezier-easing code ---
|
||||
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from '$lib/components/ui/card';
|
||||
import confetti from 'canvas-confetti';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { formatValue, playSound, showConfetti } from '$lib/utils';
|
||||
|
||||
interface CoinflipResult {
|
||||
won: boolean;
|
||||
result: 'heads' | 'tails';
|
||||
newBalance: number;
|
||||
payout: number;
|
||||
amountWagered: number;
|
||||
}
|
||||
|
||||
const cssEaseInOut = bezier(0.42, 0, 0.58, 1.0);
|
||||
|
||||
let {
|
||||
balance = $bindable(),
|
||||
onBalanceUpdate
|
||||
}: {
|
||||
balance: number;
|
||||
onBalanceUpdate?: (newBalance: number) => void;
|
||||
} = $props();
|
||||
|
||||
let betAmount = $state(10);
|
||||
let selectedSide = $state('heads');
|
||||
let isFlipping = $state(false);
|
||||
let coinRotation = $state(0);
|
||||
let lastResult = $state<CoinflipResult | null>(null);
|
||||
let activeSoundTimeouts = $state<NodeJS.Timeout[]>([]);
|
||||
|
||||
let canBet = $derived(betAmount > 0 && betAmount <= balance && !isFlipping);
|
||||
|
||||
function selectSide(side: string) {
|
||||
if (!isFlipping) {
|
||||
selectedSide = side;
|
||||
}
|
||||
}
|
||||
|
||||
function setBetAmount(amount: number) {
|
||||
if (amount >= 0 && amount <= balance) {
|
||||
betAmount = amount;
|
||||
}
|
||||
}
|
||||
|
||||
async function flipCoin() {
|
||||
if (!canBet) return;
|
||||
|
||||
isFlipping = true;
|
||||
lastResult = null;
|
||||
|
||||
activeSoundTimeouts.forEach(clearTimeout);
|
||||
activeSoundTimeouts = [];
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/gambling/coinflip', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
side: selectedSide,
|
||||
amount: betAmount
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to place bet');
|
||||
}
|
||||
|
||||
const resultData: CoinflipResult = await response.json();
|
||||
|
||||
const baseSpinsDegrees = 1800;
|
||||
const currentRotationValue = coinRotation;
|
||||
|
||||
let rotationDeltaForThisFlip = baseSpinsDegrees;
|
||||
|
||||
const faceAfterBaseSpins =
|
||||
(currentRotationValue + baseSpinsDegrees) % 360 < 180 ? 'heads' : 'tails';
|
||||
|
||||
if (faceAfterBaseSpins !== resultData.result) {
|
||||
rotationDeltaForThisFlip += 180;
|
||||
}
|
||||
|
||||
if (rotationDeltaForThisFlip === 0) {
|
||||
rotationDeltaForThisFlip = 360;
|
||||
}
|
||||
|
||||
coinRotation = currentRotationValue + rotationDeltaForThisFlip;
|
||||
|
||||
const animationDuration = 2000;
|
||||
|
||||
if (rotationDeltaForThisFlip >= 180) {
|
||||
const numHalfSpins = Math.floor(rotationDeltaForThisFlip / 180);
|
||||
|
||||
for (let i = 1; i <= numHalfSpins; i++) {
|
||||
const targetEasedProgress = (i * 180) / rotationDeltaForThisFlip;
|
||||
const normalizedTime = getNormalizedTimeForProgress(targetEasedProgress, cssEaseInOut);
|
||||
const timeToPlaySound = normalizedTime * animationDuration;
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
playSound('flip');
|
||||
}, timeToPlaySound);
|
||||
activeSoundTimeouts.push(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
balance = resultData.newBalance;
|
||||
lastResult = resultData;
|
||||
onBalanceUpdate?.(resultData.newBalance);
|
||||
|
||||
if (resultData.won) {
|
||||
showConfetti(confetti);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
isFlipping = false;
|
||||
if (!resultData.won) {
|
||||
playSound('lose');
|
||||
}
|
||||
}, 500);
|
||||
}, animationDuration);
|
||||
} catch (error) {
|
||||
console.error('Coinflip error:', error);
|
||||
toast.error('Bet failed', {
|
||||
description: error instanceof Error ? error.message : 'Unknown error occurred'
|
||||
});
|
||||
isFlipping = false;
|
||||
activeSoundTimeouts.forEach(clearTimeout);
|
||||
activeSoundTimeouts = [];
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Coinflip</CardTitle>
|
||||
<CardDescription>Choose heads or tails and double your money!</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<!-- Main Layout: Coin/Balance Left, Controls Right -->
|
||||
<div class="grid grid-cols-1 gap-8 md:grid-cols-2">
|
||||
<!-- Left Side: Coin, Balance, and Result -->
|
||||
<div class="flex flex-col space-y-4">
|
||||
<!-- Balance Display -->
|
||||
<div class="text-center">
|
||||
<p class="text-muted-foreground text-sm">Balance</p>
|
||||
<p class="text-2xl font-bold">{formatValue(balance)}</p>
|
||||
</div>
|
||||
|
||||
<!-- Coin Animation -->
|
||||
<div class="flex justify-center">
|
||||
<div class="coin-container">
|
||||
<div class="coin" style="transform: rotateY({coinRotation}deg)">
|
||||
<div class="coin-face coin-heads">
|
||||
<img
|
||||
src="/facedev/avif/bliptext.avif"
|
||||
alt="Heads"
|
||||
class="h-32 w-32 object-contain"
|
||||
/>
|
||||
</div>
|
||||
<div class="coin-face coin-tails">
|
||||
<img
|
||||
src="/facedev/avif/wattesigma.avif"
|
||||
alt="Tails"
|
||||
class="h-32 w-32 object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Result Display (Reserve Space) -->
|
||||
<div class="flex items-center justify-center text-center">
|
||||
{#if lastResult && !isFlipping}
|
||||
<div class="bg-muted/50 w-full rounded-lg p-3">
|
||||
{#if lastResult.won}
|
||||
<p class="text-success font-semibold">WIN</p>
|
||||
<p class="text-sm">
|
||||
Won {formatValue(lastResult.payout)} on {lastResult.result}
|
||||
</p>
|
||||
{:else}
|
||||
<p class="text-destructive font-semibold">LOSS</p>
|
||||
<p class="text-sm">
|
||||
Lost {formatValue(lastResult.amountWagered)} on {lastResult.result}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right Side: Betting Controls -->
|
||||
<div class="space-y-4">
|
||||
<!-- Side Selection (Inline) -->
|
||||
<div>
|
||||
<div class="mb-2 block text-sm font-medium">Choose Side</div>
|
||||
<div class="flex gap-3">
|
||||
<Button
|
||||
variant={selectedSide === 'heads' ? 'default' : 'outline'}
|
||||
onclick={() => selectSide('heads')}
|
||||
disabled={isFlipping}
|
||||
class="side-button h-16 flex-1"
|
||||
>
|
||||
<div class="text-center">
|
||||
<img
|
||||
src="/facedev/avif/bliptext.avif"
|
||||
alt="Heads"
|
||||
class="mx-auto mb-1 h-8 w-8 object-contain"
|
||||
/>
|
||||
<div>Heads</div>
|
||||
</div>
|
||||
</Button>
|
||||
<Button
|
||||
variant={selectedSide === 'tails' ? 'default' : 'outline'}
|
||||
onclick={() => selectSide('tails')}
|
||||
disabled={isFlipping}
|
||||
class="side-button h-16 flex-1"
|
||||
>
|
||||
<div class="text-center">
|
||||
<img
|
||||
src="/facedev/avif/wattesigma.avif"
|
||||
alt="Tails"
|
||||
class="mx-auto mb-1 h-8 w-8 object-contain"
|
||||
/>
|
||||
<div>Tails</div>
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bet Amount -->
|
||||
<div>
|
||||
<label for="bet-amount" class="mb-2 block text-sm font-medium">Bet Amount</label>
|
||||
<Input
|
||||
id="bet-amount"
|
||||
type="number"
|
||||
bind:value={betAmount}
|
||||
min="1"
|
||||
max={balance}
|
||||
disabled={isFlipping}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Percentage Quick Actions -->
|
||||
<div>
|
||||
<div class="grid grid-cols-4 gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor((balance || 0) * 0.25))}
|
||||
disabled={isFlipping}>25%</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor((balance || 0) * 0.5))}
|
||||
disabled={isFlipping}>50%</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor((balance || 0) * 0.75))}
|
||||
disabled={isFlipping}>75%</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor(balance || 0))}
|
||||
disabled={isFlipping}>Max</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Flip Button -->
|
||||
<Button class="h-12 w-full text-lg" onclick={flipCoin} disabled={!canBet}>
|
||||
{isFlipping ? 'Flipping...' : 'Flip'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<style>
|
||||
.coin-container {
|
||||
position: relative;
|
||||
width: 8rem; /* 128px */
|
||||
height: 8rem; /* 128px */
|
||||
perspective: 1000px;
|
||||
}
|
||||
|
||||
.coin {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
transform-style: preserve-3d;
|
||||
transition: transform 2s ease-in-out;
|
||||
}
|
||||
|
||||
.coin-face {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
backface-visibility: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.coin-heads {
|
||||
transform: rotateY(0deg);
|
||||
}
|
||||
|
||||
.coin-tails {
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
|
||||
:global(.side-button) {
|
||||
box-sizing: border-box !important;
|
||||
border: 2px solid transparent !important;
|
||||
}
|
||||
|
||||
:global(.side-button[data-variant='outline']) {
|
||||
border-color: hsl(var(--border)) !important;
|
||||
}
|
||||
|
||||
:global(.side-button[data-variant='default']) {
|
||||
border-color: hsl(var(--primary)) !important;
|
||||
}
|
||||
</style>
|
||||
431
website/src/lib/components/self/games/Slots.svelte
Normal file
431
website/src/lib/components/self/games/Slots.svelte
Normal file
|
|
@ -0,0 +1,431 @@
|
|||
<script lang="ts">
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from '$lib/components/ui/card';
|
||||
import confetti from 'canvas-confetti';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { formatValue, playSound, showConfetti, showSchoolPrideCannons } from '$lib/utils';
|
||||
|
||||
interface SlotsResult {
|
||||
won: boolean;
|
||||
symbols: string[];
|
||||
newBalance: number;
|
||||
payout: number;
|
||||
amountWagered: number;
|
||||
winType?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
balance = $bindable(),
|
||||
onBalanceUpdate
|
||||
}: {
|
||||
balance: number;
|
||||
onBalanceUpdate?: (newBalance: number) => void;
|
||||
} = $props();
|
||||
|
||||
const symbols = [
|
||||
'bliptext',
|
||||
'bussin',
|
||||
'griddycode',
|
||||
'lyntr',
|
||||
'subterfuge',
|
||||
'twoblade',
|
||||
'wattesigma',
|
||||
'webx'
|
||||
];
|
||||
|
||||
const BASE_SPINS_PER_REEL = [8, 10, 12];
|
||||
const NUM_RENDERED_CYCLES = Math.max(...BASE_SPINS_PER_REEL) + 3;
|
||||
|
||||
let betAmount = $state(10);
|
||||
let isSpinning = $state(false);
|
||||
|
||||
const createReelStrip = () => {
|
||||
const strip = [];
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const shuffled = [...symbols].sort(() => Math.random() - 0.5);
|
||||
strip.push(...shuffled);
|
||||
}
|
||||
return strip;
|
||||
};
|
||||
|
||||
let reelSymbols = $state([createReelStrip(), createReelStrip(), createReelStrip()]);
|
||||
|
||||
let reelPositions = $state([0, 0, 0]);
|
||||
let lastResult = $state<SlotsResult | null>(null);
|
||||
|
||||
let displayedSymbols = $state(
|
||||
reelSymbols.map((reel_cycle_data) => {
|
||||
return reel_cycle_data[1];
|
||||
})
|
||||
);
|
||||
|
||||
let canBet = $derived(betAmount > 0 && betAmount <= balance && !isSpinning);
|
||||
|
||||
function setBetAmount(amount: number) {
|
||||
if (amount >= 0 && amount <= balance) {
|
||||
betAmount = amount;
|
||||
}
|
||||
}
|
||||
|
||||
function getVisibleSymbolIndex(position: number, logicalReelCycleLength: number): number {
|
||||
const symbolHeight = 60;
|
||||
let index = Math.round(1 - position / symbolHeight);
|
||||
index = ((index % logicalReelCycleLength) + logicalReelCycleLength) % logicalReelCycleLength;
|
||||
return index;
|
||||
}
|
||||
|
||||
async function spin() {
|
||||
if (!canBet) return;
|
||||
|
||||
isSpinning = true;
|
||||
lastResult = null;
|
||||
|
||||
playSound('background');
|
||||
|
||||
const spinStartOffsets = [
|
||||
Math.random() * 60 - 30,
|
||||
Math.random() * 60 - 30,
|
||||
Math.random() * 60 - 30
|
||||
];
|
||||
|
||||
reelPositions = reelPositions.map((pos, i) => pos + spinStartOffsets[i]);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/gambling/slots', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
amount: betAmount
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to place bet');
|
||||
}
|
||||
|
||||
const result: SlotsResult = await response.json();
|
||||
|
||||
const targetIndices = result.symbols.map((symbol, reelIndex) => {
|
||||
const indices = reelSymbols[reelIndex]
|
||||
.map((s, i) => (s === symbol ? i : -1))
|
||||
.filter((i) => i !== -1);
|
||||
return indices[Math.floor(Math.random() * indices.length)];
|
||||
});
|
||||
|
||||
const spinDurations = [2000, 2500, 3000];
|
||||
|
||||
targetIndices.forEach((targetIndex, i) => {
|
||||
const symbolHeight = 60;
|
||||
|
||||
const targetPosition = 60 - targetIndex * symbolHeight;
|
||||
const logicalCyclePixelHeight = reelSymbols[i].length * symbolHeight;
|
||||
|
||||
const fullRotations = BASE_SPINS_PER_REEL[i] * logicalCyclePixelHeight;
|
||||
|
||||
reelPositions[i] = targetPosition - fullRotations;
|
||||
|
||||
setTimeout(() => {
|
||||
playSound('click');
|
||||
}, spinDurations[i]);
|
||||
});
|
||||
|
||||
const maxDuration = Math.max(...spinDurations);
|
||||
|
||||
setTimeout(() => {
|
||||
balance = result.newBalance;
|
||||
lastResult = result;
|
||||
onBalanceUpdate?.(result.newBalance);
|
||||
|
||||
if (result.won) {
|
||||
if (result.winType === '3 OF A KIND') {
|
||||
showSchoolPrideCannons(confetti);
|
||||
showConfetti(confetti);
|
||||
} else {
|
||||
showConfetti(confetti);
|
||||
}
|
||||
} else {
|
||||
playSound('lose');
|
||||
}
|
||||
|
||||
isSpinning = false;
|
||||
|
||||
reelPositions = reelPositions.map((pos, i) => {
|
||||
const symbolHeight = 60;
|
||||
const logicalReelCycleLength = reelSymbols[i].length;
|
||||
const logicalCyclePixelHeight = logicalReelCycleLength * symbolHeight;
|
||||
const normalized = pos % logicalCyclePixelHeight;
|
||||
return normalized > 0 ? normalized - logicalCyclePixelHeight : normalized;
|
||||
});
|
||||
}, maxDuration + 200);
|
||||
} catch (error) {
|
||||
console.error('Slots error:', error);
|
||||
toast.error('Bet failed', {
|
||||
description: error instanceof Error ? error.message : 'Unknown error occurred'
|
||||
});
|
||||
isSpinning = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!isSpinning) {
|
||||
const newDisplayedSymbols = reelSymbols.map((logicalCycle, i) => {
|
||||
const index = getVisibleSymbolIndex(reelPositions[i], logicalCycle.length);
|
||||
return logicalCycle[index];
|
||||
});
|
||||
|
||||
if (!lastResult) {
|
||||
displayedSymbols = newDisplayedSymbols;
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Slots</CardTitle>
|
||||
<CardDescription>Match 3 symbols to win big!</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div class="grid grid-cols-1 gap-8 md:grid-cols-2">
|
||||
<!-- Left Side: Slots Machine -->
|
||||
<div class="flex flex-col space-y-4">
|
||||
<!-- Balance Display -->
|
||||
<div class="text-center">
|
||||
<p class="text-muted-foreground text-sm">Balance</p>
|
||||
<p class="text-2xl font-bold">{formatValue(balance)}</p>
|
||||
</div>
|
||||
|
||||
<!-- Slots Machine -->
|
||||
<div class="slots-machine">
|
||||
<div class="slots-container">
|
||||
{#each reelSymbols as logicalCycleData, reelIndex}
|
||||
<div class="reel">
|
||||
<div
|
||||
class="reel-strip"
|
||||
style="transform: translateY({reelPositions[
|
||||
reelIndex
|
||||
]}px); transition: {isSpinning
|
||||
? `transform ${2 + reelIndex * 0.5}s cubic-bezier(0.17, 0.67, 0.16, 0.99)`
|
||||
: 'none'};"
|
||||
>
|
||||
{#each Array(NUM_RENDERED_CYCLES) as _, cycleInstanceIndex}
|
||||
{#each logicalCycleData as symbol, symbolIndexInCycle}
|
||||
<div class="symbol">
|
||||
<img src="/facedev/avif/{symbol}.avif" alt={symbol} class="symbol-image" />
|
||||
</div>
|
||||
{/each}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="payline"></div>
|
||||
</div>
|
||||
|
||||
<!-- Result Display -->
|
||||
<div class="flex items-center justify-center text-center">
|
||||
{#if lastResult && !isSpinning}
|
||||
<div class="bg-muted/50 w-full rounded-lg p-3">
|
||||
{#if lastResult.won}
|
||||
<p class="text-success font-semibold">
|
||||
WIN - {lastResult.winType}
|
||||
</p>
|
||||
<p class="text-sm">
|
||||
Won {formatValue(lastResult.payout)}
|
||||
</p>
|
||||
{:else}
|
||||
<p class="text-destructive font-semibold">NO MATCH</p>
|
||||
<p class="text-sm">
|
||||
Lost {formatValue(lastResult.amountWagered)}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right Side: Betting Controls -->
|
||||
<div class="space-y-4">
|
||||
<!-- Paytable -->
|
||||
<div>
|
||||
<div class="mb-2 block text-sm font-medium">Paytable</div>
|
||||
<div class="bg-muted/50 space-y-1 rounded-lg p-3 text-xs">
|
||||
<div class="flex justify-between">
|
||||
<span>3 Same Symbols:</span>
|
||||
<span class="text-success">5x</span>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<span>2 Same Symbols:</span>
|
||||
<span class="text-success">2x</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bet Amount -->
|
||||
<div>
|
||||
<label for="bet-amount" class="mb-2 block text-sm font-medium">Bet Amount</label>
|
||||
<Input
|
||||
id="bet-amount"
|
||||
type="number"
|
||||
bind:value={betAmount}
|
||||
min="1"
|
||||
max={balance}
|
||||
disabled={isSpinning}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Percentage Quick Actions -->
|
||||
<div>
|
||||
<div class="grid grid-cols-4 gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor(balance * 0.25))}
|
||||
disabled={isSpinning}>25%</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor(balance * 0.5))}
|
||||
disabled={isSpinning}>50%</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor(balance * 0.75))}
|
||||
disabled={isSpinning}>75%</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onclick={() => setBetAmount(Math.floor(balance))}
|
||||
disabled={isSpinning}>Max</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Spin Button -->
|
||||
<Button class="h-12 w-full text-lg" onclick={spin} disabled={!canBet}>
|
||||
{isSpinning ? 'Spinning...' : 'Spin'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<style>
|
||||
.slots-machine {
|
||||
position: relative;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.slots-container {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
background: var(--muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 8px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
height: 198px;
|
||||
}
|
||||
|
||||
.reel {
|
||||
flex: 1;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: calc(var(--radius) - 2px);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.reel::before,
|
||||
.reel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 60px;
|
||||
z-index: 5;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.reel::before {
|
||||
top: 0;
|
||||
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2), transparent);
|
||||
}
|
||||
|
||||
.reel::after {
|
||||
bottom: 0;
|
||||
background: linear-gradient(to top, rgba(0, 0, 0, 0.2), transparent);
|
||||
}
|
||||
|
||||
.reel-strip {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.symbol {
|
||||
height: 60px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.symbol:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.symbol-image {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.payline {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 8px;
|
||||
right: 8px;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, var(--primary), transparent);
|
||||
transform: translateY(-1px);
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.payline::before,
|
||||
.payline::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4px;
|
||||
width: 8px;
|
||||
height: 10px;
|
||||
background: var(--primary);
|
||||
clip-path: polygon(0 0, 100% 50%, 0 100%);
|
||||
}
|
||||
|
||||
.payline::before {
|
||||
left: -4px;
|
||||
}
|
||||
|
||||
.payline::after {
|
||||
right: -4px;
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -231,4 +231,101 @@ export function getTimeframeInSeconds(timeframe: string): number {
|
|||
}
|
||||
}
|
||||
|
||||
//
|
||||
let availableSounds = [1, 2, 3, 4, 5, 6, 7];
|
||||
|
||||
export function playRandomFireworkSound() {
|
||||
// If no sounds available, reset the array
|
||||
if (availableSounds.length === 0) {
|
||||
availableSounds = [1, 2, 3, 4, 5, 6, 7];
|
||||
}
|
||||
|
||||
// Pick a random sound from available ones
|
||||
const randomIndex = Math.floor(Math.random() * availableSounds.length);
|
||||
const soundNumber = availableSounds[randomIndex];
|
||||
|
||||
// Remove the sound from available array to prevent repetition
|
||||
availableSounds = availableSounds.filter((_, index) => index !== randomIndex);
|
||||
|
||||
playSound(`firework${soundNumber}`);
|
||||
}
|
||||
|
||||
export function playSound(sound: string) {
|
||||
try {
|
||||
const audio = new Audio(`sound/${sound}.mp3`);
|
||||
audio.volume = 0.3; // TODO: volume control
|
||||
audio.play().catch(console.error);
|
||||
} catch (error) {
|
||||
console.error('Error playing sound:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export function showConfetti(confetti: any) {
|
||||
const duration = 2 * 1000;
|
||||
const animationEnd = Date.now() + duration;
|
||||
const defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 0 };
|
||||
|
||||
function randomInRange(min: number, max: number) {
|
||||
return Math.random() * (max - min) + min;
|
||||
}
|
||||
|
||||
playRandomFireworkSound();
|
||||
|
||||
const interval = setInterval(function () {
|
||||
const timeLeft = animationEnd - Date.now();
|
||||
|
||||
if (timeLeft <= 0) {
|
||||
return clearInterval(interval);
|
||||
}
|
||||
|
||||
const particleCount = 50 * (timeLeft / duration);
|
||||
confetti({
|
||||
...defaults,
|
||||
particleCount,
|
||||
origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 }
|
||||
});
|
||||
confetti({
|
||||
...defaults,
|
||||
particleCount,
|
||||
origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 }
|
||||
});
|
||||
|
||||
if (Math.floor(timeLeft / 500) !== Math.floor((timeLeft - 250) / 500)) {
|
||||
playRandomFireworkSound();
|
||||
}
|
||||
}, 250);
|
||||
}
|
||||
|
||||
export function showSchoolPrideCannons(confetti: any) {
|
||||
const end = Date.now() + (3 * 1000);
|
||||
const colors = ['#bb0000', '#ffffff'];
|
||||
playSound('cannon');
|
||||
playSound('win');
|
||||
|
||||
setTimeout(() => {
|
||||
playSound('cannon');
|
||||
}, 100);
|
||||
|
||||
(function frame() {
|
||||
confetti({
|
||||
particleCount: 2,
|
||||
angle: 60,
|
||||
spread: 55,
|
||||
origin: { x: 0 },
|
||||
colors: colors
|
||||
});
|
||||
confetti({
|
||||
particleCount: 2,
|
||||
angle: 120,
|
||||
spread: 55,
|
||||
origin: { x: 1 },
|
||||
colors: colors
|
||||
});
|
||||
|
||||
if (Date.now() < end) {
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
}());
|
||||
}
|
||||
|
||||
export const formatMarketCap = formatValue;
|
||||
|
|
|
|||
Reference in a new issue