Private
Public Access
1
0

big Performance fix
All checks were successful
Dynamic Branch Deploy / build-and-deploy (push) Successful in 1m20s

This commit is contained in:
Sebastian Unterschütz
2025-12-04 22:43:36 +01:00
parent 13c4e7318c
commit 626493177f
8 changed files with 5136 additions and 393 deletions

View File

@@ -1,63 +1,79 @@
// ==========================================
// 1. ASSETS LADEN
// 1. ASSETS LADEN (PIXI V8)
// ==========================================
// ==========================================
// 1. ASSETS LADEN (PIXI V8 KORREKT)
// ==========================================
async function loadAssets() {
const pPromise = new Promise(resolve => {
playerSprite.src = "assets/player.png";
playerSprite.onload = resolve;
playerSprite.onerror = () => { resolve(); };
});
const keysToLoad = [];
const bgPromises = gameConfig.backgrounds.map((bgFile, index) => {
return new Promise((resolve) => {
const img = new Image();
img.src = "assets/" + bgFile;
img.onload = () => { bgSprites[index] = img; resolve(); };
img.onerror = () => { resolve(); };
// A. Player hinzufügen
PIXI.Assets.add({ alias: 'player', src: 'assets/player.png' });
keysToLoad.push('player');
// B. Hintergründe aus Config
if (gameConfig.backgrounds) {
gameConfig.backgrounds.forEach(bg => {
// Alias = Dateiname (z.B. "school-background.jpg")
PIXI.Assets.add({ alias: bg, src: 'assets/' + bg });
keysToLoad.push(bg);
});
});
}
const obsPromises = gameConfig.obstacles.map(def => {
return new Promise((resolve) => {
if (!def.image) { resolve(); return; }
const img = new Image();
img.src = "assets/" + def.image;
img.onload = () => { sprites[def.id] = img; resolve(); };
img.onerror = () => { resolve(); };
// C. Hindernisse aus Config
if (gameConfig.obstacles) {
gameConfig.obstacles.forEach(def => {
if (def.image) {
// Alias = ID (z.B. "teacher")
// Checken ob Alias schon existiert (vermeidet Warnungen)
if (!PIXI.Assets.cache.has(def.id)) {
PIXI.Assets.add({ alias: def.id, src: 'assets/' + def.image });
keysToLoad.push(def.id);
}
}
});
});
}
await Promise.all([pPromise, ...bgPromises, ...obsPromises]);
try {
console.log("Lade Assets...", keysToLoad);
// Alles auf einmal laden
await PIXI.Assets.load(keysToLoad);
console.log("✅ Alle Texturen geladen!");
} catch (e) {
console.error("❌ Asset Fehler:", e);
}
}
// ... (Rest der Datei: startGameClick, gameLoop etc. BLEIBT GLEICH)
// ...
window.startGameClick = async function() {
if (!isLoaded) return;
startScreen.style.display = 'none';
document.body.classList.add('game-active');
// Score Reset visuell
score = 0;
const scoreEl = document.getElementById('score');
if (scoreEl) scoreEl.innerText = "0";
document.getElementById('score').innerText = "0";
if (typeof startMusic === 'function') startMusic();
// WebSocket Start
startMusic();
connectGame();
resize();
};
// ==========================================
// 3. GAME OVER & SCORE
// ==========================================
window.gameOver = function(reason) {
if (isGameOver) return;
isGameOver = true;
console.log("Game Over:", reason);
// Highscore Check (Lokal)
const finalScore = Math.floor(score / 10);
const currentHighscore = localStorage.getItem('escape_highscore') || 0;
if (finalScore > currentHighscore) {
if (finalScore > parseInt(currentHighscore)) {
localStorage.setItem('escape_highscore', finalScore);
}
@@ -65,22 +81,24 @@ window.gameOver = function(reason) {
gameOverScreen.style.display = 'flex';
document.getElementById('finalScore').innerText = finalScore;
// Input Reset
document.getElementById('inputSection').style.display = 'flex';
document.getElementById('submitBtn').disabled = false;
document.getElementById('playerNameInput').value = "";
// Liste laden
loadLeaderboard();
}
};
window.submitScore = async function() {
const nameInput = document.getElementById('playerNameInput');
const name = nameInput.value.trim();
const btn = document.getElementById('submitBtn');
if (!name) return alert("Bitte Namen eingeben!");
if (!sessionID) return alert("Fehler: Keine Session ID vom Server erhalten.");
btn.disabled = true;
try {
@@ -90,11 +108,10 @@ window.submitScore = async function() {
body: JSON.stringify({ sessionId: sessionID, name: name })
});
if (!res.ok) throw new Error("Fehler beim Senden");
if (!res.ok) throw new Error("Server antwortet nicht");
const data = await res.json();
// Lokal speichern ("Meine Codes")
let myClaims = JSON.parse(localStorage.getItem('escape_claims') || '[]');
myClaims.push({
name: name,
@@ -105,52 +122,104 @@ window.submitScore = async function() {
});
localStorage.setItem('escape_claims', JSON.stringify(myClaims));
// UI Update
document.getElementById('inputSection').style.display = 'none';
loadLeaderboard();
alert(`Gespeichert! Dein Code: ${data.claimCode}`);
} catch (e) {
console.error(e);
alert("Fehler beim Speichern: " + e.message);
alert("Fehler: " + e.message);
btn.disabled = false;
}
};
async function loadLeaderboard() {
try {
const res = await fetch(`/api/leaderboard?sessionId=${sessionID}`);
const entries = await res.json();
let html = "<h3 style='margin-bottom:5px; color:#ffcc00;'>BESTENLISTE</h3>";
if(entries.length === 0) html += "<div>Noch keine Einträge.</div>";
entries.forEach(e => {
const color = e.isMe ? "cyan" : "white"; // Eigener Name in Cyan
const bgStyle = e.isMe ? "background:rgba(0,255,255,0.1);" : "";
html += `
<div style="border-bottom:1px dotted #444; padding:5px; ${bgStyle} display:flex; justify-content:space-between; color:${color}; font-size:12px;">
<span>#${e.rank} ${e.name}</span>
<span>${Math.floor(e.score/10)}</span>
</div>`;
if(!entries || entries.length === 0) html += "<div>Leer.</div>";
else entries.forEach(e => {
const color = e.isMe ? "cyan" : "white";
const bg = e.isMe ? "background:rgba(0,255,255,0.1);" : "";
html += `<div style="display:flex; justify-content:space-between; color:${color}; ${bg} padding:4px; border-bottom:1px dotted #444; font-size:12px;">
<span>#${e.rank} ${e.name}</span><span>${Math.floor(e.score/10)}</span></div>`;
});
document.getElementById('leaderboard').innerHTML = html;
} catch(e) {
console.error("Leaderboard Error:", e);
}
} catch(e) { console.error(e); }
}
// ==========================================
// 4. MEINE CODES (LOGIK)
// ==========================================
window.showMyCodes = function() {
openModal('codes');
const listEl = document.getElementById('codesList');
if(!listEl) return;
const rawClaims = JSON.parse(localStorage.getItem('escape_claims') || '[]');
if (rawClaims.length === 0) {
listEl.innerHTML = "<div style='padding:20px; text-align:center; color:#666;'>Keine Codes.</div>";
return;
}
const sortedClaims = rawClaims.sort((a, b) => b.score - a.score);
let html = "";
sortedClaims.forEach(c => {
let rankIcon = "📄";
if (c.score >= 5000) rankIcon = "⭐";
if (c.score >= 10000) rankIcon = "🔥";
html += `
<div style="border-bottom:1px solid #444; padding:8px 0; display:flex; justify-content:space-between; align-items:center;">
<div style="text-align:left;">
<span style="color:#00e5ff; font-weight:bold; font-size:12px;">${rankIcon} ${c.code}</span>
<span style="color:#ffcc00; font-weight:bold;">(${c.score} Pkt)</span><br>
<span style="color:#aaa; font-size:9px;">${c.name}${c.date}</span>
</div>
<button onclick="deleteClaim('${c.code}')"
style="background:transparent; border:1px solid #ff4444; color:#ff4444; padding:4px 8px; font-size:9px; cursor:pointer;">
LÖSCHEN
</button>
</div>`;
});
listEl.innerHTML = html;
};
window.deleteClaim = async function(code) {
if(!confirm("Eintrag wirklich löschen?")) return;
// Suchen der SessionID für den Server-Call
let claims = JSON.parse(localStorage.getItem('escape_claims') || '[]');
const item = claims.find(c => c.code === code);
if (item && item.sessionId) {
try {
await fetch('/api/claim/delete', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ sessionId: item.sessionId, claimCode: code })
});
} catch(e) { console.warn("Server delete failed"); }
}
// Lokal löschen
claims = claims.filter(c => c.code !== code);
localStorage.setItem('escape_claims', JSON.stringify(claims));
window.showMyCodes(); // Refresh
};
// ==========================================
// 5. GAME LOOP (PHYSICS + RENDER)
// ==========================================
function gameLoop(timestamp) {
requestAnimationFrame(gameLoop);
if (!isLoaded) return;
// Nur updaten, wenn Spiel läuft
if (isGameRunning && !isGameOver) {
if (!lastTime) lastTime = timestamp;
const deltaTime = timestamp - lastTime;
@@ -160,46 +229,62 @@ function gameLoop(timestamp) {
accumulator += deltaTime;
// --- FIXED TIME STEP (Physik: 20 TPS) ---
while (accumulator >= MS_PER_TICK) {
updateGameLogic();
updateGameLogic(); // logic.js (setzt prevX/prevY)
currentTick++;
// Score lokal hochzählen (damit es flüssig aussieht)
// Server korrigiert, falls Abweichung zu groß
score++;
accumulator -= MS_PER_TICK;
}
const alpha = accumulator / MS_PER_TICK;
// Score im HUD
// HUD Update
const scoreEl = document.getElementById('score');
if (scoreEl) scoreEl.innerText = Math.floor(score / 10);
}
drawGame(isGameRunning ? accumulator / MS_PER_TICK : 1.0);
// --- INTERPOLATION (Rendering: 60+ FPS) ---
// alpha berechnen: Wie viel % ist seit dem letzten Tick vergangen?
const alpha = (isGameRunning && !isGameOver) ? (accumulator / MS_PER_TICK) : 1.0;
// drawGame ist jetzt in render.js und nutzt Pixi
drawGame(alpha);
}
// ==========================================
// 6. INITIALISIERUNG
// ==========================================
async function initGame() {
try {
const cRes = await fetch('/api/config');
gameConfig = await cRes.json();
// Pixi Assets laden
await loadAssets();
await loadStartScreenLeaderboard();
if (typeof getMuteState === 'function') {
updateMuteIcon(getMuteState());
}
// Startscreen Bestenliste
await loadStartScreenLeaderboard();
isLoaded = true;
if(loadingText) loadingText.style.display = 'none';
if(startBtn) startBtn.style.display = 'inline-block';
// Mute Icon setzen (audio.js State)
if (typeof getMuteState === 'function') {
updateMuteIcon(getMuteState());
}
// Lokaler Highscore
const savedHighscore = localStorage.getItem('escape_highscore') || 0;
const hsEl = document.getElementById('localHighscore');
if(hsEl) hsEl.innerText = savedHighscore;
// Loop starten (für Idle Rendering)
requestAnimationFrame(gameLoop);
drawGame();
drawGame(1.0); // Initiale Zeichnung
} catch(e) {
console.error(e);
@@ -207,16 +292,14 @@ async function initGame() {
}
}
// Helper: Startscreen Leaderboard
async function loadStartScreenLeaderboard() {
try {
const listEl = document.getElementById('startLeaderboardList');
if (!listEl) return;
const res = await fetch('/api/leaderboard');
const entries = await res.json();
if (entries.length === 0) { listEl.innerHTML = "<div style='padding:20px'>Keine Scores.</div>"; return; }
if (!entries || entries.length === 0) { listEl.innerHTML = "<div style='padding:20px'>Noch keine Scores.</div>"; return; }
let html = "";
entries.forEach(e => {
let icon = "#" + e.rank;
@@ -227,14 +310,13 @@ async function loadStartScreenLeaderboard() {
} catch (e) {}
}
// Helper: Audio Button Logik
window.toggleAudioClick = function() {
const muted = toggleMute();
updateMuteIcon(muted);
document.getElementById('mute-btn').blur();
if (typeof toggleMute === 'function') {
const muted = toggleMute();
updateMuteIcon(muted);
document.getElementById('mute-btn').blur();
}
};
function updateMuteIcon(isMuted) {
@@ -246,100 +328,10 @@ function updateMuteIcon(isMuted) {
}
}
// Modal Helpers
window.openModal = function(id) { document.getElementById('modal-' + id).style.display = 'flex'; }
window.closeModal = function() { document.querySelectorAll('.modal-overlay').forEach(el => el.style.display = 'none'); }
window.onclick = function(event) { if (event.target.classList.contains('modal-overlay')) closeModal(); }
window.showMyCodes = function() {
openModal('codes');
const listEl = document.getElementById('codesList');
if(!listEl) return;
const rawClaims = JSON.parse(localStorage.getItem('escape_claims') || '[]');
if (rawClaims.length === 0) {
listEl.innerHTML = "<div style='padding:20px; text-align:center; color:#666;'>Keine Codes gespeichert.</div>";
return;
}
const sortedClaims = rawClaims
.map((item, index) => ({ ...item, originalIndex: index }))
.sort((a, b) => b.score - a.score);
let html = "";
sortedClaims.forEach(c => {
let rankIcon = "📄";
if (c.score >= 5000) rankIcon = "⭐";
if (c.score >= 10000) rankIcon = "🔥";
if (c.score >= 20000) rankIcon = "👑";
html += `
<div style="border-bottom:1px solid #444; padding:10px 0; display:flex; justify-content:space-between; align-items:center;">
<div style="text-align:left;">
<span style="color:#00e5ff; font-weight:bold; font-size:14px;">${rankIcon} ${c.code}</span>
<span style="color:#ffcc00; font-weight:bold;">(${c.score} Pkt)</span><br>
<span style="color:#aaa; font-size:10px;">${c.name}${c.date}</span>
</div>
<button onclick="deleteClaim('${c.sessionId}', '${c.code}')"
style="background:transparent; border:1px solid #ff4444; color:#ff4444; padding:5px 10px; font-size:10px; cursor:pointer;">
LÖSCHEN
</button>
</div>`;
});
listEl.innerHTML = html;
};
window.deleteClaim = async function(sid, code) {
if(!confirm("Eintrag wirklich löschen?")) return;
try {
await fetch('/api/claim/delete', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ sessionId: sid, claimCode: code })
});
} catch(e) {
console.warn("Server Delete fehlgeschlagen (vielleicht schon weg), lösche lokal...");
}
let claims = JSON.parse(localStorage.getItem('escape_claims') || '[]');
claims = claims.filter(c => c.code !== code);
localStorage.setItem('escape_claims', JSON.stringify(claims));
window.showMyCodes();
if(document.getElementById('startLeaderboardList')) {
loadStartScreenLeaderboard();
}
};
window.openModal = function(id) {
const el = document.getElementById('modal-' + id);
if(el) el.style.display = 'flex';
}
window.closeModal = function() {
const modals = document.querySelectorAll('.modal-overlay');
modals.forEach(el => el.style.display = 'none');
}
window.onclick = function(event) {
if (event.target.classList.contains('modal-overlay')) {
closeModal();
}
}
// Start
initGame();