示例#1
0
    // Use this for initialization
    void Start()
    {
        Debug.Log(InitialMap);
        JSONDecoder.DecodeMap(InitialMap, Map.Current, out HeroSpawns, out MonsterSpawns, out ObjectiveSpawns);
        SetupSpawnArray();
        SpawnObjectiveObjects();
        Map.Current.LockAllTiles();
        foreach (Tile t in MonsterSpawns)
        {
            t.Locked         = false;
            t.HighlightColor = ValidTileHightlightColor;
            t.Highlighted    = true;
        }

        foreach (Tile t in ObjectiveSpawns)
        {
            t.HighlightOverrideLock = true;
            t.Highlighted           = true;
            t.HighlightColor        = Color.yellow;
        }

        foreach (Tile t in HeroSpawns)
        {
            t.HighlightOverrideLock = true;
            t.Highlighted           = true;
            t.HighlightColor        = Color.red;
        }
    }
示例#2
0
        public void fillFromJSON(JSONDecoder jd)
        {
            Pos = jd.ParseNext((str) =>
            {
                float[] ax = new float[3];
                int a      = 1, b;
                string[] c = { ", ", ", ", ">" };
                for (int i = 0; i < 3; i++)
                {
                    b     = str.IndexOf(c[i], a);
                    ax[i] = float.Parse(str.Substring(a, b - a));
                    a     = b + 2;
                }

                return(new Vector3(ax[0], ax[1], ax[2]));
            });

            Dir = jd.ParseNext((str) =>
            {
                float[] ax = new float[4];
                int a      = 3, b;
                string[] c = { " Y:", " Z:", " W:", "}" };
                for (int i = 0; i < 3; i++)
                {
                    b     = str.IndexOf(c[i], a);
                    ax[i] = float.Parse(str.Substring(a, b - a));
                    a     = b + 3;
                }

                return(new Quaternion(ax[0], ax[1], ax[2], ax[3]));
            });
        }
 private void MonstersCallback(JSONObject response)
 {
     Debug.Log(response);
     if (response.list[0].GetField("status").n == 200)
     {
         collection = JSONDecoder.DecodeMonsterCards(response.list[0].GetField("monsters"));
         makeButtons();
         OnAll(true);
     }
 }
示例#4
0
        public void Float()
        {
            Assert.AreEqual("0", EncodeSimple(e => e.WriteNumber(0.0f)));
            Assert.AreEqual("1.5", EncodeSimple(e => e.WriteNumber(1.5f)));
            Assert.AreEqual("1000000", EncodeSimple(e => e.WriteNumber(1.0e6f)));
            Assert.AreEqual("-1000000", EncodeSimple(e => e.WriteNumber(-1.0e6f)));

            Assert.AreEqual(10.68728f, JSONDecoder.Decode(EncodeSimple(e => e.WriteNumber(10.68728f))).FloatValue);
            Assert.AreEqual(-10.68728f, JSONDecoder.Decode(EncodeSimple(e => e.WriteNumber(-10.68728f))).FloatValue);
        }
示例#5
0
        private Packet(string json)
        {
            JSONDecoder jd = new JSONDecoder(json);

            Key = new PacketKey();
            Key.fillFromJSON(jd);

            Data = new ComData("");
            jd.SkipLine();
            Data.fillFromJSON(jd);
        }
示例#6
0
 public void fillFromJSON(JSONDecoder jd)
 {
     //jd.SkipLine();
     DataType = jd.ParseNext((s) => { return(s.Substring(1, s.Length - 2)); });
     if (DataType.StartsWith(PRIM))
     {
         Value = null;
         return;
     }
     else
     {
         RawValue = jd;
     }
 }
示例#7
0
        public void fillFromJSON(JSONDecoder jd)
        {
            jd.SkipLine();

            Cursor = new ArmCursor();
            Cursor.fillFromJSON(jd);
            jd.SkipLine();
            Time = jd.ParseNext((str) =>
            {
                float f;
                float.TryParse(str, out f);
                return(f);
            });
        }
示例#8
0
        public bool TryParse <T>(ref T container)
        {
            JSONDecoder jd = RawValue.Clone();

            try
            {
                IJSONable raw = (IJSONable)container;
                raw.fillFromJSON(jd);
                container = (T)raw;
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#9
0
        void testBad()
        {
            printName("test bad input");

            string test = File.ReadAllText(@"C:\workspace\CSharp\AutomationHub\Tests.cs\bad.txt");

            try
            {
                JSONDecoder jd = new JSONDecoder(test);
            }catch (InvalidDataException)
            {
                return; //pass
            }

            Console.WriteLine("FAIL");
        }
    void Start()
    {
        if (GameManager.instance != null && MatchState != null)
        {
            if (instance != null)
            {
                Debug.LogError("Something went wrong in match singleton creation");
                Destroy(this);
                return;
            }
            else
            {
                MatchManager.instance = this;
            }
            queuedPackets   = new Dictionary <int, JSONObject>();
            socket          = GameManager.instance.getSocket();
            MatchIdentifier = MatchState.GetField("match_identifier").str;
            HeroPlayer      = MatchState.GetField("players").GetField("heroes").str;
            ArchitectPlayer = MatchState.GetField("players").GetField("architect").str;

            UpdatePlayers(MatchState);

            string gstate = MatchState["game_state"].str;
            if ("hero_turn".Equals(gstate))
            {
                gameState = GameState.HeroTurn;
            }
            else if ("architect_turn".Equals(gstate))
            {
                gameState = GameState.ArchitectTurn;
            }

            TurnNumber = (int)MatchState["turn_number"].n;
            RegisterJSONChangeAction("/turn_number", UpdateTurn);
            RegisterJSONChangeAction("/game_state", UpdateGameState);

            JSONDecoder.DecodeMap(MatchState.GetField("map"), Map.Current);
            JSONDecoder.DecodeMapObjects(MatchState.GetField("board_objects"), manager);
            socket.On("game_update", GameUpdate);
        }
        else
        {
            Debug.LogError("You got in here without a game manager or match start data! How did you do that!");
            Destroy(this.gameObject);
        }
    }
示例#11
0
        public static void Init()
        {
            try
            {
                WebRequest request =
                    WebRequest.Create(
                        "https://raw.githubusercontent.com/sokcuri/TwimgSpeedPatch/master/data/server_ip.json");
                request.Method = "GET";
                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        StreamReader reader         = new StreamReader(stream, Encoding.UTF8);
                        String       responseString = reader.ReadToEnd();

                        try
                        {
                            TwImgNodeIPs = JSONDecoder.Decode(responseString);
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show("JSON Decode를 실패했습니다: " + e.Message, "오류", MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                            Environment.Exit(1);
                        }

                        for (int i = 0; i < TwImgNodeIPs.Count; i++)
                        {
                            if (TwImgNodeIPs[i].StringValue == "")
                            {
                                MessageBox.Show($"정상적인 ip가 아닙니다. i: {i}, value: {TwImgNodeIPs[i].StringValue}", "오류", MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                                Environment.Exit(3);
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                MessageBox.Show("트위터 노드 서버 정보를 가져올 수 없습니다. 인터넷 연결을 확인한 후 다시 시도해주세요: " + ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(2);
            }
        }
示例#12
0
        public static Packet unPack(string s)
        {
            int    a      = s.Length - s.Replace("{", "").Replace("[", "").Length;
            int    b      = s.Length - s.Replace("}", "").Replace("]", "").Length;
            string checkS = s.Replace(Environment.NewLine, "").Trim();

            if (a != b || !checkS.Substring(0, 1).Equals("{") || !checkS.Substring(checkS.Length - 3, 1).Equals("}") ||
                !checkS.Contains("flavour") || !checkS.Contains("key"))
            {
                Console.WriteLine("Packet: invalid string");
                Console.WriteLine(s);
                Console.WriteLine("-- end print --");
                Console.WriteLine(checkS.Substring(checkS.Length - 2, 1).ToCharArray()[0]);
                //Console.WriteLine(checkS.Substring(checkS.Length - 3, 1));
                //Console.WriteLine("a: {0}, b: {1}", a, b);
                throw new InvalidDataException();
            }

            Flavour   f;
            PacketKey k = new PacketKey();
            ComData   d = new ComData();

            JSONDecoder jd = new JSONDecoder(s);

            jd.beginItem();

            string flav = jd.getField()[1].Trim();

            f = (Flavour)Enum.Parse(typeof(Flavour), flav);

            jd.getField();  // key
            k.fillFromJSON(jd);

            if (f != Flavour.ECHO)
            {
                jd.getField();  // data
                d.fillFromJSON(jd);
            }

            jd.endItem();

            return(new Packet(f, k, d));
        }
        public void TestJsonArrayJSONDecoder()
        {
            var pipeline  = PipelineFactory.CreateEmptyReceivePipeline();
            var component = new JSONDecoder {
                ArrayNodeName     = "Event",
                RootNode          = "Events",
                RootNodeNamespace = "Http://JsonDecoderTester/TestEvents"
            };

            pipeline.AddComponent(component, PipelineStage.Decode);
            var message = MessageHelper.CreateFromStream(TestHelper.GetTestStream("large.json"));
            var output  = pipeline.Execute(message);
            var retstr  = MessageHelper.ReadString(output[0]);
            var doc     = new XmlDocument();

            doc.LoadXml(retstr);
            var arr = doc.SelectNodes("/*[local-name()='Events']/*[local-name()='Event']");

            Assert.AreEqual(arr.Count, doc.DocumentElement.ChildNodes.Count);
        }
示例#14
0
 private void ListMaps(JSONObject response)
 {
     Debug.Log(response.list[0]);
     if (response.list[0].GetField("status").n == 200)
     {
         MapSelect.ClearOptions();
         mapSelectPosition.Clear();
         List <MapMetadata> maps = JSONDecoder.DecodeMapMetadata(response.list[0].GetField("maps"));
         for (int i = 0; i < maps.Count; i++)
         {
             MapSelect.options.Add(new Dropdown.OptionData()
             {
                 text = maps[i].Name
             });
             mapSelectPosition[i] = maps[i];
         }
         MapSelect.value = 1;
         MapSelect.value = 0;
     }
 }
示例#15
0
    private void SetupHeroCards(JSONObject heroes)
    {
        List <HeroCardData> cards = JSONDecoder.DecodeHeroCards(heroes);
        int heroesAdded           = 0;

        ClearDisplay();
        foreach (HeroCardData card in cards)
        {
            GameObject UICard = Instantiate(CardPrefab);
            UICard.transform.SetParent(HeroScrollContent.transform);
            //UICard.transform.localPosition= new Vector3(cardDist * (heroesAdded + 1) + UICard.transform.right.x * heroesAdded, cardDist, 0);
            RectTransform rt = (RectTransform)UICard.transform;
            calcRect(ref rt, heroesAdded);

            Transform title = rt.Find("Title");
            title.gameObject.GetComponent <Text>().text = card.Name;
            Transform description = rt.Find("Description");
            description.gameObject.GetComponent <Text>().text = "Level: " + card.level;
            UICard.GetComponent <HeroCardData>().init(card.Name, card.ownerID, card.UUID, card.health, card.attack, card.defense, card.vision, card.movement, card.actionPoints, card.Weapon, card.level);
            UICard.GetComponent <Button>().onClick.AddListener(delegate { toggleHeroCard(UICard); });
            heroesAdded++;
        }
    }
        private static string CreateCommand(string descriptorJson)
        {
            JObject desc = JSONDecoder.Decode(descriptorJson);

            // Item name
            if (!desc.ObjectValue.ContainsKey("name"))
            {
                throw new DescriptorException("Item 'name' was not found. Make sure your current document has a valid item descriptor in it.");
            }
            string name = desc["name"].StringValue;

            // Item count
            int count = 1;

            if (desc.ObjectValue.ContainsKey("count"))
            {
                count = (int)desc["count"];
            }

            // Base command
            StringBuilder command = new StringBuilder();

            command.AppendFormat("/spawnitem {0} {1}", name, count);

            // Item Parameters
            if (desc.ObjectValue.ContainsKey("parameters"))
            {
                JObject parameters  = desc["parameters"];
                string  sParameters = JSONEncoder.Encode(parameters);

                // Add parameters to command
                command.AppendFormat(" '{0}'", sParameters.Replace("'", "\\'"));
            }

            return(command.ToString());
        }
示例#17
0
 public void fillFromJSON(JSONDecoder jd)
 {
     jd.beginItem();
     value = long.Parse(jd.getField()[1]);
     jd.endItem();
 }
示例#18
0
 public void fillFromJSON(JSONDecoder jd)
 {
     value = jd.ParseNext(long.Parse);
 }
示例#19
0
 private static JObject DecodeJSON(string json)
 {
     return(JSONDecoder.Decode(json));
 }
示例#20
0
 public void fillFromJSON(JSONDecoder jd)
 {
     throw new NotImplementedException();
 }
示例#21
0
文件: core.cs 项目: willardf/Be-Me
        /// This handles the actual transactions with the Newgrounds.io server. This runs as a Coroutine in Unity.
        private IEnumerator _executeCallList(SimpleJSONImportableList call_list)
        {
            objects.input input = new objects.input();
            input.app_id = app_id;

            if (!string.IsNullOrEmpty(session_id))
            {
                input.session_id = session_id;
            }

            SimpleJSONImportableList calls = new SimpleJSONImportableList(typeof(objects.call));

            objects.call vc;
            CallModel    cm;
            ResultModel  vr;

            for (int c = 0; c < call_list.Count; c++)
            {
                vc = (objects.call)call_list[c];
                cm = CallModel.getByComponentName(vc.component);

                if (cm.require_session && string.IsNullOrEmpty(session_id))
                {
                    vr = (ResultModel)ResultModel.getByComponentName(vc.component);

                    vr.setIsLocal(true);
                    vr.setCall(vc);
                    vr.component     = vc.component;
                    vr.success       = false;
                    vr.error.message = vc.component + " requires a valid user session.";
                    vr.ngio_core     = this;

                    debug_log("Call failed local validation:\n" + vc.toJSON());
                    debug_log("Local Response:\n" + vr.toJSON());

                    if (vc.callback != null)
                    {
                        vc.callback(vr);
                    }

                    vr.dispatchMe(vc.component);
                    continue;
                }
                else
                {
                    calls.Add(vc);
                }
            }

            if (calls.Count > 0)
            {
                input.call = calls;
                string json = input.toJSON();
                debug_log("Sent to Server:\n" + json);

                WWWForm webform = new WWWForm();
                webform.AddField("input", json);

                WWW json_results = new WWW(GATEWAY_URI, webform);

                yield return(json_results);

                debug_log("Server Response:\n" + json_results.text);

                // hopefully, our results will populate to this
                objects.output _output = new objects.output();

                string default_error = "There was a problem connecting to the server at '" + GATEWAY_URI + "'.";

                // we'll try decoding what the server sent back.  If it's valid JSON there should be no problems
                try
                {
                    // decode the overall response
                    JObject jobject = JSONDecoder.Decode(json_results.text);

                    // populate the basic info our output model will need to proceed
                    if (jobject.Kind == JObjectKind.Object)
                    {
                        _output.setPropertiesFromSimpleJSON(jobject);
                    }
                }
                // catch any exceptions and update the generic error message we'll spit back.
                catch (Exception e)
                {
                    Debug.LogWarning("Caught an exception decoding the data:\n" + e.Message);
                    default_error = e.Message;
                }

                _output.ngio_core = this;

                // We'll typically only get here if the was a server or connection error.
                if (_output.success != true && _output.error == null)
                {
                    _output.error         = new objects.error();
                    _output.error.message = default_error;
                }

                // cheap way to fill debug info even with debug mode being off
                _output.debug.input = input;

                ResultModel    _rm;
                objects.result _result;
                objects.call   call;

                for (int i = 0; i < calls.Count; i++)
                {
                    call = (objects.call)calls[i];

                    if (_output.success != true)
                    {
                        _rm       = new ResultModel();
                        _rm.error = _output.error;
                    }
                    else if (_output.result.GetType() == typeof(SimpleJSONImportableList) && ((SimpleJSONImportableList)_output.result).ElementAtOrDefault <object>(i) != null)
                    {
                        _result           = (objects.result)((SimpleJSONImportableList)_output.result)[i];
                        _result.ngio_core = this;

                        if (_result.component != call.component)
                        {
                            _rm               = new ResultModel();
                            _rm.success       = false;
                            _rm.error.message = "Unexpected index mismatch in API response!";
                        }
                        else
                        {
                            _rm = (ResultModel)_result.data;
                        }
                    }
                    else
                    {
                        _rm               = new ResultModel();
                        _rm.success       = false;
                        _rm.error.message = "Unexpected index mismatch in API response!";
                    }

                    _rm.ngio_core = this;
                    _rm.setCall(call);

                    if (call.callback != null)
                    {
                        call.callback(_rm);
                    }

                    _rm.dispatchMe(call.component);
                }
            }
        }