Files
cs/public/js/client/net.js
T
rong 00d63ba736 feat: CS 枪火对决 —— Rust 权威服务端 + 手写 WebGL 前端的第一人称 1v1 对枪
- 服务端 60Hz 固定步长模拟:重力/摩擦/轴分离碰撞/上台阶,客户端预测回滚
- 命中裁决:射线打墙打人(身体 + 头部盒),射速/弹匣/换弹/伤害/比分全在服务端
- 回合制:3 秒准备、先到 8 分、100 秒平局;观战自由视角
- 机器人陪练:视线检测 + 反应延迟 + 点射偏差,能单人开练
- 前端零依赖:手写 WebGL(程序化贴图、地图合批、粒子、曳光弹、假投影、黄昏天空)
- 2D Canvas 枪模 + WebAudio 合成音效,无任何图片/音频/CDN 资源
- 地图 level.json 前后端同源,tools/gen_level.py 四分镜像生成,绝对对称
- 测试:14 组规则单测 + 6 组联机 e2e
2026-10-22 21:53:45 +08:00

94 lines
2.1 KiB
JavaScript

// WebSocket 连接:断线重连交给上层,这里只管收发和 RTT。
export class Net {
constructor({ onOpen, onClose, onMessage }) {
this.onOpen = onOpen;
this.onClose = onClose;
this.onMessage = onMessage;
this.ws = null;
this.pingId = 0;
this.pingAt = 0;
this.rtt = 0;
this.retry = 0;
this.closedByUs = false;
this.outbox = [];
}
url() {
const proto = location.protocol === "https:" ? "wss:" : "ws:";
return `${proto}//${location.host}/ws`;
}
connect() {
if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) return;
this.closedByUs = false;
let ws;
try {
ws = new WebSocket(this.url());
} catch {
this.onClose?.();
return;
}
this.ws = ws;
ws.onopen = () => {
this.retry = 0;
this.startPing();
const pending = this.outbox.splice(0, this.outbox.length);
for (const m of pending) ws.send(JSON.stringify(m));
this.onOpen?.();
};
ws.onmessage = (ev) => {
let msg;
try {
msg = JSON.parse(ev.data);
} catch {
return;
}
if (msg.t === "pong") {
this.rtt = Math.max(0, Math.round(performance.now() - this.pingAt));
return;
}
this.onMessage?.(msg);
};
ws.onclose = () => {
this.stopPing();
if (!this.closedByUs) this.onClose?.();
};
ws.onerror = () => {
/* onclose 会跟上 */
};
}
send(obj) {
if (this.ws && this.ws.readyState === 1) {
this.ws.send(JSON.stringify(obj));
return true;
}
// 还没连上:排队,连上后补发(只留最近 20 条,避免积压)
this.outbox.push(obj);
if (this.outbox.length > 20) this.outbox.shift();
return false;
}
startPing() {
this.stopPing();
this.pingTimer = setInterval(() => {
this.pingId++;
this.pingAt = performance.now();
this.send({ t: "ping", id: this.pingId });
}, 1500);
}
stopPing() {
clearInterval(this.pingTimer);
}
close() {
this.closedByUs = true;
this.stopPing();
if (this.ws) this.ws.close();
this.ws = null;
}
}