import { Symbol, SlotMachine } from '.'; import { SlotMachineState } from './types'; export class WinController { constructor(private _slotMachine: SlotMachine) { } /** * Animate symbols after stopping the spinning sequence. * @param cycle Should we cycle trough the win lines one-by-one or play them together? * @param duration The duration of the animation per win line; if we play them together, this is the time before resolve get's called. * @param winLines The win lines to animate. * @returns Promise that resolves when all animations are played at least once, or when the duration is reached. */ public animateWinLines = async (winLines: number[][][], cycle: boolean, duration: number): Promise => new Promise(async (resolve, reject) => { // If cycle is true, we cycle true each win line one-by-one, animating all symbols that correspond to 1 in the win line, if 0 don't animate. // If cycle is false, we animate all symbols that correspond to 1 in all the win lines combined. try { if (cycle) { for ( let cycleIndex = 0; cycleIndex < 20 && this._slotMachine.state === SlotMachineState.Ready; cycleIndex++ ) { for (let i = 0; i < winLines.length; i++) { const winLine = winLines[ i ]; const symbols = this.animateWinLine(winLine); await new Promise(resolve => setTimeout(() => { this.stopAnimations(symbols); resolve(null); }, duration)); } resolve(null); } } else { let symbols: Symbol[] = []; for (let i = 0; i < winLines.length; i++) { const winLine = winLines[ i ]; symbols.push(...this.animateWinLine(winLine)); } setTimeout(() => { this.stopAnimations(symbols); resolve(null); }, duration); } } catch (error) { console.error(error); reject(error); } }); /** * Animate given win line. * @param winLine The win line to animate on the grid. * @returns The symbols that were animated. */ private animateWinLine(winLine: number[][]) { const symbols: Symbol[] = []; winLine.forEach((reel, reelIndex) => { reel.forEach((symbol, symbolIndex) => { if (symbol === 1) { const realSymbol = this._slotMachine.staticGrid.reels[ reelIndex ].symbols[ symbolIndex ]; realSymbol.playWinAnimation(); symbols.push(realSymbol); } }); }); return symbols; } private stopAnimations(symbols: Symbol[]) { symbols.forEach(symbol => symbol.stopWinAnimation()); } }