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

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -