-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
95 lines (76 loc) · 2.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
var express = require('express'),
app = express(),
http = require('http').Server(app);
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
let port = 5000;
http.listen(port, function () {
console.log(`Tic-tac-toe game server running on port ${port}`);
});
const io = require('socket.io')(http);
var players = {},
unmatched;
function joinGame(socket) {
// Add the player to our object of players
players[socket.id] = {
// The opponent will either be the socket that is
// currently unmatched, or it will be null if no
// players are unmatched
opponent: unmatched,
// The symbol will become 'O' if the player is unmatched
symbol: 'X',
// The socket that is associated with this player
socket: socket
};
// Every other player is marked as 'unmatched', which means
// there is no another player to pair them with yet. As soon
// as the next socket joins, the unmatched player is paired with
// the new socket and the unmatched variable is set back to null
if (unmatched) {
players[socket.id].symbol = 'O';
players[unmatched].opponent = socket.id;
unmatched = null;
} else {
unmatched = socket.id;
}
}
// Returns the opponent socket
function getOpponent(socket) {
if (!players[socket.id].opponent) {
return;
}
return players[
players[socket.id].opponent
].socket;
}
io.on('connection', function (socket) {
console.log("Connection established...", socket.id);
joinGame(socket);
// Once the socket has an opponent, we can begin the game
if (getOpponent(socket)) {
socket.emit('game.begin', {
symbol: players[socket.id].symbol
});
getOpponent(socket).emit('game.begin', {
symbol: players[getOpponent(socket).id].symbol
});
}
// Listens for a move to be made and emits an event to both
// players after the move is completed
socket.on('make.move', function (data) {
if (!getOpponent(socket)) {
return;
}
console.log("Move made by : ", data);
socket.emit('move.made', data);
getOpponent(socket).emit('move.made', data);
});
// Emit an event to the opponent when the player leaves
socket.on('disconnect', function () {
if (getOpponent(socket)) {
getOpponent(socket).emit('opponent.left');
}
});
});