-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
96 lines (75 loc) · 2.21 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
var express = require("express");
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
const port = process.env.PORT || 3000;
app.use("/", express.static(__dirname + "/public/desktop"));
app.use("/mobile", express.static(__dirname + "/public/mobile"));
// key -> code, value: connected
const rooms = new Map();
io.on("connection", function (socket) {
socket.on("create room", (code) => {
code = code.toUpperCase();
rooms.set(code, {
desktop: socket.id,
mobile: null,
});
});
socket.on("destroy", (code) => {
code = code?.toUpperCase();
if (rooms.has(code)) {
const room = rooms.get(code);
if (room.desktop == socket.conn.id) {
rooms.delete(code);
} else {
room.mobile = null;
}
}
});
socket.on("connect mobile", (e) => {
code = e.code?.toUpperCase();
if (e.connected) {
socket.emit("connected");
return;
}
const room = rooms.get(code);
if (room && room.mobile) {
socket.emit("wrong code", "Another user already connected!");
}
if (!room) {
socket.emit("wrong code", "Please enter the code correctly!");
return;
}
room.mobile = socket.id;
socket.emit("connected");
});
socket.on("start", function () {
io.emit("start game");
});
socket.on("orientation", function (e) {
const room = rooms.get(e.code);
if (!room?.desktop) return;
socket.to(room.desktop).emit("mobile orientation", e.value);
});
socket.on("start change vechicle timer", (e) => {
const room = rooms.get(e.code);
if (!room?.mobile) return;
socket.to(room.mobile).emit("start vehicle selection");
});
socket.on("stop change vechicle timer", (e) => {
const room = rooms.get(e.code);
if (!room?.mobile) return;
socket.to(room.mobile).emit("stop vehicle selection");
});
socket.on("select vehicle", (e) => {
const room = rooms.get(e.code);
if (!room?.desktop) return;
socket.to(room.desktop).emit("choose vehicle", e.type);
});
socket.on("gameover", function () {
io.emit("mobile gameover");
});
});
http.listen(port, async () => {
console.log(`Game running at http://localhost:${port}`);
});