import { W, H, PPM, laneY, laneScale, SILKS, createScene, drawBackground, drawTrack, drawInnerRail, drawGate, drawHorse, drawLabel, drawDust, addDust, drawMiniMap } from './draw.js';
import { Race } from './race.js';
import { createAudio } from './audio.js';
import { connectServer } from './net.js';
import { createYoutube } from './youtube.js';
const params = new URLSearchParams(location.search);
const $ = (id) => document.getElementById(id);
async function loadRules() {
try {
const r = await fetch('/api/rules');
if (r.ok) return await r.json();
} catch { /* sunucu yoksa varsayılanlar */ }
return {};
}
const rules = await loadRules();
const T = rules.texts || {};
// ---------- ekrana sığdır ----------
const stage = $('stage');
function fit() {
const s = Math.min(innerWidth / W, innerHeight / H);
stage.style.transform = `scale(${s})`;
stage.style.left = `${(innerWidth - W * s) / 2}px`;
stage.style.top = `${(innerHeight - H * s) / 2}px`;
}
addEventListener('resize', fit);
fit();
// ---------- yazılar ----------
$('tTitle').textContent = T.title || 'HİPODROM';
$('card1').textContent = T.card1 || '💬 YORUM YAZ = ATINLA YARIŞA GİR';
$('card2').textContent = T.card2 || '🏇 HER YORUM ATINI HIZLANDIRIR';
$('hint').textContent = T.hint || '';
// bildirimler: çok yorum gelince ekran dolmasın, sırayla ve seyrek göster
const toastQ = [];
function toast(text) {
if (toastQ.length < 3) toastQ.push(text);
}
setInterval(() => {
if (toastQ.length) showToast(toastQ.shift());
}, 1300);
function showToast(text) {
const el = document.createElement('div');
el.className = 'toast';
el.textContent = text;
$('toasts').appendChild(el);
while ($('toasts').children.length > 3) $('toasts').firstChild.remove();
setTimeout(() => el.remove(), 3300);
}
function pop(el, cls, text) {
el.textContent = text;
el.classList.remove(cls);
void el.offsetWidth;
el.classList.add(cls);
}
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
function showResult(top, raceNo) {
const el = $('result');
const win = top[0];
const medals = ['🥇', '🥈', '🥉'];
const title = win.bot ? `🐎 ${esc(win.name)}` : `@${esc(win.name)}`;
const sub = win.bot ? 'Hipodromun atı kazandı! Yorum yaz, atını uçur!' : `${win.comments} yorumla kazandı 🎉`;
el.innerHTML = `
<div class="rt">KOŞU ${raceNo} · KAZANAN</div>
<div class="win">${title}</div>
<div class="sub">${sub}</div>
<div class="pod">${top.map((h, i) => {
const s = SILKS[h.silk];
return `<div class="pl"><span class="m">${medals[i]}</span><span class="n" style="background:${s.c};color:${light(s.c) ? '#111' : '#fff'}">${h.num}</span><span class="nm">${h.bot ? esc(h.name) : '@' + esc(h.name)}</span></div>`;
}).join('')}</div>`;
el.hidden = false;
}
function light(hex) {
const n = parseInt(hex.slice(1), 16);
return ((n >> 16) & 255) * 0.3 + ((n >> 8) & 255) * 0.59 + (n & 255) * 0.11 > 170;
}
// ---------- ses ----------
const audio = createAudio(rules);
audio.init();
// YouTube müziği (panelden link + ses düzeyi)
let ytVol = rules.volumes?.youtube ?? 0.6;
let ytDuck = 1;
let ytUrl = '';
const yt = createYoutube({
volume: ytVol,
onError: (m) => toast('🎵 ' + m),
});
function setYoutube(url) {
url = String(url || '').trim();
if (url === ytUrl) return;
ytUrl = url;
if (url) {
yt.play(url).then((ok) => audio.setYoutube(ok));
} else {
yt.stop();
audio.setYoutube(false);
}
}
const applyYtVol = () => yt.setVolume(ytVol * ytDuck);
audio.onDuck((d) => {
ytDuck = d;
applyYtVol();
});
function setVolume(key, v) {
if (key === 'youtube') {
ytVol = v;
applyYtVol();
} else {
audio.setVolume(key, v);
}
}
if (rules.youtube?.url && !params.has('demo')) setYoutube(rules.youtube.url);
const soundBtn = $('sound');
function checkSound() {
soundBtn.hidden = !(audio.needsUnlock() || yt.needsGesture) || params.has('mute');
}
const unlockAll = () => {
if (yt.needsGesture) yt.resume();
return audio.unlock().then(checkSound);
};
soundBtn.onclick = unlockAll;
addEventListener('pointerdown', () => (audio.needsUnlock() || yt.needsGesture) && unlockAll());
setInterval(checkSound, 1000);
checkSound();
// ---------- yarış ----------
let race;
let sonPlayed = false; // bu koşuda son ses çaldı mı
function makeRace() {
race = new Race(rules, {
toast,
phase(p) {
audio.setPhase(p === 'race' ? 'race' : p === 'result' ? 'result' : 'lobby');
if (p === 'register') {
$('result').hidden = true;
audio.stopSon();
sonPlayed = false;
}
},
countdown(n) {
pop($('countdown'), 'pop', n > 0 ? String(n) : 'BAŞLA!');
clearTimeout(this.cdT);
this.cdT = setTimeout(() => $('countdown').classList.remove('pop'), 950);
$('countdown').style.fontSize = n > 0 ? '300px' : '170px';
},
finishFlash() {
pop($('flash'), 'show', 'SON 200 METRE!');
setTimeout(() => $('flash').classList.remove('show'), 2300);
audio.setPhase('final');
},
result(top, no) {
showResult(top, no);
},
sfx(name) {
if (name === 'bugle') return audio.bugle();
if (name === 'beep') return audio.beep();
if (name === 'gate') return audio.gate();
if (name === 'bell') return audio.bell();
if (name === 'cheer') return audio.cheer(4);
},
});
}
makeRace();
// ---------- sunucu ----------
let ffOffset = 0; // yalnızca demo testinde ileri sarmak için
const now = () => performance.now() / 1000 + ffOffset;
const net = params.has('demo')
? { send() {} }
: connectServer((msg) => {
switch (msg.kind) {
case 'event':
if (msg.event?.type === 'chat') race.onChat(msg.event.user, msg.event.text, now());
break;
case 'restore':
race.restore(msg.state);
break;
case 'reset':
makeRace();
break;
case 'action':
if (msg.name === 'start') race.forceStart();
if (msg.name === 'cancel') race.cancel();
if (msg.name === 'clear-champions') race.clearChampions();
break;
case 'music-next':
if (ytUrl) yt.next();
else audio.next();
break;
case 'youtube':
setYoutube(msg.url);
break;
case 'volume':
setVolume(msg.key, msg.value);
break;
case 'status':
if (msg.volumes) for (const [k, v] of Object.entries(msg.volumes)) setVolume(k, v);
if (typeof msg.youtubeUrl === 'string') setYoutube(msg.youtubeUrl);
break;
case 'reload':
location.reload();
break;
}
}, (ok) => $('net').classList.toggle('bad', !ok));
setInterval(() => net.send({ kind: 'snapshot', state: race.snapshot() }), 5000);
// demo: ?demo=4 -> saniyede 4 sahte yorum (sunucusuz önizleme)
if (params.has('demo')) {
$('net').classList.remove('bad');
const rate = Number(params.get('demo')) || 4;
const names = ['aysu', 'mert', 'zeynep', 'emre', 'elif', 'burak', 'selin', 'can', 'deniz', 'ece', 'kaan', 'irem', 'onur', 'naz'];
const words = ['koş', 'hadi', 'hayda', 'bas', 'koş koş', 'yetiş', 'son düzlük'];
const pool = names.map((n, i) => ({ id: n + i, name: n + (i * 7), w: 0.3 + Math.random() * 2 }));
const fake = () => {
const tot = pool.reduce((s, u) => s + u.w, 0);
let r = Math.random() * tot;
const u = pool.find((p) => (r -= p.w) <= 0) || pool[0];
race.onChat(u, words[Math.floor(Math.random() * words.length)], now());
};
// ?ff=40 -> ilk 40 saniyeyi anında oynat (ekran görüntüsü testi için)
const ff = Number(params.get('ff')) || 0;
for (let k = 0; k < ff * 20; k++) {
ffOffset += 0.05;
if (Math.random() < rate * 0.05) fake();
race.update(0.05, now());
}
setInterval(fake, 1000 / rate);
}
// ---------- ekran ----------
const canvas = $('view');
const ctx = canvas.getContext('2d');
const scene = createScene();
let camPx = -700;
let firstFrame = true;
let last = now();
let hudTick = 0;
const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.ceil(s) % 60).padStart(2, '0')}`;
let lastStatus = '';
function updateHud() {
const st = $('status');
let text = '';
let cls = 'status';
const lead = race.leader();
switch (race.phase) {
case 'register':
text = race.registerStarted
? `🎟️ KAYIT AÇIK · ${fmt(race.registerLeft())} · ${race.humanCount()}/${race.cfg.lanes} AT`
: '💬 İLK YORUM YAZAN YARIŞI BAŞLATIR';
if (race.registerStarted && race.registerLeft() <= 5) cls += ' hot';
break;
case 'post':
text = '🎺 ATLAR START KAPISINDA';
break;
case 'countdown':
text = '⏱️ HAZIR OL!';
cls += ' hot';
break;
case 'race':
if (lead) {
const left = Math.max(0, Math.ceil(race.L - lead.x));
text = `🏁 LİDER: ${lead.num} ${lead.bot ? lead.name : '@' + lead.name} · ${left > 0 ? left + ' m kaldı' : 'FİNİŞ!'}`;
if (left <= 200) cls += ' hot';
else cls += ' go';
}
break;
case 'result':
text = `🏆 SONUÇLAR · YENİ KOŞU ${fmt(Math.max(0, race.cfg.resultSeconds - race.timer))}`;
break;
}
if (text !== lastStatus) {
st.textContent = text;
lastStatus = text;
}
st.className = cls;
$('raceNo').textContent = `KOŞU ${race.raceNo}`;
const q = race.queue;
const qt = q.length ? `⏭️ SIRADAKİ KOŞU: ${q.slice(0, 4).map((u) => '@' + u.name).join(' ')}${q.length > 4 ? ` +${q.length - 4}` : ''}` : '';
if ($('queue').textContent !== qt) $('queue').textContent = qt;
const champs = race.topChampions(4);
const html = champs.length
? champs.map(([n, w]) => `<li>@${esc(n)} <b>×${w}</b></li>`).join('')
: '<li class="empty">İlk kazanan sen ol!</li>';
if ($('champs').innerHTML !== html) $('champs').innerHTML = html;
}
function frame() {
const t = now();
const dt = Math.min(0.05, t - last);
last = t;
race.update(dt, t);
// kamera
const lead = race.leader();
let target = -700;
if ((race.phase === 'race' || race.phase === 'result') && lead) {
target = Math.max(-700, Math.min(lead.x * PPM - 760, race.L * PPM - 560));
}
camPx = firstFrame ? target : camPx + (target - camPx) * Math.min(1, dt * 4);
firstFrame = false;
// ses: nal ve tribün
if (race.phase === 'race' && lead) {
const moving = race.horses.filter((h) => h.moving).length;
audio.setHooves(0.35 + Math.min(0.5, moving * 0.06), Math.max(1.6, lead.v / 7));
} else if (race.phase === 'result') {
audio.setHooves(race.horses.some((h) => h.moving) ? 0.2 : 0, 1.5);
} else {
audio.setHooves(0);
}
// bitişe az kala son ses: kalan süre ses kadar olunca başlar, lider finişe girerken biter
if (race.phase === 'race' && !sonPlayed && lead && !lead.place && lead.v > 1) {
const eta = (race.L - lead.x) / lead.v;
if (eta <= audio.sonDuration()) {
sonPlayed = true;
audio.playSon();
}
}
const excite = race.phase === 'race' ? (lead && lead.x > race.L - 200 ? 1 : 0.4) : race.phase === 'result' ? 0.7 : 0.1;
ctx.clearRect(0, 0, W, H);
drawBackground(ctx, scene, camPx, t, excite);
drawTrack(ctx, scene, camPx, race.L);
drawGate(ctx, camPx, race.gateOpen, false);
const horses = [...race.horses].sort((a, b) => a.lane - b.lane);
for (const h of horses) {
const s = laneScale(h.lane);
const y = laneY(h.lane);
const x = h.x * PPM - camPx;
if (h.moving && h.v > 3 && Math.random() < dt * 14) addDust(scene, h.x * PPM, y, s, 1);
if (x < -80 || x > W + 300) continue;
drawHorse(ctx, x, y, s, h, t);
}
drawDust(ctx, scene, camPx, dt);
drawGate(ctx, camPx, race.gateOpen, true);
drawInnerRail(ctx, camPx);
for (const h of horses) {
const x = h.x * PPM - camPx;
if (x < -20 || x > W + 200) continue;
drawLabel(ctx, x, laneY(h.lane), laneScale(h.lane), h, t);
}
if (race.horses.length) drawMiniMap(ctx, race.horses, race.L, 90, 1410, W - 180);
hudTick -= dt;
if (hudTick <= 0) {
hudTick = 0.1;
updateHud();
}
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
Lisans bilgisi projenin LICENSE dosyasında.