簡體   English   中英

如何使用socket.io制作房間系統?

[英]How to make a room system with socket.io?

我正在創建一個多人游戲,到目前為止一切都很好,但我正在測試我前一段時間制作的房間系統,我現在正在使用它似乎當我嘗試加載到具有超過 2 個世界的游戲時(而且它們都滿了)服務器無限地創造了越來越多的世界......據說它只是為了創造一個!

我基本上有一個數組,我在其中存儲所有世界(房間),如下所示: let Worlds = [{/*World 0*/},{/**Worlds 1/}, /*ect, ect*/]

所以這是房間系統:(檢查此腳本中的所有注釋以更好地理解)

let PlayersRoom;
let PlayersIndex;

for (let index = 0; index < Worlds.length; index++) {//Checks every single world
    if (Worlds[index].Players.length >= maxplayerlimit){ //Checks if the world is maxed out in players
        if (index == Worlds.length - 1) {//checks if its the last iteration in the loop
            Worlds.push(worldtemplate);//Creates a new world
            index = 0; //restarts the loop
        }
    } else {//Room has available slot
        client.join("World " + index);//Join the room
        PlayersRoom = index;//Set the players room to this index
        break;//stop the loop
    }
}

所以,我采用了一種不同的方法,我將創建一個服務器瀏覽器,每隔 10 秒左右,我會要求服務器更新在服務器中創建的所有世界,如下所示:

let serverlist = []

function requestServerList() {
    socket.emit('UpdateServerList')//Ask the server for an update on the server list.
    document.getElementById('serverlist').innerHTML = 'Reloading...' //clear the Dom element
    serverlist = []//clear the array
}

socket.on("GetServerInfo", UpdateServerList(Data) => {
    if (!Data.isserver) {//If there is a server that exists!
        document.getElementById('serverlist').innerHTML = 'No Rooms Available'
        return;//Stop the function
    }
    //If so then push a new div element with all of the Data from the server
    serverlist.push(`
    <div class="server-column" id="${Data.id}" onclick="startGame('${Data.id}', ${Data.index})">
        Name of Room: ${Data.name}

        <span style="padding-left: 100px; text-align:right;">
            Amount Of Players: ${Data.players.in}/${Data.players.max}
        </span>
    </div>
    `)

    let data = serverlist.join('<br>')//Replace all of the commas in the server list with <br>
    document.getElementById('serverlist').innerHTML = data //Set all the elements in the browser to the newly updated array
});

然后服務器通過使用包含所有數據的 for 循環來發出所有世界:

client.on("UpdateServerList", () => {
    for (let index = 0; index < Worlds.length; index++) {//acts like an if, so if there are no rooms then ignore.
        //Send the client info.
        client.emit("GetServerInfo", {isserver: true, id: Worlds[index].id, index: index, players: {max: Worlds[index].maxplayerlimit, in: Worlds[index].Players.length}, name: Worlds[index].name})
    }

    //Tell the client that there are no servers
    if (Worlds.length == 0) client.emit("GetServerInfo", {isserver: false});
})

這意味着當我單擊服務器列表中的任何服務器時,我會像這樣簡單地加入該服務器:

socket.on('Join Game', (Info) => {
    if (Worlds[PlayersRoomIndex].Players.length >= Worlds[PlayersRoomIndex].maxplayerlimit) {//If that server has maximum players
        client.emit('CantJoin', {Reason: "That world has reach max players"})//tell the client it cant join
        return;//end the function
    }
    //else tell the client it can join
    client.emit('Can Join')
        
    client.join(Info.id);//Join the room with that id the client requested.

    //Do some other stuff like telling other players the new play updating the client on the worlds info ect.
});

現在,如果沒有創建房間,那么我將不得不創建一個房間。 您可以在服務器列表內部或外部執行此操作,我所做的是有很多輸入,例如 Name、Id、MaxPlayers 等,然后將值發送到服務器,如下所示:

function CreateRoom() {
    document.getElementById('SubmitCreateRoom').disabled = "true"//Disable the submit button so they cant spam

    //Get all the values on the inputs
    let Id = document.getElementById('IdofRoom').value;
    let Name = document.getElementById('NameofRoom').value;
    let MaxPlayer = document.getElementById('MaxofRoom').value

    //Tell the server the brand new room with data like id, name ect
    socket.emit("CreateNewRoom", {id: Id, name: Name, max: MaxPlayer})

}

然后服務器將獲取該數據並將其推送到所有房間所在的數組中。

function addroom(name, id, maxplayerlimit) {
    return {//Return an object with all the data that was inputed
        Players: [],
        name: name,
        id: id,
        maxplayerlimit: maxplayerlimit,
        Bullets: [],
        Size: {
            w: 1234,
            h: 1234,
        },
        StaticObjects: [],
        Enemys: [],
    };
}

client.on('CreateNewRoom', (Data) => {
    for (let index = 0; index < Worlds.length; index++) {
        if (Worlds[index].id == Data.id) {
            //Put some thing like client.emit('error', {reason: "Already a room created!"}) idk
            return;
        }
    }
    Worlds.push(addroom(Data.name, Data.id, Data.max)/*Returns an Object That gets pushed into an array*/)

    // Then if u want u can tell the client to join the room 
    // client.emit("RecieveRoomIndex", Data.id ,Worlds.length - 1)
})

我就是這樣做的(;如果您有任何問題或報告此答案的問題,請發表評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM