index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const express = require('express');
  2. var app = express()
  3. var http = require('http').Server(app);
  4. var io = require('socket.io')(http);
  5. app.use(express.static('public'))
  6. let gamers = []
  7. let cleanSocket = gamer => {
  8. let copy = {...gamer}
  9. delete copy.socket
  10. return copy
  11. }
  12. let emitGamers = () => io.emit('gamers', gamers.map(cleanSocket))
  13. let thisGamer = s => gamers.filter(g => g.socket === s) [0]
  14. let gamerById = id => gamers.filter(g => g.id === id)[0]
  15. io.on('connection', socket => {
  16. socket.emit('hi', {id: socket.id})
  17. socket.on('disconnect', () => {
  18. gamers = gamers.filter(n => n.socket !== socket)
  19. emitGamers()
  20. });
  21. socket.on('conn', msg => {
  22. gamers.push({nick: msg.nick, socket: socket, id: socket.id})
  23. emitGamers()
  24. })
  25. socket.on('newGame', msg => {
  26. let gamer = thisGamer(socket)
  27. gamer.newGame = msg.newGame
  28. emitGamers()
  29. })
  30. socket.on('startGame', ({id}) => {
  31. let gamer = thisGamer(socket)
  32. let enemy = gamerById(id)
  33. //console.log(id, gamers)
  34. if (enemy && enemy.newGame){
  35. gamer.inGameWith = enemy.id
  36. enemy.inGameWith = gamer.id
  37. gamer.turn = Math.random() > 0.5
  38. enemy.turn = !gamer.turn
  39. }
  40. gamer.socket.emit('startGame', cleanSocket(gamer))
  41. enemy.socket.emit('startGame', cleanSocket(enemy))
  42. if (gamer.turn) gamer.socket.emit('turn')
  43. else enemy.socket.emit('turn')
  44. emitGamers()
  45. })
  46. socket.on('turn', data => {
  47. let gamer = thisGamer(socket)
  48. let enemy = gamerById(gamer.inGameWith)
  49. if (gamer && enemy &&
  50. gamer.inGameWith === enemy.id &&
  51. enemy.inGameWith === gamer.id &&
  52. gamer.turn){
  53. gamer.turn = !gamer.turn
  54. enemy.turn = !enemy.turn
  55. enemy.socket.emit('turn', data)
  56. }
  57. })
  58. });
  59. http.listen(4000, function(){
  60. console.log(`listening`);
  61. });