我正在与后端通信,以添加“一个两个播放器” 与此我:
constructor(){
super()
this.state = {
informationReceived: 'Nothing yet!',
playerOne: 'Jogador 1',
playerTwo: 'Jogador 2',
socket: null
}
const token = localStorage.getItem('token');
this.state.socket = io('http://localhost:8080', {
query: { token: token }
});
var nome = prompt("Seu nome é:");
this.state.socket.emit('adicionar-jogador', nome);
this.state.socket.on('player conectado', (receivedInfo) => {
console.log(receivedInfo);
this.setState({
playerOne: receivedInfo[0].id,
playerTwo: receivedInfo[1].id
})
})
console.log(this.state.informationReceived);
}
emitInfoToAll = () => {
const token = localStorage.getItem('token');
console.log('entrou')
const { socket } = this.state;
socket.emit('myevent', 'Hello realtime connected users!')
console.log(this.state.informationReceived);
}
<div id="player-2" className="user-panel">
<p>Nome: <span className="nome">{this.state.playerTwo}</span></p>
<p>Pontos: <span className="pontos">0</span></p>
<div className="botoes">
<button>Pedra</button>
<button>Papel</button>
<button>Tesoura</button>
</div>
<div className="jogada"></div>
</div>
<div id="player-1" className="user-panel">
<p>Nome: <span className="nome">{this.state.playerOne}</span></p>
<p>Pontos: <span className="pontos">0</span></p>
<div className="botoes">
<button onClick= {() => this.emitInfoToAll()} >Pedra</button>
<button>Papel</button>
<button>Tesoura</button>
</div>
<div className="jogada"></div>
</div>
我正在尝试制作多人游戏jokenPo游戏,所以我首先从每个插槽添加第一个玩家:
var nome = prompt("your name is:");
this.state.socket.emit('add-player', name);
在我的后端,我的活动是这样的:
socket.on('add-player', function(name){
console.log('xd');
if(playerOne.id && playerTwo.id) {
listaEspera.push({
id: socket.id,
name: name
});
socket.emit('player in Waiting list', WaitingList);
}
if (!playerOne.id){
playerOne.id = socket.id;
playerOne.name = name;
} else if(!playerTwo.id) {
playerTwo.id = socket.id;
playerTwo.name= name;
}
console.log(WaitingList);
socket.emit('player conected', [ playerOne, playerTwo]);
})
然后我创建了两个div(玩家一个div和玩家两个div) 我希望如果没有玩家1,则不会出现玩家1的div,如果没有玩家2,则不会出现玩家2的div 我的div:
<div id="player-1" className="user-panel">
<p>Nome: <span className="nome">{this.state.playerOne}</span></p>
<p>Pontos: <span className="pontos">0</span></p>
<div className="botoes">
<button onClick= {() => this.emitInfoToAll()} >Pedra</button>
<button>Papel</button>
<button>Tesoura</button>
</div>
<div className="jogada"></div>
</div>
<br />
<br />
<br />
<div id="player-2" className="user-panel">
<p>Nome: <span className="nome">{this.state.playerTwo}</span></p>
<p>Pontos: <span className="pontos">0</span></p>
<div className="botoes">
<button>Pedra</button>
<button>Papel</button>
<button>Tesoura</button>
</div>
<div className="jogada"></div>
</div>
关于我的scoket的连接以及从后端添加/获取数据的工作正常,我打开了两个屏幕,并在其中添加了一个名称,该名称通常显示在其中:
但是,当我进入第二个窗口并添加名称时,它将进入播放器一而不是播放器二
有人可以帮我吗?