public static async Task AddGameStateHistory(TicTacToeState gameState, string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var gamesPlayed = await GameDataUtil.GetGamesPlayed(playFabId, apiSettings, authenticationContext);

            var key = $"{Constants.GAME_STATE_KEY}_{gamesPlayed + 1}";

            var serializedGameState = PlayFabSimpleJson.SerializeObject(gameState);

            var request = new UpdateUserDataRequest()
            {
                PlayFabId = playFabId,
                Data      = new Dictionary <string, string>()
                {
                    { key, serializedGameState }
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.UpdateUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occured while updating the game state: Error: {result.Error.GenerateErrorReport()}");
            }

            await GameDataUtil.SetGamesPlayed(gamesPlayed + 1, playFabId, apiSettings, authenticationContext);
        }
Beispiel #2
0
        public static async Task <dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try{
                string body = await req.ReadAsStringAsync();

                var context = JsonConvert.DeserializeObject <FunctionExecutionContext <dynamic> >(body);
                var request = JsonConvert.DeserializeObject <FunctionExecutionContext <DevelopConsumeStaminaApiRequest> >(body).FunctionArgument;

                var stamina = await StaminaUtil.ConsumeAsync(context, request.consumeStamina);

                return(PlayFabSimpleJson.SerializeObject(new DevelopConsumeStaminaApiResponse()
                {
                    stamina = stamina
                }));
            }catch (PMApiException e) {
                // レスポンスの作成
                var response = new PMApiResponseBase()
                {
                    errorCode = e.errorCode,
                    message   = e.message
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }
        }
Beispiel #3
0
    public void FilterResult(ExecuteCloudScriptResult result)
    {
        ClaimedRewards.Clear();
        JSONNode jsonResultPF = PlayFabSimpleJson.SerializeObject(result.FunctionResult);

        jsonResult = JSON.Parse(result.FunctionResult.ToString());

        Debug.Log("json result playfab " + jsonResultPF.ToString());
        Debug.Log("json result " + jsonResult.ToString());
        if ((jsonResult.Value.Equals("null") || result.Error != null))
        {
            status = FMRewardStatus.error;
            return;
        }

        /*{ "status":"success",
         * "rewards":
         * [{"achievement_key":"stages_created","reward_Key":"default_co_200","reward_type":"coins","amount":200}]
         * }
         */
        Debug.Log("function result  size" + jsonResult["rewards"].AsArray.Count);
        for (int i = 0; i < jsonResult["rewards"].AsArray.Count; i++)
        {
            string rewardKey  = jsonResult["rewards"].AsArray[i]["reward_Key"];
            string rewardType = jsonResult["rewards"].AsArray[i]["reward_type"];

            FMRewardType rewadType   = rewardType.Equals("item") ? FMRewardType.Item : FMRewardType.Currency;
            int          rewardValue = rewadType == FMRewardType.Currency ? jsonResult["rewards"].AsArray[i]["amount"].AsInt : 0;
            string       itemKey     = rewadType == FMRewardType.Item ? jsonResult["rewards"].AsArray[i]["item_key"].Value : "";

            //var ri = new FMRewardItem(rewardKey, rewardType, rewardValue, rewardValue);
            //ClaimedRewards.Add(ri);
        }
    }
Beispiel #4
0
        public static async Task <dynamic> MakeHTTPRequest(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            /* Create the function execution's context through the request */
            var context = await FunctionContext <dynamic> .Create(req);

            var args = context.FunctionArgument;

            /* Prepare the body, headers, and url of the external HTTP request */
            dynamic body = new
            {
                input  = args,
                userId = context.CurrentPlayerId,
                mode   = "foobar"
            };
            var requestContent = new StringContent(PlayFabSimpleJson.SerializeObject(body));

            requestContent.Headers.Add("X-MyCustomHeader", "Some Value");
            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var url = "http://httpbin.org/status/200";

            /* Execute the HTTP request using a simple HttpClient */
            using (var client = new HttpClient())
            {
                using (var httpResponseMessage =
                           await client.PostAsync(url, requestContent))
                {
                    using (var responseContent = httpResponseMessage.Content)
                    {
                        return(await responseContent.ReadAsAsync <dynamic>());
                    }
                }
            }
        }
        public static async Task <dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string body = await req.ReadAsStringAsync();

            var context = JsonConvert.DeserializeObject <FunctionExecutionContext <Dictionary <string, List <string> > > >(body);
            var args    = context.FunctionArgument;

            // 引数でテーブル名を渡す
            dynamic itemIdList = null;

            if (args != null && args["itemIdList"] != null)
            {
                itemIdList = args["itemIdList"];
            }

            // ドロップテーブルからアイテムを取得する
            var grantedItemList = await GrantItemsToUserTask(context, itemIdList);

            // レンポンスの作成
            var response = new GrantItemsToUserApiResponse()
            {
                itemInstanceList = grantedItemList,
            };

            return(PlayFabSimpleJson.SerializeObject(response));
        }
Beispiel #6
0
    void UpdateTeam()
    {
        string jsonToUpdate = PlayFabSimpleJson.SerializeObject(PF_PlayerData.MyTeamsCharacterId);

        PF_PlayerData.UpdateUserData(new Dictionary <string, string>()
        {
            { "Teams", jsonToUpdate }
        }, "Public", (UpdateUserDataResult) => { Debug.Log(" teams updated"); });
    }
    private void OnCloudHelloWorld(ExecuteCloudScriptResult result)
    {
        // CloudScript returns arbitrary results, so you have to evaluate them one step and one parameter at a time
        Debug.Log(PlayFabSimpleJson.SerializeObject(result.FunctionResult));
        JsonObject jsonResult = (JsonObject)result.FunctionResult;
        object     messageValue;

        jsonResult.TryGetValue("messageValue", out messageValue); // note how "messageValue" directly corresponds to the JSON values set in CloudScript
        Debug.Log((string)messageValue);
    }
        private string OnConnectionSending()
        {
            var _data = new List <HubRegistrationData>();

            foreach (var p in m_hubs)
            {
                _data.Add(new HubRegistrationData {
                    Name = p.Key
                });
            }
            return(PlayFabSimpleJson.SerializeObject(_data));
        }
Beispiel #9
0
    //TODO put in a different result class
    void OnSoldItems(ExecuteCloudScriptResult result)
    {
        //for some weird reason, result is not retutning so we put the result in a log, wth
        Debug.Log("result " + PlayFabSimpleJson.SerializeObject(result));
        //JSONNode json = JSON.Parse(result.FunctionResult.ToString());
        JSONNode json = PlayFabSimpleJson.SerializeObject(result.FunctionResult);

        //if (json == null || json["status"].Equals("error")) {
        //    string msg = json["message"] != null ? json["message"].Value : "";
        //    Debug.Log("error selling the item, "+ msg);
        //}
        //ClientSessionData.Instance.currencyCO += json["sell_price"].AsInt;
        //labCO.text = ClientSessionData.Instance.currencyCO.ToString();

        string logResult = result.Logs.Count > 0 ? result.Logs[0].Message : "";

        if (string.IsNullOrEmpty(logResult))
        {
            Debug.Log("no result");
            return;
        }

        if (logResult.Contains("success"))
        {
            string sellPrice = logResult.Split(' ')[1];
            Debug.Log("sell price string " + sellPrice);
            ClientSessionData.Instance.currencyCO += int.Parse(sellPrice);
            labCO.text = ClientSessionData.Instance.currencyCO.ToString();
        }

        //remove item if amount is 0
        selectedItem.Item.Amount -= 1;
        labDetailAmount.text      = "x " + selectedItem.Item.Amount;

        if (selectedItem.Item.Amount <= 0)
        {
            string itemID = selectedItem.Item.InstanceID;
            ClientSessionData.Instance.InventoryItems.Remove(selectedItem.Item);

            //remove from grid
            Transform gridItem = grid.GetChildList().Find(x => x.gameObject.GetComponent <FMInventoryItemUI>().Item.InstanceID.Equals(itemID));
            if (gridItem != null)
            {
                Destroy(gridItem.gameObject);
            }
            grid.Reposition();
            HideDetailScreen();
        }
    }
        public EventSignal <T> Invoke <T>(string method, params object[] args)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            var hubData = new HubInvocation
            {
                Hub        = m_hubName,
                Method     = method,
                Args       = args,
                State      = m_state,
                CallbackId = "1"
            };

            var _value     = PlayFabSimpleJson.SerializeObject(hubData);
            var _newSignal = new OptionalEventSignal <T>();
            var _signal    = m_connection.Send <HubResult <T> >(_value);

            _signal.Finished += (sender, e) =>
            {
                if (e.Result != null)
                {
                    if (e.Result.Error != null)
                    {
                        throw new InvalidOperationException(e.Result.Error);
                    }

                    HubResult <T> _hubResult = e.Result;
                    if (_hubResult.State != null)
                    {
                        foreach (var pair in _hubResult.State)
                        {
                            this[pair.Key] = pair.Value;
                        }
                    }

                    _newSignal.OnFinish(_hubResult.Result);
                }
                else
                {
                    _newSignal.OnFinish(default(T));
                }
            };
            return(_newSignal);
        }
        public static async Task <dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try{
                string body = await req.ReadAsStringAsync();

                var context = JsonConvert.DeserializeObject <FunctionExecutionContext <dynamic> >(body);
                var request = JsonConvert.DeserializeObject <FunctionExecutionContext <UpdateUserMonsterFormationApiRequest> >(body).FunctionArgument;

                var userData = await DataProcessor.GetUserDataAsync(context);

                var userMonsterPartyList = userData.userMonsterPartyList ?? new List <UserMonsterPartyInfo>();
                var index = userMonsterPartyList.FindIndex(u => u.partyId == request.partyId);
                if (index < 0)
                {
                    // 存在しない場合は新規作成して追加
                    var userMonsterParty = new UserMonsterPartyInfo()
                    {
                        id                = UserDataUtil.CreateUserDataId(),
                        partyId           = request.partyId,
                        userMonsterIdList = request.userMonsterIdList,
                    };
                    userMonsterPartyList.Add(userMonsterParty);
                }
                else
                {
                    // すでに存在する場合は更新
                    userMonsterPartyList[index].userMonsterIdList = request.userMonsterIdList;
                }
                await DataProcessor.UpdateUserDataAsync(context, new Dictionary <UserDataKey, object>() { { UserDataKey.userMonsterPartyList, userMonsterPartyList } });

                var response = new UpdateUserMonsterFormationApiResponse()
                {
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }catch (PMApiException e) {
                // レスポンスの作成
                var response = new PMApiResponseBase()
                {
                    errorCode = e.errorCode,
                    message   = e.message
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }
        }
Beispiel #12
0
        /// <summary>
        /// Fetch's an entity's profile from the PlayFab server
        /// </summary>
        /// <param name="callerEntityToken">The entity token of the entity profile being fetched</param>
        /// <returns>The entity's profile</returns>
        private static async Task <EntityProfileBody> GetEntityProfile(string callerEntityToken, EntityKey entity)
        {
            // Construct the PlayFabAPI URL for GetEntityProfile
            var getProfileUrl = GetServerApiUri("/Profile/GetProfile");

            // Create the get entity profile request
            var profileRequest = new GetEntityProfileRequest
            {
                Entity = entity
            };

            // Prepare the request headers
            var profileRequestContent = new StringContent(PlayFabSimpleJson.SerializeObject(profileRequest));

            profileRequestContent.Headers.Add("X-EntityToken", callerEntityToken);
            profileRequestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            PlayFabJsonSuccess <GetEntityProfileResponse> getProfileResponseSuccess = null;
            GetEntityProfileResponse getProfileResponse = null;

            // Execute the get entity profile request
            using (var profileResponseMessage =
                       await httpClient.PostAsync(getProfileUrl, profileRequestContent))
            {
                using (var profileResponseContent = profileResponseMessage.Content)
                {
                    string profileResponseString = await profileResponseContent.ReadAsStringAsync();

                    // Deserialize the http response
                    getProfileResponseSuccess =
                        PlayFabSimpleJson.DeserializeObject <PlayFabJsonSuccess <GetEntityProfileResponse> >(profileResponseString);

                    // Extract the actual get profile response from the deserialized http response
                    getProfileResponse = getProfileResponseSuccess?.data;
                }
            }

            // If response object was not filled it means there was an error
            if (getProfileResponseSuccess?.data == null || getProfileResponseSuccess?.code != 200)
            {
                throw new Exception($"Failed to get Entity Profile: code: {getProfileResponseSuccess?.code}");
            }

            return(getProfileResponse.Profile);
        }
    //=================================================================================
    //プレイヤーデータの新規登録処理
    //=================================================================================
    private void SetNewUserData()
    {
        var SavedCharaInfos = new List <SavedCharaInfo>
        {
            new SavedCharaInfo {
                Status = "false"
            },
            new SavedCharaInfo {
                Status = "false"
            },
            new SavedCharaInfo {
                Status = "false"
            },
            new SavedCharaInfo {
                Status = "false"
            },
            new SavedCharaInfo {
                Status = "false"
            },
            new SavedCharaInfo {
                Status = "false"
            },
            new SavedCharaInfo {
                Status = "false"
            },
            new SavedCharaInfo {
                Status = "false"
            },
        };

        // Debug.Log(SavedCharaInfos.Count);
        PlayFabClientAPI.UpdateUserData(
            new UpdateUserDataRequest
        {
            Data = new Dictionary <string, string>()
            {
                { "SavedCharaInfo", PlayFabSimpleJson.SerializeObject(SavedCharaInfos) }
            }
        },
            result => { Debug.Log("(1)新規プレイヤーデータの登録成功!GetUserData()稼働");
                        // 新規プレイヤー作成後、ゲームデータをPlayFabから取得
                        GetUserData(); },
            error => { Debug.Log(error.GenerateErrorReport()); });
    }
        private static HttpContent CompressResponseBody(object responseObject, HttpRequest request)
        {
            string responseJson  = PlayFabSimpleJson.SerializeObject(responseObject);
            var    responseBytes = Encoding.UTF8.GetBytes(responseJson);

            // Get all accepted encodings,
            string encodingsString = request.Headers["Accept-Encoding"];

            // If client doesn't specify accepted encodings, assume identity and respond decompressed
            if (string.IsNullOrEmpty(encodingsString))
            {
                return(new ByteArrayContent(responseBytes));
            }

            List <string> encodings = encodingsString.Replace(" ", String.Empty).Split(',').ToList();

            encodings.ForEach(encoding => encoding.ToLower());

            // If client accepts identity explicitly, respond decompressed
            if (encodings.Contains("identity", StringComparer.OrdinalIgnoreCase))
            {
                return(new ByteArrayContent(responseBytes));
            }

            // If client accepts gzip, compress
            if (encodings.Contains("gzip", StringComparer.OrdinalIgnoreCase))
            {
                using (var stream = new MemoryStream())
                {
                    using (var gZipStream = new GZipStream(stream, CompressionLevel.Fastest, false))
                    {
                        gZipStream.Write(responseBytes, 0, responseBytes.Length);
                    }
                    responseBytes = stream.ToArray();
                }
                var content = new ByteArrayContent(responseBytes);
                content.Headers.ContentEncoding.Add("gzip");
                return(content);
            }

            // If neither identity or gzip, throw error: we support gzip only right now
            throw new Exception($"Unknown compression requested for response. The \"Accept-Encoding\" haeder values was: ${encodingsString}. Only \"Identity\" and \"GZip\" are supported right now.");
        }
Beispiel #15
0
    private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
    {
        if (e.Message.Data != null)
        {
            string test1 = PlayFabSimpleJson.SerializeObject(e.Message.Data);

            StartCoroutine(PlayfabLogInDelay(e.Message));

            /*
             * string _dataTest = "[";
             * foreach (var pair in e.Message.Data)
             * {
             *  _dataTest += "{" + pair.Key + ":" + pair.Value + "}";
             *  Debug.Log("PlayFab data element: " + pair.Key + "," + pair.Value);
             * }
             * _dataTest += "]";
             *
             * ToastNotification.instance.Show(_dataTest);*/
        }
    }
Beispiel #16
0
        public static async Task <dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try{
                string body = await req.ReadAsStringAsync();

                var context = JsonConvert.DeserializeObject <FunctionExecutionContext <dynamic> >(body);
                var request = JsonConvert.DeserializeObject <FunctionExecutionContext <LoginApiRequest> >(body).FunctionArgument;

                // 初ログイン時処理
                var userData = await DataProcessor.GetUserDataAsync(context);

                if (userData.lastLoginDateTime == default(DateTime))
                {
                    await DataProcessor.UpdateUserDataAsync(context, new Dictionary <UserDataKey, object>(){
                        { UserDataKey.rank, 1 },
                    });
                }

                // ログイン日時の更新
                var now = DateTimeUtil.Now();
                await DataProcessor.UpdateUserDataAsync(context, new Dictionary <UserDataKey, object>(){ { UserDataKey.lastLoginDateTime, now } });

                // スタミナの更新
                await StaminaUtil.SetStamina(context);

                var response = new LoginApiResponse()
                {
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }catch (PMApiException e) {
                // レスポンスの作成
                var response = new PMApiResponseBase()
                {
                    errorCode = e.errorCode,
                    message   = e.message
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }
        }
        public static async Task UpdateCurrentGameState(TicTacToeState state, string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var serializedNewGameState = PlayFabSimpleJson.SerializeObject(state);

            var request = new UpdateUserDataRequest()
            {
                PlayFabId = playFabId,
                Data      = new Dictionary <string, string>()
                {
                    { Constants.GAME_CURRENT_STATE_KEY, serializedNewGameState }
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.UpdateUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occured while creating a new game state: {result.Error.GenerateErrorReport()}");
            }
        }
        public static async Task <dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try{
                string body = await req.ReadAsStringAsync();

                var context = JsonConvert.DeserializeObject <FunctionExecutionContext <dynamic> >(body);
                var args    = context.FunctionArgument;

                // 引数でテーブル名を渡す
                dynamic dropTableName = null;
                if (args != null && args["dropTableName"] != null)
                {
                    dropTableName = args["dropTableName"];
                }

                // ドロップテーブルからアイテムを取得する
                var evaluateResult = await EvaluateRandomResultTable(context, dropTableName);

                // プレイヤーにアイテムを付与する
                var grantResult = await ItemGiver.GrantItemsToUserAsync(context, new List <string>() { evaluateResult });

                // レスポンスの作成
                var response = new DropItemApiResponse()
                {
                    itemInstanceList = grantResult,
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }catch (PMApiException e) {
                // レスポンスの作成
                var response = new PMApiResponseBase()
                {
                    errorCode = e.errorCode,
                    message   = e.message
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }
        }
Beispiel #19
0
        /// <summary>
        /// Grabs the developer secret key from the environment variable (expected to be set) and uses it to
        /// ask the PlayFab server for a title entity token.
        /// </summary>
        /// <returns>The title's entity token</returns>
        private static async Task <string> GetTitleEntityToken()
        {
            var titleEntityTokenRequest = new AuthenticationModels.GetEntityTokenRequest();

            var getEntityTokenUrl = GetServerApiUri("/Authentication/GetEntityToken");

            // Grab the developer secret key from the environment variables (app settings) to use as header for GetEntityToken
            var secretKey = Environment.GetEnvironmentVariable(DEV_SECRET_KEY, EnvironmentVariableTarget.Process);

            if (string.IsNullOrEmpty(secretKey))
            {
                // Environment variable was not set on the app
                throw new Exception("Could not fetch the developer secret key from the environment. Please set \"PLAYFAB_DEV_SECRET_KEY\" in your app's local.settings.json file.");
            }

            var titleEntityTokenRequestContent = new StringContent(PlayFabSimpleJson.SerializeObject(titleEntityTokenRequest));

            titleEntityTokenRequestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            titleEntityTokenRequestContent.Headers.Add("X-SecretKey", secretKey);

            using (var titleEntityTokenResponseMessage =
                       await httpClient.PostAsync(getEntityTokenUrl, titleEntityTokenRequestContent))
            {
                using (var titleEntityTokenResponseContent = titleEntityTokenResponseMessage.Content)
                {
                    string titleEntityTokenResponseString = await titleEntityTokenResponseContent.ReadAsStringAsync();

                    // Deserialize the http response
                    var titleEntityTokenResponseSuccess =
                        PlayFabSimpleJson.DeserializeObject <PlayFabJsonSuccess <AuthenticationModels.GetEntityTokenResponse> >(titleEntityTokenResponseString);

                    // Extract the actual get title entity token header
                    var titleEntityTokenResponse = titleEntityTokenResponseSuccess.data;

                    return(titleEntityTokenResponse.EntityToken);
                }
            }
        }
Beispiel #20
0
 protected string GetSerializedGroups(IConnection connection)
 {
     return(Uri.EscapeDataString(PlayFabSimpleJson.SerializeObject(connection.Groups)));
 }
Beispiel #21
0
        public static async Task <HttpResponseMessage> ExecuteFunction(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "CloudScript/ExecuteFunction")] HttpRequest request, ILogger log)
        {
            // Extract the caller's entity token
            string callerEntityToken = request.Headers["X-EntityToken"];

            // Extract the request body and deserialize
            string body = await DecompressHttpBody(request);

            var       execRequest = PlayFabSimpleJson.DeserializeObject <ExecuteFunctionRequest>(body);
            EntityKey entityKey   = null;

            if (execRequest.Entity != null)
            {
                entityKey = new EntityKey
                {
                    Id   = execRequest.Entity?.Id,
                    Type = execRequest.Entity?.Type
                };
            }

            // Create a FunctionContextInternal as the payload to send to the target function
            var functionContext = new FunctionContextInternal
            {
                CallerEntityProfile        = await GetEntityProfile(callerEntityToken, entityKey),
                TitleAuthenticationContext = new TitleAuthenticationContext
                {
                    Id          = Environment.GetEnvironmentVariable(TITLE_ID, EnvironmentVariableTarget.Process),
                    EntityToken = await GetTitleEntityToken()
                },
                FunctionArgument = execRequest.FunctionParameter
            };

            // Serialize the request to the azure function and add headers
            var functionRequestContent = new StringContent(PlayFabSimpleJson.SerializeObject(functionContext));

            functionRequestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var azureFunctionUri = ConstructLocalAzureFunctionUri(execRequest.FunctionName, request.Host);

            var sw = new Stopwatch();

            sw.Start();

            // Execute the local azure function
            using (var functionResponseMessage =
                       await httpClient.PostAsync(azureFunctionUri, functionRequestContent))
            {
                sw.Stop();
                long executionTime = sw.ElapsedMilliseconds;

                if (!functionResponseMessage.IsSuccessStatusCode)
                {
                    throw new Exception($"An error occured while executing the target function locally: FunctionName: {execRequest.FunctionName}, HTTP Status Code: {functionResponseMessage.StatusCode}.");
                }

                // Extract the response content
                using (var functionResponseContent = functionResponseMessage.Content)
                {
                    // Prepare a response to reply back to client with and include function execution results
                    var functionResult = new ExecuteFunctionResult
                    {
                        FunctionName              = execRequest.FunctionName,
                        FunctionResult            = await ExtractFunctionResult(functionResponseContent),
                        ExecutionTimeMilliseconds = (int)executionTime,
                        FunctionResultTooLarge    = false
                    };

                    // Reply back to client with final results
                    var output = new PlayFabJsonSuccess <ExecuteFunctionResult>
                    {
                        code   = 200,
                        status = "OK",
                        data   = functionResult
                    };
                    // Serialize the output and return it
                    var outputStr = PlayFabSimpleJson.SerializeObject(output);

                    return(new HttpResponseMessage
                    {
                        Content = new ByteArrayContent(CompressResponseBody(output, request)),
                        StatusCode = HttpStatusCode.OK
                    });
                }
            }
        }
Beispiel #22
0
 public string SerializeObject(object json, object jsonSerializerStrategy)
 {
     return(PlayFabSimpleJson.SerializeObject(json, (IJsonSerializerStrategy)jsonSerializerStrategy));
 }
Beispiel #23
0
 public string SerializeObject(object json)
 {
     return(PlayFabSimpleJson.SerializeObject(json));
 }
        public static async Task <dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try{
                string body = await req.ReadAsStringAsync();

                var context = JsonConvert.DeserializeObject <FunctionExecutionContext <dynamic> >(body);
                var request = JsonConvert.DeserializeObject <FunctionExecutionContext <MonsterLevelUpApiRequest> >(body).FunctionArgument;

                // 対象のモンスターを取得
                var userInventory = await DataProcessor.GetUserInventoryAsync(context);

                var userMonster = userInventory.userMonsterList.FirstOrDefault(u => u.id == request.userMonsterId);
                PMApiUtil.ErrorIf(userMonster == null, PMErrorCode.Unknown, "invalid userMonsterId");

                // 経験値を十分に保持しているかチェック
                var exp = userInventory.userPropertyList.FirstOrDefault(u => u.propertyId == (long)PropertyType.MonsterExp);
                PMApiUtil.ErrorIf(exp == null || exp.num < request.exp, PMErrorCode.Unknown, "not enough exp");

                // 何レベになるか計算
                var levelUpTableList = await DataProcessor.GetMasterAsyncOf <MonsterLevelUpTableMB>(context);

                var afterExp           = userMonster.customData.exp + request.exp;
                var targetLevelUpTable = levelUpTableList.OrderBy(m => m.id).LastOrDefault(m => m.totalRequiredExp <= afterExp);
                PMApiUtil.ErrorIf(targetLevelUpTable == null, PMErrorCode.Unknown, "invalid levelUpTable");
                var afterLevel = targetLevelUpTable.level;

                // 対象のモンスターがマスタに存在するかチェック
                var monsterList = await DataProcessor.GetMasterAsyncOf <MonsterMB>(context);

                var monster = monsterList.FirstOrDefault(m => m.id == userMonster.monsterId);
                PMApiUtil.ErrorIf(monster == null, PMErrorCode.Unknown, "invalie monsterId");

                // モンスターをレベルアップ
                var afterStatus = MonsterUtil.GetMonsterStatus(monster, afterLevel);
                var customData  = new UserMonsterCustomData()
                {
                    level  = afterLevel,
                    exp    = afterExp,
                    hp     = afterStatus.hp,
                    attack = afterStatus.attack,
                    heal   = afterStatus.heal,
                    grade  = userMonster.customData.grade,
                };
                await DataProcessor.UpdateUserMonsterCustomDataAsync(context, userMonster.id, customData);

                // 経験値を消費
                await DataProcessor.ConsumeItemAsync(context, exp.id, request.exp);

                // 強化後のレベルを返す
                var response = new MonsterLevelUpApiResponse()
                {
                    level = afterLevel
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }catch (PMApiException e) {
                // レスポンスの作成
                var response = new PMApiResponseBase()
                {
                    errorCode = e.errorCode,
                    message   = e.message
                };
                return(PlayFabSimpleJson.SerializeObject(response));
            }
        }
Beispiel #25
0
            public static TargetClass Convert(SourceClass input)
            {
                var json = PlayFabSimpleJson.SerializeObject(input);

                return(PlayFabSimpleJson.DeserializeObject <TargetClass>(json));
            }
Beispiel #26
0
        /// <summary>
        /// This is a helper function that verifies that the player's move wasn't made
        /// too quickly following their previous move, according to the rules of the game.
        /// If the move is valid, then it updates the player's statistics and profile data.
        /// This function is called from the "UpdatePlayerMove" handler above and also is
        /// triggered by the "RoomEventRaised" Photon room event in the Webhook handler
        /// below.
        ///
        /// For this example, the script defines the cooldown period (playerMoveCooldownInSeconds)
        /// as 15 seconds.A recommended approach for values like this would be to create them in Title
        /// Data, so that they can be queries in the script with a call to GetTitleData
        /// (https://api.playfab.com/Documentation/Server/method/GetTitleData). This would allow you to
        /// make adjustments to these values over time, without having to edit, test, and roll out an
        /// updated script.
        /// </summary>
        /// <param name="playerMove">The player's move object</param>
        /// <param name="currentPlayerId">The player's PlayFab ID</param>
        /// <param name="log">The logger object to log to</param>
        /// <returns>True if the player's move was valid, false otherwise</returns>
        private static async Task <bool> ProcessPlayerMove(PlayFabServerInstanceAPI serverApi, dynamic playerMove, string currentPlayerId, ILogger log)
        {
            var now = DateTime.Now;
            var playerMoveCooldownInSeconds = -15;

            var userInternalDataRequest = new GetUserDataRequest
            {
                PlayFabId = currentPlayerId,
                Keys      = new List <string>
                {
                    "last_move_timestamp"
                }
            };

            var playerDataResponse = await serverApi.GetUserInternalDataAsync(userInternalDataRequest);

            var playerData = playerDataResponse.Result.Data;
            var lastMoveTimeStampSetting = playerData["last_move_timestamp"];

            if (lastMoveTimeStampSetting != null)
            {
                var lastMoveTime = DateTime.Parse(lastMoveTimeStampSetting.Value);
                var timeSinceLastMoveInSeconds = (now - lastMoveTime) / 1000;
                log.LogDebug($"lastMoveTime: {lastMoveTime} now: {now} timeSinceLastMoveInSeconds: {timeSinceLastMoveInSeconds}");

                if (timeSinceLastMoveInSeconds.TotalSeconds < playerMoveCooldownInSeconds)
                {
                    log.LogError($"Invalid move - time since last move: {timeSinceLastMoveInSeconds}s less than minimum of {playerMoveCooldownInSeconds}s.");
                    return(false);
                }
            }

            var getStatsRequest = new GetPlayerStatisticsRequest
            {
                PlayFabId = currentPlayerId
            };

            var playerStats = (await serverApi.GetPlayerStatisticsAsync(getStatsRequest)).Result.Statistics;
            var movesMade   = 0;

            for (var i = 0; i < playerStats.Count; i++)
            {
                if (string.IsNullOrEmpty(playerStats[i].StatisticName))
                {
                    movesMade = playerStats[i].Value;
                }
            }
            movesMade += 1;
            var updateStatsRequest = new UpdatePlayerStatisticsRequest
            {
                PlayFabId  = currentPlayerId,
                Statistics = new List <StatisticUpdate>
                {
                    new StatisticUpdate
                    {
                        StatisticName = "movesMade",
                        Value         = movesMade
                    }
                }
            };

            await serverApi.UpdatePlayerStatisticsAsync(updateStatsRequest);

            await serverApi.UpdateUserInternalDataAsync(new UpdateUserInternalDataRequest
            {
                PlayFabId = currentPlayerId,
                Data      = new Dictionary <string, string>
                {
                    { "last_move_timestamp", DateTime.Now.ToUniversalTime().ToString() },
                    { "last_move", PlayFabSimpleJson.SerializeObject(playerMove) }
                }
            });

            return(true);
        }
Beispiel #27
0
    void Start()
    {
        gm = GameManager.GetGMInstance();

        for (int i = gm.tank_list.Count; i < 4; i++)
        {
            rank[i].SetActive(false);
        }



        string[] tankNames = new string[gm.tank_list.Count];
        int      index     = 0;

        foreach (string tankName in gm.dead_tank_list)
        {
            tankNames[index] = tankName;
            index++;
        }
        if (gm.dead_tank_list.Count != gm.tank_list.Count)
        {
            gm.tank_list.Sort((tank1, tank2) =>
            {
                return(tank1.GetComponent <TankModel>().health - tank2.GetComponent <TankModel>().health);
            });
            foreach (GameObject tank in gm.tank_list)
            {
                if (!gm.dead_tank_list.Contains(tank.name))
                {
                    tankNames[index] = tank.name;
                    index++;
                }
            }
        }

        for (int i = 0; i < tankNames.Length; i++)
        {
            string     teamName   = tankNames [tankNames.Length - i - 1];
            GameResult gameresult = new GameResult();
            gameresult.rank   = i + 1;
            gameresult.damage = gm.damageRecord [teamName];
            rank[i].GetComponentInChildren <Text>().text = "第" + gameresult.rank + "名:" + teamName + " 本局伤害:" + gameresult.damage;
            if (teamName == PhotonNetwork.player.CustomProperties ["Team"].ToString())               // 每个人更新自己的游戏数据
            {
                UpdateUserDataRequest request = new UpdateUserDataRequest();
                request.Data = new Dictionary <string, string> ();

                PlayFabUserData.totalGame++;
                request.Data.Add("TotalGame", PlayFabUserData.totalGame.ToString());
                PlayFabUserData.totalDamage += gameresult.damage;
                request.Data.Add("TotalDamage", PlayFabUserData.totalDamage.ToString());
                PlayFabUserData.damagPerGame = PlayFabUserData.totalDamage / PlayFabUserData.totalGame;
                PlayFabUserData.gameResults.Add(gameresult);
                request.Data.Add("GameResult", PlayFabSimpleJson.SerializeObject(PlayFabUserData.gameResults));

                PlayFabClientAPI.UpdateUserData(request, (result) => { }, (error) => { });
            }
//			if (PhotonNetwork.isMasterClient) {
//				// 跟新每局排名和伤害
//				UpdateUserDataRequest request = new UpdateUserDataRequest();
//				Dictionary<string,string> data = new Dictionary<string, string>();
//				data.Add("Rank","");
//			}
        }
    }
Beispiel #28
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "CloudScript/ExecuteFunction")] HttpRequest request, ILogger log)
        {
            // Extract the caller's entity token
            string callerEntityToken = request.Headers["X-EntityToken"];

            // Extract the request body and deserialize
            StreamReader reader = new StreamReader(request.Body);
            string       body   = await reader.ReadToEndAsync();

            ExecuteFunctionRequest execRequest = PlayFabSimpleJson.DeserializeObject <ExecuteFunctionRequest>(body);

            // Grab the title entity token for authentication
            var titleEntityToken = await GetTitleEntityToken();

            var argumentsUri = GetArgumentsUri();

            // Prepare the `Get Arguments` request
            var contextRequest = new GetArgumentsForExecuteFunctionRequest
            {
                AuthenticationContext = new PlayFabAuthenticationContext
                {
                    EntityToken = titleEntityToken
                },
                CallingEntity = callerEntityToken,
                Request       = execRequest
            };

            // Execute the arguments request
            PlayFabResult <GetArgumentsForExecuteFunctionResult> getArgsResponse =
                await PlayFabCloudScriptAPI.GetArgumentsForExecuteFunctionAsync(contextRequest);

            // Validate no errors on arguments request
            if (getArgsResponse.Error != null)
            {
                throw new Exception("Failed to retrieve functions argument");
            }

            // Extract the request for the next stage from the get arguments response
            EntityRequest entityRequest = getArgsResponse?.Result?.Request;

            // Assemble the target function's path in the current App
            string routePrefix  = GetHostRoutePrefix();
            string functionPath = routePrefix != null ? routePrefix + "/" + execRequest.FunctionName
                : execRequest.FunctionName;

            // Build URI of Azure Function based on current host
            var uriBuilder = new UriBuilder
            {
                Host = request.Host.Host,
                Port = request.Host.Port ?? 80,
                Path = functionPath
            };

            // Serialize the request to the azure function and add headers
            var functionRequestContent = new StringContent(PlayFabSimpleJson.SerializeObject(entityRequest));

            functionRequestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var sw = new Stopwatch();

            sw.Start();

            // Execute the local azure function
            using (var client = new HttpClient())
            {
                using (HttpResponseMessage functionResponseMessage =
                           await client.PostAsync(uriBuilder.Uri.AbsoluteUri, functionRequestContent))
                {
                    sw.Stop();
                    double executionTime = sw.ElapsedMilliseconds;

                    // Extract the response content
                    using (HttpContent functionResponseContent = functionResponseMessage.Content)
                    {
                        string functionResponseString = await functionResponseContent.ReadAsStringAsync();

                        // Prepare a response to reply back to client with and include function execution results
                        var functionResult = new ExecuteFunctionResult
                        {
                            FunctionName         = execRequest.FunctionName,
                            FunctionResult       = PlayFabSimpleJson.DeserializeObject(functionResponseString),
                            ExecutionTimeSeconds = executionTime
                        };

                        // Reply back to client with final results
                        var output = new PlayFabJsonSuccess <ExecuteFunctionResult>
                        {
                            code   = 200,
                            status = "OK",
                            data   = functionResult
                        };
                        var outputStr = PlayFabSimpleJson.SerializeObject(output);
                        return(new HttpResponseMessage
                        {
                            Content = new StringContent(outputStr, Encoding.UTF8, "application/json"),
                            StatusCode = HttpStatusCode.OK
                        });
                    }
                }
            }
        }