import { GridProps, ReelProps, SymbolData, SymbolsConfig } from "../types"; import { Reel } from "."; import { ObjectBase, Style } from "dsg-engine"; type ReelConstructor = new (index: number, symbolsConfig: SymbolsConfig, props: ReelProps) => T; export class Grid extends ObjectBase { private _reelsResetPos: {x: number, y: number}[] = []; protected _reels: TReel[] = []; protected _reelCount: number = 0; public get reels(): TReel[] { return this._reels; } constructor( private _reelClass: ReelConstructor, private _props: GridProps, name: string = "Grid", style: Style = {} ){ super({name, style}); this._reelCount = this._props.reelProps.length; this.verifyProps(); this.createReels(); } /** * Copy symbols from another grid to this one. * Goes from bottom to top, copying from smaller reel to bigger is accepted. * @param from grid to copy from * @throws Error if trying to copy from bigger grid to smaller */ public copySymbols(from: Grid) { from.reels.forEach((reel, reelIndex) => { if (reel.props.symbolCount <= this._props.reelProps[reelIndex].symbolCount) { reel.symbols.forEach((symbol, symbolIndex) => { this.reels[reelIndex].symbols[symbolIndex].copy(symbol); }); } else { throw new Error("Trying to copy symbols from bigger reel to smaller reel"); } }); } public setResetPositions() { this._reelsResetPos = this.reels.flatMap(reel => {return {x: reel.position.x, y: reel.position.y}}); } public setSymbols(symbolsData: SymbolData[][]) { if (symbolsData.length !== this._reelCount) { throw new Error("Symbols data length does not match reel length"); } this._reels.forEach((reel, index) => { reel.setSymbols(symbolsData[index]); }); } /** * Verify that all props are valid */ private verifyProps() { if (this._reelCount < 1) { throw new Error("Reel count must be greater than 0"); } } /** * Create all reels. * Goes from left to right. */ protected createReels(): void { let posX = 0; for (let reelIndex = 0; reelIndex < this._reelCount; reelIndex++, posX += this._props.offsetX) { const reel = new this._reelClass(reelIndex, this._props.symbolsConfig, this._props.reelProps[reelIndex]); reel.position.x = posX; this.addChild(reel); this._reels[ reelIndex ] = reel; this.setResetPositions(); // const bounds = new BoundBox(reel); // this.addChild(bounds); } } public setReelVisibility(columnIndex: number, visible: boolean) { this._reels[columnIndex].visible = visible; } public reset() { this._reels.forEach((reel, index) => { reel.position.set(this._reelsResetPos[index].x, this._reelsResetPos[index].y); }); } }