feat: 新增多项功能并添加新工具
- 私人剪贴板新增限时直通URL生成功能 - doc_cloud_keeper新增标题复制按钮 - 新增贪蛇出动游戏工具 - 新增OSS中转直链工具 - 添加批量抽帧测试脚本
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
/* 贪蛇出动 - AI 蛇控制器:觅食/避障/边界回避/随机加速 */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
const U = GS.U;
|
||||
|
||||
class AI {
|
||||
constructor(snake) {
|
||||
this.s = snake;
|
||||
this.decideTimer = U.rand(0, 0.3);
|
||||
this.wanderAngle = snake.angle;
|
||||
this.boostTimer = 0;
|
||||
}
|
||||
|
||||
update(dt, world, snakes) {
|
||||
const s = this.s;
|
||||
if (s.dead) return;
|
||||
this.decideTimer -= dt;
|
||||
this.boostTimer -= dt;
|
||||
if (this.decideTimer > 0) {
|
||||
s.boosting = this.boostTimer > 0;
|
||||
return;
|
||||
}
|
||||
this.decideTimer = 0.15;
|
||||
|
||||
const h = s.head;
|
||||
const look = 90 + s.radius * 3;
|
||||
const aheadX = h.x + Math.cos(s.angle) * look;
|
||||
const aheadY = h.y + Math.sin(s.angle) * look;
|
||||
|
||||
// 1) 边界回避
|
||||
const margin = 220;
|
||||
let avoid = null;
|
||||
if (aheadX < margin || aheadY < margin || aheadX > world.size - margin || aheadY > world.size - margin) {
|
||||
avoid = Math.atan2(world.size / 2 - h.y, world.size / 2 - h.x);
|
||||
}
|
||||
|
||||
// 2) 蛇身回避:检查前方采样点是否撞上其他蛇
|
||||
if (avoid == null) {
|
||||
for (const o of snakes) {
|
||||
if (o === s || o.dead) continue;
|
||||
const segs = o.segments();
|
||||
const rr = (s.radius + o.radius + 26);
|
||||
for (let i = 0; i < segs.length; i += 2) {
|
||||
if (U.dist2(aheadX, aheadY, segs[i].x, segs[i].y) < rr * rr) {
|
||||
// 向左或向右转,选更开阔的一侧
|
||||
const left = s.angle - Math.PI / 2, right = s.angle + Math.PI / 2;
|
||||
avoid = this._clearer(left, right, h, snakes, s);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (avoid != null) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (avoid != null) {
|
||||
s.targetAngle = avoid;
|
||||
s.boosting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) 觅食:找最近金币
|
||||
let best = null, bestD = 520 * 520;
|
||||
const near = world.grid.query(h.x, h.y, 520);
|
||||
for (const c of near) {
|
||||
const d2 = U.dist2(h.x, h.y, c.x, c.y);
|
||||
if (d2 < bestD) { bestD = d2; best = c; }
|
||||
}
|
||||
if (best) {
|
||||
s.targetAngle = Math.atan2(best.y - h.y, best.x - h.x);
|
||||
} else {
|
||||
// 漫游:小幅随机偏转
|
||||
this.wanderAngle += U.rand(-0.6, 0.6);
|
||||
s.targetAngle = this.wanderAngle;
|
||||
}
|
||||
|
||||
// 4) 随机加速:追食或逃跑时小概率冲刺
|
||||
if (Math.random() < 0.06 && s.score > 30) this.boostTimer = U.rand(0.4, 1.0);
|
||||
s.boosting = this.boostTimer > 0;
|
||||
}
|
||||
|
||||
_clearer(a1, a2, h, snakes, s) {
|
||||
const score = a => {
|
||||
const px = h.x + Math.cos(a) * 160, py = h.y + Math.sin(a) * 160;
|
||||
let d = 1e9;
|
||||
for (const o of snakes) {
|
||||
if (o === s || o.dead) continue;
|
||||
const segs = o.segments();
|
||||
for (let i = 0; i < segs.length; i += 3) {
|
||||
const dd = U.dist2(px, py, segs[i].x, segs[i].y);
|
||||
if (dd < d) d = dd;
|
||||
}
|
||||
}
|
||||
return d;
|
||||
};
|
||||
return score(a1) >= score(a2) ? a1 : a2;
|
||||
}
|
||||
}
|
||||
|
||||
GS.AI = AI;
|
||||
})();
|
||||
@@ -0,0 +1,49 @@
|
||||
/* 贪蛇出动 - 全局常量配置(前端默认值,服务端 config/greedy_snake.json 可覆盖) */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
|
||||
GS.CFG = {
|
||||
worldSize: 4000, // 世界边长
|
||||
botCount: 9, // AI 蛇数量
|
||||
coinCount: 320, // 场内常驻金币数
|
||||
baseSpeed: 130, // 基础移速 px/s
|
||||
boostSpeed: 250, // 加速移速 px/s
|
||||
turnRate: 4.6, // 玩家转向速度 rad/s
|
||||
botTurnRate: 3.2, // AI 转向速度 rad/s
|
||||
startScore: 10, // 初始长度分
|
||||
treasureTarget: 2000, // 宝藏屋目标
|
||||
rerollCost: 20, // 换一换钻石
|
||||
initialGems: 100, // 初始钻石
|
||||
reviveCountdown: 5, // 复活倒计时
|
||||
playerName: '贪蛇小将',
|
||||
uiMode: 'debug' // debug / normal,服务端配置优先
|
||||
};
|
||||
|
||||
// 道具定义
|
||||
GS.ITEMS = {
|
||||
helmet: { key: 'helmet', name: '头盔护盾', desc: '开局获得护盾,可抵挡一次致命碰撞' },
|
||||
rocket: { key: 'rocket', name: '火箭冲刺', desc: '开局自动冲刺 4 秒,冲刺期间无敌' },
|
||||
magnet: { key: 'magnet', name: '吸铁石', desc: '开局 20 秒内吸附附近金币' },
|
||||
expcard: { key: 'expcard', name: '体验卡', desc: '开局直接 +200 长度' }
|
||||
};
|
||||
GS.ITEM_KEYS = ['helmet', 'rocket', 'magnet', 'expcard'];
|
||||
|
||||
// 蛇配色(玩家固定红色,AI 随机)
|
||||
GS.SNAKE_COLORS = [
|
||||
{ body: '#f2f2f7', dark: '#c9c9d8' }, // 白
|
||||
{ body: '#f0c070', dark: '#c8934a' }, // 面包黄
|
||||
{ body: '#8fd0ff', dark: '#5a9cd0' }, // 浅蓝
|
||||
{ body: '#a0e8a0', dark: '#6ab86a' }, // 绿
|
||||
{ body: '#e0a0e8', dark: '#b06ab8' }, // 粉紫
|
||||
{ body: '#ffb060', dark: '#d08030' }, // 橙
|
||||
{ body: '#b8b8c8', dark: '#8a8a9c' } // 灰
|
||||
];
|
||||
GS.PLAYER_COLOR = { body: '#e8394a', dark: '#b81f33' };
|
||||
|
||||
GS.BOT_NAMES = [
|
||||
'Wanderer', 'MILu', '夜行者', '黑白的熊猫', '木头宇', '星空',
|
||||
'态度', '林小八', 'Angel', '疾风少年', '小旋风', '贪吃鬼',
|
||||
'史蒂文', '米奇的k夏', '石家庄一起快乐', '不记得了'
|
||||
];
|
||||
})();
|
||||
@@ -0,0 +1,109 @@
|
||||
/* 贪蛇出动 - 输入控制:左摇杆 + 右加速按钮 + 桌面键盘 */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
|
||||
class Input {
|
||||
constructor() {
|
||||
this.angle = -Math.PI / 2; // 目标方向
|
||||
this.boost = false;
|
||||
this.enabled = false;
|
||||
this._joyId = null;
|
||||
this._joyBase = { x: 0, y: 0 };
|
||||
this._keys = new Set();
|
||||
this._bind();
|
||||
}
|
||||
|
||||
_bind() {
|
||||
const joy = document.getElementById('gs-joystick');
|
||||
const knob = document.getElementById('gs-joystick-knob');
|
||||
const boostBtn = document.getElementById('gs-boost');
|
||||
this.joyEl = joy; this.knobEl = knob; this.boostEl = boostBtn;
|
||||
|
||||
// 摇杆:触摸左下区域
|
||||
joy.addEventListener('touchstart', e => {
|
||||
e.preventDefault();
|
||||
const t = e.changedTouches[0];
|
||||
this._joyId = t.identifier;
|
||||
const r = joy.getBoundingClientRect();
|
||||
this._joyBase = { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||
this._moveKnob(t.clientX, t.clientY);
|
||||
}, { passive: false });
|
||||
joy.addEventListener('touchmove', e => {
|
||||
e.preventDefault();
|
||||
for (const t of e.changedTouches) if (t.identifier === this._joyId) this._moveKnob(t.clientX, t.clientY);
|
||||
}, { passive: false });
|
||||
const endJoy = e => {
|
||||
for (const t of e.changedTouches) if (t.identifier === this._joyId) {
|
||||
this._joyId = null;
|
||||
this.knobEl.style.transform = 'translate(-50%, -50%)';
|
||||
}
|
||||
};
|
||||
joy.addEventListener('touchend', endJoy);
|
||||
joy.addEventListener('touchcancel', endJoy);
|
||||
|
||||
// 桌面鼠标拖拽摇杆
|
||||
let mouseDown = false;
|
||||
joy.addEventListener('mousedown', e => {
|
||||
mouseDown = true;
|
||||
const r = joy.getBoundingClientRect();
|
||||
this._joyBase = { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||
this._moveKnob(e.clientX, e.clientY);
|
||||
});
|
||||
window.addEventListener('mousemove', e => { if (mouseDown) this._moveKnob(e.clientX, e.clientY); });
|
||||
window.addEventListener('mouseup', () => { mouseDown = false; this.knobEl.style.transform = 'translate(-50%, -50%)'; });
|
||||
|
||||
// 加速按钮:按住加速
|
||||
const boostOn = e => { e.preventDefault(); this.boost = true; boostBtn.classList.add('active'); };
|
||||
const boostOff = () => { this.boost = false; boostBtn.classList.remove('active'); };
|
||||
boostBtn.addEventListener('touchstart', boostOn, { passive: false });
|
||||
boostBtn.addEventListener('touchend', boostOff);
|
||||
boostBtn.addEventListener('touchcancel', boostOff);
|
||||
boostBtn.addEventListener('mousedown', boostOn);
|
||||
boostBtn.addEventListener('mouseup', boostOff);
|
||||
boostBtn.addEventListener('mouseleave', boostOff);
|
||||
|
||||
// 键盘(桌面调试):方向键/WSAD 转向,空格加速
|
||||
window.addEventListener('keydown', e => {
|
||||
this._keys.add(e.code);
|
||||
if (e.code === 'Space') { this.boost = true; boostBtn.classList.add('active'); }
|
||||
this._applyKeys();
|
||||
});
|
||||
window.addEventListener('keyup', e => {
|
||||
this._keys.delete(e.code);
|
||||
if (e.code === 'Space') { this.boost = false; boostBtn.classList.remove('active'); }
|
||||
this._applyKeys();
|
||||
});
|
||||
|
||||
// 阻止页面滚动/双击缩放
|
||||
document.addEventListener('touchmove', e => { e.preventDefault(); }, { passive: false });
|
||||
document.addEventListener('gesturestart', e => e.preventDefault());
|
||||
}
|
||||
|
||||
_applyKeys() {
|
||||
let dx = 0, dy = 0;
|
||||
if (this._keys.has('ArrowLeft') || this._keys.has('KeyA')) dx -= 1;
|
||||
if (this._keys.has('ArrowRight') || this._keys.has('KeyD')) dx += 1;
|
||||
if (this._keys.has('ArrowUp') || this._keys.has('KeyW')) dy -= 1;
|
||||
if (this._keys.has('ArrowDown') || this._keys.has('KeyS')) dy += 1;
|
||||
if (dx || dy) this.angle = Math.atan2(dy, dx);
|
||||
}
|
||||
|
||||
_moveKnob(cx, cy) {
|
||||
const maxR = 40;
|
||||
let dx = cx - this._joyBase.x, dy = cy - this._joyBase.y;
|
||||
const d = Math.sqrt(dx * dx + dy * dy);
|
||||
if (d > maxR) { dx = dx / d * maxR; dy = dy / d * maxR; }
|
||||
this.knobEl.style.transform = `translate(calc(-50% + ${dx}px), calc(-50% + ${dy}px))`;
|
||||
if (d > 8) this.angle = Math.atan2(dy, dx);
|
||||
}
|
||||
|
||||
setVisible(v) {
|
||||
this.enabled = v;
|
||||
this.joyEl.classList.toggle('gs-hidden', !v);
|
||||
this.boostEl.classList.toggle('gs-hidden', !v);
|
||||
}
|
||||
}
|
||||
|
||||
GS.Input = Input;
|
||||
})();
|
||||
@@ -0,0 +1,337 @@
|
||||
/* 贪蛇出动 - 主控:状态机 / 游戏循环 / 击杀与死亡 / 复活 / 服务端数据同步 */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
const U = GS.U;
|
||||
|
||||
const API = '/api/greedy_snake';
|
||||
|
||||
class Game {
|
||||
constructor() {
|
||||
this.ui = new GS.UI();
|
||||
this.render = new GS.Render(document.getElementById('gs-canvas'));
|
||||
this.input = new GS.Input();
|
||||
this.state = 'idle'; // idle / roulette / playing / dead / result
|
||||
this.stats = { gems: GS.CFG.initialGems, totalCoins: 0, best: 0, todayBest: null };
|
||||
this.player = null;
|
||||
this.bots = [];
|
||||
this.ais = new Map();
|
||||
this.world = null;
|
||||
this.selectedItem = -1;
|
||||
this.reelKeys = [];
|
||||
this.freeReviveUsed = false;
|
||||
this.treasureDone = false;
|
||||
this._last = 0;
|
||||
this._boardTimer = 0;
|
||||
this._respawnQueue = [];
|
||||
this._killerName = '';
|
||||
this._reviveTimer = null;
|
||||
this._bindUI();
|
||||
}
|
||||
|
||||
async init() {
|
||||
// 拉取服务端配置与存档
|
||||
const cfg = await this.ui.trackFetch('加载游戏配置', API + '/config');
|
||||
if (cfg && cfg.ok && cfg.data) {
|
||||
Object.assign(GS.CFG, {
|
||||
worldSize: cfg.data.world_size || GS.CFG.worldSize,
|
||||
botCount: cfg.data.bot_count || GS.CFG.botCount,
|
||||
coinCount: cfg.data.coin_count || GS.CFG.coinCount,
|
||||
baseSpeed: cfg.data.base_speed || GS.CFG.baseSpeed,
|
||||
boostSpeed: cfg.data.boost_speed || GS.CFG.boostSpeed,
|
||||
treasureTarget: cfg.data.treasure_target || GS.CFG.treasureTarget,
|
||||
rerollCost: cfg.data.reroll_cost || GS.CFG.rerollCost,
|
||||
initialGems: cfg.data.initial_gems || GS.CFG.initialGems,
|
||||
reviveCountdown: cfg.data.revive_countdown || GS.CFG.reviveCountdown,
|
||||
playerName: cfg.data.player_name || GS.CFG.playerName
|
||||
});
|
||||
this.ui.setUiMode(cfg.data.ui_mode || 'debug');
|
||||
}
|
||||
const st = await this.ui.trackFetch('加载存档', API + '/stats');
|
||||
if (st && st.ok && st.data) this.stats = Object.assign(this.stats, st.data);
|
||||
document.getElementById('gs-progress-target').textContent = GS.CFG.treasureTarget;
|
||||
this._openRoulette();
|
||||
requestAnimationFrame(t => this._loop(t));
|
||||
}
|
||||
|
||||
/* ---------------- 转盘阶段 ---------------- */
|
||||
_openRoulette() {
|
||||
this.state = 'roulette';
|
||||
this.input.setVisible(false);
|
||||
this.ui.showHud(false);
|
||||
this.ui.hideResult();
|
||||
this.ui.hideRevive();
|
||||
this.selectedItem = -1;
|
||||
this._rollReels();
|
||||
this.ui.showRoulette(this.stats.gems);
|
||||
}
|
||||
|
||||
_rollReels() {
|
||||
const pool = GS.ITEM_KEYS.slice();
|
||||
this.reelKeys = [U.pick(pool), U.pick(pool), U.pick(pool)];
|
||||
this.ui.spinReels(this.reelKeys);
|
||||
setTimeout(() => this.ui.setReels(this.reelKeys, this.selectedItem), 900);
|
||||
}
|
||||
|
||||
_bindUI() {
|
||||
// 转盘:选择道具 / 换一换 / 直接开始
|
||||
document.querySelectorAll('.gs-reel').forEach(reel => {
|
||||
reel.addEventListener('click', () => {
|
||||
const idx = Number(reel.dataset.idx);
|
||||
this.selectedItem = this.selectedItem === idx ? -1 : idx;
|
||||
this.ui.setReels(this.reelKeys, this.selectedItem);
|
||||
});
|
||||
});
|
||||
document.getElementById('gs-reroll').addEventListener('click', async () => {
|
||||
if (this.stats.gems < GS.CFG.rerollCost) { this.ui.toast('钻石不足', 'error'); return; }
|
||||
const btn = document.getElementById('gs-reroll');
|
||||
btn.disabled = true;
|
||||
this.stats.gems -= GS.CFG.rerollCost;
|
||||
this.ui.updateGems(this.stats.gems);
|
||||
this._saveStats({ gems: this.stats.gems });
|
||||
this.selectedItem = -1;
|
||||
this._rollReels();
|
||||
});
|
||||
document.getElementById('gs-roulette-skip').addEventListener('click', () => this._startGame(null));
|
||||
document.getElementById('gs-reels').addEventListener('dblclick', () => {
|
||||
if (this.selectedItem >= 0) this._startGame(this.reelKeys[this.selectedItem]);
|
||||
});
|
||||
|
||||
// 复活
|
||||
document.getElementById('gs-revive-btn').addEventListener('click', () => this._revive());
|
||||
document.getElementById('gs-revive-close').addEventListener('click', () => this._toResult());
|
||||
|
||||
// 结算
|
||||
document.getElementById('gs-result-again').addEventListener('click', () => this._openRoulette());
|
||||
document.getElementById('gs-result-home').addEventListener('click', () => this._openRoulette());
|
||||
|
||||
// 弹窗
|
||||
document.getElementById('gs-dialog-close').addEventListener('click', () => this.ui.hideDialog());
|
||||
document.getElementById('gs-dialog-copy').addEventListener('click', () => {
|
||||
const txt = document.getElementById('gs-dialog-body').textContent;
|
||||
if (navigator.clipboard) navigator.clipboard.writeText(txt).then(() => this.ui.toast('已复制', 'success'));
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------- 开局 ---------------- */
|
||||
_startGame(itemKey) {
|
||||
this.ui.hideRoulette();
|
||||
this.world = new GS.World();
|
||||
this.bots = [];
|
||||
this.ais.clear();
|
||||
this._respawnQueue = [];
|
||||
this.freeReviveUsed = false;
|
||||
this.treasureDone = false;
|
||||
|
||||
// 玩家
|
||||
const px = U.rand(800, GS.CFG.worldSize - 800);
|
||||
const py = U.rand(800, GS.CFG.worldSize - 800);
|
||||
this.player = new GS.Snake({ id: 'p', name: GS.CFG.playerName, isPlayer: true, color: GS.PLAYER_COLOR, x: px, y: py });
|
||||
this._applyItem(this.player, itemKey);
|
||||
|
||||
// AI
|
||||
for (let i = 0; i < GS.CFG.botCount; i++) this._spawnBot();
|
||||
|
||||
this.state = 'playing';
|
||||
this.input.setVisible(true);
|
||||
this.ui.showHud(true);
|
||||
if (itemKey) this.ui.toast('已装备:' + GS.ITEMS[itemKey].name, 'success');
|
||||
}
|
||||
|
||||
_applyItem(s, key) {
|
||||
if (!key) return;
|
||||
const now = performance.now();
|
||||
if (key === 'helmet') s.shield = true;
|
||||
if (key === 'rocket') s.invincibleUntil = now + 4000;
|
||||
if (key === 'magnet') s.magnetUntil = now + 20000;
|
||||
if (key === 'expcard') s.grow(200);
|
||||
}
|
||||
|
||||
_spawnBot() {
|
||||
const b = new GS.Snake({
|
||||
id: 'b' + Math.random().toString(36).slice(2, 7),
|
||||
name: U.pick(GS.BOT_NAMES),
|
||||
color: U.pick(GS.SNAKE_COLORS),
|
||||
skin: Math.random() < 0.5 ? 1 : 0,
|
||||
x: U.rand(300, GS.CFG.worldSize - 300),
|
||||
y: U.rand(300, GS.CFG.worldSize - 300),
|
||||
score: U.randInt(10, 400)
|
||||
});
|
||||
this.bots.push(b);
|
||||
this.ais.set(b.id, new GS.AI(b));
|
||||
}
|
||||
|
||||
/* ---------------- 主循环 ---------------- */
|
||||
_loop(t) {
|
||||
const dt = Math.min(0.05, (t - this._last) / 1000 || 0.016);
|
||||
this._last = t;
|
||||
if (this.state === 'playing' || this.state === 'dead') this._step(dt, t);
|
||||
if (this.world) this.render.draw(this.world, this._allSnakes(), this.player, t);
|
||||
requestAnimationFrame(tt => this._loop(tt));
|
||||
}
|
||||
|
||||
_allSnakes() { return this.player ? [this.player, ...this.bots] : this.bots; }
|
||||
|
||||
_step(dt, now) {
|
||||
const p = this.player;
|
||||
// 玩家输入
|
||||
if (this.state === 'playing' && !p.dead) {
|
||||
p.targetAngle = this.input.angle;
|
||||
const wantBoost = this.input.boost;
|
||||
p.boosting = wantBoost && p.score > 15;
|
||||
if (p.boosting) {
|
||||
p.score = Math.max(10, p.score - 6 * dt); // 加速消耗长度
|
||||
if (Math.random() < dt * 2) this.world.addCoin(
|
||||
p.head.x - Math.cos(p.angle) * p.radius * 2,
|
||||
p.head.y - Math.sin(p.angle) * p.radius * 2, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// AI 决策
|
||||
for (const b of this.bots) this.ais.get(b.id).update(dt, this.world, this._allSnakes());
|
||||
|
||||
// 移动
|
||||
for (const s of this._allSnakes()) s.update(dt, now);
|
||||
|
||||
// 金币/磁铁
|
||||
this.world.update(dt, this._allSnakes(), now);
|
||||
|
||||
// 相机
|
||||
if (!p.dead) this.world.updateCam(p.head, this.render.w, this.render.h, dt);
|
||||
|
||||
// 碰撞与死亡
|
||||
const snakes = this._allSnakes();
|
||||
for (const s of snakes) {
|
||||
if (s.dead) continue;
|
||||
const hit = this.world.collide(s, snakes);
|
||||
if (!hit) continue;
|
||||
if (s.shield) { s.shield = false; s.invincibleUntil = now + 1500; continue; }
|
||||
if (s.invincible(now)) continue;
|
||||
this._onDeath(s, hit, now);
|
||||
}
|
||||
|
||||
// 复活队列
|
||||
for (let i = this._respawnQueue.length - 1; i >= 0; i--) {
|
||||
const r = this._respawnQueue[i];
|
||||
if (now >= r.at) { this._respawnQueue.splice(i, 1); this._spawnBot(); }
|
||||
}
|
||||
|
||||
// 宝藏屋进度
|
||||
if (!this.treasureDone && p && !p.dead && p.score >= GS.CFG.treasureTarget) {
|
||||
this.treasureDone = true;
|
||||
this.world.treasureBurst(p.head.x, p.head.y);
|
||||
p.lucky += 5;
|
||||
this.ui.toast('长度达标!宝藏屋开启,幸运星 +5', 'success');
|
||||
}
|
||||
|
||||
// HUD 刷新
|
||||
this._boardTimer -= dt;
|
||||
if (this._boardTimer <= 0) {
|
||||
this._boardTimer = 0.5;
|
||||
this._refreshHud();
|
||||
}
|
||||
}
|
||||
|
||||
_onDeath(s, hit, now) {
|
||||
const segs = s.die();
|
||||
this.world.dropFromSegments(segs);
|
||||
if (hit.type === 'body' && hit.snake) hit.snake.kills += 1;
|
||||
if (s.isPlayer) {
|
||||
this._killerName = hit.type === 'wall' ? '' : (hit.snake ? hit.snake.name : '对手');
|
||||
this.state = 'dead';
|
||||
this.input.setVisible(false);
|
||||
this.input.boost = false;
|
||||
this._startReviveCountdown();
|
||||
} else {
|
||||
// 玩家击杀判定:撞到玩家身体
|
||||
if (hit.type === 'body' && hit.snake === this.player) this.ui.toast('击杀 ' + s.name + '!', 'success');
|
||||
this.bots = this.bots.filter(b => b !== s);
|
||||
this.ais.delete(s.id);
|
||||
this._respawnQueue.push({ at: now + 3000 });
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 复活 / 结算 ---------------- */
|
||||
_startReviveCountdown() {
|
||||
const total = GS.CFG.reviveCountdown;
|
||||
let left = total;
|
||||
this.ui.showRevive(this._killerName, this.freeReviveUsed);
|
||||
this.ui.updateReviveCount(left, 1);
|
||||
clearInterval(this._reviveTimer);
|
||||
this._reviveTimer = setInterval(() => {
|
||||
left -= 0.1;
|
||||
if (left <= 0) { clearInterval(this._reviveTimer); this._toResult(); return; }
|
||||
this.ui.updateReviveCount(Math.ceil(left), left / total);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
_revive() {
|
||||
if (this.freeReviveUsed) return;
|
||||
this.freeReviveUsed = true;
|
||||
clearInterval(this._reviveTimer);
|
||||
const p = this.player;
|
||||
p.dead = false;
|
||||
// 安全点重生:世界中心附近
|
||||
const x = U.clamp(p.head.x + U.rand(-600, 600), 400, GS.CFG.worldSize - 400);
|
||||
const y = U.clamp(p.head.y + U.rand(-600, 600), 400, GS.CFG.worldSize - 400);
|
||||
p.path = [{ x, y }];
|
||||
p.pathLen = 0;
|
||||
p.shield = true;
|
||||
p.invincibleUntil = performance.now() + 3000;
|
||||
this.ui.hideRevive();
|
||||
this.input.setVisible(true);
|
||||
this.state = 'playing';
|
||||
this.ui.toast('复活成功,护盾保护中', 'success');
|
||||
}
|
||||
|
||||
_toResult() {
|
||||
clearInterval(this._reviveTimer);
|
||||
this.ui.hideRevive();
|
||||
this.state = 'result';
|
||||
const p = this.player;
|
||||
const score = Math.floor(p.score);
|
||||
if (score > this.stats.best) this.stats.best = score;
|
||||
this.stats.totalCoins += p.coins;
|
||||
this.stats.gems += p.kills * 5 + p.lucky;
|
||||
this.ui.showResult({ score, coins: p.coins, kills: p.kills, lucky: p.lucky, best: this.stats.best });
|
||||
this._saveStats({ score, coins: p.coins, kills: p.kills, lucky: p.lucky, gems: this.stats.gems, totalCoins: this.stats.totalCoins });
|
||||
}
|
||||
|
||||
_refreshHud() {
|
||||
const p = this.player;
|
||||
if (!p) return;
|
||||
this.ui.updateStats(this.stats.totalCoins + p.coins, p.lucky, p.kills);
|
||||
this.ui.updateProgress(p.score, GS.CFG.treasureTarget, p.score >= 1000 && !this.treasureDone);
|
||||
// 排行榜
|
||||
const rows = this._allSnakes().filter(s => !s.dead)
|
||||
.map(s => ({ name: s.name, score: Math.floor(s.score), me: s.isPlayer }))
|
||||
.sort((a, b) => b.score - a.score);
|
||||
const top = rows.slice(0, 9);
|
||||
const meRow = rows.find(r => r.me);
|
||||
if (meRow && !top.includes(meRow)) top.push(meRow);
|
||||
this.ui.updateBoard(top, meRow, this.stats.todayBest && this.stats.todayBest.score >= 0 ? this.stats.todayBest : { name: '-', score: this.stats.best });
|
||||
}
|
||||
|
||||
/* ---------------- 服务端同步 ---------------- */
|
||||
async _saveStats(extra) {
|
||||
const body = Object.assign({}, extra);
|
||||
const res = await this.ui.trackFetch('保存战绩', API + '/stats', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (res && res.ok && res.data) {
|
||||
this.stats.best = res.data.best != null ? res.data.best : this.stats.best;
|
||||
this.stats.gems = res.data.gems != null ? res.data.gems : this.stats.gems;
|
||||
this.stats.totalCoins = res.data.totalCoins != null ? res.data.totalCoins : this.stats.totalCoins;
|
||||
this.stats.todayBest = res.data.todayBest || this.stats.todayBest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
const g = new Game();
|
||||
GS.game = g;
|
||||
g.init();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,198 @@
|
||||
/* 贪蛇出动 - 渲染:Canvas 程序化绘制(背景网格/边界/金币/蛇/特效) */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
const U = GS.U;
|
||||
|
||||
class Render {
|
||||
constructor(canvas) {
|
||||
this.cv = canvas;
|
||||
this.ctx = canvas.getContext('2d');
|
||||
this.w = 0; this.h = 0; this.dpr = 1;
|
||||
this.resize();
|
||||
window.addEventListener('resize', () => this.resize());
|
||||
}
|
||||
|
||||
resize() {
|
||||
this.dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
this.w = window.innerWidth;
|
||||
this.h = window.innerHeight;
|
||||
this.cv.width = Math.floor(this.w * this.dpr);
|
||||
this.cv.height = Math.floor(this.h * this.dpr);
|
||||
}
|
||||
|
||||
draw(world, snakes, player, now) {
|
||||
const ctx = this.ctx;
|
||||
const cam = world.cam;
|
||||
ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
|
||||
|
||||
// 背景
|
||||
ctx.fillStyle = '#222b57';
|
||||
ctx.fillRect(0, 0, this.w, this.h);
|
||||
|
||||
const sc = cam.scale;
|
||||
const ox = this.w / 2 - cam.x * sc;
|
||||
const oy = this.h / 2 - cam.y * sc;
|
||||
const toX = x => x * sc + ox;
|
||||
const toY = y => y * sc + oy;
|
||||
|
||||
// 网格
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
|
||||
ctx.lineWidth = 1;
|
||||
const gridStep = 100 * sc;
|
||||
const gx0 = ((ox % gridStep) + gridStep) % gridStep;
|
||||
const gy0 = ((oy % gridStep) + gridStep) % gridStep;
|
||||
ctx.beginPath();
|
||||
for (let x = gx0; x < this.w; x += gridStep) { ctx.moveTo(x, 0); ctx.lineTo(x, this.h); }
|
||||
for (let y = gy0; y < this.h; y += gridStep) { ctx.moveTo(0, y); ctx.lineTo(this.w, y); }
|
||||
ctx.stroke();
|
||||
|
||||
// 边界(红粉色发光线)+ 界外压暗
|
||||
const bx0 = toX(0), by0 = toY(0), bx1 = toX(world.size), by1 = toY(world.size);
|
||||
ctx.fillStyle = 'rgba(8,10,26,0.55)';
|
||||
if (bx0 > 0) ctx.fillRect(0, 0, bx0, this.h);
|
||||
if (bx1 < this.w) ctx.fillRect(bx1, 0, this.w - bx1, this.h);
|
||||
if (by0 > 0) ctx.fillRect(0, 0, this.w, by0);
|
||||
if (by1 < this.h) ctx.fillRect(0, by1, this.w, this.h - by1);
|
||||
ctx.strokeStyle = '#ff4d6d';
|
||||
ctx.lineWidth = 3;
|
||||
ctx.shadowColor = '#ff4d6d';
|
||||
ctx.shadowBlur = 12;
|
||||
ctx.strokeRect(bx0, by0, bx1 - bx0, by1 - by0);
|
||||
ctx.shadowBlur = 0;
|
||||
|
||||
// 金币(视口内)
|
||||
for (const c of world.coins) {
|
||||
const x = toX(c.x), y = toY(c.y);
|
||||
if (x < -40 || y < -40 || x > this.w + 40 || y > this.h + 40) continue;
|
||||
const pulse = 1 + Math.sin(now / 300 + c.phase) * 0.12;
|
||||
const r = c.r * sc * pulse;
|
||||
if (c.kind === 1) this._starCoin(ctx, x, y, r);
|
||||
else this._coin(ctx, x, y, r, c.kind === 2);
|
||||
}
|
||||
|
||||
// 蛇:先画 AI 再画玩家
|
||||
for (const s of snakes) if (!s.isPlayer && !s.dead) this._snake(ctx, s, toX, toY, sc, now);
|
||||
if (player && !player.dead) this._snake(ctx, player, toX, toY, sc, now);
|
||||
}
|
||||
|
||||
_coin(ctx, x, y, r, big) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, r, 0, Math.PI * 2);
|
||||
ctx.fillStyle = big ? '#ffca28' : '#f5b921';
|
||||
ctx.fill();
|
||||
ctx.lineWidth = Math.max(1, r * 0.28);
|
||||
ctx.strokeStyle = big ? '#c98f00' : '#b8860b';
|
||||
ctx.stroke();
|
||||
ctx.beginPath();
|
||||
ctx.arc(x - r * 0.25, y - r * 0.25, r * 0.4, 0, Math.PI * 2);
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.35)';
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
_starCoin(ctx, x, y, r) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, r, 0, Math.PI * 2);
|
||||
ctx.fillStyle = '#ffc233';
|
||||
ctx.fill();
|
||||
ctx.lineWidth = Math.max(1, r * 0.22);
|
||||
ctx.strokeStyle = '#c98f00';
|
||||
ctx.stroke();
|
||||
// 五角星
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const rr = i % 2 === 0 ? r * 0.62 : r * 0.28;
|
||||
const a = -Math.PI / 2 + i * Math.PI / 5;
|
||||
const px = Math.cos(a) * rr, py = Math.sin(a) * rr;
|
||||
if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);
|
||||
}
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = '#fff3c4';
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
_snake(ctx, s, toX, toY, sc, now) {
|
||||
const segs = s.segments();
|
||||
const r = s.radius * sc;
|
||||
const wob = Math.sin(s.wobble) * 0.06;
|
||||
|
||||
// 磁铁光环
|
||||
if (now < s.magnetUntil) {
|
||||
const h = segs[0];
|
||||
ctx.beginPath();
|
||||
ctx.arc(toX(h.x), toY(h.y), 260 * sc, 0, Math.PI * 2);
|
||||
ctx.strokeStyle = 'rgba(90,200,255,0.25)';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.stroke();
|
||||
}
|
||||
// 护盾圈
|
||||
if (s.shield || s.invincible(now)) {
|
||||
const h = segs[0];
|
||||
const sr = r * 3.2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(toX(h.x), toY(h.y), sr, 0, Math.PI * 2);
|
||||
ctx.fillStyle = 'rgba(80,160,255,0.10)';
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(120,200,255,0.8)';
|
||||
ctx.lineWidth = 2.5;
|
||||
ctx.stroke();
|
||||
}
|
||||
// 加速尾焰
|
||||
if (s.boosting && segs.length > 2) {
|
||||
const t = segs[segs.length - 1];
|
||||
ctx.beginPath();
|
||||
ctx.arc(toX(t.x), toY(t.y), r * 0.8, 0, Math.PI * 2);
|
||||
ctx.fillStyle = 'rgba(255,220,120,0.35)';
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
// 身体:从尾到头
|
||||
for (let i = segs.length - 1; i >= 1; i--) {
|
||||
const g = segs[i];
|
||||
const rr = r * (1 - (i / segs.length) * 0.25) * (1 + wob * Math.sin(i * 0.6));
|
||||
ctx.beginPath();
|
||||
ctx.arc(toX(g.x), toY(g.y), rr, 0, Math.PI * 2);
|
||||
ctx.fillStyle = (s.skin === 1 && i % 4 < 2) ? s.color.dark : s.color.body;
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
// 头
|
||||
const h = segs[0];
|
||||
const hx = toX(h.x), hy = toY(h.y);
|
||||
ctx.beginPath();
|
||||
ctx.arc(hx, hy, r * 1.08, 0, Math.PI * 2);
|
||||
ctx.fillStyle = s.color.body;
|
||||
ctx.fill();
|
||||
|
||||
// 眼睛:朝向前方
|
||||
const a = s.angle;
|
||||
const ex = Math.cos(a), ey = Math.sin(a);
|
||||
const px = -ey, py = ex;
|
||||
for (const side of [1, -1]) {
|
||||
const cx = hx + (ex * 0.45 + px * 0.5 * side) * r;
|
||||
const cy = hy + (ey * 0.45 + py * 0.5 * side) * r;
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r * 0.34, 0, Math.PI * 2);
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx + ex * r * 0.12, cy + ey * r * 0.12, r * 0.15, 0, Math.PI * 2);
|
||||
ctx.fillStyle = '#111';
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
// 名字 + 分数
|
||||
ctx.font = `${Math.max(11, 13 * sc)}px "PingFang SC", sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.92)';
|
||||
ctx.fillText(String(Math.floor(s.score)), hx, hy - r * 2.4);
|
||||
ctx.fillStyle = s.isPlayer ? 'rgba(255,255,255,0.75)' : 'rgba(200,210,255,0.7)';
|
||||
ctx.fillText(s.name, hx, hy - r * 2.4 + 14 * sc);
|
||||
}
|
||||
}
|
||||
|
||||
GS.Render = Render;
|
||||
})();
|
||||
@@ -0,0 +1,112 @@
|
||||
/* 贪蛇出动 - 蛇实体:移动/转向/生长/路径采样 */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
const U = GS.U;
|
||||
|
||||
class Snake {
|
||||
constructor(opts) {
|
||||
this.id = opts.id;
|
||||
this.name = opts.name;
|
||||
this.isPlayer = !!opts.isPlayer;
|
||||
this.color = opts.color;
|
||||
this.skin = opts.skin || 0; // 0 纯色 1 条纹
|
||||
this.angle = opts.angle != null ? opts.angle : U.rand(0, Math.PI * 2);
|
||||
this.targetAngle = this.angle;
|
||||
this.turnRate = this.isPlayer ? GS.CFG.turnRate : GS.CFG.botTurnRate;
|
||||
this.score = opts.score || GS.CFG.startScore;
|
||||
this.dead = false;
|
||||
this.boosting = false;
|
||||
this.shield = false; // 护盾:抵挡一次致命碰撞
|
||||
this.invincibleUntil = 0; // 无敌时间戳(火箭/复活保护)
|
||||
this.magnetUntil = 0; // 磁铁截止
|
||||
this.kills = 0;
|
||||
this.coins = 0; // 本局吃到的金币数
|
||||
this.lucky = 0; // 本局幸运星
|
||||
// 路径:密集头轨迹点
|
||||
this.path = [{ x: opts.x, y: opts.y }];
|
||||
this.pathLen = 0;
|
||||
this._segs = [];
|
||||
this._segsDirty = true;
|
||||
this.wobble = U.rand(0, Math.PI * 2); // 身体摆动相位
|
||||
}
|
||||
|
||||
get head() { return this.path[this.path.length - 1]; }
|
||||
|
||||
// 半径随分数增长
|
||||
get radius() { return U.clamp(7 + Math.sqrt(Math.max(0, this.score)) * 0.32, 7, 30); }
|
||||
|
||||
// 身体节数
|
||||
get segCount() { return Math.floor(10 + this.score / 6); }
|
||||
|
||||
get spacing() { return Math.max(5, this.radius * 0.5); }
|
||||
|
||||
get speed() { return this.boosting ? GS.CFG.boostSpeed : GS.CFG.baseSpeed; }
|
||||
|
||||
invincible(now) { return now < this.invincibleUntil; }
|
||||
|
||||
update(dt, now) {
|
||||
if (this.dead) return;
|
||||
// 转向限速
|
||||
const da = U.normAngle(this.targetAngle - this.angle);
|
||||
const maxTurn = this.turnRate * dt;
|
||||
this.angle += U.clamp(da, -maxTurn, maxTurn);
|
||||
|
||||
const sp = this.speed;
|
||||
const h = this.head;
|
||||
const nx = h.x + Math.cos(this.angle) * sp * dt;
|
||||
const ny = h.y + Math.sin(this.angle) * sp * dt;
|
||||
this.path.push({ x: nx, y: ny });
|
||||
this.pathLen += sp * dt;
|
||||
|
||||
// 裁剪路径:保留足够长度
|
||||
const need = this.segCount * this.spacing + this.radius * 4;
|
||||
while (this.path.length > 2 && this.pathLen > need) {
|
||||
const d = U.dist(this.path[0].x, this.path[0].y, this.path[1].x, this.path[1].y);
|
||||
if (this.pathLen - d < need) break;
|
||||
this.pathLen -= d;
|
||||
this.path.shift();
|
||||
}
|
||||
this._segsDirty = true;
|
||||
this.wobble += dt * (this.boosting ? 14 : 9);
|
||||
}
|
||||
|
||||
// 从头部沿路径每隔 spacing 采样一节(不修改原路径)
|
||||
segments() {
|
||||
if (!this._segsDirty && this._segs.length) return this._segs;
|
||||
const segs = [{ x: this.head.x, y: this.head.y }];
|
||||
const n = this.segCount;
|
||||
const spacing = this.spacing;
|
||||
let acc = 0; // 自上一个采样点起已走过但不足 spacing 的距离
|
||||
for (let i = this.path.length - 1; i > 0 && segs.length < n; i--) {
|
||||
let ax = this.path[i].x, ay = this.path[i].y;
|
||||
const b = this.path[i - 1];
|
||||
let d = U.dist(ax, ay, b.x, b.y);
|
||||
if (d < 1e-9) continue;
|
||||
while (acc + d >= spacing && segs.length < n) {
|
||||
const t = (spacing - acc) / d;
|
||||
const px = ax + (b.x - ax) * t;
|
||||
const py = ay + (b.y - ay) * t;
|
||||
segs.push({ x: px, y: py });
|
||||
d -= (spacing - acc);
|
||||
ax = px; ay = py;
|
||||
acc = 0;
|
||||
}
|
||||
acc += d;
|
||||
}
|
||||
this._segs = segs;
|
||||
this._segsDirty = false;
|
||||
return segs;
|
||||
}
|
||||
|
||||
grow(v) { this.score += v; }
|
||||
|
||||
// 死亡:返回尸体坐标(用于掉币)
|
||||
die() {
|
||||
this.dead = true;
|
||||
return this.segments().slice();
|
||||
}
|
||||
}
|
||||
|
||||
GS.Snake = Snake;
|
||||
})();
|
||||
@@ -0,0 +1,213 @@
|
||||
/* 贪蛇出动 - UI:HUD 刷新 / 道具转盘 / 复活 / 结算 / Toast 与交互详情弹窗(双模式) */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
const U = GS.U;
|
||||
|
||||
/* ---------- 道具图标:程序化 SVG ---------- */
|
||||
function itemSvg(key) {
|
||||
switch (key) {
|
||||
case 'helmet':
|
||||
return '<svg viewBox="0 0 64 64"><path d="M10 38a22 22 0 0 1 44 0v6H36l-4-8-4 8H10z" fill="#e04a3a"/><path d="M14 38a18 18 0 0 1 36 0" fill="none" stroke="#fff" stroke-width="3" opacity=".55"/><rect x="8" y="42" width="48" height="6" rx="3" fill="#b83224"/></svg>';
|
||||
case 'rocket':
|
||||
return '<svg viewBox="0 0 64 64"><path d="M32 4c8 8 10 20 10 28l-10 10-10-10c0-8 2-20 10-28z" fill="#e8ecf5"/><circle cx="32" cy="24" r="5" fill="#5a8dd0"/><path d="M22 32l-8 12 10-2zM42 32l8 12-10-2z" fill="#e04a3a"/><path d="M28 44l4 12 4-12z" fill="#ffb62e"/></svg>';
|
||||
case 'magnet':
|
||||
return '<svg viewBox="0 0 64 64"><path d="M18 12v20a14 14 0 0 0 28 0V12H36v20a4 4 0 0 1-8 0V12z" fill="#e04a3a"/><rect x="18" y="12" width="10" height="10" fill="#e8ecf5"/><rect x="36" y="12" width="10" height="10" fill="#e8ecf5"/></svg>';
|
||||
case 'expcard':
|
||||
return '<svg viewBox="0 0 64 64"><rect x="8" y="16" width="48" height="32" rx="5" fill="#ffd23e"/><rect x="8" y="16" width="48" height="32" rx="5" fill="none" stroke="#c98f00" stroke-width="2"/><circle cx="24" cy="32" r="8" fill="#fff3c4"/><path d="M38 26h12M38 32h12M38 38h8" stroke="#c98f00" stroke-width="3" stroke-linecap="round"/></svg>';
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
|
||||
class UI {
|
||||
constructor() {
|
||||
this.el = id => document.getElementById(id);
|
||||
this.statsEl = this.el('gs-hud-stats');
|
||||
this.coinsEl = this.el('gs-stat-coins');
|
||||
this.luckyEl = this.el('gs-stat-lucky');
|
||||
this.killsEl = this.el('gs-stat-kills');
|
||||
this.progEl = this.el('gs-hud-progress');
|
||||
this.progFill = this.el('gs-progress-fill');
|
||||
this.progText = this.el('gs-progress-text');
|
||||
this.boardEl = this.el('gs-hud-board');
|
||||
this.boardList = this.el('gs-board-list');
|
||||
this.bestName = this.el('gs-best-name');
|
||||
this.bestScore = this.el('gs-best-score');
|
||||
this.rouletteEl = this.el('gs-roulette');
|
||||
this.reviveEl = this.el('gs-revive');
|
||||
this.resultEl = this.el('gs-result');
|
||||
this.toastEl = this.el('gs-toast');
|
||||
this.dlgEl = this.el('gs-dialog');
|
||||
this._bulbs();
|
||||
this._toastTimer = null;
|
||||
this._dlgTimer = null;
|
||||
}
|
||||
|
||||
/* 转盘灯泡装饰 */
|
||||
_bulbs() {
|
||||
document.querySelectorAll('.gs-bulbs').forEach(box => {
|
||||
const vert = box.classList.contains('gs-bulbs-left') || box.classList.contains('gs-bulbs-right');
|
||||
const n = vert ? 7 : 12;
|
||||
for (let i = 0; i < n; i++) box.appendChild(document.createElement('i'));
|
||||
});
|
||||
setInterval(() => {
|
||||
document.querySelectorAll('.gs-bulbs i').forEach((b, i) => b.classList.toggle('off', (i + Math.floor(Date.now() / 400)) % 2 === 0));
|
||||
}, 400);
|
||||
}
|
||||
|
||||
setUiMode(mode) { GS.CFG.uiMode = mode; }
|
||||
|
||||
/* ---------- HUD ---------- */
|
||||
showHud(v) {
|
||||
this.statsEl.classList.toggle('gs-hidden', !v);
|
||||
this.boardEl.classList.toggle('gs-hidden', !v);
|
||||
}
|
||||
|
||||
updateStats(totalCoins, lucky, kills) {
|
||||
this.coinsEl.textContent = U.fmt(totalCoins);
|
||||
this.luckyEl.textContent = U.fmt(lucky);
|
||||
this.killsEl.textContent = U.fmt(kills);
|
||||
}
|
||||
|
||||
updateProgress(score, target, visible) {
|
||||
this.progEl.classList.toggle('gs-hidden', !visible);
|
||||
if (!visible) return;
|
||||
this.progFill.style.width = U.clamp(score / target * 100, 0, 100) + '%';
|
||||
this.progText.textContent = Math.floor(Math.min(score, target)) + '/' + target;
|
||||
}
|
||||
|
||||
updateBoard(rows, me, best) {
|
||||
if (best) {
|
||||
this.bestName.textContent = best.name || '-';
|
||||
this.bestScore.textContent = U.fmt(best.score || 0);
|
||||
}
|
||||
let html = '';
|
||||
rows.forEach((r, i) => {
|
||||
const rank = i + 1;
|
||||
const medal = rank === 1 ? '👑' : (rank <= 3 ? ['①', '②', '③'][rank - 1] : rank);
|
||||
html += `<div class="gs-board-row${r.me ? ' me' : ''}">
|
||||
<span class="gs-board-rank r${rank}">${medal}</span>
|
||||
<span class="gs-board-name">${this._esc(r.name)}</span>
|
||||
<span class="gs-board-score">${U.fmt(r.score)}</span></div>`;
|
||||
});
|
||||
this.boardList.innerHTML = html;
|
||||
}
|
||||
|
||||
_esc(s) { return String(s).replace(/[<>&"]/g, c => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c])); }
|
||||
|
||||
/* ---------- 转盘 ---------- */
|
||||
showRoulette(gems) {
|
||||
this.rouletteEl.classList.remove('gs-hidden');
|
||||
this.el('gs-reroll-text').textContent = GS.CFG.rerollCost + ' 换一换';
|
||||
this.updateGems(gems);
|
||||
}
|
||||
hideRoulette() { this.rouletteEl.classList.add('gs-hidden'); }
|
||||
updateGems(gems) {
|
||||
const btn = this.el('gs-reroll');
|
||||
btn.disabled = gems < GS.CFG.rerollCost;
|
||||
}
|
||||
setReels(keys, selected) {
|
||||
document.querySelectorAll('.gs-reel').forEach((reel, i) => {
|
||||
reel.classList.toggle('selected', selected === i);
|
||||
reel.querySelector('.gs-reel-icon').innerHTML = itemSvg(keys[i]);
|
||||
reel.title = GS.ITEMS[keys[i]].name + ':' + GS.ITEMS[keys[i]].desc;
|
||||
});
|
||||
}
|
||||
spinReels(keys) {
|
||||
// 滚动动画:快速切换图标后落定
|
||||
const reels = document.querySelectorAll('.gs-reel');
|
||||
reels.forEach((reel, i) => {
|
||||
const icon = reel.querySelector('.gs-reel-icon');
|
||||
let n = 0;
|
||||
const timer = setInterval(() => {
|
||||
icon.innerHTML = itemSvg(U.pick(GS.ITEM_KEYS));
|
||||
if (++n > 8 + i * 4) { clearInterval(timer); icon.innerHTML = itemSvg(keys[i]); }
|
||||
}, 70);
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 复活 ---------- */
|
||||
showRevive(killerName, usedFree) {
|
||||
this.reviveEl.classList.remove('gs-hidden');
|
||||
this.el('gs-revive-killer').textContent = killerName || '对手';
|
||||
const btn = this.el('gs-revive-btn');
|
||||
btn.disabled = usedFree;
|
||||
btn.textContent = usedFree ? '已复活过' : '▶ 免费复活';
|
||||
}
|
||||
hideRevive() { this.reviveEl.classList.add('gs-hidden'); }
|
||||
updateReviveCount(n, pct) {
|
||||
this.el('gs-revive-count').textContent = n;
|
||||
this.el('gs-revive-count-ring').style.setProperty('--p', (pct * 100) + '%');
|
||||
}
|
||||
|
||||
/* ---------- 结算 ---------- */
|
||||
showResult(data) {
|
||||
this.resultEl.classList.remove('gs-hidden');
|
||||
this.el('gs-result-score').textContent = U.fmt(data.score);
|
||||
this.el('gs-result-coins').textContent = U.fmt(data.coins);
|
||||
this.el('gs-result-kills').textContent = U.fmt(data.kills);
|
||||
this.el('gs-result-lucky').textContent = U.fmt(data.lucky);
|
||||
this.el('gs-result-best-num').textContent = U.fmt(data.best);
|
||||
}
|
||||
hideResult() { this.resultEl.classList.add('gs-hidden'); }
|
||||
|
||||
/* ---------- Toast(normal 模式 / 强提示) ---------- */
|
||||
toast(msg, type) {
|
||||
const el = this.toastEl;
|
||||
el.textContent = msg;
|
||||
el.className = type || '';
|
||||
el.classList.remove('gs-hidden');
|
||||
clearTimeout(this._toastTimer);
|
||||
this._toastTimer = setTimeout(() => el.classList.add('gs-hidden'), 2000);
|
||||
}
|
||||
|
||||
/* ---------- 交互详情弹窗(debug 模式) ---------- */
|
||||
showDialog(info, mode) {
|
||||
// mode: view=查看类(normal 降级 toast) / error=异常(双模式保留)
|
||||
const isDebug = GS.CFG.uiMode === 'debug';
|
||||
if (!isDebug && mode === 'view') { this.toast(info.action + ' 成功', 'success'); return; }
|
||||
if (!isDebug && mode !== 'error') { this.toast(info.action + (info.ok ? ' 成功' : ' 失败'), info.ok ? 'success' : 'error'); return; }
|
||||
const body = this.el('gs-dialog-body');
|
||||
body.textContent =
|
||||
'触发动作:' + info.action + '\n' +
|
||||
'时间:' + U.nowStr() + '\n' +
|
||||
'接口地址:' + (info.url || '-') + '\n' +
|
||||
'HTTP 方法:' + (info.method || '-') + '\n' +
|
||||
'请求参数:' + (info.req || '-') + '\n' +
|
||||
'返回结果:' + (info.res || '-') + '\n' +
|
||||
'错误信息:' + (info.err || '-') + '\n' +
|
||||
'耗时:' + (info.ms != null ? info.ms + 'ms' : '-') + '\n' +
|
||||
'当前状态:' + (info.ok ? '成功' : '失败');
|
||||
this.dlgEl.classList.remove('gs-hidden');
|
||||
this._dlgInfo = info;
|
||||
clearTimeout(this._dlgTimer);
|
||||
if (mode !== 'error') this._dlgTimer = setTimeout(() => this.hideDialog(), 3000);
|
||||
}
|
||||
hideDialog() { this.dlgEl.classList.add('gs-hidden'); }
|
||||
|
||||
/* 带交互记录的 fetch 包装(双模式) */
|
||||
async trackFetch(action, url, opts) {
|
||||
const t0 = performance.now();
|
||||
let info = { action, url, method: (opts && opts.method) || 'GET', req: opts && opts.body ? opts.body : '-' };
|
||||
try {
|
||||
const res = await fetch(url, opts);
|
||||
const text = await res.text();
|
||||
info.ms = Math.round(performance.now() - t0);
|
||||
info.res = text.slice(0, 400);
|
||||
info.ok = res.ok;
|
||||
if (!res.ok) info.err = 'HTTP ' + res.status;
|
||||
this.showDialog(info, res.ok ? 'view' : 'error');
|
||||
return res.ok ? JSON.parse(text) : null;
|
||||
} catch (e) {
|
||||
info.ms = Math.round(performance.now() - t0);
|
||||
info.ok = false;
|
||||
info.err = String(e && e.message || e);
|
||||
this.showDialog(info, 'error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GS.UI = UI;
|
||||
GS.itemSvg = itemSvg;
|
||||
})();
|
||||
@@ -0,0 +1,69 @@
|
||||
/* 贪蛇出动 - 通用工具函数 */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
|
||||
const U = {};
|
||||
GS.U = U;
|
||||
|
||||
U.rand = (a, b) => a + Math.random() * (b - a);
|
||||
U.randInt = (a, b) => Math.floor(U.rand(a, b + 1));
|
||||
U.pick = arr => arr[Math.floor(Math.random() * arr.length)];
|
||||
U.clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||||
U.dist2 = (x1, y1, x2, y2) => { const dx = x2 - x1, dy = y2 - y1; return dx * dx + dy * dy; };
|
||||
U.dist = (x1, y1, x2, y2) => Math.sqrt(U.dist2(x1, y1, x2, y2));
|
||||
|
||||
// 角度归一化到 [-PI, PI]
|
||||
U.normAngle = a => {
|
||||
while (a > Math.PI) a -= Math.PI * 2;
|
||||
while (a < -Math.PI) a += Math.PI * 2;
|
||||
return a;
|
||||
};
|
||||
|
||||
// 数字格式化:>=1e6 显示为 "1,194k",否则千分位
|
||||
U.fmt = n => {
|
||||
n = Math.floor(n);
|
||||
if (n >= 1e6) return Math.floor(n / 1000).toLocaleString('en-US') + 'k';
|
||||
return n.toLocaleString('en-US');
|
||||
};
|
||||
|
||||
// 北京时间日期串 YYYY-MM-DD(今日最佳用)
|
||||
U.todayBJ = () => {
|
||||
const d = new Date(Date.now() + (8 * 60 + new Date().getTimezoneOffset()) * 60000);
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return d.getFullYear() + '-' + m + '-' + day;
|
||||
};
|
||||
|
||||
U.nowStr = () => {
|
||||
const d = new Date();
|
||||
const p = x => String(x).padStart(2, '0');
|
||||
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' +
|
||||
p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());
|
||||
};
|
||||
|
||||
// 简单空间哈希网格(金币拾取/碰撞加速)
|
||||
class Grid {
|
||||
constructor(cell) { this.cell = cell; this.m = new Map(); }
|
||||
clear() { this.m.clear(); }
|
||||
_key(cx, cy) { return cx + ',' + cy; }
|
||||
insert(obj) {
|
||||
const cx = Math.floor(obj.x / this.cell), cy = Math.floor(obj.y / this.cell);
|
||||
const k = this._key(cx, cy);
|
||||
let arr = this.m.get(k);
|
||||
if (!arr) { arr = []; this.m.set(k, arr); }
|
||||
arr.push(obj);
|
||||
}
|
||||
query(x, y, r) {
|
||||
const out = [];
|
||||
const c0 = Math.floor((x - r) / this.cell), c1 = Math.floor((x + r) / this.cell);
|
||||
const r0 = Math.floor((y - r) / this.cell), r1 = Math.floor((y + r) / this.cell);
|
||||
for (let cx = c0; cx <= c1; cx++) for (let cy = r0; cy <= r1; cy++) {
|
||||
const arr = this.m.get(this._key(cx, cy));
|
||||
if (arr) for (const o of arr) out.push(o);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
U.Grid = Grid;
|
||||
})();
|
||||
@@ -0,0 +1,146 @@
|
||||
/* 贪蛇出动 - 世界:金币生成/拾取/磁铁/边界/相机/死亡掉币 */
|
||||
(function () {
|
||||
'use strict';
|
||||
window.GS = window.GS || {};
|
||||
const U = GS.U;
|
||||
|
||||
class World {
|
||||
constructor() {
|
||||
this.size = GS.CFG.worldSize;
|
||||
this.coins = []; // {x,y,r,value,kind:0普通 1星 2大, phase}
|
||||
this.grid = new U.Grid(220);
|
||||
this.cam = { x: this.size / 2, y: this.size / 2, scale: 1 };
|
||||
this.seed();
|
||||
}
|
||||
|
||||
seed() {
|
||||
this.coins.length = 0;
|
||||
for (let i = 0; i < GS.CFG.coinCount; i++) this.coins.push(this._makeCoin());
|
||||
this._rebuild();
|
||||
}
|
||||
|
||||
_makeCoin(x, y, kind) {
|
||||
const k = kind != null ? kind : (Math.random() < 0.08 ? 1 : 0);
|
||||
const base = {
|
||||
0: { r: 7, value: 2 },
|
||||
1: { r: 12, value: 10 }, // 星币:+幸运星
|
||||
2: { r: 14, value: 20 } // 大金币:尸体掉落
|
||||
}[k];
|
||||
return {
|
||||
x: x != null ? x : U.rand(60, this.size - 60),
|
||||
y: y != null ? y : U.rand(60, this.size - 60),
|
||||
r: base.r, value: base.value, kind: k,
|
||||
phase: U.rand(0, Math.PI * 2),
|
||||
vx: 0, vy: 0
|
||||
};
|
||||
}
|
||||
|
||||
_rebuild() {
|
||||
this.grid.clear();
|
||||
for (const c of this.coins) this.grid.insert(c);
|
||||
}
|
||||
|
||||
// 尸体掉币:沿身体间隔掉落
|
||||
dropFromSegments(segs) {
|
||||
for (let i = 0; i < segs.length; i += 2) {
|
||||
const s = segs[i];
|
||||
this.coins.push(this._makeCoin(
|
||||
U.clamp(s.x + U.rand(-14, 14), 40, this.size - 40),
|
||||
U.clamp(s.y + U.rand(-14, 14), 40, this.size - 40), 2));
|
||||
}
|
||||
this._rebuild();
|
||||
}
|
||||
|
||||
// 外部新增单枚金币(加速掉落等),并重建网格索引
|
||||
addCoin(x, y, kind) {
|
||||
const c = this._makeCoin(
|
||||
U.clamp(x, 40, this.size - 40),
|
||||
U.clamp(y, 40, this.size - 40), kind || 0);
|
||||
c.r = kind === 2 ? 14 : (kind === 1 ? 12 : 5);
|
||||
c.value = kind === 2 ? 20 : (kind === 1 ? 10 : 1);
|
||||
this.coins.push(c);
|
||||
this.grid.insert(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
// 宝藏屋奖励:玩家附近撒一大簇金币
|
||||
treasureBurst(x, y) {
|
||||
for (let i = 0; i < 70; i++) {
|
||||
const a = U.rand(0, Math.PI * 2), d = U.rand(30, 320);
|
||||
this.coins.push(this._makeCoin(
|
||||
U.clamp(x + Math.cos(a) * d, 40, this.size - 40),
|
||||
U.clamp(y + Math.sin(a) * d, 40, this.size - 40),
|
||||
Math.random() < 0.25 ? 1 : (Math.random() < 0.4 ? 2 : 0)));
|
||||
}
|
||||
this._rebuild();
|
||||
}
|
||||
|
||||
update(dt, snakes, now) {
|
||||
let moved = false;
|
||||
for (const s of snakes) {
|
||||
if (s.dead) continue;
|
||||
const h = s.head;
|
||||
const magnet = now < s.magnetUntil;
|
||||
const eatR = s.radius + 16;
|
||||
const pullR = magnet ? 260 : eatR;
|
||||
const near = this.grid.query(h.x, h.y, Math.max(pullR, 60));
|
||||
for (const c of near) {
|
||||
if (c._eaten) continue;
|
||||
const d2 = U.dist2(h.x, h.y, c.x, c.y);
|
||||
if (magnet && d2 < pullR * pullR) {
|
||||
const d = Math.sqrt(d2) || 1;
|
||||
const pull = 420 * dt;
|
||||
c.x += (h.x - c.x) / d * pull;
|
||||
c.y += (h.y - c.y) / d * pull;
|
||||
moved = true;
|
||||
}
|
||||
if (d2 < (eatR + c.r) * (eatR + c.r)) {
|
||||
c._eaten = true;
|
||||
s.grow(c.value);
|
||||
s.coins += c.value;
|
||||
if (c.kind === 1) s.lucky += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.coins.some(c => c._eaten)) {
|
||||
this.coins = this.coins.filter(c => !c._eaten);
|
||||
// 补充普通金币保持总量
|
||||
while (this.coins.length < GS.CFG.coinCount) this.coins.push(this._makeCoin());
|
||||
moved = true;
|
||||
}
|
||||
if (moved) this._rebuild();
|
||||
}
|
||||
|
||||
// 相机跟随
|
||||
updateCam(target, viewW, viewH, dt) {
|
||||
const k = 1 - Math.pow(0.001, dt); // 平滑跟随
|
||||
this.cam.x += (target.x - this.cam.x) * k;
|
||||
this.cam.y += (target.y - this.cam.y) * k;
|
||||
const base = Math.min(viewW, viewH) / 720;
|
||||
this.cam.scale = U.clamp(base, 0.7, 1.6);
|
||||
}
|
||||
|
||||
inBounds(x, y, margin) {
|
||||
return x > margin && y > margin && x < this.size - margin && y < this.size - margin;
|
||||
}
|
||||
|
||||
// 碰撞判定:返回 {type:'body', snake} 或 {type:'wall'} 或 null
|
||||
collide(s, snakes) {
|
||||
const h = s.head;
|
||||
if (!this.inBounds(h.x, h.y, s.radius * 0.5)) return { type: 'wall' };
|
||||
for (const o of snakes) {
|
||||
if (o === s || o.dead) continue;
|
||||
const segs = o.segments();
|
||||
const rr = (s.radius * 0.8 + o.radius * 0.9);
|
||||
// 跳过对方头部附近(允许并排)
|
||||
for (let i = 2; i < segs.length; i++) {
|
||||
const g = segs[i];
|
||||
if (U.dist2(h.x, h.y, g.x, g.y) < rr * rr) return { type: 'body', snake: o };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
GS.World = World;
|
||||
})();
|
||||
Reference in New Issue
Block a user