Skip to content

Commit

Permalink
add asset preloading
Browse files Browse the repository at this point in the history
  • Loading branch information
naueramant committed Sep 1, 2024
1 parent 6129533 commit 4557f59
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
Binary file removed public/cards.png
Binary file not shown.
Binary file removed public/cards2.png
Binary file not shown.
84 changes: 84 additions & 0 deletions src/hooks/preloader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { useEffect, useState } from "react";
import { SoundNames } from "./sounds";

function useAssetsPreloader() {
const [done, setDone] = useState<boolean>(false);
const [error, setError] = useState<boolean>(false);
const [loaded, setLoadedCount] = useState<number>(0);
const [total, setTotal] = useState<number>(0);

// Other
const assets: string[] = [
"cards/cardback.png",
"cards/cardback-au.png",
"blackheart.svg",
"skull.svg",
"wave.svg",
"whiteheart.svg",
];

// Sounds
for (const sound of SoundNames) {
assets.push(`/sounds/${sound}.mp3`);
assets.push(`/sounds/${sound}.ogg`);
}

// Cards
for (const s of ["A", "C", "D", "H", "I", "S"]) {
for (let i = 2; i <= 14; i++) {
assets.push(`/cards/${s}-${i}.png`);
}
}

useEffect(() => {
setTotal(assets.length);

for (const asset of assets) {
if (hasSuffix(asset, [".png", ".svg"])) {
loadImages(asset);
}

if (hasSuffix(asset, [".mp3", ".ogg"])) {
loadSound(asset);
}
}
}, []);

const incrementLoadedCount = () => {
setLoadedCount((prev) => {
if (prev + 1 === assets.length) {
setDone(true);
}
return prev + 1;
});
};

const loadImages = async (path: string) => {
const img = new Image();
img.src = path;
img.onload = () => {
incrementLoadedCount();
};
img.onerror = () => {
setError(true);
};
};

const loadSound = async (path: string) => {
const audio = new Audio(path);
audio.oncanplaythrough = () => {
incrementLoadedCount();
};
audio.onerror = () => {
setError(true);
};
};

return { done, error, loaded, total };
}

const hasSuffix = (str: string, substr: string[]) => {
return substr.some((s) => str.includes(s));
};

export { useAssetsPreloader };
3 changes: 3 additions & 0 deletions src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Route,
Routes as RouterRoutes,
} from "react-router-dom";
import { useAssetsPreloader } from "../hooks/preloader";
import GameView from "../views/Game";
import LoginView from "../views/Login";
import ContinueGameView from "../views/Login/Continue";
Expand All @@ -13,6 +14,8 @@ import RemoteView from "../views/Remote";
import { GameGuard } from "./guard";

const Routes: FunctionComponent = () => {
useAssetsPreloader();

return (
<Suspense>
<RouterRoutes>
Expand Down

0 comments on commit 4557f59

Please sign in to comment.