const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const HIGH_SCORES_FILE = path.join(process.cwd(), 'high_scores.json');
const LATEST_SCORE_FILE = '/tmp/alpaca_score.json';
function loadHighScores() {
try {
const data = fs.readFileSync(HIGH_SCORES_FILE, 'utf8');
const scores = JSON.parse(data);
if (Array.isArray(scores)) return scores;
} catch (e) {}
return [];
}
function saveHighScores(scores) {
try {
fs.writeFileSync(HIGH_SCORES_FILE, JSON.stringify(scores, null, 2));
} catch (e) {}
}
function saveLatestScore(initials, score) {
try {
fs.writeFileSync(LATEST_SCORE_FILE, JSON.stringify({ initials, score }));
} catch (e) {}
}
function addHighScore(initials, score) {
const scores = loadHighScores();
scores.push({ initials, score });
scores.sort((a, b) => b.score - a.score);
const top5 = scores.slice(0, 5);
saveHighScores(top5);
saveLatestScore(initials, score);
return top5;
}
const HTML = `
Space Invaders
`;
const server = http.createServer((req, res) => {
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(HTML);
} else if (req.method === 'GET' && req.url === '/api/scores') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ scores: loadHighScores() }));
} else if (req.method === 'POST' && req.url === '/api/score') {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
try {
const data = JSON.parse(body);
const initials = String(data.initials || 'AAA').toUpperCase().replace(/[^A-Z0-9]/g, '').padEnd(3, 'A').slice(0, 3);
const score = Math.max(0, Math.floor(Number(data.score) || 0));
const scores = addHighScore(initials, score);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ scores, ok: true }));
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'invalid' }));
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});
server.listen(PORT, () => {
console.log('Space Invaders running at http://localhost:' + PORT);
});