index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. let socket;
  2. let ourId;
  3. let enemyId;
  4. let startGame = id => socket.emit('startGame', {id})
  5. connect.onchange = () => ({
  6. true(){
  7. socket = io() //connect
  8. socket.on('hi',({id}) => ourId = id)
  9. socket.emit('conn', {nick: nick.value})
  10. socket.on('gamers', gamers => nicksDiv.innerHTML =
  11. gamers.reduce((str, {nick, newGame, id, inGameWith}) => str +
  12. `<div style="${inGameWith ? "color:#BBB" : ''}">${nick}
  13. ${newGame && ourId !== id && !inGameWith ?
  14. `<button onclick="startGame('${id}')">
  15. Start Game
  16. </button>
  17. `: ''}
  18. </div>`,"")
  19. )
  20. socket.on('startGame', ({inGameWith, turn}) => {
  21. enemyId = inGameWith
  22. gameDiv.style.display = 'block';
  23. //time to init board
  24. send.disabled = true;
  25. })
  26. socket.on('turn', data => {
  27. send.disabled = false;
  28. enemyData.innerHTML = data ? data.data : 'your turn';
  29. })
  30. },
  31. false(){
  32. socket.disconnect()
  33. nicksDiv.innerHTML = ''
  34. }
  35. })[nick.disabled = connect.checked]()
  36. nick.oninput = () => connect.disabled = !nick.value
  37. newGame.onchange = () => socket.emit('newGame', {newGame: newGame.checked})
  38. gameDiv.style.display = 'none';
  39. send.onclick = () => {
  40. socket.emit('turn', {data: data.value})
  41. enemyData.innerHTML = 'enemy turn';
  42. send.disabled = true;
  43. }