diff --git a/2048_User_Interface.js b/2048_User_Interface.js index 201c941..0507558 100644 --- a/2048_User_Interface.js +++ b/2048_User_Interface.js @@ -92,10 +92,10 @@ function showGameOver() { const finalScore = currentScore; if (typeof saveScore === 'function') { - console.log("Mengirim skor ke database:", finalScore); + console.log("Sending score to the database:", finalScore); saveScore(finalScore); } else { - console.error("Fungsi saveScore tidak ditemukan! Pastikan Score_Request.js sudah diload."); + console.error("saveScore function not found! Make sure Score_Request.js is loaded."); } const isNewHighScore = finalScore >= highScore && finalScore > 0; diff --git a/Logout.js b/Logout.js index f3a0997..e893c7a 100644 --- a/Logout.js +++ b/Logout.js @@ -1,13 +1,11 @@ (function() { 'use strict'; - // CHECK LOGIN STATUS function checkLoginStatus() { const loggedInUser = sessionStorage.getItem("loggedInUser"); const loginBtn = document.querySelector('.btn-login'); if (loggedInUser && loginBtn) { - // Mengubah button login menjadi logout loginBtn.textContent = 'Logout'; loginBtn.classList.remove('btn-login'); loginBtn.classList.add('btn-logout'); @@ -25,14 +23,11 @@ } } - // LOGOUT CLICK HANDLER - // Mencegah halaman refresh secara otomatis dan langsung menampilkan jendela pop-up konfirmasi logout function handleLogoutClick(e) { e.preventDefault(); showLogoutModal(); } - // SHOW LOGOUT CONFIRMATION MODAL function showLogoutModal() { const overlay = document.getElementById('logout-overlay'); if (overlay) { @@ -42,13 +37,11 @@ } } - // SETUP MODAL BUTTONS function setupModalButtons() { const cancelBtn = document.getElementById('btn-logout-cancel'); const confirmBtn = document.getElementById('btn-logout-confirm'); const overlay = document.getElementById('logout-overlay'); - // Remove previous listeners (mencegah error double click) if (cancelBtn) { const newCancelBtn = cancelBtn.cloneNode(true); cancelBtn.replaceWith(newCancelBtn); @@ -61,7 +54,6 @@ newConfirmBtn.onclick = confirmLogout; } - // Close on overlay click (area gelap) if (overlay) { overlay.onclick = function(e) { if (e.target === overlay) { @@ -70,12 +62,9 @@ }; } - // Aktifkan tombol escape untuk menutup modal document.addEventListener('keydown', handleEscapeKey); } - // HANDLE ESCAPE KEY - // Menutup jendela pop-up (modal) logout menggunakan tombol keyboard Esc function handleEscapeKey(e) { if (e.key === 'Escape') { const overlay = document.getElementById('logout-overlay'); @@ -85,7 +74,6 @@ } } - // CLOSE LOGOUT MODAL function closeLogoutModal() { const overlay = document.getElementById('logout-overlay'); if (overlay) { @@ -95,53 +83,45 @@ }, 300); } - // Remove escape key listener document.removeEventListener('keydown', handleEscapeKey); } - // CONFIRM LOGOUT function confirmLogout() { - console.log("Mencoba logout ke server..."); // Debugging + console.log("Attempting to log out to the server..."); - // Panggil PHP untuk hancurkan sesi server fetch('Logout.php') .then(response => { console.log("Respon server:", response); - return response.json(); // Ubah ke JSON biar bisa dicek + return response.json(); }) .then(data => { console.log("Status Logout:", data); - // Hapus data di browser (Session Storage) sessionStorage.removeItem("loggedInUser"); sessionStorage.removeItem("authToken"); - sessionStorage.clear(); // Bersihkan semuanya biar aman + sessionStorage.clear(); - // Tutup Modal & Redirect closeLogoutModal(); showSuccessModal(); setTimeout(() => { - // Redirect ke Homepage window.location.replace('Homepage.html'); }, 1500); }) .catch(error => { console.error('Logout error:', error); - // Fallback: Kalau server error, tetap paksa keluar di tampilan + sessionStorage.clear(); window.location.replace('Homepage.html'); }); } - // SHOW SUCCESS MODAL function showSuccessModal() { const successOverlay = document.getElementById('logout-success-overlay'); if (successOverlay) { successOverlay.style.display = 'flex'; setTimeout(() => successOverlay.classList.add('active'), 10); - // Auto close after 1.3 seconds setTimeout(() => { successOverlay.classList.remove('active'); setTimeout(() => { @@ -150,10 +130,7 @@ }, 1300); } } - - - // INITIALIZE - // Menjamin agar kode tidak mencuri start sebelum elemen HTML tersedia. + function init() { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', checkLoginStatus); diff --git a/Logout.php b/Logout.php index b7179fd..b0000eb 100644 --- a/Logout.php +++ b/Logout.php @@ -1,11 +1,10 @@ "success", "message" => "Logout berhasil" diff --git a/Register.js b/Register.js index 0f51ab4..3235324 100644 --- a/Register.js +++ b/Register.js @@ -1,7 +1,6 @@ import { showModal, closeModal, setupModalOk, setupOutsideClose } from "./Modal_Register.js"; import { registerRequest } from "./Register_Request.js"; -// Aktifkan tombol modal setupModalOk(); setupOutsideClose(); @@ -12,13 +11,11 @@ document.getElementById("registerForm").addEventListener("submit", async functio const password = document.getElementById("password").value.trim(); const confirmPassword = document.getElementById("confirmPassword").value.trim(); - // Validasi kosong if (!username || !password || !confirmPassword) { showModal("error", "Register Failed!", "All fields are required."); return; } - // Validasi password tidak sama if (password !== confirmPassword) { showModal("error", "Password Mismatch!", "Password and Confirm Password must match."); setInputError("password"); @@ -26,7 +23,6 @@ document.getElementById("registerForm").addEventListener("submit", async functio return; } - // Button loading state const submitBtn = this.querySelector("button[type='submit']"); submitBtn.disabled = true; @@ -34,10 +30,9 @@ document.getElementById("registerForm").addEventListener("submit", async functio const data = await registerRequest(username, password); if (data.status === "success") { - // 1. Tampilkan modal sukses + showModal("success", "Register Successful!", data.message); - // 2. Simpan Score (Logic Anda) const pendingScore = localStorage.getItem('lastScore'); if (pendingScore && typeof saveScore === "function") { console.log("Menyimpan skor pending: " + pendingScore); @@ -45,32 +40,22 @@ document.getElementById("registerForm").addEventListener("submit", async functio } else if (typeof score !== 'undefined') { saveScore(score); } - - // --- 🔥 PERUBAHAN DI SINI 🔥 --- - - // Cari tombol OK pada modal. - // PENTING: Pastikan ID ini ("modalOkBtn") sesuai dengan ID tombol OK di HTML/Modal Anda. - // Jika ID-nya beda, ganti string di bawah ini. - - // --- 🔥 TAMBAHKAN KODE DI SINI (Bagian Tombol OK) 🔥 --- const okBtn = document.getElementById("modalOkBtn"); if (okBtn) { okBtn.addEventListener("click", function() { - // [BARU] Simpan username ke sessionStorage AGAR TUTORIAL MUNCUL - // Ini penting supaya logic di 2048.js tahu ini user baru + sessionStorage.setItem("loggedInUser", username); - // Setelah disimpan, baru pindah ke Homepage window.location.href = "Homepage.html"; }, { once: true }); } else { - // Fallback jika tombol error - console.warn("Tombol OK tidak ditemukan, redirect otomatis."); + + console.warn("OK button not found, redirecting automatically."); setTimeout(() => { - // [BARU] Simpan juga disini buat jaga-jaga + sessionStorage.setItem("loggedInUser", username); window.location.href = "Homepage.html"; }, 2000); @@ -95,12 +80,10 @@ document.getElementById("registerForm").addEventListener("submit", async functio } }); -// Hilangkan efek error saat user mengetik document.getElementById("username").addEventListener("input", clearInputStyle); document.getElementById("password").addEventListener("input", clearInputStyle); document.getElementById("confirmPassword").addEventListener("input", clearInputStyle); -// Efek error merah neon function setInputError(id) { const el = document.getElementById(id); if(el) { @@ -109,7 +92,6 @@ function setInputError(id) { } } -// Hilangkan error visual function clearInputStyle() { this.style.borderColor = ""; this.style.boxShadow = ""; diff --git a/Register.php b/Register.php index b5df56b..fcacbbe 100644 --- a/Register.php +++ b/Register.php @@ -1,5 +1,5 @@ "error", "message" => "Username and password are required"]); exit; } -// Validasi Password if (strlen($password) < 6) { echo json_encode(["status" => "error", "message" => "Password must be at least 6 characters"]); exit; } -// Validasi Username if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) { echo json_encode(["status" => "error", "message" => "Invalid username format"]); exit; } -// Cek Username $check = $conn->prepare("SELECT id FROM users WHERE username = ?"); $check->bind_param("s", $username); $check->execute(); @@ -52,9 +46,8 @@ if ($check->num_rows > 0) { } $check->close(); -// Simpan User Baru -$hashedPassword = password_hash($password, PASSWORD_DEFAULT); // Hash password -$created_at = date("Y-m-d H:i:s"); // Waktu daftar +$hashedPassword = password_hash($password, PASSWORD_DEFAULT); +$created_at = date("Y-m-d H:i:s"); $stmt = $conn->prepare( "INSERT INTO users (username, password, created_at) VALUES (?, ?, ?)" @@ -62,11 +55,11 @@ $stmt = $conn->prepare( $stmt->bind_param("sss", $username, $hashedPassword, $created_at); if ($stmt->execute()) { - $new_user_id = $stmt->insert_id; // Ambil ID user baru + $new_user_id = $stmt->insert_id; - session_start(); // Mulai session - $_SESSION['user_id'] = $new_user_id; // Set session ID - $_SESSION['username'] = $username; // Set session username + session_start(); + $_SESSION['user_id'] = $new_user_id; + $_SESSION['username'] = $username; echo json_encode([ "status" => "success", @@ -80,6 +73,6 @@ if ($stmt->execute()) { ]); } -$stmt->close(); // Tutup statement -$conn->close(); // Tutup DB +$stmt->close(); +$conn->close(); ?> \ No newline at end of file diff --git a/Score.php b/Score.php index d32d57c..2afa3a9 100644 --- a/Score.php +++ b/Score.php @@ -1,9 +1,8 @@ "error", @@ -12,12 +11,10 @@ if (!isset($_SESSION['username']) || !isset($_SESSION['user_id'])) { exit; } -// Ambil Data -$username = $_SESSION['username']; // Username dari session -$user_id = $_SESSION['user_id']; // User ID dari session -$score = intval($_POST['score'] ?? 0); // Score dari client +$username = $_SESSION['username']; +$user_id = $_SESSION['user_id']; +$score = intval($_POST['score'] ?? 0); -// Validasi Score if ($score <= 0) { echo json_encode([ "status" => "error", @@ -26,22 +23,17 @@ if ($score <= 0) { exit; } -// Cek Data Leaderboard -$checkStmt = $conn->prepare( - "SELECT score FROM leaderboard WHERE user_id = ?" -); // Cek berdasarkan user_id +$checkStmt = $conn->prepare("SELECT score FROM leaderboard WHERE user_id = ?"); $checkStmt->bind_param("i", $user_id); $checkStmt->execute(); $result = $checkStmt->get_result(); -// Jika sudah ada score if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $oldScore = $row['score']; if ($score > $oldScore) { - // Update jika score lebih tinggi $updateStmt = $conn->prepare( "UPDATE leaderboard SET score = ?, username = ? WHERE user_id = ?" ); @@ -63,7 +55,6 @@ if ($result->num_rows > 0) { } else { - // Score lebih rendah dari record lama echo json_encode([ "status" => "success", "message" => "Score not higher than previous", @@ -73,7 +64,6 @@ if ($result->num_rows > 0) { } else { - // Jika Belum Ada Score $insertStmt = $conn->prepare( "INSERT INTO leaderboard (user_id, username, score) VALUES (?, ?, ?)" ); diff --git a/Score_Request.js b/Score_Request.js index 191409e..483b4d3 100644 --- a/Score_Request.js +++ b/Score_Request.js @@ -1,15 +1,15 @@ function saveScore(score) { - // Kirim score ke server + fetch('Score.php', { - method: 'POST', // Method POST + method: 'POST', headers: { - 'Content-Type': 'application/x-www-form-urlencoded' // Data dikirim dalam format form data + 'Content-Type': 'application/x-www-form-urlencoded' }, - body: 'score=' + encodeURIComponent(score) // Data score yang dikirim + body: 'score=' + encodeURIComponent(score) }) - .then(response => response.json()) // Ubah response ke JSON + .then(response => response.json()) .then(data => { - // Cek status dari server + if (data.status === "success") { console.log("Score saved successfully"); } else {