2 changed files with 95 additions and 0 deletions
@ -0,0 +1,46 @@ |
|||||
|
export function clamp(value: number, min: number, max: number): number { |
||||
|
return Math.min(max, Math.max(min, value)); |
||||
|
} |
||||
|
|
||||
|
export function lerp(a: number, b: number, t: number): number { |
||||
|
return a + (b - a) * t; |
||||
|
} |
||||
|
|
||||
|
export function random(min: number, max: number): number { |
||||
|
return min + Math.random() * (max - min); |
||||
|
} |
||||
|
|
||||
|
export function randomInt(min: number, max: number): number { |
||||
|
return Math.floor(random(min, max + 1)); |
||||
|
} |
||||
|
|
||||
|
export function randomChoice<T>(array: T[]): T { |
||||
|
return array[randomInt(0, array.length - 1)]; |
||||
|
} |
||||
|
|
||||
|
export function distance(x1: number, y1: number, x2: number, y2: number): number { |
||||
|
const dx = x2 - x1; |
||||
|
const dy = y2 - y1; |
||||
|
return Math.sqrt(dx * dx + dy * dy); |
||||
|
} |
||||
|
|
||||
|
export function degToRad(deg: number): number { |
||||
|
return (deg * Math.PI) / 180; |
||||
|
} |
||||
|
|
||||
|
export function radToDeg(rad: number): number { |
||||
|
return (rad * 180) / Math.PI; |
||||
|
} |
||||
|
|
||||
|
const MathUtils = { |
||||
|
clamp, |
||||
|
lerp, |
||||
|
random, |
||||
|
randomInt, |
||||
|
randomChoice, |
||||
|
distance, |
||||
|
degToRad, |
||||
|
radToDeg, |
||||
|
}; |
||||
|
|
||||
|
export default MathUtils; |
||||
@ -0,0 +1,49 @@ |
|||||
|
class Storage { |
||||
|
private prefix: string; |
||||
|
|
||||
|
constructor(prefix: string = "game_") { |
||||
|
this.prefix = prefix; |
||||
|
} |
||||
|
|
||||
|
get<T>(key: string, defaultValue: T): T { |
||||
|
try { |
||||
|
const item = localStorage.getItem(this.prefix + key); |
||||
|
if (item === null) { |
||||
|
return defaultValue; |
||||
|
} |
||||
|
return JSON.parse(item) as T; |
||||
|
} catch { |
||||
|
return defaultValue; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
set(key: string, value: any): void { |
||||
|
try { |
||||
|
localStorage.setItem(this.prefix + key, JSON.stringify(value)); |
||||
|
} catch { |
||||
|
console.warn("Storage: failed to save to localStorage"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
remove(key: string): void { |
||||
|
localStorage.removeItem(this.prefix + key); |
||||
|
} |
||||
|
|
||||
|
clear(): void { |
||||
|
const keysToRemove: string[] = []; |
||||
|
for (let i = 0; i < localStorage.length; i++) { |
||||
|
const key = localStorage.key(i); |
||||
|
if (key?.startsWith(this.prefix)) { |
||||
|
keysToRemove.push(key); |
||||
|
} |
||||
|
} |
||||
|
keysToRemove.forEach(key => localStorage.removeItem(key)); |
||||
|
} |
||||
|
|
||||
|
has(key: string): boolean { |
||||
|
return localStorage.getItem(this.prefix + key) !== null; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
export const storage = new Storage(); |
||||
|
export default storage; |
||||
Loading…
Reference in new issue