All files / repo/src/shared/utils generateTiles.ts

100% Statements 64/64
86.66% Branches 13/15
100% Functions 3/3
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 761x   1x 1x   1x 1x 34x 34x 34x 34x 1x   1x   6x 6x 6x 50x 50x 50x 6x 140x 140x 140x 140x 140x 6x   6x 6x 6x 6x 140x 140x 140x 6x 6x   1x 3x 3x   3x   3x 22x 22x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 3x   3x   3x 3x 3x 44x 44x 44x 44x 3x   3x 3x  
import { weapons } from '@/components/GameCanvas/GameCanvas.const';
import type { Skin, Tile } from '@/components/GameCanvas/GameCanvas.types';
import { getRandomRarity } from './getRandomRarity';
import { preloadImagesSync } from './imageCache';
 
export const skins: Skin[] =
  weapons?.map((name, index) => ({
    id: index,
    name: name?.toUpperCase(),
    imagePath: `/images/weapons/${name.replace(/ /g, '_')}.png`,
    rarity: getRandomRarity(),
  })) ?? [];
 
preloadImagesSync(skins.map((skin) => skin.imagePath));
 
function xmur3(str: string): () => number {
  let h = 1779033703 ^ str.length;
  for (let i = 0; i < str.length; i++) {
    h = Math.imul(h ^ str.charCodeAt(i), 3432918353);
    h = (h << 13) | (h >>> 19);
  }
  return function () {
    h = Math.imul(h ^ (h >>> 16), 2246822507);
    h = Math.imul(h ^ (h >>> 13), 3266489909);
    h ^= h >>> 16;
    return (h >>> 0) / 4294967296;
  };
}
 
function shuffleArray<T>(array: T[], seed: string): T[] {
  const rng = xmur3(seed);
  const copy = [...array];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(rng() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}
 
export const generateShuffledTiles = (seed: string, difficulty: number): Tile[] => {
  const tiles: Tile[] = [];
  const numPairs = difficulty === 1 ? 6 : difficulty === 2 ? 10 : 15;
 
  const selectedSkins = shuffleArray(skins, seed).slice(0, numPairs);
 
  selectedSkins.forEach((skin, index) => {
    const pairId = index;
    for (let i = 0; i < 2; i++) {
      tiles.push({
        id: tiles.length,
        name: skin.name,
        pairId,
        flipped: false,
        matched: false,
        x: 0,
        y: 0,
        rarity: skin.rarity,
        imagePath: skin.imagePath,
      });
    }
  });
 
  const shuffled = shuffleArray(tiles, seed);
 
  const cols = 6;
  const spacing = 110;
  shuffled.forEach((tile, index) => {
    const row = Math.floor(index / cols);
    const col = index % cols;
    tile.x = col * spacing + 20;
    tile.y = row * spacing + 20;
  });
 
  return shuffled;
};