Пример #1
0
    public static string ToJson <T>(T[] array, bool prettyPrint)
    {
        JSONWrapper <T> wrapper = new JSONWrapper <T>();

        wrapper.Events = array;
        return(UnityEngine.JsonUtility.ToJson(wrapper, prettyPrint));
    }
Пример #2
0
    public static Name Generate(Gender gender = Gender.Male)
    {
        var path = Application.streamingAssetsPath;

        if (gender == Gender.Male)
        {
            path += "/male.json";
        }
        else
        {
            path += "/female.json";
        }

        if (!File.Exists(path))
        {
            return(null);
        }

        var         jsonFile = File.ReadAllText(path);
        JSONWrapper wrapper  = JsonUtility.FromJson <JSONWrapper>(jsonFile);

        int    randomFirstIndex = Random.Range(0, wrapper.Names.Length - 1);
        int    randomLastIndex  = Random.Range(0, wrapper.Names.Length - 1);
        string firstName        = wrapper.Names[randomFirstIndex].First;
        string lastName         = wrapper.Names[randomLastIndex].Last;

        return(new Name(firstName, lastName));
    }
Пример #3
0
    // Async operation to get scores and wait for response.
    private IEnumerator GetScores()
    {
        UnityWebRequest www = UnityWebRequest.Get(url + "/scores" + "/" + Secret);

        www.SetRequestHeader("Authorization", "tamk_2018");
        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            string      result     = www.downloadHandler.text;
            string      JSONString = "{\"values\":" + result + "}";
            JSONWrapper scores     = JsonUtility.FromJson <JSONWrapper>(JSONString);
            Scoreboard.SetScores(scores.values);
            Debug.Log("HERE");
        }
    }
Пример #4
0
    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        string dataString = "";

        HttpListenerRequest request = context.Request;
        StreamReader reader = new StreamReader(request.InputStream);
        string s = reader.ReadToEnd();
        string ID = request.RemoteEndPoint.Address.ToString();

        JSONWrapper j = new JSONWrapper(s);

        if (WebServer.controllerRoster.ContainsKey (ID)) {
            CommandPanel cp = WebServer.controllerRoster [ID].GetComponent<CommandPanel> ();
            Debug.Log("Processing tile data");
            // TODO: rewrite this because holy shit it uses a public accessor
            cp.pathSelection (FindObjectOfType<TileGen> ().tileArray [int.Parse (j ["x"]), int.Parse (j ["z"])]);
            Debug.Log ("x:" + j ["x"] + "," + "z:" + j ["z"]);
        }

        byte[] data = Encoding.ASCII.GetBytes(dataString);

        yield return null;

        HttpListenerResponse response = context.Response;

        response.ContentType = "text/plain";

        Stream responseStream = response.OutputStream;

        int count = data.Length;
        int i = 0;
        while(i < count)
        {
            if (i != 0)
                yield return null;

            int writeLength = Math.Min((int)writeStaggerCount, count - i);
            responseStream.Write(data, i, writeLength);
            i += writeLength;
        }
    }
Пример #5
0
    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        HttpListenerRequest request = context.Request;
        StreamReader        reader  = new StreamReader(request.InputStream);
        string command    = reader.ReadToEnd();
        string dataString = "";

        JSONWrapper j            = new JSONWrapper(command);
        string      givenCommand = "";
        string      user         = "";

        try
        {
            givenCommand = j["command"];
            user         = j["username"];
            Debug.Log("Receiving command " + givenCommand + " from " + user);
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
        if (PlayerRegisterRule.PlayerRegister.ContainsKey(user))
        {
            Debug.Log(user + " found, entering command switch");
            CommandPanel cp = PlayerRegisterRule.PlayerRegister[user];
            cp.IsConnected = true;
            switch (givenCommand)
            {
            // for getting the size (and more if needed) of the map, to generate a grid at runtime
            case "GetMapData":
                if (selectedMap != null)
                {
                    dataString = JsonUtility.ToJson(selectedMap.ToJSON());
                }
                break;

            // for use during charcter select
            case "ChooseCharacter":
                if (GameStateManager.Instance.GameState == GameState.CharacterSelect)
                {
                    string charSelected = "";
                    try
                    {
                        charSelected = j["character"];
                        Debug.Log(charSelected);
                    } catch (Exception e)
                    {
                        Debug.Log(e.Message);
                    }

                    // if the character was able to be assigned
                    if (charSelected != "" && charSelectManager != null)
                    {
                        charSelectManager.SelectCharForPlayer(charSelected, cp);
                    }
                }
                break;

            case "ToggleReady":
                if (charSelectManager != null)
                {
                    cp.IsReady = !cp.IsReady;
                    List <bool> readies = new List <bool>();
                    foreach (CommandPanel r in PlayerRegisterRule.PlayerRegister.Values)
                    {
                        readies.Add(r.IsReady);
                    }
                    if (!readies.Contains(false) && !CharSelectManager.InCountdown)
                    {
                        charSelectManager.StartCoroutine("Countdown");
                    }
                    else if (readies.Contains(false))
                    {
                        charSelectManager.StartCoroutine(charSelectManager.StopCountdown());
                    }
                }
                break;

            // commit their movement path and execute a move
            case "CommitMove":
                if (IsYourTurn(cp))
                {
                    cp.CommitToMove();
                }
                break;

            // select a tile to add to the movement path
            case "SelectTile":
                if (IsYourTurn(cp))
                {
                    if (mapGenerator != null)
                    {
                        try
                        {
                            Debug.Log("Processing tile data: {x:" + j["x"] + "," + "z:" + j["z"] + "}");
                            cp.PathSelection(mapGenerator.TileArray[int.Parse(j["x"]), int.Parse(j["z"])]);
                            PathTile          p            = new PathTile();
                            List <Coordinate> queuedCoords = new List <Coordinate>();
                            foreach (TileBehavior tb in cp.QueuedPath)
                            {
                                queuedCoords.Add(tb.Coords);
                            }
                            p.path = queuedCoords.ToArray();
                            Debug.Log(JsonUtility.ToJson(p));
                            dataString = JsonUtility.ToJson(p);
                        }
                        catch (Exception e)
                        {
                            Debug.Log(e.Message);
                        }
                    }
                }
                break;

            // none of the above
            default:
                Debug.Log("Command either not parsed or not valid. Given command was: " + givenCommand);
                break;
            }
        }

        Debug.Log("Sending " + user + ": " + dataString);
        byte[] data = Encoding.ASCII.GetBytes(dataString);

        yield return(null);

        HttpListenerResponse response = context.Response;

        response.ContentType = "text/plain";

        Stream responseStream = response.OutputStream;

        int count = data.Length;
        int i     = 0;

        while (i < count)
        {
            if (i != 0)
            {
                yield return(null);
            }

            int writeLength = Math.Min((int)writeStaggerCount, count - i);
            responseStream.Write(data, i, writeLength);
            i += writeLength;
        }
    }
Пример #6
0
        public static Boolean TryParseJObjectRequestBody(this HTTPRequest  HTTPRequest,
                                                         out JSONWrapper   JSON,
                                                         out HTTPResponse  HTTPResponse,
                                                         Boolean           AllowEmptyHTTPBody = false,
                                                         String            JSONLDContext      = null)
        {

            #region AllowEmptyHTTPBody

            JSON          = null;
            HTTPResponse  = null;

            if (HTTPRequest.ContentLength == 0 && AllowEmptyHTTPBody)
            {

                HTTPResponse = new HTTPResponseBuilder(HTTPRequest) {
                    HTTPStatusCode = HTTPStatusCode.OK,
                };

                return false;

            }

            #endregion

            #region Get text body

            var RequestBodyString = HTTPRequest.GetRequestBodyAsUTF8String(HTTPContentType.JSON_UTF8);
            if (RequestBodyString.HasErrors)
            {
                HTTPResponse  = RequestBodyString.Error;
                return false;
            }

            #endregion

            #region Try to parse the JSON

            try
            {

                JSON = new JSONWrapper(RequestBodyString.Data);

            }
            catch (Exception e)
            {

                HTTPResponse  = new HTTPResponseBuilder(HTTPRequest) {
                    HTTPStatusCode  = HTTPStatusCode.BadRequest,
                    ContentType     = HTTPContentType.JSON_UTF8,
                    Content         = JSONObject.Create(
                                          JSONLDContext.IsNotNullOrEmpty()
                                              ? new JProperty("context",  JSONLDContext)
                                              : null,
                                          new JProperty("description",  "Invalid JSON request body!"),
                                          new JProperty("hint",         e.Message)
                                      ).ToUTF8Bytes()
                };

                return false;

            }

            return true;

            #endregion

        }
Пример #7
0
    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        string dataString = "";

        HttpListenerRequest request = context.Request;
        StreamReader reader = new StreamReader(request.InputStream);
        string s = reader.ReadToEnd();

        JSONWrapper j = new JSONWrapper(s);
        CommandPanel cp;
        try {

            cp = PlayerRegisterRule.PlayerRegister[j["username"]];
            cp.Pulse();
            Alliance playerTeam = cp.Team;

            // List of other players
            List<PlayerJSON> pj = new List<PlayerJSON>();
            foreach (CommandPanel c in PlayerRegisterRule.PlayerRegister.Values)
            {
                pj.Add((PlayerJSON)c.ToJSON());
            }

            // List of characters
            List<CharacterJSON> cj = new List<CharacterJSON>();
            foreach (CharacterBehavior c in FindObjectsOfType<CharacterBehavior>())
            {
                // if you're allies OR you're made visible
                if(c.Team == cp.Team || c.IsVisible)
                    cj.Add((CharacterJSON)c.ToJSON());
            }
            Heartbeat h = new Heartbeat();
            h.state = GameStateManager.Instance.GameState;
            h.players = pj.ToArray();
            if (cp.Character != null)
                h.myCharacter = (CharacterJSON) cp.Character.ToJSON();
            h.characters = cj.ToArray();

            dataString = JsonUtility.ToJson(h);

        }
        catch (Exception e)
        {
            // Put code here to refresh the web page
            Debug.Log(e.Message);
        }

        Debug.Log(dataString);
        byte[] data = Encoding.ASCII.GetBytes(dataString);

        yield return null;

        HttpListenerResponse response = context.Response;

        response.ContentType = "text/plain";

        Stream responseStream = response.OutputStream;
        try {
            int count = data.Length;
            int i = 0;
            while (i < count)
            {
                if (i != 0)
                    yield return null;

                int writeLength = Math.Min((int)writeStaggerCount, count - i);
                responseStream.Write(data, i, writeLength);
                i += writeLength;
            }
        }
        finally {
            // Nothing needs to go here, try-finally used to safely fail if a client disconnects mid-write
            // Which doesn't really have any negative consequences
        }
    }
Пример #8
0
    public static T[] FromJson <T>(string json)
    {
        JSONWrapper <T> wrapper = UnityEngine.JsonUtility.FromJson <JSONWrapper <T> >(json);

        return(wrapper.Events);
    }
Пример #9
0
    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        HttpListenerRequest request = context.Request;
        StreamReader reader = new StreamReader(request.InputStream);
        string command = reader.ReadToEnd();
        string dataString = "";

        JSONWrapper j = new JSONWrapper(command);
        string givenCommand = "";
        string user = "";
            try
            {
                givenCommand = j["command"];
                user = j["username"];
                Debug.Log("Receiving command " + givenCommand + " from " + user);
        }
        catch(Exception e)
            {
                Debug.Log(e.Message);
            }
        if (PlayerRegisterRule.PlayerRegister.ContainsKey(user))
        {
            Debug.Log(user + " found, entering command switch");
            CommandPanel cp = PlayerRegisterRule.PlayerRegister[user];
            cp.IsConnected = true;
            switch (givenCommand)
            {
                // for getting the size (and more if needed) of the map, to generate a grid at runtime
                case "GetMapData":
                    if (selectedMap != null)
                    {
                        dataString = JsonUtility.ToJson(selectedMap.ToJSON());
                    }
                    break;

                // for use during charcter select
                case "ChooseCharacter":
                    if(GameStateManager.Instance.GameState == GameState.CharacterSelect)
                    {
                        string charSelected = "";
                        try
                        {
                            charSelected = j["character"];
                            Debug.Log(charSelected);
                        } catch(Exception e)
                        {
                            Debug.Log(e.Message);
                        }

                        // if the character was able to be assigned
                        if(charSelected != "" && charSelectManager != null)
                        {

                               charSelectManager.SelectCharForPlayer(charSelected, cp);

                        }
                    }
                    break;
                case "ToggleReady":
                    if (charSelectManager != null)
                    {
                        cp.IsReady = !cp.IsReady;
                        List<bool> readies = new List<bool>();
                        foreach (CommandPanel r in PlayerRegisterRule.PlayerRegister.Values)
                        {
                            readies.Add(r.IsReady);
                        }
                        if (!readies.Contains(false) && !CharSelectManager.InCountdown)
                        {
                            charSelectManager.StartCoroutine("Countdown");
                        }
                        else if(readies.Contains(false))
                        {
                            charSelectManager.StartCoroutine(charSelectManager.StopCountdown());
                        }
                    }
                    break;

                // commit their movement path and execute a move
                case "CommitMove":
                    if(IsYourTurn(cp))
                    {
                        cp.CommitToMove();
                    }
                    break;

                // select a tile to add to the movement path
                case "SelectTile":
                    if (IsYourTurn(cp))
                    {
                        if (mapGenerator != null)
                        {
                            try
                            {
                                Debug.Log("Processing tile data: {x:" + j["x"] + "," + "z:" + j["z"] + "}");
                                cp.PathSelection(mapGenerator.TileArray[int.Parse(j["x"]), int.Parse(j["z"])]);
                                PathTile p = new PathTile();
                                List<Coordinate> queuedCoords = new List<Coordinate>();
                                foreach (TileBehavior tb in cp.QueuedPath)
                                {
                                    queuedCoords.Add(tb.Coords);
                                }
                                p.path = queuedCoords.ToArray();
                                Debug.Log(JsonUtility.ToJson(p));
                                dataString = JsonUtility.ToJson(p);
                            }
                            catch (Exception e)
                            {
                                Debug.Log(e.Message);
                            }
                        }
                    }
                    break;

                // none of the above
                default:
                    Debug.Log("Command either not parsed or not valid. Given command was: " + givenCommand);
                    break;
            }
        }

        Debug.Log("Sending " + user + ": " + dataString);
        byte[] data = Encoding.ASCII.GetBytes(dataString);

        yield return null;

        HttpListenerResponse response = context.Response;

        response.ContentType = "text/plain";

        Stream responseStream = response.OutputStream;

        int count = data.Length;
        int i = 0;
        while (i < count)
        {
            if (i != 0)
                yield return null;

            int writeLength = Math.Min((int)writeStaggerCount, count - i);
            responseStream.Write(data, i, writeLength);
            i += writeLength;
        }
    }
Пример #10
0
    protected override IEnumerator OnRequest(HttpListenerContext context)
    {
        string dataString = "";

        HttpListenerRequest request = context.Request;
        StreamReader        reader  = new StreamReader(request.InputStream);
        string s = reader.ReadToEnd();

        JSONWrapper  j = new JSONWrapper(s);
        CommandPanel cp;

        try {
            cp = PlayerRegisterRule.PlayerRegister[j["username"]];
            cp.Pulse();
            Alliance playerTeam = cp.Team;

            // List of other players
            List <PlayerJSON> pj = new List <PlayerJSON>();
            foreach (CommandPanel c in PlayerRegisterRule.PlayerRegister.Values)
            {
                pj.Add((PlayerJSON)c.ToJSON());
            }

            // List of characters
            List <CharacterJSON> cj = new List <CharacterJSON>();
            foreach (CharacterBehavior c in FindObjectsOfType <CharacterBehavior>())
            {
                // if you're allies OR you're made visible
                if (c.Team == cp.Team || c.IsVisible)
                {
                    cj.Add((CharacterJSON)c.ToJSON());
                }
            }
            Heartbeat h = new Heartbeat();
            h.state   = GameStateManager.Instance.GameState;
            h.players = pj.ToArray();
            if (cp.Character != null)
            {
                h.myCharacter = (CharacterJSON)cp.Character.ToJSON();
            }
            h.characters = cj.ToArray();

            dataString = JsonUtility.ToJson(h);
        }
        catch (Exception e)
        {
            // Put code here to refresh the web page
            Debug.Log(e.Message);
        }

        Debug.Log(dataString);
        byte[] data = Encoding.ASCII.GetBytes(dataString);

        yield return(null);

        HttpListenerResponse response = context.Response;

        response.ContentType = "text/plain";

        Stream responseStream = response.OutputStream;

        try {
            int count = data.Length;
            int i     = 0;
            while (i < count)
            {
                if (i != 0)
                {
                    yield return(null);
                }

                int writeLength = Math.Min((int)writeStaggerCount, count - i);
                responseStream.Write(data, i, writeLength);
                i += writeLength;
            }
        }
        finally {
            // Nothing needs to go here, try-finally used to safely fail if a client disconnects mid-write
            // Which doesn't really have any negative consequences
        }
    }