Level 8
Pertemuan 8

Random, Timer, Spawn, dan Countdown

Menggunakan Math.random(), setInterval, dan setTimeout untuk game mechanics.

Timer: 30 Spawn: random

Tujuan Pembelajaran

Menggunakan Math.random() untuk spawn enemy atau item.
Menggunakan setInterval dan setTimeout.
Membuat countdown dan random position.

Math.random()

              
                const x = Math.random() * 800; const y = Math.random() * 600; coin.style.left = `${x}px`; coin.style.top = `${y}px`;
              
            

Random Spawn

              
                function spawnEnemy() { const enemy = document.createElement("div"); enemy.className = "enemy"; enemy.style.left = `${Math.random() * 760}px`; enemy.style.top = `${Math.random() * 560}px`; gameArea.appendChild(enemy); }
              
            

Countdown dengan setInterval

              
                let timeLeft = 30; const timer = setInterval(() => { timeLeft -= 1; timerText.textContent = `Time: ${timeLeft}`; if (timeLeft
                <= 0) clearInterval(timer);
}, 1000);
                

setTimeout

                  
                    setTimeout(() => { console.log("Enemy appears!"); spawnEnemy(); }, 2000);
                  
                

Activity

  1. Buat item spawn di random position.
  2. Buat enemy spawn di random position.
  3. Buat countdown timer.
  4. Stop game saat waktu habis.

Mini Quiz

Function untuk menjalankan kode berulang setiap interval waktu adalah...

Output Pertemuan

Game dengan random spawn dan timer mechanics.