diff --git a/GameLogic.js b/GameLogic.js index 85f0940..0bd607b 100644 --- a/GameLogic.js +++ b/GameLogic.js @@ -336,5 +336,35 @@ : speed; }); } + + function updatedatabase(scoreBaru) { + // 1. Buat objek data yang akan dikirim + const KirimScore = { + action: 'SaveScore', // Identifier untuk PHP + score: scoreBaru + }; + + // 2. Gunakan Fetch API untuk mengirim permintaan POST + fetch('score.php', { // Ganti dengan nama file PHP Anda + method: 'POST', + headers: { + 'Content-Type': 'application/json' // Beri tahu server bahwa yang dikirim adalah JSON + }, + body: JSON.stringify(KirimScore) // Konversi data JS menjadi string JSON + }) + .then(response => response.json()) // Ubah respons server kembali menjadi objek JS + .then(data => { + // 3. Tangani respons dari PHP + if (data.status === 'success') { + console.log('Score berhasil disimpan:', data.message); + // Lakukan sesuatu (misalnya: tampilkan pesan sukses di UI) + } else { + console.error('Gagal menyimpan score:', data.message); + } + }) + .catch(error => { + console.error('Terjadi kesalahan koneksi:', error); + }); +} InputKeyboard(); gameLoop(); \ No newline at end of file diff --git a/score.php b/score.php new file mode 100644 index 0000000..ed7fe70 --- /dev/null +++ b/score.php @@ -0,0 +1,59 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; + +try { + $pdo = new PDO($dsn, $user, $pass, $options); +} catch (\PDOException $e) { + http_response_code(500); // Internal Server Error + echo json_encode(['status' => 'error', 'message' => 'Gagal koneksi database.']); + exit; +} + +// --- 2. Ambil Data dari JavaScript (AJAX) --- +$data = json_decode(file_get_contents('php://input'), true); + +if (!isset($data['action']) || $data['action'] !== 'simpan_score') { + http_response_code(400); // Bad Request + echo json_encode(['status' => 'error', 'message' => 'Aksi tidak valid.']); + exit; +} + +$score = filter_var($data['score'] ?? 0, FILTER_SANITIZE_NUMBER_INT); +$userId = 1; // Contoh: Asumsikan ID pengguna 1 (Anda harus mengambilnya dari sesi atau input) + +if (!is_numeric($score) || $score < 0) { + http_response_code(400); + echo json_encode(['status' => 'error', 'message' => 'Score tidak valid.']); + exit; +} + +// --- 3. Simpan ke Database (menggunakan Prepared Statements) --- +try { + $sql = "INSERT INTO scores (user_id, score, created_at) VALUES (?, ?, NOW())"; + $stmt = $pdo->prepare($sql); + $stmt->execute([$userId, $score]); + + // Berikan respons sukses ke JavaScript + echo json_encode(['status' => 'success', 'message' => 'Score berhasil disimpan.']); + +} catch (\PDOException $e) { + http_response_code(500); + echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan score ke DB: ' . $e->getMessage()]); +} + +?> \ No newline at end of file