      //bagian tempat main ama buat generate game 2d
      var canvas = document.getElementById("game");
      var content = canvas.getContext("2d");
      const Text = document.getElementById("text");
      const UpDead = document.getElementById("gameover-overlay");
      const ScoreMain = document.getElementById("gameover-score");
      const PlayAgain = document.getElementById("ulangi");
      const Udahan = document.getElementById("keluar");

      //settingan awal
      var grid = 24;
      var count = 0;
      var speed = 10;
      var score = 0;
      var highscore = 0;
      var ArahUlar = 0;
      var GameOverTimer = 0;
      var GameStart = false;
      var ModeH = false;
      const persiapan = document.getElementById("start");

      //generate gambar external
      var KepalaUlarImage = new Image();
      KepalaUlarImage.src = "image/KepalaHorizontalKanan.png";
      var KepalAtas = new Image();
      KepalAtas.src = "image/KepalaVertikalAtas.png";
      var KepalaBawah = new Image();
      KepalaBawah.src = "image/KepalaVertikalBawah.png";
      var KepalaKiri = new Image();
      KepalaKiri.src = "image/KepalaHorizontalKiri.png";
      var KepalaKanan = new Image();
      KepalaKanan.src = "image/KepalaHorizontalKanan.png";
      // ↑ kepala ular

      var BadanUlarImage = new Image();
      BadanUlarImage.src = "image/BadanVertikal.png";
      // ↑ badan ular

      var ApelImage = new Image();
      ApelImage.src = "image/ApelLayer.png"; // Apel
      var TembokImage = new Image();
      TembokImage.src = "image/Tembok.png"; // Tembok Batagor

      //set posisi ular dan Apel
      var Ular = { x: 528, y: 240, dx: grid, dy: 0, cells: [], maxCells: 4 };
      var Apel = { x: 0, y: 0 };
      var Tembok = [];
      UpdateScore(0);
      RandomizeApel();

      //mastiin gambar external generate dulu sebelum game start
      KepalaUlarImage.onload = function () {
        function gameLoop() {}
      };

      //ngatur biar game ga langsung jalan
      function StartingGame(menantang) {
        ModeH = menantang;
        persiapan.style.display = "none";
        if (ModeH) {
          RandomSpawnWall();
        } else {
          Tembok = [];
        }
        GameStart = true;
      }

      //buat ngatur batu spwan apa ga nanti
      const halaman = document.querySelector(".HalamanFull");
      const gameCanvas = document.getElementById("game");

      document.getElementById("mode-normal").addEventListener("click", function () {
          halaman.style.backgroundImage ='url("halamanFull/cherryBlossom.png")';
          halaman.style.setProperty("--overlay-opacity", "0.4");
          gameCanvas.style.filter = "brightness(1)";

          StartingGame(false);
        });

      document.getElementById("mode-tambahan").addEventListener("click", function () {
          halaman.style.backgroundImage ='url("halamanFull/cherryBlossomNight.png")';
          halaman.style.setProperty("--overlay-opacity", "0.7");
          gameCanvas.style.filter = "brightness(0.5)";

          StartingGame(true);
        });

      //play again pas gameover
      function resetGame() {
        Ular.x = 528;
        Ular.y = 240;
        Ular.cells = [];
        Ular.maxCells = 4;
        Ular.dx = grid;
        Ular.dy = 0;
        Tembok = [];
        RandomizeApel();
        UpdateScore(0);
        ModeH = false;
        GameStart = false;
      }

      //ngatur tombol pas gameover kemana abis di klik
      PlayAgain.addEventListener("click", function () {
        UpDead.style.display = "none";
        resetGame();
        persiapan.style.display = "flex";
      });

      Udahan.addEventListener("click", function () {
        UpDead.style.display = "none";
        resetGame();
      });

      //gameover terus ngatur ular ke setting awal
      function gameLoop() {
        if (!GameStart) {
          requestAnimationFrame(gameLoop);
          return;
        }
        ClearCanvas();
        Movement();
        IntiGame();

        requestAnimationFrame(gameLoop);
      }

      //random spawn Apel
      function RandomizeApel() {
        var pembataslebar = Math.floor(canvas.width / grid);
        var pembatastinggi = Math.floor(canvas.height / grid);
        Apel.x = Math.floor(Math.random() * pembataslebar) * grid;
        Apel.y = Math.floor(Math.random() * pembatastinggi) * grid;
      }

      //random spawn tembok
      function RandomSpawnWall() {
        var TembokX, TembokY;
        var kosong;
        var pembataslebar = Math.floor(canvas.width / grid);
        var pembatastinggi = Math.floor(canvas.height / grid);

        //create tembok
        do {
          kosong = true;

          TembokX = Math.floor(Math.random() * pembataslebar) * grid;
          TembokY = Math.floor(Math.random() * pembatastinggi) * grid;

          //cek untuk posisi yang mau di kasih tembok ada/tidak ada ularnya
          for (var i = 0; i < Ular.cells.length; i++) {
            if (Ular.cells[i].x === TembokX && Ular.cells[i].y === TembokY) {
              kosong = false;
              break;
            }
          }

          //tidak memperbolehkan tembok spawn sama dengan apel
          if (TembokX === Apel.x && TembokY === Apel.y) {
            kosong = false;
          }

          for (var i = 0; i < Tembok.length; i++) {
            if (Tembok[i].x === TembokX && Tembok[i].y === TembokY) {
              kosong = false;
              break;
            }
          }
        } while (kosong === false);
        Tembok.push({ x: TembokX, y: TembokY });
      }

      //nambah tembok tiap score kelipatan ... berapa enaknya ya? 😁
      function PenambahanTembok() {
        if (ModeH) {
          if (Tembok.length < Math.floor(score / 2)) {
            RandomSpawnWall();
          }
        }
      }

      //set dan update score
      function UpdateScore(amount) {
        score = amount > 0 ? score + amount : 0;
        console.log("UPDATE SCORE , score:",score);
        highscore = score > highscore ? score : highscore;
        Text.innerHTML =
          "Score: " +
          score +
          "<br>Highscore: " +
          highscore +
          "<br>Speed: " +
          speed;

        PenambahanTembok();
      }

      //tampilin gameover
      function GameOver() {
        GameStart = false;
        ClearCanvas();
        
        // Simpan score ke database
        saveScore(score);

        // TAMPILKAN POP-UP GAME OVER
        ScoreMain.innerHTML = "Score: " + score;
        UpDead.style.display = "flex";
      }
      
      //fungsi untuk menyimpan score ke database
      function saveScore(finalScore) {
        console.log("SAVING SCORE , score:",finalScore);
        // Buat form tersembunyi untuk submit score
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = 'simpan_score.php';
        form.style.display = 'none';
        
        var scoreInput = document.createElement('input');
        scoreInput.type = 'hidden';
        scoreInput.name = 'score';
        scoreInput.value = finalScore;
        
        form.appendChild(scoreInput);
        document.body.appendChild(form);
        form.submit();
      }

      //reset isi canvas doang
      function ClearCanvas() {
        content.clearRect(0, 0, canvas.width, canvas.height);
      }

      //bagian utama:
      //ular makan dan mati pas ketemu badannya
      function IntiGame() {
        //buat gambarnya bisa keluar
        content.drawImage(ApelImage, Apel.x, Apel.y, grid, grid);
        Tembok.forEach(function (bata) {
          content.drawImage(TembokImage, bata.x, bata.y, grid, grid);
        });

        Ular.cells.forEach(function (cell, index) {
          if (index === 0) {
            // Logika Pemilihan Gambar Kepala Ular
            var posisiKepalaImage;
            if (Ular.dx === grid) {
              // KANAN
              posisiKepalaImage = KepalaKanan;
            } else if (Ular.dx === -grid) {
              // KIRI
              posisiKepalaImage = KepalaKiri;
            } else if (Ular.dy === -grid) {
              // ATAS
              posisiKepalaImage = KepalAtas;
            } else if (Ular.dy === grid) {
              // BAWAH
              posisiKepalaImage = KepalaBawah;
            } else {
              // Default, misalnya saat game baru mulai (dx=grid, dy=0, atau default awal)
              posisiKepalaImage = KepalaKanan;
            }

            content.drawImage(posisiKepalaImage, cell.x, cell.y, grid, grid);
          } else {
            content.drawImage(BadanUlarImage, cell.x, cell.y, grid, grid);
          }
        });

        //bagian generate ular
        Ular.cells.forEach(function (cell, index) {
          if (index === 0) {
            content.drawImage(KepalaUlarImage, cell.x, cell.y, grid, grid);
          } else {
            content.drawImage(BadanUlarImage, cell.x, cell.y, grid, grid);
          }

          //buat pas ular makan Apel
          if (cell.x === Apel.x && cell.y === Apel.y) {
            Ular.maxCells += 1;
            UpdateScore(1);
            RandomizeApel();
          }

          //tabrak tembok = mati
          if (index === 0) {
            Tembok.forEach(function (bata) {
              if (cell.x === bata.x && cell.y === bata.y) {
                GameOver();
              }
            });
          }

          //buat pas ular mati kena badan sendiri
          for (var i = index + 1; i < Ular.cells.length; i++)
            if (cell.x === Ular.cells[i].x && cell.y === Ular.cells[i].y)
              GameOver();
        });
      }

      //update teks pada speed kalau score update
      function Movement() {
        if (++count < speed) return;
        if (ArahUlar > 0) ArahUlar--;
        count = 0;
        Ular.x += Ular.dx;
        Ular.y += Ular.dy;
        if (
          Ular.x < 0 ||
          Ular.x >= canvas.width ||
          Ular.y < 0 ||
          Ular.y >= canvas.height
        )
          GameOver();
        Ular.cells.unshift({ x: Ular.x, y: Ular.y });
        if (Ular.cells.length > Ular.maxCells) Ular.cells.pop();
      }

      //input keyboard
      function InputKeyboard() {
        document.addEventListener("keydown", function (e) {
          if (!GameStart) return;

          // jalan buat ular
          if (
            ArahUlar == 0 &&
            ((e.code == "KeyA" && Ular.dx === 0) ||
              (e.code == "KeyD" && Ular.dx === 0))
          ) {
            ArahUlar = 1;
            Ular.dx = e.code === "KeyA" ? -grid : grid;
            Ular.dy = 0;
          } else if (
            ArahUlar == 0 &&
            ((e.code === "KeyW" && Ular.dy === 0) ||
              (e.code == "KeyS" && Ular.dy === 0))
          ) {
            ArahUlar = 1;
            Ular.dy = e.code == "KeyW" ? -grid : grid;
            Ular.dx = 0;
          } else if (
            ArahUlar == 0 &&
            ((e.code === "ArrowUp" && Ular.dy === 0) ||
              (e.code == "ArrowDown" && Ular.dy === 0))
          ) {
            ArahUlar = 1;
            Ular.dy = e.code == "ArrowUp" ? -grid : grid;
            Ular.dx = 0;
          } else if (
            ArahUlar == 0 &&
            ((e.code === "ArrowLeft" && Ular.dx === 0) ||
              (e.code == "ArrowRight" && Ular.dx === 0))
          ) {
            ArahUlar = 1;
            Ular.dx = e.code == "ArrowLeft" ? -grid : grid;
            Ular.dy = 0;
          } 

          if (e.code === "KeyE" || e.code == "KeyQ")
            speed =
              e.code == "KeyE" && speed > 5
                ? speed - 1
                : e.code == "KeyQ" && speed < 15
                ? speed + 1
                : speed;
        });
      }
      InputKeyboard();
      gameLoop();