reactjs - separating clients' actions when using socket.io -


i'm new socket.io, need help. i'm building tic-tac-toe game using socket.io , want played 2 people on ngrok server. want player runs server(me) play x , player connects server play o , need them take turns. can't figure out how implement that, i'd grateful if helps. snippets of code responsible below.

the function handles move:

handleclick(i) { const squares = this.state.squares;  if (calculatewinner(squares) || squares[i]) {   return; } const buttons = document.queryselectorall('.square'); buttons[i].classlist.add('flip'); squares[i] = this.state.xisnext ? 'x' : 'o'; let index = i; const step = {   squares: squares,   xisnext: !this.state.xisnext,   number: index,   togglesound: true }; this.state.xisnext ? this.socket.emit('movex', step) : this.socket.emit('moveo', step) } 

server:

socket.on('movex', step => { socket.broadcast.emit('movex', {   squares: step.squares,   xisnext: step.xisnext,   number: step.number,   togglesound: step.togglesound }) }) socket.on('moveo', step => { socket.broadcast.emit('moveo', {   squares: step.squares,   xisnext: step.xisnext,   number: step.number,   togglesound: step.togglesound }) }) 

code component:

componentdidmount () {     this.socket.on('movex', step => {     this.setstate({     squares: step.squares,     xisnext: step.xisnext,     togglesound: step.togglesound   })   const buttons = document.queryselectorall('.square');   buttons[step.number].classlist.add('flip'); }) this.socket.on('moveo', step => {   this.setstate({     squares: step.squares,     xisnext: step.xisnext,     togglesound: step.togglesound   })   const buttons = document.queryselectorall('.square');   buttons[step.number].classlist.add('flip'); }) } 


Comments

Popular posts from this blog

javascript - Confirm a form & display message if form is valid with JQuery -

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -