// Yarış kuralları: kayıt -> boru -> geri sayım -> koşu -> sonuç -> yeni koşu.
// Her yorum yazan kendi atıyla yarışa girer; yarıştayken yazdığı her yorum atını hızlandırır.
// Bahis / ödül yok.
import { LANES, SILKS, COATS } from './draw.js';
const BOT_NAMES = ['Karayel', 'Şimşek', 'Yıldırım', 'Fırtına', 'Tarçın', 'Kısmet', 'Poyraz', 'Bahadır', 'Ceylan', 'Rüzgar', 'Sultan', 'Kartal'];
const norm = (s) => String(s || '').toLocaleLowerCase('tr').trim();
export class Race {
constructor(rules, hooks) {
const R = rules.race || {};
this.cfg = {
lanes: Math.min(LANES, R.horses || LANES),
minHorses: R.minHorses ?? 2,
L: R.lengthMeters || 600,
registerSeconds: R.registerSeconds ?? 25,
resultSeconds: R.resultSeconds ?? 12,
baseSpeed: R.baseSpeed ?? 11,
boostPer: R.boostPerComment ?? 1,
boostMax: R.boostMax ?? 4,
boostSpeed: R.boostSpeed ?? 1.6,
boostDecay: R.boostDecayPerSecond ?? 0.6,
cooldown: R.commentCooldownSeconds ?? 0.7,
bubble: rules.bubbleSeconds ?? 3,
};
this.hooks = hooks; // { toast, phase, countdown, finishFlash, result, sfx }
this.raceNo = 1;
this.champions = {}; // ad -> kazanma sayısı
this.queue = []; // sıradaki koşuya yazılanlar [{id,name}]
this.resetRace();
}
get L() {
return this.cfg.L;
}
resetRace() {
this.phase = 'register';
this.timer = 0;
this.registerStarted = false;
this.horses = [];
this.finishOrder = [];
this.sinceWinner = 0;
this.finalFlashed = false;
this.gateOpen = 0;
// sıradakileri yerleştir
const q = this.queue.splice(0);
for (const u of q) this.addHorse(u, true);
if (this.horses.length) this.registerStarted = true;
this.hooks.phase?.('register');
}
// ---------- olaylar ----------
onChat(user, text, now) {
const h = this.horses.find((x) => !x.bot && x.id === user.id);
if (h) {
h.name = user.name;
h.bubble = String(text || '').trim();
h.bubbleUntil = now + this.cfg.bubble;
if (this.phase === 'race' && !h.place && now - h.lastBoost >= this.cfg.cooldown) {
h.lastBoost = now;
h.boost = Math.min(this.cfg.boostMax, h.boost + this.cfg.boostPer);
h.comments++;
}
return;
}
if (this.phase === 'register') {
if (this.humanCount() < this.cfg.lanes) {
this.addHorse(user);
const nh = this.horses.find((x) => x.id === user.id);
if (nh) {
nh.bubble = String(text || '').trim();
nh.bubbleUntil = now + this.cfg.bubble;
}
if (!this.registerStarted) {
this.registerStarted = true;
this.timer = 0;
}
// kulvarlar dolduysa bekleme kısalsın
if (this.humanCount() >= this.cfg.lanes) this.timer = Math.max(this.timer, this.cfg.registerSeconds - 5);
return;
}
}
// yarış dolu ya da sürüyor: sıradaki koşuya
if (!this.queue.some((u) => u.id === user.id) && this.queue.length < this.cfg.lanes) {
this.queue.push({ id: user.id, name: user.name });
this.hooks.toast?.(`🎟️ @${user.name} sıradaki koşuya yazıldı`);
}
}
humanCount() {
return this.horses.filter((h) => !h.bot).length;
}
addHorse(user, fromQueue = false) {
if (this.horses.some((h) => h.id === user.id)) return;
const used = new Set(this.horses.map((h) => h.lane));
// bot varsa yerini al
if (used.size >= this.cfg.lanes) {
const bot = this.horses.find((h) => h.bot);
if (!bot) return;
this.horses.splice(this.horses.indexOf(bot), 1);
used.delete(bot.lane);
}
const free = [];
for (let i = 0; i < this.cfg.lanes; i++) if (!used.has(i)) free.push(i);
const lane = free[Math.floor(Math.random() * free.length)];
const seed = hash(user.id);
const h = {
id: user.id,
name: user.name,
bot: !!user.bot,
lane,
num: lane + 1,
silk: lane % SILKS.length,
coat: seed % COATS.length,
seed: (seed % 1000) / 100,
stat: 0.97 + ((seed >> 5) % 60) / 1000,
x: 0,
v: 0,
boost: 0,
lastBoost: -9,
gait: Math.random(),
moving: false,
place: 0,
comments: 0,
bubble: '',
bubbleUntil: 0,
nextBotBoost: 0,
};
this.horses.push(h);
if (!h.bot) this.hooks.toast?.(`🏇 @${user.name} ${h.num} numarayla ${fromQueue ? 'kapıda' : 'yarışa girdi'}`);
}
fillBots() {
const need = Math.max(0, Math.min(this.cfg.lanes, Math.max(this.cfg.minHorses, 4)) - this.horses.length);
const names = BOT_NAMES.slice().sort(() => Math.random() - 0.5);
for (let i = 0; i < need; i++) {
const n = names[i];
this.addHorse({ id: 'bot:' + n, name: n, bot: true });
}
}
// panelden
forceStart() {
if (this.phase !== 'register') return;
if (!this.horses.length) this.fillBots();
this.registerStarted = true;
this.timer = this.cfg.registerSeconds;
}
cancel() {
// koşuyu iptal et, yarışanları sıraya geri koy
for (const h of this.horses) if (!h.bot && !this.queue.some((u) => u.id === h.id)) this.queue.push({ id: h.id, name: h.name });
this.resetRace();
}
registerLeft() {
return Math.max(0, this.cfg.registerSeconds - this.timer);
}
// ---------- zaman ----------
update(dt, now) {
this.timer += dt;
const c = this.cfg;
switch (this.phase) {
case 'register':
if (!this.registerStarted) this.timer = 0;
if (this.registerStarted && this.timer >= c.registerSeconds) {
this.fillBots();
this.phase = 'post';
this.timer = 0;
this.postLen = this.hooks.sfx?.('bugle') || 3.5;
this.hooks.phase?.('post');
}
break;
case 'post':
if (this.timer >= this.postLen + 0.3) {
this.phase = 'countdown';
this.timer = 0;
this.lastCount = 4;
this.hooks.phase?.('countdown');
}
break;
case 'countdown': {
const n = 3 - Math.floor(this.timer);
if (n !== this.lastCount && n >= 1) {
this.lastCount = n;
this.hooks.countdown?.(n);
this.hooks.sfx?.('beep');
}
if (this.timer >= 3) {
this.phase = 'race';
this.timer = 0;
for (const h of this.horses) {
h.moving = true;
h.v = 2;
}
this.hooks.countdown?.(0);
this.hooks.sfx?.('gate');
this.hooks.phase?.('race');
}
break;
}
case 'race':
this.gateOpen = Math.min(1, this.gateOpen + dt * 3);
this.updateHorses(dt, now);
if (this.finishOrder.length) this.sinceWinner += dt;
{
const allDone = this.horses.every((h) => h.place);
const podiumDone = this.finishOrder.length >= Math.min(3, this.horses.length);
if (allDone || (podiumDone && this.sinceWinner > 5) || this.sinceWinner > 14) this.finish();
}
break;
case 'result':
for (const h of this.horses) this.coast(h, dt);
if (this.timer >= c.resultSeconds) {
this.raceNo++;
this.resetRace();
}
break;
}
}
leader() {
let best = null;
for (const h of this.horses) if (!best || h.x > best.x) best = h;
return best;
}
updateHorses(dt, now) {
const c = this.cfg;
const lead = this.leader();
for (const h of this.horses) {
if (h.place) {
this.coast(h, dt);
continue;
}
if (h.bot && now >= h.nextBotBoost) {
h.boost = Math.min(c.boostMax, h.boost + c.boostPer);
h.nextBotBoost = now + 0.9 + Math.random() * 1.8;
}
h.boost = Math.max(0, h.boost - c.boostDecay * dt);
// gerideki biraz rüzgar alır (yarış çekişmeli kalsın)
const gap = lead ? lead.x - h.x : 0;
const draft = gap > 60 ? 1.16 : gap > 30 ? 1.09 : gap > 12 ? 1.04 : 1;
const wobble = 1 + Math.sin(now * 0.7 + h.seed * 3) * 0.03;
const target = (c.baseSpeed * h.stat * wobble + c.boostSpeed * h.boost) * draft;
h.v += (target - h.v) * Math.min(1, dt * 1.6);
h.x += h.v * dt;
h.gait += (h.v / 7) * dt;
if (h.x >= c.L) {
h.place = this.finishOrder.length + 1;
this.finishOrder.push(h);
if (h.place === 1) {
this.hooks.sfx?.('bell');
this.hooks.sfx?.('cheer');
}
}
}
if (lead && !this.finalFlashed && lead.x >= c.L - 200) {
this.finalFlashed = true;
this.hooks.finishFlash?.();
}
}
coast(h, dt) {
if (!h.moving) return;
h.v = Math.max(0, h.v - 5 * dt);
h.x += h.v * dt;
h.gait += (h.v / 7) * dt;
if (h.v <= 0.3) h.moving = false;
}
finish() {
// bitiremeyenleri sıraya koy
const rest = this.horses.filter((h) => !h.place).sort((a, b) => b.x - a.x);
for (const h of rest) {
h.place = this.finishOrder.length + 1;
this.finishOrder.push(h);
}
const win = this.finishOrder[0];
if (win && !win.bot) this.champions[win.name] = (this.champions[win.name] || 0) + 1;
this.phase = 'result';
this.timer = 0;
this.hooks.result?.(this.finishOrder.slice(0, 3), this.raceNo);
this.hooks.phase?.('result');
}
topChampions(n = 5) {
return Object.entries(this.champions).sort((a, b) => b[1] - a[1]).slice(0, n);
}
// ---------- kayıt ----------
snapshot() {
return { v: 1, raceNo: this.raceNo, champions: this.champions, queue: this.queue };
}
restore(s) {
if (!s || s.v !== 1) return;
this.raceNo = s.raceNo || 1;
this.champions = s.champions || {};
if (this.phase === 'register' && !this.horses.length) {
this.queue = Array.isArray(s.queue) ? s.queue.slice(0, this.cfg.lanes) : [];
this.resetRace();
}
}
clearChampions() {
this.champions = {};
}
}
function hash(str) {
let h = 2166136261;
for (const ch of String(str)) h = Math.imul(h ^ ch.codePointAt(0), 16777619);
return h >>> 0;
}
export { norm };
Lisans bilgisi projenin LICENSE dosyasında.