index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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('http://localhost:4000') //connect
  8. socket = io() //connect
  9. socket.on('hi',({id}) => ourId = id) //our id from serverside
  10. socket.emit('conn', {nick: nick.value}) //our nick to serverside
  11. socket.on('gamers', gamers => nicksDiv.innerHTML = //show gamers
  12. gamers.reduce((str, {nick, newGame, id, inGameWith}) => str +
  13. `<div style="${inGameWith ? "color:#BBB" : ''}">${nick}
  14. ${newGame && ourId !== id && !inGameWith ?
  15. `<button onclick="startGame('${id}')">
  16. Start Game
  17. </button>
  18. `: ''}
  19. </div>`,"")
  20. )
  21. socket.on('startGame', ({inGameWith, turn}) => { //when someone else accept our game
  22. enemyId = inGameWith
  23. gameDiv.style.display = 'block';
  24. //time to init board
  25. send.disabled = true;
  26. })
  27. socket.on('turn', data => { //our turn
  28. send.disabled = false;
  29. enemyData.innerHTML = data ? data.data : 'your turn';
  30. })
  31. },
  32. false(){
  33. socket.disconnect()
  34. nicksDiv.innerHTML = ''
  35. gameDiv.style.display = 'none';
  36. }
  37. })[nick.disabled = connect.checked]()
  38. nick.oninput = () => connect.disabled = !nick.value
  39. newGame.onchange = () => socket.emit('newGame', {newGame: newGame.checked})
  40. gameDiv.style.display = 'none';
  41. send.onclick = () => {
  42. socket.emit('turn', {data: data.value})
  43. enemyData.innerHTML = 'enemy turn';
  44. send.disabled = true;
  45. }