const express = require('express'); const cors = require('cors') var app = express() var http = require('http').Server(app); var io = require('socket.io')(http); const jwtSecret = 'AjnjLhjxM' const { verify } = require('jsonwebtoken') app.use(express.static('public')) app.use(cors()) let gamers = [] let cleanSocket = gamer => { let {socket, ...copy} = gamer return copy } let emitGamers = () => io.emit('gamers', gamers.map(cleanSocket)) let thisGamer = s => gamers.filter(g => g.socket === s) [0] let gamerById = id => gamers.filter(g => g.id === id)[0] const dice = () => Math.ceil(Math.random()*6) const startBoard = () => [ {color: 'white', count: 15}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, {color: 'black', count: 15}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, { count: 0}, ] io.on('connection', socket => { socket.emit('hi', {id: socket.id}) socket.on('disconnect', () => { gamers = gamers.filter(n => n.socket !== socket) emitGamers() }); socket.on('conn', token => { const decoded = verify(token, jwtSecret) if (decoded){ gamers.push({nick: decoded.sub.login, socket: socket, id: socket.id}) } else { socket.emit("error", 'jwt failed') } emitGamers() }) socket.on('newGame', msg => { let gamer = thisGamer(socket) gamer.newGame = msg.newGame emitGamers() }) socket.on('startGame', ({id}) => { let gamer = thisGamer(socket) let enemy = gamerById(id) //console.log(id, gamers) if (enemy && enemy.newGame){ gamer.inGameWith = enemy.id enemy.inGameWith = gamer.id gamer.turn = Math.random() > 0.5 enemy.turn = !gamer.turn } gamer.socket.emit('startGame', cleanSocket(gamer)) enemy.socket.emit('startGame', cleanSocket(enemy)) if (gamer.turn) gamer.socket.emit('turn', {board: startBoard(), dice: [dice(), dice()]}) else enemy.socket.emit('turn', {board: startBoard(), dice: [dice(), dice()]}) emitGamers() }) socket.on('turn', data => { let gamer = thisGamer(socket) let enemy = gamerById(gamer.inGameWith) if (gamer && enemy && gamer.inGameWith === enemy.id && enemy.inGameWith === gamer.id && gamer.turn){ gamer.turn = !gamer.turn enemy.turn = !enemy.turn data.dice = [dice(), dice()] enemy.socket.emit('turn', data) } }) }); http.listen(4000, function(){ console.log(`listening`); });