-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
117 lines (92 loc) · 2.8 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const express = require("express");
const http = require("http");
const path = require("path");
const socketIO = require("socket.io");
const { initGame, gameLoop, getUpdateVelocity } = require('./game');
const { FRAME_RATE } = require('./constants');
const { makeid } = require('./utils');
const state = {};
const clientRooms = {};
const app = express();
const server = http.Server(app);
const io = socketIO(server);
app.set("port", 5000);
app.use(express.static(__dirname + "/public"));
app.get("/", function (request, response) {
response.sendFile(path.join(__dirname + "/public", "index.html"));
});
server.listen(5000, function () {
console.log("Start server on port 5000")
});
io.on("connection", client => {
client.on('keydown', handleKeydown);
client.on('newGame', handleNewGame);
client.on('joinGame', handleJoinGame);
// join to existing room
function handleJoinGame(roomName) {
const room = io.sockets.adapter.rooms.get(roomName);
let numClients = 0;
if (room) {
numClients = room.size;
}
if (numClients === 0) {
client.emit('unknownCode');
return;
} else if (numClients > 1) {
client.emit('tooManyPlayers');
return;
}
clientRooms[client.id] = roomName;
client.join(roomName);
client.number = 2;
client.emit('init', 2);
startGameInterval(roomName);
}
// new game creating
function handleNewGame(){
let roomName = makeid(5);
clientRooms[client.id] = roomName;
client.emit('gameCode', roomName);
state[roomName] = initGame();
client.join(roomName);
client.number = 1;
client.emit('init', 1);
}
function handleKeydown(keyCode){
const roomName = clientRooms[client.id];
if (!roomName) {
return;
}
try {
keyCode = parseInt(keyCode);
} catch (e) {
console.error(e);
return;
}
const vel = getUpdateVelocity(keyCode);
if (vel) {
state[roomName].players[client.number - 1].vel = vel;
}
}
});
// game session
function startGameInterval(roomName) {
const intervalId = setInterval(() => {
const winner = gameLoop(state[roomName]);
if (!winner) {
emitGameState(roomName, state[roomName]);
} else {
emitGameOver(roomName, winner);
state[roomName] = null;
clearInterval(intervalId);
}
}, 2000 / FRAME_RATE);
}
function emitGameState(roomName, state) {
io.sockets.in(roomName)
.emit('gameState', JSON.stringify(state));
}
function emitGameOver(roomName, winner) {
io.sockets.in(roomName)
.emit('gameOver', JSON.stringify({ winner }));
}