-1

I want to create a Connect Four multiplayer game with SignalR. I'm able to play against another player on two different devices, but if a third person connects nothing works like supposed to. My main problem is to create a SignalR Group with the limit of 2 connections. If a third person connects it should create a new group rather than entering the first group. Also i don't understand how use groups within my javascript code.

I tried to store every connectionID in a hashset but don't know how to create a new group every time the number of connections is odd.

public static class UserHandler
{
    public static HashSet<string> ConnectedIds = new HashSet<string>();
}

public class OnlinegameHub : Hub
{
    public void SendUserInformation(string username, int colorCode)
    {
        Clients.Others.getUserInformation(username, colorCode);
    }

    public void SendTurn(int col, int colorCode, string yourColor)
    {
        Clients.Others.updateBoard(col, colorCode, yourColor);
    }

    public Task JoinLobby(string groupName)
    {
        return Groups.Add(Context.ConnectionId, groupName);

    }

    public override Task OnConnected()
    {
        UserHandler.ConnectedIds.Add(Context.ConnectionId);
        return base.OnConnected();
    }
}

//Javascript part

$.connection.hub.start().done(function () {
    game.server.sendUserInformation(playerOneUsername, yourCode);
    $(".column").click(function () {
        if (yourTurn) {
            game.server.sendTurn($(this).index(), yourCode, yourColor);
            insertColorCode(yourCode, $(this).index());
            yourTurn = false;
            $(".turn-text").html("It's " + playerTwoUsername + "'s turn");
        }
    });

});
Eddie
  • 35
  • 1
  • 7

1 Answers1

2

You have to handle your different groups in your code, every players will be on the same SignalR hub, then your application must handle the groups. I suggest you to read the documentation about Groups : https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups

The examples are quite explicit :

public class ContosoChatHub : Hub
{
    public Task JoinRoom(string roomName)
    {
        return Groups.Add(Context.ConnectionId, roomName);
    }

    public Task LeaveRoom(string roomName)
    {
        return Groups.Remove(Context.ConnectionId, roomName);
    }
}

Of course you have to maintain a List of rooms, then when a new player arrives look into this list to find an available room or create a new one.

Leogiciel
  • 263
  • 2
  • 10
  • thank you, but it doesn't really help me. I already read the documentation but cannot understand it. Frankly i'm unable to understand how to implement groups within my javascript code. – Eddie Jan 02 '19 at 12:33
  • 2
    You have to handle the groups in your C# code. Javascript won't know of client's group, the server will handle this based on the connection ID of your client. – Leogiciel Jan 02 '19 at 12:38