index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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) //our id from serverside
  9. socket.emit('conn', {nick: nick.value}) //our nick to serverside
  10. socket.on('gamers', gamers => nicksDiv.innerHTML = //show gamers
  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}) => { //when someone else accept our game
  21. enemyId = inGameWith
  22. gameDiv.style.display = 'block';
  23. //time to init board
  24. send.disabled = true;
  25. })
  26. socket.on('turn', data => { //our turn
  27. send.disabled = false;
  28. enemyData.innerHTML = data ? data.data : 'your turn';
  29. })
  30. },
  31. false(){
  32. socket.disconnect()
  33. nicksDiv.innerHTML = ''
  34. gameDiv.style.display = 'none';
  35. }
  36. })[nick.disabled = connect.checked]()
  37. nick.oninput = () => connect.disabled = !nick.value
  38. newGame.onchange = () => socket.emit('newGame', {newGame: newGame.checked})
  39. gameDiv.style.display = 'none';
  40. send.onclick = () => {
  41. socket.emit('turn', {data: data.value})
  42. enemyData.innerHTML = 'enemy turn';
  43. send.disabled = true;
  44. }