@@ -13,6 +13,23 @@ const AsteroidsCanvas = styled.canvas`
1313
1414const spacepics = 10 ;
1515
16+ const MAX_ASTEROID_IMAGES = 30 ;
17+
18+ function loadAsteroidImages ( ) : Promise < HTMLImageElement [ ] > {
19+ const attempts = Array . from ( { length : MAX_ASTEROID_IMAGES } , ( _ , i ) => i + 1 ) ;
20+ return Promise . all (
21+ attempts . map (
22+ ( n ) =>
23+ new Promise < HTMLImageElement | null > ( ( resolve ) => {
24+ const img = new Image ( ) ;
25+ img . onload = ( ) => resolve ( img ) ;
26+ img . onerror = ( ) => resolve ( null ) ;
27+ img . src = `asteroids/asteroid${ n } .png` ;
28+ } ) ,
29+ ) ,
30+ ) . then ( ( imgs ) => imgs . filter ( ( img ) : img is HTMLImageElement => img !== null ) ) ;
31+ }
32+
1633export default function Asteroids ( ) {
1734 const canvasRef = useRef < HTMLCanvasElement > ( null ) ;
1835 const [ score , setScore ] = useState ( 0 ) ;
@@ -28,6 +45,7 @@ export default function Asteroids() {
2845 score : 0 ,
2946 highscore : 0 ,
3047 shots : { } as Record < string , any > ,
48+ asteroidImages : [ ] as HTMLImageElement [ ] ,
3149 asteroids : { } as Record < string , any > ,
3250 powerups : { } as Record < string , any > ,
3351 explosions : { } as Record < string , any > ,
@@ -61,6 +79,10 @@ export default function Asteroids() {
6179 const explosionImage = new Image ( ) ;
6280 explosionImage . src = "asteroids/explosion.png" ;
6381
82+ loadAsteroidImages ( ) . then ( ( imgs ) => {
83+ g . asteroidImages = imgs ;
84+ } ) ;
85+
6486 const powerupTypes = [
6587 {
6688 name : "speed" ,
@@ -267,7 +289,11 @@ export default function Asteroids() {
267289 } ;
268290 a . height = a . width ;
269291 a . position = getEntryPosition ( a . width , a . height ) ;
270- a . img . src = `asteroids/asteroid${ Math . round ( Math . random ( ) * 6 ) + 1 } .png` ;
292+ if ( g . asteroidImages . length > 0 ) {
293+ a . img = g . asteroidImages [ Math . floor ( Math . random ( ) * g . asteroidImages . length ) ] ;
294+ } else {
295+ a . img . src = "asteroids/asteroid1.png" ;
296+ }
271297 a . explode = ( ) => {
272298 g . explosions [ a . id ] = makeExplosion ( a ) ;
273299 delete g . asteroids [ a . id ] ;
0 commit comments