index.js 2.0 KB

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