public override void onDataChange(DataSnapshot dataSnapshot)
			{
				if (outerInstance.mDrawingView != null)
				{
					((ViewGroup) outerInstance.mDrawingView.Parent).removeView(outerInstance.mDrawingView);
					outerInstance.mDrawingView.cleanup();
					outerInstance.mDrawingView = null;
				}
				IDictionary<string, object> boardValues = (IDictionary<string, object>) dataSnapshot.Value;
				if (boardValues != null && boardValues["width"] != null && boardValues["height"] != null)
				{
					outerInstance.mBoardWidth = ((long?) boardValues["width"]).intValue();
					outerInstance.mBoardHeight = ((long?) boardValues["height"]).intValue();

					outerInstance.mDrawingView = new DrawingView(outerInstance, outerInstance.mFirebaseRef.child("boardsegments").child(boardId), outerInstance.mBoardWidth, outerInstance.mBoardHeight);
					ContentView = outerInstance.mDrawingView;
				}
			}
    private void updateModel(DataSnapshot snapshot)
    {
        Mesh m = parametricModel.GetComponent <MeshFilter>().mesh;

        m.Clear();


        Vector3[] vertices = new Vector3[snapshot.Child("vertices").ChildrenCount];
        Color[]   colors   = new Color[snapshot.Child("vertices").ChildrenCount];
        Vector3[] normals  = new Vector3[snapshot.Child("vertices").ChildrenCount];

        int i = 0;

        while (i < vertices.Length)
        {
            DataSnapshot v = snapshot.Child("vertices").Child(i.ToString());
            vertices[i].x = Convert.ToSingle((v.Child("x").Value));
            vertices[i].y = Convert.ToSingle((v.Child("y").Value));
            vertices[i].z = Convert.ToSingle((v.Child("z").Value));

            DataSnapshot n = snapshot.Child("normals").Child(i.ToString());
            normals[i].x = Convert.ToSingle((n.Child("x").Value));
            normals[i].y = Convert.ToSingle((n.Child("y").Value));
            normals[i].z = Convert.ToSingle((n.Child("z").Value));

            DataSnapshot c = snapshot.Child("colors").Child(i.ToString());
            colors[i]   = new Color();
            colors[i].r = float.Parse(c.Child("r").Value.ToString()) / (float)255.0;
            colors[i].g = float.Parse(c.Child("g").Value.ToString()) / (float)255.0;
            colors[i].b = float.Parse(c.Child("b").Value.ToString()) / (float)255.0;

            //Grasshopper serves alpha from 0 to 255
            colors[i].a = float.Parse(c.Child("a").Value.ToString()) / (float)255.0;

            i++;
        }

        int k = 0;

        int[] triangles = new int[snapshot.Child("faces").ChildrenCount * 3];
        while (k < triangles.Length / 3)
        {
            DataSnapshot f = snapshot.Child("faces").Child(k.ToString());
            int          A = -1;
            int          B = -1;
            int          C = -1;
            Int32.TryParse(f.Child("a").Value.ToString(), out A);
            Int32.TryParse(f.Child("b").Value.ToString(), out B);
            Int32.TryParse(f.Child("c").Value.ToString(), out C);
            int j = k * 3;

            // Unity's faces are arranged clockwise and Grasshoppers are counter-clockwise, so we must re-arrange here
            triangles[j]     = A;
            triangles[j + 1] = B;
            triangles[j + 2] = C;
            k++;
        }
        m.vertices  = vertices;
        m.normals   = normals;
        m.colors    = colors;
        m.triangles = triangles;
        m.RecalculateNormals();
        m.RecalculateBounds();
        Camera.main.Render();
    }
    void Start()
    {
        musicTitleUI.text = PlayerInformation.musicTitle;
        scoreUI.text      = "점수: " + (int)PlayerInformation.score;
        maxComboUI.text   = "최대 콤보: " + PlayerInformation.maxCombo;
        //리소스에서 비트(Beat) 텍스트 파일을 불러옵니다.
        TextAsset    textAsset = Resources.Load <TextAsset>("Beats/" + PlayerInformation.selectedMusic);
        StringReader reader    = new StringReader(textAsset.text);

        //첫 번째 줄과 두 번째 줄을 무시합니다.
        reader.ReadLine();
        reader.ReadLine();
        //세 번째 줄에 적힌 비트 정보 (S 랭크 점수, A 랭크 점수, B 랭크 점수)를 읽습니다.
        string beatInformation = reader.ReadLine();
        int    scoreS          = Convert.ToInt32(beatInformation.Split(' ')[3]);
        int    scoreA          = Convert.ToInt32(beatInformation.Split(' ')[4]);
        int    scoreB          = Convert.ToInt32(beatInformation.Split(' ')[5]);

        //성적에 맞는 랭크 이미지를 불러옵니다.
        if (PlayerInformation.score >= scoreS)
        {
            RankUI.sprite = Resources.Load <Sprite>("Sprites/Rank S");
        }
        else if (PlayerInformation.score >= scoreA)
        {
            RankUI.sprite = Resources.Load <Sprite>("Sprites/Rank A");
        }
        else if (PlayerInformation.score >= scoreB)
        {
            RankUI.sprite = Resources.Load <Sprite>("Sprites/Rank B");
        }
        else
        {
            RankUI.sprite = Resources.Load <Sprite>("Sprites/Rank C");
        }

        rank1UI.text = "데이터를 불러오는 중입니다.";
        rank2UI.text = "데이터를 불러오는 중입니다.";
        rank3UI.text = "데이터를 불러오는 중입니다.";

        DatabaseReference reference = PlayerInformation.GetDatabaseReference().Child("ranks")
                                      .Child(PlayerInformation.selectedMusic);

        //데이터 셋의 모든 데이터를 JSON 형태로 가져옵니다.
        reference.OrderByChild("socre").GetValueAsync().ContinueWith(task =>
        {
            //성공적으로 데이터를 가져온 경우
            if (task.IsCompleted)
            {
                List <string> rankList  = new List <string>();
                List <string> emailList = new List <string>();
                DataSnapshot snapshot   = task.Result;

                //JSON 데이터의 각 원소에 접근합니다.
                foreach (DataSnapshot data in snapshot.Children)
                {
                    IDictionary rank = (IDictionary)data.Value;
                    emailList.Add(rank["email"].ToString());
                    rankList.Add(rank["score"].ToString());
                }
                //정렬 이후 순서를 뒤집어 내림차순 정렬합니다.
                emailList.Reverse();
                rankList.Reverse();
                //최대 상위 3명의 순위를 차례대로 화면에 출력합니다.
                rank1UI.text         = "플레이 한 사용자가 없습니다.";
                rank2UI.text         = "플레이 한 사용자가 없습니다.";
                rank3UI.text         = "플레이 한 사용자가 없습니다.";
                List <Text> textList = new List <Text>();
                textList.Add(rank1UI);
                textList.Add(rank2UI);
                textList.Add(rank3UI);
                int count = 1;
                for (int i = 0; i < rankList.Count && i < 3; i++)
                {
                    textList[i].text = count + "위: " + emailList[i] + " (" + rankList[i] + " 점)";
                    count            = count + 1;
                }
            }
        });
    }
Beispiel #4
0
    private static void OnRoomChange(object Sender, ValueChangedEventArgs Argument)
    {
        DataSnapshot Room = Argument.Snapshot;

        if (Room.Children.Any())
        {
            if (ConnectionStep < 4 && ConnectionStep != 3.5)
            {
                Debug.Log("Step: 3.5 - Waiting in room");

                ConnectionStep = 3.5;
                ConnectionStepChange?.Invoke();
            }
            else if (ConnectionStep < 5 && ConnectionStep != 4.3)
            {
                Debug.Log("Step: 4.3 - Waiting in room");

                ConnectionStep = 4.3;
                ConnectionStepChange?.Invoke();
            }

            if (!(ConnectionStep != 5))
            {
                if (Room.Children.Count() < RoomCapacity)
                {
                    Disconnect();
                }
                else
                {
                    Collect(Room);
                }
            }
            else if (!(Room.Children.Count() != RoomCapacity))
            {
                Collect(Room);

                Debug.Log("Step: 5.0 - Ready");

                ConnectionStep = 5.0;
                ConnectionStepChange?.Invoke();
            }
        }
        else
        {
            Debug.Log("Step: 4.1 - Checking lobby");

            ConnectionStep = 4.1;
            ConnectionStepChange?.Invoke();

            BaseReference.Child("Lobby").GetValueAsync().ContinueWith(Task =>
            {
                if (Task.IsFaulted)
                {
                    return;
                }

                DataSnapshot Lobby = Task.Result;

                foreach (KeyValuePair <string, string> Data in MyData)
                {
                    BaseTracking.Child(MyName).Child(Data.Key).SetValueAsync(Data.Value);
                }

                for (int i = 1; i < RoomCapacity; i++)
                {
                    string LastName = Lobby.Children.ElementAt(Lobby.Children.Count() - i).Key;

                    foreach (DataSnapshot Data in Lobby.Child(LastName).Children)
                    {
                        BaseTracking.Child(LastName).Child(Data.Key).SetValueAsync(Data.Value);
                    }

                    Debug.Log($"Step: 4.2 - Inviting {LastName}");

                    ConnectionStep = 4.2;
                    ConnectionStepChange?.Invoke();

                    BaseReference.Child("Lobby").Child(LastName).SetValueAsync(null);
                }
            });
        }
    }
Beispiel #5
0
    private void InitMission()
    {
        showLoading();
        Debug.Log("Start init misson");
        MissionManager.instance.InitMission();
        DatabaseReference missionRef = reference.Child("User").Child(PlayerPrefs.GetString("uid")).Child("Missions");

        //missionRef.
        missionRef.GetValueAsync().ContinueWith(task =>
        {
            if (task.IsCanceled || task.IsFaulted)
            {
                Debug.Log("Get missoon error");
            }
            else if (task.IsCompleted)
            {
                Debug.Log("Get missoon complete");
                DataSnapshot snapshot = task.Result;
                for (int i = 0; i < MissionManager.instance.missionList.Count; i++)
                {
                    int j = i;
                    DataSnapshot missionSnapshot = snapshot.Child(j.ToString());
                    bool isComplete = (bool)missionSnapshot.Child("Complete").Value;
                    bool isReceive  = (bool)missionSnapshot.Child("Receive").Value;
                    if (j <= 2)
                    {
                        //pass misson
                        ((PassAreaMission)MissionManager.instance.missionList[j]).isComplete = isComplete;
                        ((PassAreaMission)MissionManager.instance.missionList[j]).isReceive  = isReceive;
                        Debug.Log("Pass Area Mission " + j + isComplete + " " + isReceive);
                    }
                    else
                    {
                        //kill mission
                        int process = System.Int32.Parse(missionSnapshot.Child("Process").Value.ToString());
                        ((KillMission)MissionManager.instance.missionList[j]).isComplete = isComplete;
                        ((KillMission)MissionManager.instance.missionList[j]).isReceive  = isReceive;
                        ((KillMission)MissionManager.instance.missionList[j]).process    = process;
                        Debug.Log("Kill Mission " + j + isComplete + " " + isReceive + " " + process);
                    }
                }
                disableLoading();
            }
        });


        //for (int i = 0; i < MissionManager.instance.missionList.Count; i++)
        //{
        //    int j = i;
        //    missionRef.Child(j.ToString()).GetValueAsync().ContinueWith(task =>
        //    {
        //        if (task.IsCanceled || task.IsFaulted)
        //        {
        //            Debug.Log("Get missoon " + j + " error");
        //        }
        //        else if (task.IsCompleted)
        //        {
        //            Debug.Log("Get missoon " + j + " complete");
        //            DataSnapshot snapshot = task.Result;
        //            bool isComplete = (bool)snapshot.Child("Complete").Value;
        //            bool isReceive = (bool)snapshot.Child("Receive").Value;
        //            if (j <= 2)
        //            {
        //                //pass misson
        //                ((PassAreaMission)MissionManager.instance.missionList[j]).isComplete = isComplete;
        //                ((PassAreaMission)MissionManager.instance.missionList[j]).isReceive = isReceive;
        //                Debug.Log("Pass Area Mission " + j + isComplete + " " + isReceive);
        //            } else
        //            {
        //                //kill mission
        //                int process = System.Int32.Parse(snapshot.Child("Process").Value.ToString());
        //                ((KillMission)MissionManager.instance.missionList[j]).isComplete = isComplete;
        //                ((KillMission)MissionManager.instance.missionList[j]).isReceive = isReceive;
        //                ((KillMission)MissionManager.instance.missionList[j]).process = process;
        //                Debug.Log("Kill Mission " + j + isComplete + " " + isReceive + " " + process);
        //            }
        //        }
        //    });
        //}
    }
Beispiel #6
0
    public async void Signup(string username, string password, string re_password, string email)
    {
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(re_password) || string.IsNullOrEmpty(email))
        {
            ErrorText.text = "Empty Values";
            return;
        }

        if (password != re_password)
        {
            ErrorText.text = "Passwords do not match";
            return;
        }

        if (password.Length != 12)
        {
            ErrorText.text = "Password must have 12 characters";
            return;
        }

        Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        Match match = regex.Match(email);

        if (!match.Success)
        {
            ErrorText.text = "Invalid Email Format";
            return;
        }

        ErrorText.text = "";

        await dbInstance.GetReference("users").GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                foreach (DataSnapshot user in snapshot.Children)
                {
                    IDictionary dictUser = (IDictionary)user.Value;
                    if (dictUser["username"].ToString() == username)
                    {
                        uname = true;
                        break;
                    }
                    if (dictUser["email"].ToString() == email)
                    {
                        mail = true;
                        break;
                    }
                }
            }
        });


        if (uname)
        {
            ErrorText.text = "Username Already Exists";
            return;
        }

        if (mail)
        {
            ErrorText.text = "Email Already in the System";
        }

        User   new_user = new User(username, email, password, 0, 0, "none", "none", "none");
        string json     = JsonUtility.ToJson(new_user);
        await reference.Child("users").Push().SetRawJsonValueAsync(json);

        just_created = true;
        Login(username, password);
    }
			public override void onChildMoved(DataSnapshot dataSnapshot, string s)
			{
				string key = dataSnapshot.Key;
				OfficeThing existingThing = dataSnapshot.getValue(typeof(OfficeThing));

				Log.v(TAG, "Thing moved " + existingThing);

				outerInstance.addUpdateThingToLocalModel(key, existingThing);
			}
					/// <param name="dataSnapshot"> The data we need to construct a new Segment </param>
					/// <param name="previousChildName"> Supplied for ordering, but we don't really care about ordering in this app </param>
			public override void onChildAdded(DataSnapshot dataSnapshot, string previousChildName)
			{
				string name = dataSnapshot.Key;
				// To prevent lag, we draw our own segments as they are created. As a result, we need to check to make
				// sure this event is a segment drawn by another user before we draw it
				if (!outerInstance.mOutstandingSegments.Contains(name))
				{
					// Deserialize the data into our Segment class
					Segment segment = dataSnapshot.getValue(typeof(Segment));
					outerInstance.drawSegment(segment, paintFromColor(segment.Color));
					// Tell the view to redraw itself
					invalidate();
				}
			}
Beispiel #9
0
    }//After Check That Internet Connection.

    IEnumerator LoadPuzzles()
    {
        loadPuzzle = false;
        loadAll    = false;

        float time = 0;

        while (time < 5f)
        {
            if (NetworkConnectionChecker.instance.success == true)
            {
                List <DataBase.Puzzle> tempPuzzleList = new List <DataBase.Puzzle>();
                #region LoadPuzzleDB_Firebase
                FirebaseDatabase.DefaultInstance.GetReference("Puzzles").GetValueAsync().ContinueWith
                (
                    task =>
                {
                    if (task.IsFaulted)
                    {
                        Debug.Log("Puzzle, Handle the error");
                    }   // Handle the error...
                    else if (task.IsCompleted)
                    {
                        Debug.Log("Puzzle, TaskComplite");
                        DataSnapshot snapshot = task.Result;

                        #region tempPuzzleList
                        for (int i = 1; i < snapshot.ChildrenCount; i++)
                        {
                            DataBase.Puzzle tempPuzzle = new DataBase.Puzzle();
                            string i_ = i.ToString();

                            tempPuzzle.id            = snapshot.Child(i_).Child("0").GetValue(true).ToString();
                            tempPuzzle.name          = snapshot.Child(i_).Child("1").GetValue(true).ToString();
                            tempPuzzle.size          = System.Convert.ToInt32(snapshot.Child(i_).Child("2").GetValue(true));
                            tempPuzzle.useSpriteNum1 = System.Convert.ToInt32(snapshot.Child(i_).Child("3").GetValue(true));
                            tempPuzzle.useSpriteNum2 = System.Convert.ToInt32(snapshot.Child(i_).Child("4").GetValue(true));
                            tempPuzzle.type          = snapshot.Child(i_).Child("5").GetValue(true).ToString();
                            tempPuzzle.spawnCount    = System.Convert.ToInt32(snapshot.Child(i_).Child("6").GetValue(true));
                            tempPuzzle.maxCount      = System.Convert.ToInt32(snapshot.Child(i_).Child("7").GetValue(true));

                            tempPuzzleList.Add(tempPuzzle);
                        }  //칼럼 제외 이유로 i = 1 부터 시작.
                        #endregion

                        List <DataBase.Puzzle[]> puzzleList = new List <DataBase.Puzzle[]>(); //tempPuzzleList의 것을 Land 별로 옮겨담을 곳.

                        #region puzzleList
                        int targetPuzzleListNum = 1;
                        int puzzleCount         = tempPuzzleList.Count;

                        while (puzzleCount > 0)
                        {
                            #region tempBaseSetting
                            List <DataBase.Puzzle> tempTempPuzzleList = new List <DataBase.Puzzle>(); //tempPuzzleList의 Puzzle을 Land순서별로 담는다.
                            List <int> tempTempNum = new List <int>();                                //tempTempPuzzleList의 퍼즐을 가져올때 사용할 int
                            #endregion
                            for (int i = 0; i < tempPuzzleList.Count; i++)
                            {
                                string targetPuzzleListStr = targetPuzzleListNum < 10 ? "0" + targetPuzzleListNum : targetPuzzleListNum.ToString();
                                if (targetPuzzleListStr == HarimTool.EditValue.EditText.Left(tempPuzzleList[i].id, 2))
                                {
                                    tempTempPuzzleList.Add(tempPuzzleList[i]);
                                    tempTempNum.Add(i);
                                    puzzleCount--;
                                } //Debug.Log(targetPuzzleListStr +", "+ puzzleCount);
                            }     //Land가 같은 것 끼리 모음.1번 Land부터 시작.
                            DataBase.Puzzle[] tempPuzzleArr = new DataBase.Puzzle[tempTempPuzzleList.Count];
                            for (int i = 0; i < tempTempPuzzleList.Count; i++)
                            {
                                tempPuzzleArr[i] = tempTempPuzzleList[i];
                            }  //PuzzleList에 순차적으로 Puzzle들을 담기 위해 List를 Array로 만든다.
                            puzzleList.Add(tempPuzzleArr);
                            tempTempPuzzleList.Clear();
                            tempTempNum.Clear();
                            targetPuzzleListNum++;
                        }
                        #endregion

                        #region PuzzleManager.puzzles
                        PuzzleManager.instance.puzzles = new DataBase.Puzzle[puzzleList.Count][];// [landCount][puzzleCount]
                        for (int i = 0; i < puzzleList.Count; i++)
                        {
                            for (int j = 0; j < puzzleList[i].Length; j++)
                            {
                                Array.Sort(puzzleList[i], delegate(DataBase.Puzzle a, DataBase.Puzzle b)
                                {
                                    return(a.id.CompareTo(b.id));
                                });  //퍼즐 ID를 순서대로 정렬
                            }
                            PuzzleManager.instance.puzzles[i] = puzzleList[i];
                        }
                        #endregion

                        loadPuzzle = true;
                        SaveDB_Local();
                        Debug.Log("Kind of Puzzle : Land Count : " + PuzzleManager.instance.puzzles.Length);
                        // Debug.Log(snapshot.Child("1").Child("0").GetValue(true));
                    }
                }
                );
                #endregion
                if (loadPuzzle == true)
                {
                    break;
                }
            }
            else
            {
                if (LoadDB_Local() == true)
                {
                    loadPuzzle = true;
                    Debug.Log("Load_LocalDB");
                }
                else
                {
                    Debug.Log("Network_Error");
                }
            }
            yield return(new WaitForSeconds(0.05f));

            time += 0.02f;
        }
        Debug.Log("NeedMoreTime_LoadPuzzleDB");
    }//After Check That Internet Connection.
Beispiel #10
0
    public async void GetQuestions()
    {
        string RootName = "StageNames/World" + currentWorld + "/Stage" + currentStage + "/Difficulty/" + currentDiff + "/Questions";

        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://cz3003-waffles.firebaseio.com/");
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
        await FirebaseDatabase.DefaultInstance.GetReference(RootName).GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                snapshot = null;
                Debug.Log("Error encountered, check input parameters");
                // Handle the error...
            }
            else if (task.IsCompleted)
            {     // Do something with snapshot...
                this.snapshot = task.Result;
                Debug.Log("Finally fetched snapshot " + RootName);
            }
        });

        //GetSnapshotFromDatabase("StageNames/World0/Stage1/Difficulty/1/Questions/What Is Software Engineering/1");
        Debug.Log("3");
        //DataSnapshot rootSnapshot = GetSnapshot();

        string[] temp  = new string[5];
        int      temp1 = 0;

        if (childcount == 0)
        {
            foreach (DataSnapshot a in snapshot.Children)
            {
                childcount++;
            }

            Debug.Log("childcount if childcount = 0 = " + childcount);
        }

        //int temp2 = Random.Range(0,snapshot.Children.getChildrenCount());
        Debug.Log("childcount = " + childcount);

        int temp2 = getRand(childcount);

        Debug.Log(temp2);
        int i = 0;

        foreach (DataSnapshot a in snapshot.Children)
        {
            i++;
            Debug.Log(a.Key.ToString());
            if (i == temp2)
            {
                QuestionField.text = a.Key.ToString();
                foreach (var s in a.Children)
                {
                    //IDictionary dictUsers = (IDictionary)s.Value;
                    temp[temp1] = s.Value.ToString();
                    Debug.Log(temp[temp1]);
                    temp1++;
                }
                break;
            }
        }
        Option1.text = temp[0];
        Option2.text = temp[1];
        Option3.text = temp[2];
        Option4.text = temp[3];
        correctAns   = int.Parse(temp[4]);

        //Debug.Log(snapshot.Value.ToString());
        //foreach(var s in rootSnapshot.Children){
        //IDictionary dictUsers = (IDictionary)s.Value;
        //Debug.Log(s.Value.ToString());
        //}
    }
Beispiel #11
0
    public async void updateProgress()
    {
        //string scoreText =score+'/'+scoreCheck;
        //ScoreText.text=score.ToString()+'/'+scoreCheck.ToString();
        //double total = (double)((double)score / scoreCheck);
        //userToken = "0nVjQmDgZtcSG0tvkLZ5saGeTd";
        Debug.Log("update called");
        userToken = "0nVjQmDgZtcSG0tvkLZ5saGeTdC2";
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://cz3003-waffles.firebaseio.com/");
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
        String            RootName  = "Progress/" + userToken + "/World" + currentWorld + "/Stage" + currentStage;
        await FirebaseDatabase.DefaultInstance.GetReference(RootName).GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                snapshot = null;
                Debug.Log("Error encountered, check input parameters");
                // Handle the error...
            }
            else if (task.IsCompleted)
            {     // Do something with snapshot...
                this.snapshot = task.Result;
                Debug.Log("Finally fetched snapshot " + RootName);
            }
        });

        currentProgress = Convert.ToInt32(snapshot.Value);
        Debug.Log(currentProgress);

        currentWorld = 1;

        double finishedStage = ((double)score / scoreCheck) * 100;

        if ((((double)score / scoreCheck) > (double)0.5) && (finishedStage > currentProgress))
        {
            //currentProgress = finishedStage;
            //update firebase progress/usertoken/world/stage/%value%


            Debug.Log(userToken);
            FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://cz3003-waffles.firebaseio.com/");
            reference = FirebaseDatabase.DefaultInstance.RootReference;
            RootName  = "Progress/" + userToken + "/World" + currentWorld + "/Stage" + currentStage;
            await FirebaseDatabase.DefaultInstance.GetReference(RootName).SetRawJsonValueAsync(finishedStage.ToString());


            FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://cz3003-waffles.firebaseio.com/");
            reference = FirebaseDatabase.DefaultInstance.RootReference;
            RootName  = "Leaderboard/" + userToken + "/Score";
            await FirebaseDatabase.DefaultInstance.GetReference(RootName).GetValueAsync().ContinueWith(task => {
                if (task.IsFaulted)
                {
                    snapshot = null;
                    Debug.Log("Error encountered, check input parameters");
                    // Handle the error...
                }
                else if (task.IsCompleted)
                {     // Do something with snapshot...
                    this.snapshot = task.Result;
                    Debug.Log("Finally fetched snapshot " + RootName);
                }
            });

            int leaderboard = Convert.ToInt32(snapshot.Value);

            FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://cz3003-waffles.firebaseio.com/");
            reference = FirebaseDatabase.DefaultInstance.RootReference;
            RootName  = "Leaderboard/" + userToken + "/Score";
            await FirebaseDatabase.DefaultInstance.GetReference(RootName).SetRawJsonValueAsync((leaderboard + finishedStage - currentProgress).ToString());
        }

        //score = scoreCheck = 0;
        resetQuestions();
    }
Beispiel #12
0
 public void OnDataChange(DataSnapshot snapshot)
 {
     ChangedData.Value = snapshot;
 }
Beispiel #13
0
 public void OnComplete(DatabaseError error, bool committed, DataSnapshot currentData)
 {
     CompleteAction?.Invoke(error, committed, currentData);
 }
 private void HandleChildChange <T>(FirebaseChildEventDelegate <T> handler, FirebaseChildChangeEnum type, DataSnapshot snapshot, string previousChildName)
 {
     FirebaseXamarinHelper.RunOnUIThread(() =>
     {
         var snapData = DataConverter.Convert <T>(snapshot.GetValue(), GetObjectFromHandler(handler));
         handler.OnSnapshot(type, previousChildName, new KeyValuePair <string, T>(snapshot.Key, snapData));
         SetObjectFromHandler(handler, snapData);
     });
 }
 public void OnChildMoved(DataSnapshot dataSnapshot, String s)
 {
     //this will not happen
 }
Beispiel #16
0
    public void OnLoadAdmin()
    {
        LoadLocal();

        bool firstTime = true;

        Debug.Log("default ID : " + UserManager.Instance.currentUser.id);
        FirebaseDatabase.DefaultInstance.GetReference("Users").Child(UserManager.Instance.currentUser.id).GetValueAsync().ContinueWith
        (
            task =>
        {
            if (!task.IsCompleted)
            {
                Debug.Log("OnLoadAdmin_Error");
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                if (snapshot.ChildrenCount > 0)
                {
                    if (Convert.ToInt32(snapshot.Child("playTime").GetValue(true)) > UserManager.Instance.currentUser.PlayTime)
                    {
                        #region Admin
                        UserManager.Instance.currentUser.name = snapshot.Child("username").GetValue(true).ToString(); //snapShot에서 name 가져오기.
                        EventManager.instance.NickNameCheckedFunc(true);

                        UserManager.Instance.currentUser.gem            = Convert.ToInt32(snapshot.Child("gem").GetValue(true));
                        UserManager.Instance.currentUser.star           = Convert.ToInt32(snapshot.Child("star").GetValue(true));
                        UserManager.Instance.currentUser.ClearLandCount = Convert.ToInt32(snapshot.Child("clrLndCnt").GetValue(true));
                        UserManager.Instance.currentUser.PlayTime       = Convert.ToInt32(snapshot.Child("playTime").GetValue(true));
                        Debug.Log("playTime : " + UserManager.Instance.currentUser.PlayTime);
                        UserManager.Instance.currentUser.lastLand = Convert.ToInt32(snapshot.Child("lastLand").GetValue(true));
                        #endregion

                        #region Land
                        if (UserManager.Instance.currentUser.gotLandList.Count > 0)
                        {
                            UserManager.Instance.currentUser.gotLandList.Clear();
                        }
                        for (int i = 0; i < snapshot.Child("gotLands").ChildrenCount; i++)
                        {
                            string i_ = i.ToString();
                            SaveData.GotLand tempGotLand = new SaveData.GotLand();

                            tempGotLand.id      = Convert.ToInt32(snapshot.Child("gotLands").Child(i_).Child("id").GetValue(true));
                            tempGotLand.weather = Convert.ToInt32(snapshot.Child("gotLands").Child(i_).Child("weather").GetValue(true));

                            for (int j = 0; j < snapshot.Child("gotLands").Child(i_).Child("clrPuzzles").ChildrenCount; j++)
                            {
                                string j_ = j.ToString();
                                tempGotLand.clearPuzzleList.Add(snapshot.Child("gotLands").Child(i_).Child("clrPuzzles").Child(j_).GetValue(true).ToString());
                            }
                            for (int j = 0; j < snapshot.Child("gotLands").Child(i_).Child("units").ChildrenCount; j++)
                            {
                                string j_ = j.ToString();
                                tempGotLand.unitList.Add(snapshot.Child("gotLands").Child(i_).Child("units").Child(j_).GetValue(true).ToString());
                            }
                            UserManager.Instance.currentUser.gotLandList.Add(tempGotLand);
                        }
                        #endregion
                    }
                }

                if (UserManager.Instance.currentUser.PlayTime > 0)
                {
                    firstTime = false;
                }

                Debug.Log(UserManager.Instance.currentUser.name + ", firstTime : " + firstTime);

                loadAdmin = true;
            }
        });
    }
			public override void onChildRemoved(DataSnapshot dataSnapshot)
			{
				// No-op
			}
Beispiel #18
0
    /// <summary>
    /// 0: ID, 1:Name, 2:Size, 3:UseSpriteNum_Min, 4: UseSpriteNum_Max, 5: Type(N or S)
    /// LoadPuzzles 보다 먼저 실행.
    /// </summary>
    IEnumerator LoadLands()
    {
        loadAll = false;
        Debug.Log("tryLoadLand");

        float time = 0;

        while (time < 3f)
        {
            if (NetworkConnectionChecker.instance.success == true)
            {
                List <DataBase.Land> tempLandList = new List <DataBase.Land>();
                #region LoadLandDB_Firebase
                FirebaseDatabase.DefaultInstance.GetReference("Lands").GetValueAsync().ContinueWith
                (
                    task =>
                {
                    if (task.IsFaulted)
                    {
                        Debug.Log("Land, Handle the error");
                        // Handle the error...
                    }
                    else if (task.IsCompleted && loadLand == false)
                    {
                        //Debug.Log("Land, TaskComplite");
                        DataSnapshot snapshot = task.Result;

                        for (int i = 1; i < snapshot.ChildrenCount; i++)
                        {
                            DataBase.Land tempLand = new DataBase.Land();
                            string i_            = i.ToString();                                                  //'Lands'DB 용 ID.
                            tempLand.id          = Convert.ToInt32(snapshot.Child(i_).Child("0").GetValue(true)); //snapShot에서 Land ID가져오기.
                            tempLand.name        = snapshot.Child(i_).Child("1").GetValue(true).ToString();
                            tempLand.price       = Convert.ToInt32(snapshot.Child(i_).Child("7").GetValue(true));
                            string puzzleIDFront = tempLand.id < 10 ? "0" + tempLand.id : tempLand.id.ToString();

                            #region puzzleList_S
                            List <string> skillNum = new List <string>();
                            for (int j = 0; j < 4; j++)
                            {
                                int tempj = 3 + j;

                                string spNum = snapshot.Child(i_).Child(tempj.ToString()).GetValue(true).ToString();
                                if (spNum != "0")
                                {
                                    spNum = System.Convert.ToInt32(spNum) < 10 ? "0" + spNum : spNum;
                                    skillNum.Add(spNum);    //skillPuzzleID_Back
                                }
                            }
                            tempLand.puzzleList_S = new List <string>();
                            for (int j = 0; j < skillNum.Count; j++)
                            {
                                tempLand.puzzleList_S.Add(puzzleIDFront + skillNum[j]); //skillPuzzleID_All
                            }
                            #endregion                                                  //skill Puzzle 만 모아놓기

                            #region puzzleList_N
                            List <string> normalIDList = new List <string>();
                            //tempLand.puzzleList_N = new string[System.Convert.ToInt32(snapshot.Child(i_).Child("2").GetValue(true))];
                            for (int j = 0; j < System.Convert.ToInt32(snapshot.Child(i_).Child("2").GetValue(true)); j++)
                            {
                                int sameCnt         = 0;
                                int max             = j + 1;
                                string puzzleIDBack = max < 10 ? "0" + max : max.ToString();
                                foreach (string x in skillNum)
                                {
                                    if (x == puzzleIDBack)
                                    {
                                        sameCnt++;
                                    }
                                }
                                if (sameCnt == 0)
                                {
                                    string normalID = puzzleIDFront + puzzleIDBack;
                                    normalIDList.Add(normalID);
                                }
                            }
                            tempLand.puzzleList_N = new List <string>();
                            for (int j = 0; j < normalIDList.Count; j++)
                            {
                                tempLand.puzzleList_N.Add(normalIDList[j]);
                            }
                            #endregion // 모아놓은 skill puzzle을 제외한 normal puzzle만 모아놓기.


                            tempLandList.Add(tempLand);
                        }
                        LandManager.instance.landList = new List <DataBase.Land>();
                        LandManager.instance.landList = tempLandList;
                        loadLand = true; Debug.Log("land_True");
                    }
                }
                );
                #endregion
            }
            else
            {
                loadLand = true;
                //읽씹.
            }
            yield return(new WaitForSeconds(0.02f));

            time += 0.02f;
        }
    }//After Check That Internet Connection.
			public override void onDataChange(DataSnapshot dataSnapshot)
			{
				string floor = dataSnapshot.getValue(typeof(string));
				if (floor == null || floor.Equals("none"))
				{
					outerInstance.mOfficeFloorView.Background = null;
				}
				else if (floor.Equals("carpet"))
				{
					outerInstance.mOfficeFloorView.Background = Resources.getDrawable(R.drawable.floor_carpet);
				}
				else if (floor.Equals("grid"))
				{
					outerInstance.mOfficeFloorView.Background = Resources.getDrawable(R.drawable.floor_grid);
				}
				else if (floor.Equals("tile"))
				{
					outerInstance.mOfficeFloorView.Background = Resources.getDrawable(R.drawable.floor_tile);
				}
				else if (floor.Equals("wood"))
				{
					outerInstance.mOfficeFloorView.Background = Resources.getDrawable(R.drawable.floor_wood);
				}
				outerInstance.mOfficeFloorView.invalidate();
			}
Beispiel #20
0
    IEnumerator SignInDefaultUser()
    {
        bool          done   = false;
        bool          error  = false;
        List <string> emails = new List <string>();

        auth.SignInWithEmailAndPasswordAsync("*****@*****.**", "TbRXffBJBGg3yqVaHFCdowZZG4Bv0MrobigcXaRrcIn3VxSVGq").ContinueWith(task =>
        {
            if (task.IsFaulted || task.IsCanceled)
            {
                done = true;
                return;
            }
            else if (task.IsCompleted)
            {
                done = true;
            }
        });

        yield return(new WaitUntil(() => done == true));

        done = false;

        FirebaseDatabase.DefaultInstance.GetReference("Email List").GetValueAsync().ContinueWith(task =>
        {
            if (task.IsCanceled || task.IsFaulted)
            {
                Debug.LogError("error recieving email list: " + task.Exception);
                error = true;
                done  = true;
                return;
            }
            if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                if (snapshot.ChildrenCount < 1 || snapshot.HasChildren == false)
                {
                    Debug.LogError("no emails");
                    error = true;
                    done  = true;
                    return;
                }

                foreach (DataSnapshot snapshotEmail in snapshot.Children)
                {
                    string email = (string)snapshotEmail.Value;
                    emails.Add(email);
                }

                done = true;
            }
        });

        yield return(new WaitUntil(() => done == true));

        done = false;

        if (error)
        {
            yield break;
        }

        StartCoroutine(verifyAndReset(emails));
    }
			public override void onDataChange(DataSnapshot dataSnapshot)
			{
				foreach (DataSnapshot segmentSnapshot in dataSnapshot.Children)
				{
					Segment segment = segmentSnapshot.getValue(typeof(Segment));
					buffer.drawPath(DrawingView.getPathForPoints(segment.Points, scale), DrawingView.paintFromColor(segment.Color));
				}
				string encoded = encodeToBase64(b);
				metadataRef.child("thumbnail").setValue(encoded, new CompletionListenerAnonymousInnerClassHelper2(this));
			}
 public void OnChildMoved(DataSnapshot snapshot, string previousChildName)
 {
     //??
 }
Beispiel #23
0
 public void OnDataChange(DataSnapshot snapshot)
 {
     Toast.MakeText(Application.Context, "Success", ToastLength.Short);
 }
 public override void onChildRemoved(DataSnapshot dataSnapshot)
 {
     // No-op
 }
Beispiel #25
0
    public static void Connect()
    {
        Debug.Log("Step: 2.0 - Connecting");

        ConnectionStep = 2.0;
        ConnectionStepChange?.Invoke();

        BaseReference.GetValueAsync().ContinueWith(Task =>
        {
            if (Task.IsFaulted)
            {
                return;
            }

            DataSnapshot ActivePlayer = Task.Result.Child("ActivePlayer");
            DataSnapshot ActiveRoom   = Task.Result.Child("ActivePlayer");
            DataSnapshot Lobby        = Task.Result.Child("Lobby");

            if (!(MyName != ""))
            {
                MyName = GenerateKey(PrettyTextPlayer);

                while (!Free(ActivePlayer, MyName))
                {
                    MyName = GenerateKey(PrettyTextPlayer);
                }

                Debug.Log($"Step: 2.0 - {MyName}");

                foreach (KeyValuePair <string, string> Data in MyData)
                {
                    BaseReference.Child("ActivePlayer").Child(MyName).Child(Data.Key).SetValueAsync(Data.Value);
                }
            }

            if (Lobby.Children.Count() + 1 >= RoomCapacity)
            {
                Debug.Log("Step: 4.0 - Creating room");

                ConnectionStep = 4.0;
                ConnectionStepChange?.Invoke();

                MyRoom = GenerateKey(PrettyTextRoom);

                while (!Free(ActiveRoom, MyRoom))
                {
                    MyRoom = GenerateKey(PrettyTextRoom);
                }

                Debug.Log($"Step: 4.0 - {MyRoom}");

                BaseTracking = BaseReference.Child("ActiveRoom").Child(MyRoom);
                BaseTracking.ValueChanged += OnRoomChange;
            }
            else
            {
                Debug.Log("Step: 3.0 - Joining lobby");

                ConnectionStep = 3.0;
                ConnectionStepChange?.Invoke();

                BaseTracking = BaseReference.Child("Lobby").Child(MyName);
                BaseTracking.ValueChanged += OnLobbyChange;
            }
        });
    }
 public override void onChildMoved(DataSnapshot dataSnapshot, string s)
 {
     // No-op
 }
Beispiel #27
0
    public async void RetrieveHighscore()
    {
        DataSnapshot score = await database.GetReference(playerKey() + "/highscore").GetValueAsync();

        gm.highscore = int.Parse(score.Value.ToString());
    }
Beispiel #28
0
 void UpdateOKHandler(Firebase sender, DataSnapshot snapshot)
 {
     DebugLog("[OK] Update from key: <" + sender.FullKey + ">");
 }
    public void AddUserInQueue(string topic, long timestamp = 0)
    {
        if (!canUseFirebase || DBref == null)
        {
            return;
        }

//		get the top most node from that topic
//		check whether the node is active (i.e. the other player is still online)
//		if the other player is online start game
//		else delete that node and call the function again
//		if there are no nodes, create a new one
//		if the topmost node is from same player reset the node
//
//		checking if node is active:
//		when the node is first created set the check field to 0
//		when other player joins they set it to 1
//		and then to confirm the owner sets the check field to 2

        DBref.Child("Matches").Child(topic).OrderByChild("timestamp").LimitToFirst(1).StartAt(timestamp)
        .GetValueAsync().ContinueWith(task1 => {
            if (task1.IsFaulted)
            {
                // Handle the error...
                Debug.Log("error fetching data match data");
            }
            else if (task1.IsCompleted)
            {
                DataSnapshot snapshot = task1.Result;
                Debug.Log(snapshot);

//				if snapshop.Value == null => there is no node avaliable
//				so create a new node
//				Debug.Log (snapshot.Value);

//				create a reference to current match node
                DatabaseReference matchRef = DBref.Child("Matches").Child(topic);

                if (snapshot.Value == null)
                {
                    Debug.Log("condition 1 check");
                    Match newMatch = new Match(GetUserID(), topic);
                    string json    = JsonUtility.ToJson(newMatch);

                    matchRef = matchRef.Child(GetUserID());
                    matchRef.SetRawJsonValueAsync(json).ContinueWith(task2 => {
                        if (task2.IsFaulted)
                        {
                            Debug.Log("error");
                            // TODO: throw and handle error!
                        }
                        else if (task2.IsCompleted)
                        {
                            // handle all important things here
                            Debug.Log("created a new match: " + json);

//							add value change listner to the match reference node
                            matchRef.ValueChanged += MatchCheckListner;
                        }
                    });
                }
                else
                {
                    Debug.Log("condition 2 check");
//					Debug.Log (snapshot.Value);

                    Dictionary <string, object> snap  = snapshot.Value as Dictionary <string, object>;
                    Dictionary <string, object> match = new Dictionary <string, object> ();

//					there will only be one entry in the snapshot as we are limiting our search to 1st node only
                    foreach (var entry in snap)
                    {
                        match = snap[entry.Key] as Dictionary <string, object>;
                    }

                    foreach (var entry in match)
                    {
                        Debug.Log(entry.Key + " : " + entry.Value);
                    }

//					matchRef = matchRef.Child (GetUserID ());
//					add value change listner to the match reference node
//					matchRef.ValueChanged += MatchCheckListner;
                }
            }
        });
    }
Beispiel #30
0
 void PushOKHandler(Firebase sender, DataSnapshot snapshot)
 {
     DebugLog("[OK] Push from key: <" + sender.FullKey + ">");
 }
Beispiel #31
0
 public void Add(SnapshotCallback callback, DataSnapshot snap, object context)
 {
     EnsureStarted();
     _queue.Enqueue(_token, new QueueSubscriptionEvent(callback, snap, context));
 }
Beispiel #32
0
 void GetRulesOKHandler(Firebase sender, DataSnapshot snapshot)
 {
     DebugLog("[OK] GetRules");
     DebugLog("[OK] Raw Json: " + snapshot.RawJson);
 }
Beispiel #33
0
    public void getHabits(string playerID) //, Dictionary<string, string> actions)
    {
        string petUpdate = "";
        Dictionary <string, object> habits = null;

        _database.GetReference(playerID).Child("activePet").GetValueAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                Debug.Log("Could Not Retrieve Active Pet");
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                petUpdate             = snapshot.Value.ToString();

                // string sampleJson = " {\"actions\": {\"water\": {\"habit\": \"jogging\", \"healvalue\": \"1\", \"hurtvalue\": \"1\", \"lastcared\": \"timestamp\", \"timeframe\": \"6\" }, {\"feed\": \"habit\": \"eating healthy\", \"healvalue\": \"1\", \"hurtvalue\": \"1\", \"lastcared\": \"timestamp\", \"timeframe\": \"6\" }}, \"obstacles\":[\"laziness\", \"money\"] } ";
                // _database.GetReference(playerID).Child("currentPets").Child(petUpdate).Child("habits").Child("actions").SetValueAsync(actions);
                // Dictionary<string, object> sampleJson =
                _database.GetReference(playerID).Child("currentPets").Child(petUpdate).Child("habits").Child("actions").GetValueAsync().ContinueWithOnMainThread(res =>
                {
                    if (res.IsFaulted)
                    {
                        Debug.Log("Could Not Retrieve Active Pet");
                    }
                    else if (res.IsCompleted)
                    {
                        DataSnapshot snap  = res.Result;
                        habits             = (Dictionary <string, object>)snap.Value;
                        int numberOfHabits = habits.Count;
                        Debug.Log(numberOfHabits);
                        switch (numberOfHabits)
                        {
                        case 0:
                            break;

                        case 1:
                            GameObject.Find("room-feed").SetActive(false);
                            GameObject.Find("room-walk").SetActive(false);
                            GameObject.Find("room-play").SetActive(false);
                            GameObject.Find("room-groom").SetActive(false);
                            GameObject.Find("room-bath").SetActive(false);
                            GameObject.Find("room-six").SetActive(false);
                            GameObject.Find("room-seven").SetActive(false);
                            break;

                        case 2:
                            GameObject.Find("room-walk").SetActive(false);
                            GameObject.Find("room-play").SetActive(false);
                            GameObject.Find("room-groom").SetActive(false);
                            GameObject.Find("room-bath").SetActive(false);
                            GameObject.Find("room-six").SetActive(false);
                            GameObject.Find("room-seven").SetActive(false);
                            break;

                        case 3:
                            GameObject.Find("room-play").SetActive(false);
                            GameObject.Find("room-groom").SetActive(false);
                            GameObject.Find("room-bath").SetActive(false);
                            GameObject.Find("room-six").SetActive(false);
                            GameObject.Find("room-seven").SetActive(false);
                            break;

                        case 4:
                            GameObject.Find("room-groom").SetActive(false);
                            GameObject.Find("room-bath").SetActive(false);
                            GameObject.Find("room-six").SetActive(false);
                            GameObject.Find("room-seven").SetActive(false);
                            break;

                        case 5:
                            GameObject.Find("room-bath").SetActive(false);
                            GameObject.Find("room-six").SetActive(false);
                            GameObject.Find("room-seven").SetActive(false);
                            break;

                        case 6:
                            GameObject.Find("room-six").SetActive(false);
                            GameObject.Find("room-seven").SetActive(false);
                            break;

                        case 7:
                            GameObject.Find("room-seven").SetActive(false);
                            break;

                        case 8:
                            break;
                        }
                    }
                });
                // _database.GetReference(playerID).Child("currentPets").Child(petUpdate).Child("habits").SetRawJsonValueAsync(json);
                // Debug.Log(json);
            }
        });

        //_database.ref("users").Child(playerName).SetRawJsonValueAsync(json);
    }
Beispiel #34
0
 public void OnDataChange(DataSnapshot snapshot)
 {
     postListener.Invoke(snapshot);
 }
			public override void onChildMoved(DataSnapshot dataSnapshot, string s)
			{
				// No-op
			}
Beispiel #36
0
    public void Lotter()
    {
        Chance = 0;
        if (!isTutorEgg)
        {
            Chance = Random.Range(0f, 100f);
        }
        else
        {
            Chance = Random.Range(76f, 100f);
        }

        if (0 <= Chance && Chance <= 15)   //GOat
        {
            PetManager.PetNumList.Add(1);
            PetId = 1;
//			PMM.GoatUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Goat.GetComponent <SpriteRenderer>().sprite;
            PetBeLotteredAudio = GoatAudio;
            PetText.text       = "恭喜獲得 <color=#FFFFFF>口水羊</color>";
        }
        else if (Chance <= 30)     //Cat
        {
            PetManager.PetNumList.Add(2);
            PetId = 2;
//			PMM.CatUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Cat.GetComponent <SpriteRenderer>().sprite;
            PetBeLotteredAudio = CatAudio;
            PetText.text       = "恭喜獲得 <color=#FFFFFF>厭世貓</color>";
        }
        else if (Chance <= 45)     //Pig
        {
            PetManager.PetNumList.Add(3);
            PetId = 3;
//			PMM.PigUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Pig.GetComponent <SpriteRenderer>().sprite;
            PetBeLotteredAudio = PigAudio;
            PetText.text       = "恭喜獲得 <color=#FFFFFF>暴走豬</color>";
        }
        else if (Chance <= 60)     //Chicken
        {
            PetManager.PetNumList.Add(5);
            PetId = 5;
//			PMM.ChickenUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Chicken.GetComponent <SpriteRenderer>().sprite;
            PetBeLotteredAudio = ChickenAudio;
            PetText.text       = "恭喜獲得 <color=#FFFFFF>窩母雞</color>";
        }
        else if (Chance <= 75)     //BearCat
        {
            PetManager.PetNumList.Add(4);
            PetId = 4;
//			PMM.BearCatUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = BearCat.GetComponent <SpriteRenderer>().sprite;
            PetBeLotteredAudio = BearCatAudio;
            PetText.text       = "恭喜獲得 <color=#FFFFFF>小熊貓</color>";
        }
        else if (Chance <= 80)     //Horse
        {
            PetManager.PetNumList.Add(6);
            PetId = 6;
//			PMM.HorseUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Horse.GetComponent <SpriteRenderer>().sprite;
            PetBeLotteredAudio = HorseAudio;
            PetText.text       = "恭喜獲得 <color=#FFCC22>糖果馬</color>";
        }
        else if (Chance <= 85)     //Loris
        {
            PetManager.PetNumList.Add(6);
            PetId = 7;
//			PMM.HorseUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Loris;
            PetBeLotteredAudio = LorisAudio;
            PetText.text       = "恭喜獲得 <color=#FFCC22>懶猴王</color>";
        }
        else if (Chance <= 90)     //Owl
        {
            PetManager.PetNumList.Add(6);
            PetId = 8;
//			PMM.HorseUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Owl;
            PetBeLotteredAudio = OwlAudio;
            PetText.text       = "恭喜獲得 <color=#FFCC22>木頭鷹</color>";
        }
        else if (Chance <= 95)     //CHemeleon
        {
            PetManager.PetNumList.Add(6);
            PetId = 9;
//			PMM.HorseUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Chemeleon;
            PetBeLotteredAudio = ChameleonAudio;
            PetText.text       = "恭喜獲得 <color=#FFCC22>黃綠龍</color>";
        }
        else if (Chance <= 100)     //Turtle
        {
            PetManager.PetNumList.Add(6);
            PetId = 10;
//			PMM.HorseUnlock();
            PetImg.GetComponent <SpriteRenderer>().sprite = Turtle;
            PetBeLotteredAudio = TurtleAudio;
            PetText.text       = "恭喜獲得 <color=#FFCC22>大方龜</color>";
        }

        if (PMM.GetReadInfoStatus())
        {
            Debug.Log("PetId = " + PetId);
            WaitPanel.SetActive(true);
            StartCoroutine(Wait(PetId));
            return;
        }


        FirebaseDatabase.DefaultInstance.GetReference("users").Child(PlayerData.UserId.ToString()).Child("Pet").GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                Debug.Log("error");
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;

                float PetNumNow = snapshot.ChildrenCount;
                DatabaseReference mDatabaseRef = FirebaseDatabase.DefaultInstance.GetReference("users").Child(PlayerData.UserId.ToString()).Child("Pet").Child("Pet" + PetNumNow.ToString());
                mDatabaseRef.Child("PetId").SetValueAsync(PetId);
                mDatabaseRef.Child("PetLife").SetValueAsync(5);
                mDatabaseRef.Child("PetLevel").SetValueAsync(1);
                mDatabaseRef.Child("PetGrade").SetValueAsync(1);
                mDatabaseRef.Child("IsWarrior").SetValueAsync(0);
                mDatabaseRef.Child("PetExp").SetValueAsync(0);
                mDatabaseRef.Child("IsOnIsland").SetValueAsync(0);
                mDatabaseRef.Child("Burial").SetValueAsync(0);
            }
        });


//		CM.UpdateNum();
//		PlayerPrefs.SetInt("PetListNum",PetManager.PetNumList.Count);
//		PlayerPrefs.SetInt("Pet" + PetManager.PetNumList.Count , PetId);

        EggProgressButton.SetActive(true);
        PetEggPanel.SetActive(true);
    }
 public QueueSubscriptionEvent(SnapshotCallback callback, DataSnapshot snap, object context)
 {
     _callback = callback;
     _snap = snap;
     _context = context;
 }
 public void Add(SnapshotCallback callback, DataSnapshot snap, object context)
 {
     EnsureStarted();
     _queue.Enqueue(_token, new QueueSubscriptionEvent(callback, snap, context));
 }
			public override void onChildRemoved(DataSnapshot dataSnapshot)
			{
				string key = dataSnapshot.Key;

				Log.v(TAG, "Thing removed " + key);

				outerInstance.removeThingFromLocalModel(key);
			}
Beispiel #40
0
    public void LoadData()
    {
        FirebaseDatabase.DefaultInstance
        .GetReference("Questions")
        .GetValueAsync().ContinueWith(task => {
            Debug.Log("Opened db");

            if (task.IsFaulted)
            {
                print("Task is Faulted");
            }
            if (task.IsCompleted)
            {
                DataSnapshot dataSnapshot = task.Result;
                string playerdata         = dataSnapshot.Child("QID1").Child("question").GetRawJsonValue();

                Debug.Log("Data Retrieved");



                tempQueString = playerdata.ToString();
                //test.text = playerdata.ToString();
                //print(playerdata);
                string optionVal = dataSnapshot.Child("QID1").Child("option1").GetRawJsonValue();
                print(playerdata + "___" + optionVal);

                opt1String = optionVal.ToString();
            }
        });
        //FirebaseDatabase.DefaultInstance.GetReferenceFromUrl(DATA_URL)
        //    .GetValueAsync().ContinueWith(task => {
        //        if (task.IsCanceled)
        //        {

        //        }

        //        if (task.IsFaulted)
        //        {

        //        }

        //        if (task.IsCompleted)
        //        {
        //            //Firebase.Auth.FirebaseUser user = Firebase.Auth.FirebaseAuth.DefaultInstance.CurrentUser;
        //            //if (user != null)
        //            //{
        //            //    string name = user.UserId;
        //            //    print("user is valid" + name);
        //            //} else
        //            //{
        //            //    print("user is null");
        //            //}
        //            DataSnapshot dataSnapshot = task.Result;

        //            string playerData = dataSnapshot.GetRawJsonValue();

        //            //For single player valure retrive
        //            //Player m = JsonUtility.FromJson<Player>(playerData);

        //            foreach (var child in dataSnapshot.Children)
        //            {
        //                string t = child.GetRawJsonValue();

        //                //Convert into single data
        //                //Player extractedData = JsonUtility.FromJson<Player>(t);

        //                //print("The Player username is: " + extractedData.username);
        //                print("The Player password i: " + extractedData.password);


        //                //For full user record
        //                //print("Date is " + t);
        //            }
        //        }
        //    });
    }
Beispiel #41
0
 internal void Fire(SnapshotCallback callback, DataSnapshot snap, object context)
 {
     _subProcessor.Add(callback, snap, context);
 }
			public override void onDataChange(DataSnapshot dataSnapshot)
			{
				bool connected = (bool?) dataSnapshot.Value;
				if (connected)
				{
					Toast.makeText(outerInstance, "Connected to Firebase", Toast.LENGTH_SHORT).show();
				}
				else
				{
					Toast.makeText(outerInstance, "Disconnected from Firebase", Toast.LENGTH_SHORT).show();
				}
			}