-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
218 lines (189 loc) · 6.48 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
require('dotenv').config();
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');
const session = require('express-session');
const routes = require('./routes/route');
const bodyParser = require('body-parser');
const User = require('./models/user');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static('public'));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}));
app.get('/chess', function(req, res) {
res.sendFile(__dirname + '/public/chess.html');
});
app.get('/game', function(req, res) {
res.sendFile(__dirname + '/public/chessPhone.html');
});
app.get('/login', function(req, res) {
res.sendFile(__dirname + '/public/pc/loginpc.html');
});
app.get('/login-page', function(req, res) {
res.sendFile(__dirname + '/public/phone/loginphone.html');
});
app.get('/about', function(req, res) {
res.sendFile(__dirname + '/public/devPage.html');
});
let numUsers = 0;
let currentGame = 'start';
let chatMessages = [];
let userToSocketId = {};
let movesHistory = [];
let teams = {
'w': false,
'b': false
};
// MongoDB connection
mongoose.connect(process.env.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connected to the database");
});
io.on('connection', (socket) => {
numUsers++;
console.log('------------------');
console.log('A user connected. Total users: ', numUsers);
// Send current game state and chat messages
socket.emit('init', { game: currentGame, chat: chatMessages, teams: teams, movesHistory: movesHistory });
socket.on('team selected', function({team, username}) {
if (!teams[team]) {
teams[team] = username;
userToSocketId[username] = socket.id;
socket.username = username;
io.emit('teams update', teams);
io.emit('player joined', {username: username, team: team});
}
});
socket.on('move', function(msg, piece, from, to) {
if (!(teams['w'] === socket.username || teams['b'] === socket.username)) {
return;
}
let colors = {
'w': 'White',
'b': 'Black'
};
let pieces = {
'p': 'pawn',
'r': 'rook',
'n': 'knight',
'b': 'bishop',
'q': 'queen',
'k': 'king'
};
currentGame = msg;
movesHistory.push(`${colors[piece.color]} ${pieces[piece.type]} from ${from} to ${to}`);
io.emit('move', msg);
io.emit('updateHistory', movesHistory);
io.emit('move sound');
});
socket.on('chat message', function(msg) {
if (chatMessages.length > 150) {
chatMessages = chatMessages.slice(-150);
}
chatMessages.push(msg);
io.emit('chat message', msg);
});
socket.on('end game', function({ winner, loser }) {
if (winner === null && loser === null) {
io.emit('game result', { message: `Game ended in a draw!` });
return;
}
User.findOne({username: winner})
.then(user => {
if(!user) {
console.error(`User not found: ${winner}`);
return;
}
user.elo = user.elo + 10;
user.save().then(() => {
io.to(userToSocketId[winner]).emit('update elo', { username: winner, elo: user.elo }); // send to correct socket id
io.to(userToSocketId[winner]).emit('game result', { message: `Wow, you're so good ${winner}! 😎`});
});
})
.catch(err => {
console.error(err);
});
User.findOne({username: loser})
.then(user => {
if(!user) {
console.error(`User not found: ${loser}`);
return;
}
user.elo = Math.max(user.elo - 10, 0); // Don't let ELO drop below 0
user.save().then(() => {
io.to(userToSocketId[loser]).emit('update elo', { username: loser, elo: user.elo }); // send to correct socket id
io.to(userToSocketId[loser]).emit('game result', { message: `You're so bad it's incredible. RIP BOZO 😂` });
});
})
.catch(err => {
console.error(err);
});
});
socket.on('requestRestart', function() {
let otherPlayer = teams['w'] === socket.username ? teams['b'] : teams['w'];
io.to(userToSocketId[otherPlayer]).emit('promptRestart', { username: socket.username });
});
socket.on('responseRestart', function({ username }) {
io.to(userToSocketId[username]).emit('responseRestart', { username: socket.username });
});
socket.on('restart', function(msg) {
currentGame = msg;
teams = {
'w': false,
'b': false
};
movesHistory = [];
io.emit('teams update', teams);
io.emit('restart', msg);
io.emit('teams update', teams);
});
// reset the game when restarting
socket.on('init', function() {
currentGame = 'start';
});
socket.on('disconnect', () => {
numUsers--;
console.log('------------------');
console.log('A user disconnected. Total users: ', numUsers);
if (teams['w'] === socket.username) {
teams['w'] = false;
} else if (teams['b'] === socket.username) {
teams['b'] = false;
}
delete userToSocketId[socket.username];
io.emit('teams update', teams);
if (numUsers == 0) {
currentGame = 'start';
chatMessages = [];
movesHistory = [];
teams = {
'w': false,
'b': false
};
io.emit('teams update', teams);
}
});
io.emit('teams update', teams);
if (teams['w'] === socket.username) {
socket.emit('team selected', {team: 'w', username: socket.username});
} else if (teams['b'] === socket.username) {
socket.emit('team selected', {team: 'b', username: socket.username});
}
});
const port = 8080;
server.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`)
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use("/", routes);