// Oyun kuralları: yorum -> orduya katıl, komutlar -> top / hücum / ok / gemi, beğeni -> top ateşi,
// surların canı biter -> FETİH, sonra yeni kuşatma.
import * as THREE from 'three';
import { Soldier, makeLadder } from './soldier.js';
import { WALL_Z, CANNON_Z, makeShip, makeFlag } from './world.js';
export function normalizeText(s) {
return String(s || '')
.toLocaleLowerCase('tr')
.replace(/ı/g, 'i').replace(/ş/g, 's').replace(/ğ/g, 'g')
.replace(/ü/g, 'u').replace(/ö/g, 'o').replace(/ç/g, 'c')
.normalize('NFD').replace(/[̀-ͯ]/g, '');
}
export function findCommand(text, commands) {
const words = normalizeText(text).split(/[^a-z0-9]+/).filter(Boolean);
for (const [cmd, aliases] of Object.entries(commands || {})) {
for (const a of aliases) if (words.includes(normalizeText(a))) return cmd;
}
return null;
}
// Ordugâh yerleri: öndeki sıralar dolar, kameraya yaklaştıkça sıra daralır
function buildSlots() {
const slots = [];
for (let r = 0; r < 8; r++) {
const z = 0 + r * 1.4;
const half = 6.0 - r * 0.3;
const n = Math.floor((half * 2) / 1.3) + 1;
for (let i = 0; i < n; i++) {
const x = -half + (i * (half * 2)) / (n - 1) + (r % 2 ? 0.25 : -0.25);
slots.push({ x, z, occupant: null, row: r });
}
}
// önce merkeze yakın ve öndeki yerler
return slots.sort((a, b) => a.row - b.row || Math.abs(a.x) - Math.abs(b.x));
}
export class Game {
constructor({ scene, rules, audio, hud, world, wall, fx }) {
Object.assign(this, { scene, rules, audio, hud, world, wall, fx });
this.soldiers = new Map();
this.slots = buildSlots();
this.round = 1;
this.phase = 'siege'; // siege | victory
this.likeEnergy = 0;
this.roundDmg = new Map(); // id -> {name, dmg}
this.totalDmg = new Map();
this.cool = new Map(); // `${id}:${cmd}` -> zaman
this.globalCool = {};
this.tickTimer = 0;
this.time = 0;
this.ships = [];
this.victoryFlag = null;
this.fatihId = null;
const hp = rules.wall?.hp ?? 1500;
this.wall.setHp(hp, hp);
this.refreshHud();
}
get d() { return this.rules.damage || {}; }
// ---------- Askerler ----------
ensure(user) {
let s = this.soldiers.get(user.id);
if (s) {
s.lastActive = performance.now();
return s;
}
const max = this.rules.maxSoldiers ?? 60;
if (this.soldiers.size >= max) {
const idle = [...this.soldiers.values()].sort((a, b) => a.lastActive - b.lastActive)[0];
this.dismiss(idle);
}
const slot = this.slots.find((x) => !x.occupant);
const sol = new Soldier(user.name);
s = { id: user.id, name: user.name, sol, slot, lastActive: performance.now() };
if (slot) slot.occupant = s;
const home = slot ? { x: slot.x, z: slot.z } : { x: (Math.random() - 0.5) * 6, z: 9 };
sol.home = home;
// kameranın altından (ön taraftan) gelir
sol.root.position.set(home.x * 0.6, 0, 13);
this.scene.add(sol.root);
this.soldiers.set(user.id, s);
if (this.phase === 'victory') sol.run([{ go: { x: home.x, z: home.z } }, { call: (x) => { x.cheering = true; } }]);
else sol.goHome();
if (user.id === this.fatihId) sol.setLabelClass('fatih');
this.hud.feed(`🪖 ${user.name} orduya katıldı`);
return s;
}
dismiss(s) {
if (!s) return;
if (s.slot?.occupant === s) s.slot.occupant = null;
s.sol.dispose();
this.soldiers.delete(s.id);
}
credit(s, amount) {
if (!s || amount <= 0) return;
for (const map of [this.roundDmg, this.totalDmg]) {
const r = map.get(s.id) || { name: s.name, dmg: 0 };
r.dmg += amount;
map.set(s.id, r);
}
}
ready(s, cmd) {
const cd = (this.rules.cooldownSeconds?.[cmd] ?? 3) * 1000;
const key = `${s.id}:${cmd}`;
const now = performance.now();
if (now - (this.cool.get(key) || -1e9) < cd) return false;
this.cool.set(key, now);
return true;
}
/** Hasar ver (mermi değdiğinde çağrılır) */
hit(s, amount, at, big = false) {
if (this.phase !== 'siege' || amount <= 0) return;
this.credit(s, amount);
const fell = this.wall.damage(amount);
if (at) {
this.fx.dust(at, big ? 22 : 8);
if (big) this.fx.fire(at, 10);
this.fx.shake(big ? 0.9 : amount >= 25 ? 0.35 : 0);
if (amount >= 15) this.audio.fx.impact(big);
this.hud.damageText(at, amount, big);
}
if (s && amount >= 25) s.sol.pop('💥');
this.refreshHud();
if (fell) this.victory(s);
}
// ---------- Olaylar ----------
handle(e) {
if (!e?.user?.id) return;
if (e.type === 'fetih') return this.cmdTop(this.ensure(e.user), true, 9999); // panelden: son darbe
const s = this.ensure(e.user);
switch (e.type) {
case 'chat': return this.onChat(s, e.text || '');
case 'like': return this.onLike(s, Math.max(1, e.count | 0));
case 'gift': return this.onGift(s, Math.max(1, e.coins | 0), e.giftName);
case 'follow':
s.sol.pop('💖');
this.hud.feed(`💖 ${s.name} takip etti`);
return;
case 'share':
s.sol.pop('🔁');
this.hud.feed(`🔁 ${s.name} paylaştı`);
return;
}
}
onChat(s, text) {
text = text.trim();
if (text) s.sol.say(text, this.rules.bubbleSeconds ?? 5);
const cmd = findCommand(text, this.rules.commands);
if (this.phase !== 'siege') {
if (cmd) s.sol.pop('🌙');
return;
}
switch (cmd) {
case 'top': return this.ready(s, 'top') ? this.cmdTop(s) : s.sol.pop('⏳');
case 'hucum': return this.ready(s, 'hucum') ? this.cmdHucum(s) : s.sol.pop('⏳');
case 'ok': return this.ready(s, 'ok') ? this.cmdOk(s) : s.sol.pop('⏳');
case 'gemi': return this.cmdGemi(s);
case 'tekbir': return this.cmdTekbir(s);
}
// sıradan yorum: tek ok
if (this.ready(s, 'chat') && !s.sol.busy) this.arrowFrom(s, this.d.chat ?? 3);
}
onLike(s, n) {
const now = performance.now();
if (!s.lastHeart || now - s.lastHeart > 3000) {
s.lastHeart = now;
s.sol.pop('❤️');
}
if (this.phase !== 'siege') return;
this.likeEnergy += n;
const need = this.rules.likesPerShot ?? 30;
while (this.likeEnergy >= need) {
this.likeEnergy -= need;
this.fireCannon(s, this.d.likeShot ?? 30, false, true);
}
this.refreshHud();
}
/** Hediye: sadece teşekkür, oyunda avantaj yok (TikTok hediye karşılığı otomatik ödülü kısıtlıyor). */
onGift(s) {
s.sol.pop('💖');
this.hud.feed(`💖 ${s.name} teşekkürler!`);
}
// ---------- Komutlar ----------
/** 'top': asker topa koşar, fitili yakar, gülle surlara */
cmdTop(s, big = false, dmg = this.d.top ?? 30) {
if (this.phase !== 'siege') return;
const cannon = this.nearestCannon(s.sol.root.position.x);
const spot = cannon.gunnerSpot;
s.sol.run([
{ go: spot, run: true },
{ wait: 0.6, pose: 'torch', face: Math.PI },
{ call: () => this.fireCannon(s, dmg, big, false, cannon) },
{ wait: 0.5, pose: 'cheer' },
{ go: s.sol.home },
{ call: (x) => { x.targetFacing = 0; } },
]);
if (big && dmg > 1000) this.hud.banner(`💣 ${s.name} SON DARBEYİ VURUYOR!`, 'gift');
}
nearestCannon(x) {
return this.world.cannons.reduce((a, b) => (Math.abs(b.x - x) < Math.abs(a.x - x) ? b : a));
}
fireCannon(s, dmg, big = false, auto = false, cannon = null) {
if (this.phase !== 'siege') return;
cannon = cannon || this.world.cannons[Math.floor(Math.random() * this.world.cannons.length)];
const muzzle = cannon.fire();
this.audio.fx.cannon();
this.fx.smoke(muzzle, big ? 16 : 9);
this.fx.fire(muzzle, 8);
this.fx.shake(big ? 0.6 : 0.25);
const target = this.wall.targetPoint();
this.fx.shoot(big ? 'big' : 'ball', muzzle, target, (at) => this.hit(s, dmg, at, big));
if (auto && s) this.hud.feed(`${big ? '🎁' : '❤️'} ${s.name} topu ateşletti`);
}
arrowFrom(s, dmg, owner = s) {
const p = s.sol.root.position;
const from = new THREE.Vector3(p.x, 1.4, p.z - 0.3);
s.sol.run([{ wait: 0.35, pose: 'aim', face: Math.PI }, { call: (x) => { x.targetFacing = 0; } }], false);
setTimeout(() => this.fx.shoot('arrow', from, this.wall.randomPoint(), (at) => this.hit(owner, dmg, at)), 300);
}
cmdOk(s) {
// okçu yağmuru: kendisi + yakındaki 4 asker birlikte atar
const p = s.sol.root.position;
const near = [...this.soldiers.values()]
.filter((x) => x !== s && !x.sol.busy)
.sort((a, b) => a.sol.root.position.distanceTo(p) - b.sol.root.position.distanceTo(p))
.slice(0, 4);
const each = Math.round((this.d.ok ?? 15) / (near.length + 1));
this.arrowFrom(s, each + ((this.d.ok ?? 15) - each * (near.length + 1)));
// komşuların okları da komutu yazana sayılır
near.forEach((x, i) => setTimeout(() => this.arrowFrom(x, each, s), 80 * (i + 1)));
s.sol.pop('🏹');
}
/** 'hücum': merdivenle surlara koş, tırman, vuruş, atla, geri dön */
cmdHucum(s) {
const x = Math.max(-4.6, Math.min(4.6, s.sol.root.position.x + (Math.random() - 0.5) * 2));
const base = { x, z: WALL_Z + 1.25 };
let ladder = null;
const sol = s.sol;
sol.pop('⚔️');
this.audio.fx.clash();
sol.run([
{ call: () => sol.carryLadder() },
{ go: { x, z: CANNON_Z + 0.5 }, run: true },
{ go: base, run: true },
{ call: () => {
sol.dropLadder();
ladder = makeLadder();
ladder.position.set(x, 0, WALL_Z + 0.9);
ladder.rotation.x = -0.12;
this.scene.add(ladder);
sol.root.position.z = WALL_Z + 1.0;
} },
{ climb: this.wall.down ? 0.5 : 3.6 },
{ call: () => {
this.audio.fx.clash();
const at = new THREE.Vector3(x, 4.2, WALL_Z + 0.4);
this.hit(s, this.d.hucum ?? 40, at);
} },
{ wait: 1.0, pose: 'swing', face: Math.PI },
{ call: () => this.audio.fx.clash() },
{ wait: 0.4, pose: 'swing', face: Math.PI },
{ drop: true },
{ call: () => ladder && this.scene.remove(ladder) },
{ go: sol.home },
{ call: (q) => { q.targetFacing = 0; } },
]);
}
cmdGemi(s) {
const cd = (this.rules.cooldownSeconds?.gemi ?? 45) * 1000;
const now = performance.now();
if (now - (this.globalCool.gemi || -1e9) < cd) {
s.sol.pop('⏳');
return;
}
this.globalCool.gemi = now;
this.launchShip(s);
}
/** Gemiler karadan yürütülür: sağdan girer, Haliç'e (sola) iner, surları döver */
launchShip(s) {
const ship = makeShip();
ship.position.set(16, 0, WALL_Z + 3.3);
ship.scale.setScalar(1.35);
this.scene.add(ship);
this.ships.push({ ship, s, t: 0, fired: 0 });
this.hud.banner(`⛵ ${s.name} GEMİLERİ KARADAN YÜRÜTTÜ!`, 'gift');
s.sol.pop('⛵');
}
cmdTekbir(s) {
const now = performance.now();
if (now - (this.globalCool.tekbir || -1e9) < 10000) return s.sol.pop('📣');
this.globalCool.tekbir = now;
this.audio.fx.cheer();
s.sol.pop('📣');
for (const x of this.soldiers.values()) {
if (!x.sol.busy) x.sol.run([{ wait: 1.6 + Math.random() * 0.4, pose: 'cheer' }], false);
}
this.hud.feed(`📣 ${s.name} orduyu coşturdu`);
}
// ---------- Fetih ----------
victory(s) {
if (this.phase === 'victory') return;
this.phase = 'victory';
this.victoryAt = performance.now();
this.wall.collapse();
this.audio.fx.impact(true);
this.fx.shake(1.4);
setTimeout(() => this.audio.fx.horn(), 900);
setTimeout(() => this.audio.fx.cheer(), 1600);
// kahramanlar
const heroes = [...this.roundDmg.entries()].sort((a, b) => b[1].dmg - a[1].dmg).slice(0, 3);
const top = heroes[0];
if (top) {
this.fatihId = top[0];
for (const x of this.soldiers.values()) x.sol.setLabelClass(x.id === this.fatihId ? 'fatih' : '');
}
this.hud.victory(this.round, heroes.map(([, r]) => r), s?.name);
// bayrak gediğe dikilir
const flag = makeFlag({ pole: 5.2, w: 2.2, h: 1.46 });
flag.position.set(0, -5.4, WALL_Z);
flag.userData.rise = 0;
this.scene.add(flag);
this.victoryFlag = flag;
// ordu gedikten içeri akar
let i = 0;
for (const x of this.soldiers.values()) {
const tx = (Math.random() - 0.5) * 9;
const tz = WALL_Z - 2.5 - Math.random() * 5;
x.sol.run([
{ wait: 0.6 + (i++ % 12) * 0.12, pose: 'cheer' },
{ go: { x: Math.max(-3.5, Math.min(3.5, tx * 0.5)), z: WALL_Z + 2 }, run: true },
{ go: { x: tx, z: tz }, run: true },
{ call: (q) => { q.targetFacing = 0; q.cheering = true; } },
]);
}
setTimeout(() => this.fx.confetti(new THREE.Vector3(0, 6, WALL_Z + 2), 500, 14), 2200);
setTimeout(() => this.fx.confetti(new THREE.Vector3(0, 6, -2), 300, 12), 4500);
}
newRound() {
this.round++;
this.phase = 'siege';
const max = Math.round((this.rules.wall?.hp ?? 1500) * (this.rules.wall?.growth ?? 1.3) ** (this.round - 1));
this.wall.rebuild(max);
this.roundDmg.clear();
this.likeEnergy = 0;
if (this.victoryFlag) this.victoryFlag.userData.sink = true;
for (const x of this.soldiers.values()) {
x.sol.cheering = false;
x.sol.run([{ go: { x: x.sol.root.position.x * 0.5, z: WALL_Z + 2 }, run: true }, { go: x.sol.home }, { call: (q) => { q.targetFacing = 0; } }]);
}
this.hud.hideVictory();
this.hud.banner(`⚔️ KUŞATMA #${this.round} BAŞLADI! Surlar yeniden örüldü`, 'party');
this.audio.fx.horn();
this.refreshHud();
}
// ---------- Döngü ----------
update(dt, beat) {
this.time += dt;
for (const s of this.soldiers.values()) s.sol.update(dt, beat);
// gemiler
for (let i = this.ships.length - 1; i >= 0; i--) {
const sh = this.ships[i];
sh.t += dt;
const p = sh.ship.position;
// sağdan girer, ortada durup borda ateşi açar, sonra Haliç'e (sola) iner
if (sh.fired < 3 && p.x <= 0) {
p.x = 0;
sh.pause = (sh.pause || 0) + dt;
if (sh.pause > 0.6 + sh.fired * 0.8) {
sh.fired++;
const from = p.clone().add(new THREE.Vector3(-1 + sh.fired, 1.8, -1.2));
this.audio.fx.cannon();
this.fx.smoke(from, 10);
this.fx.fire(from, 6);
this.fx.shake(0.3);
this.fx.shoot('ball', from, this.wall.targetPoint(), (at) => this.hit(sh.s, Math.round((this.d.gemi ?? 150) / 3), at));
}
} else {
p.x -= dt * 3.4;
}
sh.ship.rotation.z = Math.sin(sh.t * 3) * 0.04;
sh.ship.userData.update(this.time);
if (p.x < -20) {
this.scene.remove(sh.ship);
this.ships.splice(i, 1);
}
}
// zafer bayrağı yükselir
const f = this.victoryFlag;
if (f) {
f.userData.update(this.time);
if (f.userData.sink) {
f.position.y -= dt * 3;
if (f.position.y < -6) {
this.scene.remove(f);
this.victoryFlag = null;
}
} else if (performance.now() - this.victoryAt > 1500) {
f.position.y = Math.min(0.3, f.position.y + dt * 2.2);
}
}
if (this.phase === 'victory' && performance.now() - this.victoryAt > (this.rules.victorySeconds ?? 25) * 1000) this.newRound();
this.tickTimer += dt;
if (this.tickTimer >= 1) {
this.tickTimer = 0;
this.tick();
}
}
tick() {
const leave = (this.rules.leaveSeconds ?? 900) * 1000;
const now = performance.now();
for (const s of [...this.soldiers.values()]) if (now - s.lastActive > leave && !s.sol.busy) this.dismiss(s);
this.refreshHud();
}
refreshHud() {
const map = this.roundDmg.size ? this.roundDmg : this.totalDmg;
const leaders = [...map.values()].sort((a, b) => b.dmg - a.dmg).slice(0, 3);
this.hud.setState({
round: this.round,
hp: this.wall.hp,
maxHp: this.wall.maxHp,
army: this.soldiers.size,
leaders,
likes: this.likeEnergy,
likesNeed: this.rules.likesPerShot ?? 30,
});
}
// ---------- Kayıt ----------
snapshot() {
const now = performance.now();
return {
savedAt: Date.now(),
round: this.round,
hp: this.phase === 'victory' ? 0 : this.wall.hp,
maxHp: this.wall.maxHp,
likeEnergy: this.likeEnergy,
fatihId: this.fatihId,
roundDmg: [...this.roundDmg.entries()],
totalDmg: [...this.totalDmg.entries()],
soldiers: [...this.soldiers.values()].map((s) => ({ id: s.id, name: s.name, idleMs: now - s.lastActive })),
};
}
restore(st) {
if (!st || this.soldiers.size) return;
const away = Math.max(0, Date.now() - (st.savedAt || Date.now()));
this.round = st.round || 1;
this.fatihId = st.fatihId || null;
this.roundDmg = new Map(st.roundDmg || []);
this.totalDmg = new Map(st.totalDmg || []);
this.likeEnergy = st.likeEnergy || 0;
const leave = (this.rules.leaveSeconds ?? 900) * 1000;
for (const x of st.soldiers || []) {
if (x.idleMs + away > leave) continue;
const s = this.ensure({ id: x.id, name: x.name });
s.lastActive = performance.now() - x.idleMs - away;
s.sol.root.position.set(s.sol.home.x, 0, s.sol.home.z);
s.sol.queue = [];
s.sol.step = null;
s.sol.targetFacing = 0;
}
this.hud.clearFeed();
if (st.hp > 0) this.wall.setHp(st.hp, st.maxHp || this.wall.maxHp);
else {
// fetih sırasında yenilendi: yeni kuşatmaya geç
this.wall.setHp(st.maxHp, st.maxHp);
this.round = (st.round || 1);
this.phase = 'victory';
this.victoryAt = -1e9;
}
this.refreshHud();
}
reset() {
for (const s of [...this.soldiers.values()]) this.dismiss(s);
this.slots.forEach((x) => { x.occupant = null; });
this.round = 1;
this.phase = 'siege';
this.roundDmg.clear();
this.totalDmg.clear();
this.likeEnergy = 0;
this.fatihId = null;
const hp = this.rules.wall?.hp ?? 1500;
this.wall.rebuild(hp);
if (this.victoryFlag) this.victoryFlag.userData.sink = true;
this.hud.hideVictory();
this.refreshHud();
}
}
Lisans bilgisi projenin LICENSE dosyasında.