重写一下那个联机射击的网页小游戏吧,这次逻辑和运算都要写在后端。
今晚只完成了一小部分后端,前端还没开始写:
app.js
const express = require('express');
const WebSocket = require('ws');
const cors = require('cors');
const app = express();app.use(express.json());
app.use(cors());const server = app.listen(5000, () => {console.log('服务器运行在 http://localhost:5000');
});const wss = new WebSocket.Server({server});let players = []
let bullets = []let config = {FPS: 1000 / 60,shootGap: 1000,
}wss.on('connection', ws => {console.log('有玩家连接服务器');ws.on('message', message => {const msg = JSON.parse(message);const type = msg.type;const data = msg.data;const tsp = Date.now();let index;switch (type) {//玩家加入case 'pJoin':players.push(new Player(data))console.log(data.name + " 加入游戏")break;//玩家移动case 'pMove':index = players.findIndex(player => player.id === data.id)if (index > -1) {players[index].up = data.up;players[index].down = data.down;players[index].left = data.left;players[index].right = data.right;}break;//玩家射击case 'pShoot':index = players.findIndex(player => player.id === data.id)if ((index > -1) && (tsp - players[index].latestShoot > config.shootGap)) {//新建子弹bullets.push(new Bullet({id: bullets.length,from: players[index].name,color: players[index].color,at: players[index].at,x: players[index].x,y: players[index].y,w: 10,h: 10,a: 0,v: 5,angle: players[index].angle}));}break;//玩家死亡case 'pDelete':index = players.findIndex(player => player.id === data.id)if (index > -1) {players.splice(index, 1)console.log(data.name + " 离开游戏")}break;}})
})
//广播定时器
setInterval(() => {players.forEach(player => {//更新玩家位置player.playerMove();})bullets.forEach(bullet => {//更新子弹位置bullet.bulletMove();})//碰撞检测//广播位置}, config.FPS)//玩家类
class Player {constructor({name,id,color,maxHp,hp,at,latestShoot,latestHurt,x,y,w,h,a,v,up,down,left,right,angle}) {this.name = name;this.id = id;this.color = color;this.maxHp = maxHp;this.hp = hp;this.at = at;this.latestShoot = latestShoot;this.latestHurt = latestHurt;this.x = x;this.y = y;this.w = w;this.h = h;this.a = a;this.v = v;this.up = up;this.down = down;this.left = left;this.right = right;this.angle = angle;}playerMove() {if (this.up) {this.y -= this.v;}if (this.down) {this.y += this.v;}if (this.left) {this.x -= this.v;}if (this.right) {this.x += this.v;}}
}//子弹类
class Bullet {constructor({id, from, color, at, x, y, w, h, a, v, angle}) {this.id = id;this.from = from;this.color = color;this.at = at;this.x = x;this.y = y;this.w = w;this.h = h;this.a = a;this.v = v;this.angle = angle;}bulletMove() {const rad = (this.angle * Math.PI) / 180;this.x += Math.cos(rad) * this.v;this.y += Math.sin(rad) * this.v;}
}
