插座之间的交替匝数

Alternating turns between sockets

本文关键字:之间 插座      更新时间:2023-09-26

假设在html文件中有一个div,游戏是每个玩家都可以改变颜色,但他们只能在其他玩家轮到他的时候改变颜色,他们可以整天轮流。

我一直有问题将玩家的回合与他们所在的插槽联系起来。我真的希望当第一个客户端访问像localhost:8080这样的网站时,他们应该受到"你是player1"的欢迎,而第二个访问该网站的访问者应该说"你是玩家2"。我也想这样,当页面刷新时,客户端失去连接,其他播放器自动变成1。最近刷新的连接变为2,因为这是最后一次创建连接。

我怎么能做到这一点?我还想插入这个信息这样我就可以像点击头一样做一些事情。

我希望能够做这样的事情。

var player; 
//player will be changed dynamically depending
$("div").on("click", function(){
    //if player == 1
    //player 1 cannot click again until player 2 from another socket clicks and the color has changed
    //change color
})

io.on("connection", function(socket){
    //Every time a person connects output their player number. Max 2 players
    //So on first connection == player 1
    //Second connection == player 2
    //If first connection refreshes page that browser / tab becomes player 2
    //  and the original player 2 become player 1
}

(我假设您使用的是客户机/服务器架构,而不是P2P)

在连接时向服务器发送一个数据包,指示连接请求:

socket.emit('joinReq', {}); //Send request to server

在服务器端监听该事件并处理它。您还需要跟踪服务器上当前的玩家数量

io.on('connection', function (socket) {
    socket.on('joinReq', function (data) {
        //update player count
        //Send player count over socket
        socket.emit('playerNumUpdate', { playerNum: <playernum variable> });
    });
});

最后在客户端接收并处理这个

socket.on('playerNumUpdate', function (data) {
    <playernum variable> = data.playerNum; //Get the number sent by the server
});