-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
65 lines (53 loc) · 1.78 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
const port = 3000
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
const http = require('http').createServer(app)
const io = require('socket.io')(http);
const games = new Array()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static("."))
function getRandomNumber() {
return (Math.random() * (9 - 0)).toFixed(0).toString()
}
function getRandomRoomId() {
let random = new String()
for (let i = 0; i < 6; i++) {
random += getRandomNumber()
}
return !games.find(room => room.id === random) ? random : getRandomRoomId()
}
app.post("/playroom", (req, res) => {
try {
room = {
room: getRandomRoomId(),
players: new Array()
}
games.push(room)
res.status(200).send(room)
} catch (error) {
res.status(401).send(error)
}
})
io.on('connection', (socket) => {
socket.on('player-connected', (room, player) => {
game = games.find(element => element.room === room)
if (game) {
socket.join(room)
game.players.push(player)
if (game.players.length == 2) {
// Randomize the player who starts playing
startPlayer = game.players[((Math.random() * 1).toFixed(0))]
io.to(game.room).emit(`${room}-start`, game.players, startPlayer);
}
console.log(player.name + ' connected to room ' + room);
}
});
socket.on('played-cell', (room, cell, player) => {
io.to(room).emit(`${room}-played`, cell, player);
});
socket.on('play-again', (choice, room, player) => {
io.to(room).emit(`${room}-again`, choice, player);
});
});
http.listen(process.env.PORT || port, () => console.log("Running on " + port))