2021-02-21 23:59:23 +00:00
|
|
|
const express = require('express')
|
|
|
|
const socketio = require('socket.io')
|
|
|
|
const http = require('http')
|
|
|
|
const cors = require('cors')
|
2021-02-22 15:34:17 +00:00
|
|
|
const { addUser, removeUser, getUser, getUsersInRoom } = require('./users')
|
2021-02-21 23:59:23 +00:00
|
|
|
|
|
|
|
const PORT = process.env.PORT || 5000
|
|
|
|
|
|
|
|
const app = express()
|
|
|
|
const server = http.createServer(app)
|
|
|
|
const io = socketio(server)
|
|
|
|
|
|
|
|
app.use(cors())
|
|
|
|
|
|
|
|
io.on('connection', socket => {
|
2021-02-22 15:34:17 +00:00
|
|
|
socket.on('join', (payload, callback) => {
|
|
|
|
let numberOfUsersInRoom = getUsersInRoom(payload.room).length
|
|
|
|
|
|
|
|
const { error, newUser} = addUser({
|
|
|
|
id: socket.id,
|
|
|
|
name: numberOfUsersInRoom===0 ? 'Player 1' : 'Player 2',
|
|
|
|
room: payload.room
|
|
|
|
})
|
|
|
|
|
|
|
|
if(error)
|
|
|
|
return callback(error)
|
|
|
|
|
|
|
|
socket.join(newUser.room)
|
|
|
|
|
|
|
|
io.to(newUser.room).emit('roomData', {room: newUser.room, users: getUsersInRoom(newUser.room)})
|
|
|
|
socket.emit('currentUserData', {name: newUser.name})
|
|
|
|
callback()
|
|
|
|
})
|
2021-02-21 23:59:23 +00:00
|
|
|
|
2021-02-22 01:03:25 +00:00
|
|
|
socket.on('initGameState', gameState => {
|
2021-02-22 15:34:17 +00:00
|
|
|
const user = getUser(socket.id)
|
|
|
|
if(user)
|
|
|
|
io.to(user.room).emit('initGameState', gameState)
|
2021-02-22 01:03:25 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
socket.on('updateGameState', gameState => {
|
2021-02-22 15:34:17 +00:00
|
|
|
const user = getUser(socket.id)
|
|
|
|
if(user)
|
|
|
|
io.to(user.room).emit('updateGameState', gameState)
|
2021-02-22 01:03:25 +00:00
|
|
|
})
|
|
|
|
|
2021-02-21 23:59:23 +00:00
|
|
|
socket.on('disconnect', () => {
|
2021-02-22 15:34:17 +00:00
|
|
|
const user = removeUser(socket.id)
|
|
|
|
if(user)
|
|
|
|
io.to(user.room).emit('roomData', {room: user.room, users: getUsersInRoom(user.room)})
|
2021-02-21 23:59:23 +00:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
server.listen(PORT, () => {
|
|
|
|
console.log(`Server running on port ${PORT}`)
|
|
|
|
})
|