This repository has been archived by the owner on Dec 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
81 lines (70 loc) · 1.66 KB
/
game.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
var friendlyWords = require('friendly-words');
var sio;
/**
* Initialize game
*/
exports.initGame = function(io, socket) {
sio = io;
socket.on('newGame', newGame);
socket.on('joinGame', joinGame);
socket.on('milkCow', milkCow);
}
/**
* Create new game
*/
function newGame() {
/* create game id */
var gameId = friendlyWords.objects[Math.floor(Math.random()*friendlyWords.objects.length)];
/* emit game to client */
this.emit('newGameCreated', {
gameId
});
/* join game room */
this.join(gameId);
}
/**
* Join existing game
*/
function joinGame(data) {
var gameId = data.gameId;
var rooms = this.adapter.rooms;
/* check if room exists */
if (!rooms[gameId]) {
/* room doesn't exist */
this.emit('error2', 'game doesn\'t exist')
return;
}
/* check if room is full (max 2 players) */
if (Object.keys(rooms[gameId].sockets).length >= 2) {
/* room is full */
this.emit('error2', 'game full')
return;
}
/* join game */
this.join(gameId);
/* start game */
startGame(gameId);
}
/**
* Start game
*/
function startGame(gameId) {
/* notify players that game is starting soon */
sio.in(gameId).emit('showCountdown')
/* count down and start game */
setTimeout(function() {
sio.in(gameId).emit('startGame')
}, 3000);
}
/**
* Milk cow
* @param {object} data
*/
function milkCow(data) {
var gameId = data.gameId;
var socketId = data.socketId;
/* get sender socket */
var socket = sio.of('/').connected[socketId]
/* notify clients (excluding sender) */
socket.to(gameId).emit('otherPlayerMilked')
}