RSS

Tag Archives: howto

Ramda function explained: lens


Ramda is a practical functional library for JavaScript programmers. It follows functional programming paradigm, and official doc for lens is shown here. One of the limitation of ramda is that its docuementation is too abstract and the learning curve is just too steep!

In this series of articles,  ramda functions are going to be explained in an intuitive ways so that usage of Ramda is straightforward.

The 1st article of this series is on lens or a family of functions related to lens.

First let’s ask a simple question, why is the function named “lens”? Understanding why is important, it makes one easily recall which function to use in ramda, without referring to the doc again and look for a candidate function among hunderds of them.

Lens make it focus, full stop.

lens-1209823_1280

With lens, you do not see the whole picture, but parts of it, yet with much more details. That fully describes what lens is.

Analogous to this, if you have a very large amount of data, but your interest is not on the whole data set, but parts of it, and you want to manipulate it, read, write, delete …… That is where lens come into play.

With this understanding, you will never forget what lens is!

Example 1: Use lens to access/read data:

const input = ['a', 'b', 'c']
const o1 = view(lensIndex(0), input);            //=> 'a'

Here, lensIndex(0) tells us we are using lens to focus on the first element, that is it. But hold on, we know lens allow you to view the object, but lens is not the object it self! That is why we have a related function view, which returns the element itself.

Emmmm, I can easily do the same thing as below, why bother?

const input = ['a', 'b', 'c']
const o1 = input[0]                              //=> 'a'

Absolutely right! But consider the following example:

const input = {
  id: 'a1',
  features: [
    {
      id: 'f1',
      children: [
        { id: 'c1' }
      ]
    },
    {
      id: 'f2',
      children: [
        { id: 'c2' },
        { id: 'c3' }
      ]
    }
  ]
};

How do you get/focus ‘c2‘ in this? There is no trivial solutions. That is where lensPath come into play:

const o1= view(lensPath(['features', 1, 'children', 0, 'id']), input) //c2

Wow! That is really powerful! It reads naturally like this:

const o1= input ['features'] [1] [ 'children'] [0].'id']

Equally, we can also set the value along that path:

const output = set(lensPath(['features', 1, 'children', 0, 'id']), 'x100', input)

and now output is:

{
    features: [
        {
            children: [
                {
                    id: "c1"
                }
            ],
            id: "f1"
        },
        {
            children: [
                {
                    id: "x100"   // <---- updated
                },
                {
                    id: "c3"
                }
            ],
            id: "f2"
        }
    ],
    id: "a1"
}

If your path to the location of interest is very simple, you can also use lensProp to replace lensPath:

const o2= view(lensProp('features'), input) ;

and now O2 is

[
    {
        id: "f1"
        children: [
            {
                id: "c1"
            }
        ],

    },
    {
        id: "f2"
        children: [
            {
                id: "c2"
            },
            {
                id: "c3"
            }
        ],

    }
]

That is it.

To recap, you can use lensIndex, lensProp and lensPath to locate the data of interest, this is analogous to use a lens to focus on specific fields. And then you can use view, set to read/write the values.

Happy coding.

Advertisements
 
Leave a comment

Posted by on March 4, 2019 in Programming, ramda

 

Tags: , , , ,

Backend server for Unity3D MMO games


There are many backend server systems that are commonly used in MMO games. Below are a few of them.

  1. You might try SmartFox, this link might be a good start for you. Below tutorials are also helpful for a quick start:

Specifically, you can connect to the smartfox server and get notified on connection:

private SmartFox client;
private string serverIP = "127.0.0.1";
private int serverPort = 9933;  
private string zone = "BasicExamples";

client = new SmartFox();           
client.ThreadSafeMode = false; //true for Unity3D
client.AddEventListener(SFSEvent.CONNECTION, (evt) =>
        {
            bool bSuccess = (bool)evt.Params[“success”];
            Console.WriteLine(client.IsConnected ?
                “Successfully connected to SmartFox Server” :
                “Failed to connect to SmartFox Server”);
        });           
client.Connect(serverIP, serverPort);            

To Login and get hooked when login succeeds:

var request = new LoginRequest("UserName", "Password", zone);  //[1]
client.Send(request);                                          //[2]

client.AddEventListener(SFSEvent.LOGIN, (evt) => {             //[3]
            Console.WriteLine("The User login success");       
});

client.Connect(serverIP, serverPort);   

 

2.  Photon is another popular backend server/service.

Photon Server provides you with turnkey frameworks for multiplayer games. Start from scratch or build your own custom logic on top of several demo applications included in source code with the free server SDKs. This lets you achieve great results fast and easy.

Code snippet for setup connection:

using UnityEngine;

public class RandomMatchmaker : MonoBehaviour
{
    void Start() {
        PhotonNetwork.ConnectUsingSettings("0.1");
    }

    void OnGUI(){
       GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
    }
} 

Code snippet for join room/lobby:

public override void OnJoinedLobby()
{
    PhotonNetwork.JoinRandomRoom();
}

Code snippet for setup logging:

PhotonNetwork.logLevel = PhotonLogLevel.Full;

Code snippet for error handling:

void OnPhotonRandomJoinFailed()
{
    Debug.Log("Can't join random room!");
    PhotonNetwork.CreateRoom(null);
}

A good tutorial on this topic can be found here.

3. Firebase might be the 3rd choice, though the performance is arguably unclear.

  • As an example, in roll20.net, you might find MMO game powered by Firbase.
  • Among others, FireSharp might be a very useful open source project for your quick start.

4. Others (OpenSpace, RedDwarf, ElectroServer, Player.IO, Red5, Mesmotronic Multiuser Server etc.)

See this great post for details.

 
Leave a comment

Posted by on December 31, 2015 in Programming, Unity 3d

 

Tags: , , , , , , ,