GitHub | Documentation | Discord (chat) | Become a Patron

Stencyl (HaXe) Extension



  • This week I've started using Colyseus. I'm going to try to create a HaXe Extension for Stencyl so that I can publish multiplayer games with Colyseus.
    Previously I've created a couple of multiplayer extensions for Stencyl but failed to get anything near realtime. Maybe Colyseus can help?!?
    From first glance the Colyseus stuff looks great. I love the fact that I can run the server on my own infrastructure.

    It will be a long road ahead and I've decided to start this Showcase thread to let you all follow my progress. Maybe you can help me along the way?!?

    First I started by porting the example nyancat to a Stencyl game (Using a bitmap for the cat)

    Flash publication failed! I've tried to put the flash (swf) on the same server and experimented with crossdomain.xml. But apparently websockets do not care about that.

    Working clients:

    • HTML5 (Tested only Chrome)
    • Windows native
    • Mac OSX native
    • iOS (iPad mini)
    • iOS Simulator (iPhone 5s)
    • Android (Samsung S3 Note)
    • Linux


  • Since I like developers journals myself, I'm writing one for the Stencyl Colyseus Extension journey.

    The main idea of the Stencyl Extension is a general purpose Server with accommodating Stencyl blocks.
    Not sure if that is the right approach, but that is the path I take now.

    Goals:

    • Application ID system
    • Lobby system
    • Turn Based system
    • System that one client acts as a server for the other clients and itself
    • Chat system

    First, I want something persistent. Currently the thought process is that there is a LobbyRoom.
    That can be used for MatchMaking but I hope to use it for public storage of the application IDs.

    Persistence

    The journey leads to investigations on how to store application ids.
    This can be using a simple text file since I'm aiming for a single server (at this time) and I
    hopefully don't need a (shared) database server.

    Test LocalPresence : adjusted rooms/01-chat-room.ts

    import { LocalPresence } from "colyseus";
    

    after maxClients = 4;

    private presence:LocalPresence=new LocalPresence();
    

    Added to onMessage:

    var msg = this.presence.hget("MdotTest","Field");
    console.log("Last Message: ", msg);
    this.presence.hset("MdotTest", "Field", data.message);
    

    This works really well. When leaving room and joining again it still knew the last message.
    However, when I kill the server and start it up the data is lost.

    I couldn't find any writing to files in https://github.com/colyseus/colyseus/tree/master/src/presence

    In RedisPresence there is use of promisfy but no where is something with files (at least so far I can see)

    How do we do server reboot persistence?!

    This is what I hacked together and I'm sure there is something else that I should be doing so please point m.e. to the better thing!!!

    import { readFileSync,writeFileSync } from "fs";
    

    Added to onJoin:

    var jsonfile=JSON.parse(readFileSync('temp.txt','utf8'));
    var item=jsonfile.hash;
    //console.log('item', item.MdotTest.Field);
    this.presence.hset("MdotTest", "Field", item);
    

    Added to onDispose:

    writeFileSync("temp.txt", JSON.stringify(this.presence));
    

    Now at least the data is persistent even when there is a server boot/crash/shutdown (not when it crashes when writing ...)


  • administrators

    hey @mdotedot, not exactly sure what you're planning to build, but to persist the data across server reboots you can use the RedisPresence alternative. The LocalPresence really doesn't persist any data. Cheers!



  • Thanks Endel! It appears that RedisPresence needs a Redis Server!
    When using RedisPresence and you don't have a running Redis Server you get this:

    Could not connect to Redis at 127.0.0.1:6379: Connection refused
    

    For running a server this quick start is available : https://redis.io/topics/quickstart

    I hate to run different things on the server since I want to have deployment by the Extension users as easy as it can be.

    Maybe I will revisit this approach when I need persistence.
    I've changed the approach to ApplicationIDs and 'just' generate some IDs for the Extension Users.

    In the chat I've been told that one of my room-mechanism approach will fail. We will see where this thing is going to crash ...
    I'm not promising that I can create a general purpose server for all kinds of clients.
    If an approach don't work, extension users still have the ability to change the server themselves.
    Although they probably lack the skills, they can hire you guys to make the server for them :D
    There will be overhead on the proxy mechanism, but we will see what can be done.
    Rather than saying that running logic on client is impossible I still want to try it.
    Using the Colyseus server as a proxy to the active client.

    For now I've created a turn based mechanism on the server that I need to write some clients for.

    The example : 02-state-handler.ts appears to be working correctly with below additions, but I guess that I need to investigate
    different types of turn based games and their server-side logic.

    These are the steps taken to rotate player activity: (Modify 02-state-handler.ts)

    After : something = "This ...

    
            nextPlayer(){
                    var doNext=false;
                    for(var m in this.players){
                            if(doNext){
                                    this.players[m].ActivePlayer=m;
                                    doNext=false;
                            }else{
                                    if(this.players[m].ActivePlayer != ""){
                                            this.players[m].ActivePlayer="";
                                            doNext=true;
                                    }
                            }
                    } // check Next available player
                    if(doNext){ // if we need to shift but there are no players after : first player
                            for(var m in this.players){
                                    if(doNext){
                                            this.players[m].ActivePlayer=m;
                                            doNext=false;
                                    }
                            }// go through all players
                    } // check first available player
            }// ActivePlayer shift
    // Changed createPlayer
        createPlayer (id: string, room:Room) {
            this.players[ id ] = new Player();
            if(room.clients.length == 1){ // first player in room
                    this.players[id].ActivePlayer=id;
            }
        } // createPlayer
    
    

    In removePlayer we need to check if the leaving player is the active player and rotate when necessary:

        if(this.players[id].ActivePlayer!="")this.nextPlayer(); 
    

    movePlayer includes a check on activity: After movePlayer(id: string, movement: any){

       
            if(this.players[id].ActivePlayer != id)	return; // ignore move when not active
    		
    

    And before the end of the function:

    	this.nextPlayer(); // after move 
    

    Adjusted class Player with the ActivePlayer :

    
    export class Player {
        x = Math.floor(Math.random() * 400);
        y = Math.floor(Math.random() * 400);
            ActivePlayer = "";
    }
    
    

    Adjusted onJoin :

       this.state.createPlayer(client.sessionId, this);
    

    When running this example the players can only move when it is their turn.
    It is a basic example with no validation on move or if time expired etc..



  • This week I've tried to make a few Stencyl Extension blocks:

    • get Player (ID / Name)
    • get Room (ID / Name)
    • assign Name [..] to [room/player] with id []
    • List of Rooms
    • List of Players

    It took me a while to find out that client.id != player.id. It appears that player is instantiated with room.SessionId.

    Then it took me a lot longer to get a list of rooms (of the same type).
    getAvailableRooms seems to show a list of rooms where you can join to, not the ones that are full or something like that.
    I (also) want rooms with large number of possible clients, so the client is now always joining the same room where I want the client to be able to create a new room.

    Apparently we need to use the MatchMaker to get a list of rooms. But I fail to get it to use.
    It is a Server component, but how do I access this from the client when the client isn't in a room?

    I've also looked at the example on MatchMaker but it registered the rooms differently then I was seeing in the 02-state-change example
    Source: https://github.com/colyseus/colyseus/blob/master/src/MatchMaker.ts

    At last I've hacked something together that appears to be working for now.

    globals.ts:

    //
    // Global data for the server
    //
    export abstract class Globals{
            private static theRooms =  [];
    
            public static set(index:string,value:string){
                    this.theRooms[index]=value;
            }
    // get, remove as well when room gets disposed
    }
    

    This static class can hold 'server-wide' globals as long as you import them in your room-code, like:

    import { Globals } from "../globals"; // global data from the server
    
    //  onInit :
      Globals.set(""+this.roomId, "state_handler");
    
    

    This method allows me to get the list of rooms from other client sessions and even for other rooms when I want...

    I'm sure that there is another way to get this done using the MatchMaker but I couldn't find example of this.



  • Since a couple of days I'm making a mess of things :(

    I have a feeling that I'm doing this the wrong way.

    It all started with the 02-state-handler.ts

    What I conclude is that you have a client that has an ID and that is constant no matter what room is created or joined.
    However each joining or creation of a room is done with a session ID. SessionID != Client.ID

    I want the game(s) to be able to get a list of players in the room.

    export class RoomData{
        playernames = "";
        roomnames = "";
        roomids = "";
        sessionids = "";
    }
    
    export class Player {
    	ID = "";
    	Name = "";
        x = Math.floor(Math.random() * 400);
        y = Math.floor(Math.random() * 400);
        width = 132;
        height = 132;
    
    }
    

    Currently I use the RoomData class to alter the state of the server. These RoomData members are being broadcasted to the clients.
    It feels kind of hacky to set these variables to have the roomstate being synchronized.

    The way that I'm currently setting these values is in client (room.send) and server onMessage communications.

    This is the current client perspective:

    New Room:

    http://photoquesting.com/Colyseus/NewRoom.PNG

    Second Room:

    http://photoquesting.com/Colyseus/SecondRoom.PNG

    Joining From the other Room (looks like it works)

    http://photoquesting.com/Colyseus/JoinedRoom.PNG

    And second player joining the third (this fails : player seems to be in two rooms ??!? )

    http://photoquesting.com/Colyseus/ThirdRoom.PNG

    Server Side Data :

    
    roomName with id:  RoomName:3tAeV4aU7 the changeID is pQZlJiSNb  the ID without Name:  3tAeV4aU7  the name is  Room424
    roomName with id:  RoomName:MZOaBj7hu the changeID is pQZlJiSNb  the ID without Name:  MZOaBj7hu  the name is  Room6959
    roomName with id:  RoomName:pQZlJiSNb the changeID is pQZlJiSNb  the ID without Name:  pQZlJiSNb  the name is  Room7704
    roomnames:  3tAeV4aU7=Room424:MZOaBj7hu=Room6959:pQZlJiSNb=Room7704:
    playername with id:  PlayerName:iwIpOcjZs  the changeID is pQZlJiSNb  the id without name:  iwIpOcjZs  the name is  Player8707
    playername with id:  PlayerName:j6a-rk8dc  the changeID is pQZlJiSNb  the id without name:  j6a-rk8dc  the name is  Player4301
    playername with id:  PlayerName:EsP17dY-m  the changeID is pQZlJiSNb  the id without name:  EsP17dY-m  the name is  Player1374
    playernames:  iwIpOcjZs=Player8707:j6a-rk8dc=Player4301:EsP17dY-m=Player1374
    
    

    As it is fairly hacky stuff I'm hoping that someone has dealt with this before and can shed some light ....

    When I don't use Client.ID and only show SessionIDs it worked much better, but how can I get a client (name) from a session?
    The Player Class data does not appear to be part of a state. What should I do to get Player List with Names?!



  • Since I couldn't get HaXe Json to work (it doesn't know the format) I used Reflection to get the information I need:

    // Get The Player ID/Name
    			var thePlayers:Dynamic = Reflect.field(state, "players" );
    			var sessionIDs:Array<Dynamic> = Std.string(thePlayers).split(": {");
    			for(sessionID in sessionIDs){
    				var sessionid:String="";
    				if(sessionID.indexOf("{") == 0) sessionid=sessionID.split("{")[1]; // for the first player
    				if(sessionID.indexOf("},") > 0) sessionid=sessionID.split("},")[1]; // for all the rest
    				if(sessionid == null) sessionid=sessionID;
    
    				var onePlayer:Dynamic = Reflect.field(thePlayers, StringTools.trim(sessionid));
    	
    				var ID:String = Reflect.field(onePlayer, "ID" );
    				if(ID != null && ID.length > 0)	trace("playerlist One Player . ID : "+ID);
    				var Name:String = Reflect.field(onePlayer, "Name" );
    				if(Name != null && Name.length > 0) trace("playerlist OnePlayer . Name : " + Name);
    				
    			} // for all sessionIDs in the room
    			
    

    Now it can get the ID and Name from the Player Class !

    This seems a lot better than the previous approach.

    I can also now use the availableRooms construction since I use a method on the requestJoin where an option is given when joining a room as oposed to creating a new one...

    I might need to use the RoomData for the name of the Room. But maybe someone else has some opinions about it?!



  • Client debugging ... Leaving both current and joining room with just one room.leave() call ....

    HTML5 works well, Windows is doing well most of the time, but Mac and Android are having troubles in leaving and joining. I suspect that Windows problems are caused by the same issue, but couldn't steadily reproduce that.

    It is the same HaXe client-code due to being a HaXe extension.
    There are only differences in Player Name gathering on HTML versus native. Didn't test iOS/Linux.

    What I think is happening is that room.leave() is done twice on Mac/Android?!?
    What can be the cause of this?!

    HTML5 debug:

     Colyseus.hx:156:  JoinRoom to joinID: BWNT-kGd0  Calling Room Leave with room.id: NRL_w4txR
     Colyseus.hx:421: leavecounter: 1 room.onLeave RoomID: NRL_w4txR Session ID: XqE4dF-s6  
     Colyseus.hx:275: (Client: )p6_HgFPtE join room to JoinID : BWNT-kGd0
     
    Good: 
     Colyseus.hx:304:  joinRoom : joinCounter: 2  Joined Room BWNT-kGd0 sessionID : VXeeGm4oI
    

    Debug Mac:

     Colyseus.hx:156:  JoinRoom to joinID: z40eavIgr  Calling Room Leave with room.id: Ge_RICPir
     Colyseus.hx:421: leavecounter: 1 room.onLeave RoomID: Ge_RICPir Session ID: f2c1YeU3i  
     Colyseus.hx:275: (Client: )9EoXglrY9 join room to JoinID : z40eavIgr
     Colyseus.hx:421: leavecounter: 2 room.onLeave RoomID: z40eavIgr Session ID: null  
    

    Never reached joinRoom!!
    And it does TWO leave rooms !!!

    The output on server side is the same (of course not the IDs and names ...)

    HTML5

    Request join : this.roomId: NRL_w4txR  options.Type:  undefined PlayerName:  APlayer3642  OldMax:  1
    Number of clients in room:  1  the room id is :  NRL_w4txR
    Request join : this.roomId: NRL_w4txR  options.Type:  undefined PlayerName:  APlayer7523  OldMax:  100
    Request join : this.roomId: NRL_w4txR  options.Type:  undefined PlayerName:  APlayer7523  OldMax:  100
    StateHandlerRoom created! { PlayerName: 'APlayer7523',
      RoomName: 'Room5672',
      requestId: 2,
      clientId: '3VTAK8HPh',
      lobby: { rooms: [] } }
    Request join : this.roomId: BWNT-kGd0  options.Type:  undefined PlayerName:  APlayer7523  OldMax:  1
    Number of clients in room:  1  the room id is :  BWNT-kGd0
    Number of clients in room:  0  the room id is :  NRL_w4txR
    Dispose StateHandlerRoom :   remove room.id     :  NRL_w4txR
    Request join : this.roomId: BWNT-kGd0  options.Type:  JOIN PlayerName:  APlayer3642  OldMax:  100
    Number of clients in room:  2  the room id is :  BWNT-kGd0
    Number of clients in room:  1  the room id is :  BWNT-kGd0
    

    MAC:

    Request join : this.roomId: Ge_RICPir  options.Type:  undefined PlayerName:  APlayer7255  OldMax:  1
    Number of clients in room:  1  the room id is :  Ge_RICPir
    Request join : this.roomId: Ge_RICPir  options.Type:  undefined PlayerName:  Player5710  OldMax:  100
    Request join : this.roomId: Ge_RICPir  options.Type:  undefined PlayerName:  Player5710  OldMax:  100
    StateHandlerRoom created! { PlayerName: 'Player5710',
      RoomName: 'Room1021',
      requestId: 4,
      clientId: 'vJGYZCiJ5',
      lobby: { rooms: [] } }
    Request join : this.roomId: z40eavIgr  options.Type:  undefined PlayerName:  Player5710  OldMax:  1
    Number of clients in room:  1  the room id is :  z40eavIgr
    Number of clients in room:  0  the room id is :  Ge_RICPir
    Dispose StateHandlerRoom :   remove room.id     :  Ge_RICPir
    Request join : this.roomId: z40eavIgr  options.Type:  JOIN PlayerName:  APlayer7255  OldMax:  100
    Number of clients in room:  2  the room id is :  z40eavIgr
    Number of clients in room:  1  the room id is :  z40eavIgr
    

    I even used a timer to call join after the leave so that it does it 5 or 10 seconds later.
    As soon as I do the join the leave call is executed !!!