Пример #1
0
    public IEnumerator DeleteMatchLobby(string matchLobbyId)
    {
        ExecutionCompleted = false;

        var request = GetExecuteFunctionRequest(
            Constants.DELETE_MATCH_LOBBY_FUNCTION_NAME,
            new DeleteMatchLobbyInfoRequest
        {
            Id           = matchLobbyId,
            MatchLobbyId = matchLobbyId
        });

        PlayFabCloudScriptAPI.ExecuteFunction(request,
                                              (result) =>
        {
            ExecutionCompleted = true;
        },
                                              (error) =>
        {
            ExecutionCompleted = true;
            Debug.Log($"DeleteMatchLobby request failed. Message: ${error.ErrorMessage}, Code: ${error.HttpCode}");
        }
                                              );

        yield return(WaitForExecution());
    }
    public IEnumerator JoinMatchLobby(string id, string invitationCode = null)
    {
        ExecutionCompleted = false;

        var request = GetExecuteFunctionRequest(
            Constants.JOIN_MATCH_LOBBY,
            new JoinMatchLobbyRequest {
            MatchLobbyId = id, InvitationCode = invitationCode
        });

        PlayFabCloudScriptAPI.ExecuteFunction(request,
                                              (result) =>
        {
            JoinMatchLobbyResponse = result?.FunctionResult != null ? JsonUtility.FromJson <ResponseWrapper <JoinMatchLobbyResponse> >(result.FunctionResult.ToString()) : null;
            ExecutionCompleted     = true;
        },
                                              (error) =>
        {
            JoinMatchLobbyResponse = null;
            ExecutionCompleted     = true;
            Debug.Log($"MatchLobby join request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
        }
                                              );

        yield return(WaitForExecution());
    }
    public IEnumerator CreateMatchLobby(string matchLobbyId, string networkId, bool locked)
    {
        ExecutionCompleted = false;

        var request = GetExecuteFunctionRequest(
            Constants.CREATE_MATCH_LOBBY,
            new CreateMatchLobbyRequest
        {
            MatchLobbyId = matchLobbyId,
            NetworkId    = networkId,
            Locked       = locked
        });

        PlayFabCloudScriptAPI.ExecuteFunction(request,
                                              (result) =>
        {
            MatchLobby         = result?.FunctionResult != null ? JsonUtility.FromJson <MatchLobby>(result.FunctionResult.ToString()) : null;
            ExecutionCompleted = true;
        },
                                              (error) =>
        {
            MatchLobby         = null;
            ExecutionCompleted = true;
            Debug.Log($"MatchLobby creation request failed. Message: ${error.ErrorMessage}, Code: ${error.HttpCode}");
        }
                                              );

        yield return(WaitForExecution());
    }
    public IEnumerator LeaveMatchLobby(string matchLobbyId)
    {
        ExecutionCompleted = false;

        var request = GetExecuteFunctionRequest(
            Constants.LEAVE_MATCH_LOBBY,
            new LeaveMatchLobbyRequest {
            MatchLobbyId = matchLobbyId
        });

        PlayFabCloudScriptAPI.ExecuteFunction(request,
                                              (result) =>
        {
            MatchLobby         = result?.FunctionResult != null ? JsonUtility.FromJson <MatchLobby>(result.FunctionResult.ToString()) : null;
            ExecutionCompleted = true;
        },
                                              (error) =>
        {
            MatchLobby         = null;
            ExecutionCompleted = true;
            Debug.Log($"MatchLobby Leave request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
        }
                                              );

        yield return(WaitForExecution());
    }
    public IEnumerator SetMatchLobbyLockState(string matchLobbyId, bool lockState)
    {
        ExecutionCompleted = false;

        var request = GetExecuteFunctionRequest(
            Constants.SET_MATCH_LOBBY_LOCK_STATE,
            new SetMatchLobbyLockStateRequest
        {
            MatchLobbyId = matchLobbyId,
            Locked       = lockState
        }
            );

        PlayFabCloudScriptAPI.ExecuteFunction(request,
                                              (result) =>
        {
            SetMatchLobbyLockStateResponse = result?.FunctionResult != null ? JsonUtility.FromJson <ResponseWrapper <SetMatchLobbyLockStateResponse> >(result.FunctionResult.ToString()) : null;
            ExecutionCompleted             = true;
        },
                                              (error) =>
        {
            SetMatchLobbyLockStateResponse = null;
            ExecutionCompleted             = true;
            Debug.Log($"MatchLobby Lobby locked state setting has failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
        }
                                              );

        yield return(WaitForExecution());
    }
Пример #6
0
    private void OnLoginSuccess(LoginResult result)
    {
        // Get Entity Information
        entityId   = result.EntityToken.Entity.Id;
        entityType = result.EntityToken.Entity.Type;

        // Get Account info to see if user has a linked account.
        var request = new GetAccountInfoRequest {
            PlayFabId = result.PlayFabId
        };

        PlayFabClientAPI.GetAccountInfo(request,
                                        resultA => {
            // If no linked account show the link account panel.
            if (resultA.AccountInfo.Username == "" || resultA.AccountInfo.Username == null &&
                (!PlayerPrefs.HasKey("LINK_ACCOUNT_REMINDER") || PlayerPrefs.GetInt("LINK_ACCOUNT_REMINDER") == 1))
            {
                panel.SetActive(true);
            }
        },
                                        error => { Debug.LogError(error.GenerateErrorReport()); });

        // Get object of title entity.
        var getRequest = new GetObjectsRequest {
            Entity = new EntityKey {
                Id = entityId, Type = entityType
            }
        };

        PlayFabDataAPI.GetObjects(getRequest,
                                  r => {
            // If user has no pc yet, create one with the server function.
            if (!r.Objects.ContainsKey("pc1"))
            {
                var cloudscriptrequest = new ExecuteEntityCloudScriptRequest {
                    FunctionName = "createFirstComputer", GeneratePlayStreamEvent = true
                };
                PlayFabCloudScriptAPI.ExecuteEntityCloudScript(cloudscriptrequest,
                                                               re => {
                    GameManager.gm.SetComputer("cpu1", "mem1");
                },
                                                               error => { Debug.LogError(error.GenerateErrorReport()); });
            }
            else
            {
                JsonObject jsonResult = (JsonObject)r.Objects["pc1"].DataObject;

                GameManager.gm.SetComputer(jsonResult["cpu"].ToString(), jsonResult["memory"].ToString());
            }

            // A way to loop through dictionary.

            /*foreach(KeyValuePair<string, ObjectResult> obj in r.Objects)
             * {
             *  Debug.Log(obj.Key);
             *  Debug.Log(obj.Value.ObjectName);
             * }*/
        },
                                  error => { });
    }
        public IEnumerator SetWinner(string playerId)
        {
            var request = GetExecuteFunctionRequest(
                Constants.SET_WINNER_GAME_FUNCTION_NAME,
                new SetGameWinnerRequest()
            {
                SharedGroupId = sharedGroupId,
                PlayerId      = playerId
            });

            PlayFabCloudScriptAPI.ExecuteFunction(
                request,
                (result) =>
            {
                ExecutionCompleted = true;
                GameState          = JsonUtility.FromJson <GameState>(result.FunctionResult.ToString());
            },
                (error) =>
            {
                Debug.Log($"Set Game Winner request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            }
                );

            yield return(WaitForExecution());
        }
        public IEnumerator MakeMove(TicTacToeMove move)
        {
            var request = GetExecuteFunctionRequest(
                Constants.MULTIPLAYER_MOVE_FUNCTION_NAME,
                new MakeMultiplayerMoverRequest()
            {
                SharedGroupId = sharedGroupId,
                PlayerId      = Player.PlayFabId,
                PlayerMove    = move
            });

            PlayFabCloudScriptAPI.ExecuteFunction(
                request,
                (result) =>
            {
                ExecutionCompleted      = true;
                MultiplayerMoveResponse = JsonUtility.FromJson <MakeMultiplayerMoveResponse>(result.FunctionResult.ToString());
            },
                (error) =>
            {
                Debug.Log($"Make multiplayer move request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            }
                );

            yield return(WaitForExecution());
        }
Пример #9
0
    public IEnumerator CreateMatchLobby(string groupName)
    {
        ExecutionCompleted = false;

        var request = GetExecuteFunctionRequest(
            Constants.CREATE_MATCH_LOBBY,
            new CreateMatchLobbyRequest {
            SharedGroupId = groupName
        });

        PlayFabCloudScriptAPI.ExecuteFunction(request,
                                              (result) =>
        {
            TicTacToeSharedGroupData = result?.FunctionResult != null ? JsonUtility.FromJson <TicTacToeSharedGroupData>(result.FunctionResult.ToString()) : null;
            ExecutionCompleted       = true;
        },
                                              (error) =>
        {
            TicTacToeSharedGroupData = null;
            ExecutionCompleted       = true;
            Debug.Log($"MatchLobby creation request failed. Message: ${error.ErrorMessage}, Code: ${error.HttpCode}");
        }
                                              );

        yield return(WaitForExecution());
    }
Пример #10
0
    public IEnumerator GetMatchLobbyList(string filter = "")
    {
        ExecutionCompleted = false;

        var request = GetExecuteFunctionRequest(
            Constants.SEARCH_MATCH_LOBBIES_FUNCTION_NAME,
            new SearchMatchLobbiesRequest {
            SearchTerm = filter
        });

        PlayFabCloudScriptAPI.ExecuteFunction(request,
                                              (result) =>
        {
            var resultList = JsonHelper.FromJson <MatchLobby>(result.FunctionResult.ToString());
            MatchLobbyList = resultList.ToList();

            ExecutionCompleted = true;
        },
                                              (error) =>
        {
            MatchLobbyList     = null;
            ExecutionCompleted = true;
            Debug.Log($"GetMatchLobbyList request failed. Message: ${error.ErrorMessage}, Code: ${error.HttpCode}");
        }
                                              );

        yield return(WaitForExecution());
    }
        public override IEnumerator ExecuteRequest()
        {
            // Create the move request
            var request = new ExecuteFunctionRequest
            {
                FunctionName      = Constants.PLAYER_MOVE_FUNCTION_NAME,
                FunctionParameter = new MakePlayerMoveRequest
                {
                    PlayFabId = Player.PlayFabId,
                    Move      = MoveToExecute
                },
                AuthenticationContext = new PlayFabAuthenticationContext
                {
                    EntityToken = Player.EntityToken
                }
            };

            // Execute the move request
            PlayFabCloudScriptAPI.ExecuteFunction(request,
                                                  (result) =>
            {
                ExecutionCompleted = true;
                MoveResult         = PlayFabSimpleJson.DeserializeObject <MakePlayerMoveResult>(result.FunctionResult.ToString());
            },
                                                  (error) =>
            {
                throw new Exception($"MakePlayerMove request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            });

            yield return(WaitForExecution());
        }
        public IEnumerator Delete(string sharedGroupId)
        {
            ExecutionCompleted = false;
            Debug.Log($"DeleteShcaredGroupHandler request '{sharedGroupId}'");

            var request = GetExecuteFunctionRequest(
                Constants.DELETE_SHARED_GROUP_FUNCTION_NAME,
                new DeleteSharedGroupRequest {
                SharedGroupId = sharedGroupId
            });

            PlayFabCloudScriptAPI.ExecuteFunction(request,
                                                  (result) =>
            {
                Debug.Log("Deleted");
                ExecutionCompleted = true;
            },
                                                  (error) =>
            {
                Debug.Log($"DeleteSharedGroupHandler request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            }
                                                  );

            yield return(WaitForExecution());
        }
Пример #13
0
    /*
     *
     *  Execute a PlayFab Cloud Script function to update the group entity object data to the
     *  updated CSV. Title-level data should not be changed directly from the client.
     *
     *  @param dataobj: the updated CSV; the Cloud Script function sets the entity group object data to
     *      this value.
     *  @param item_id: ItemID of the item that was either added or removed
     *
     */

    private void UpdateGroupObject(string dataobj, bool adding_item, string item_id)
    {
        /* Call a Cloud Script function to update the group entity object data */
        PlayFabCloudScriptAPI.ExecuteEntityCloudScript(new PlayFab.CloudScriptModels.ExecuteEntityCloudScriptRequest()
        {
            // Group entity on which we call Cloud Script function
            Entity = new PlayFab.CloudScriptModels.EntityKey {
                Id = WishList.group_entityKeyId, Type = WishList.group_entityKeyType
            },
            // Cloud Script function name
            FunctionName = "addItemtoWishlist",
            // Function parameters for Cloud Script function; prop1 is the updated CSV
            FunctionParameter = new { prop1 = dataobj },
            // Create a Playstream event, which can be found in Game Manager; helpful for debugging and logging
            GeneratePlayStreamEvent = true
        }, result => {
            /* The Cloud Script function returned successfully, so we must update the store in our Unity game. */
            if (adding_item)
            {
                /* The item with ItemID item_id was added, so update store accordingly. */
                StoreSetup.SetUpStore(item_id, false);
            }
            else
            {
                /* The item with ItemID item_id was removed, so update store accordingly. */
                StoreSetup.SetUpStore(item_id, true);
            }
        }, error => { Debug.LogError(error.GenerateErrorReport()); });
    }
        public IEnumerator Get(string sharedGroupId)
        {
            ExecutionCompleted = false;
            SharedGroupData    = null;

            var request = GetExecuteFunctionRequest(
                Constants.GET_SHARED_GROUP,
                new GetSharedGroupRequest {
                SharedGroupId = sharedGroupId
            });

            PlayFabCloudScriptAPI.ExecuteFunction(request,
                                                  (result) =>
            {
                SharedGroupData    = result?.FunctionResult != null ? JsonUtility.FromJson <TicTacToeSharedGroupData>(result.FunctionResult.ToString()) : null;
                ExecutionCompleted = true;
            },
                                                  (error) =>
            {
                SharedGroupData    = null;
                ExecutionCompleted = true;
                Debug.Log($"Shared Group get request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            }
                                                  );

            yield return(WaitForExecution());
        }
Пример #15
0
        public IEnumerator JoinMatch()
        {
            ExecutionCompleted = false;

            var request = GetExecuteFunctionRequest(
                Constants.JOIN_MATCH_FUNCTION_NAME,
                new StartMatchRequest {
                SharedGroupId = sharedGroupId
            });

            PlayFabCloudScriptAPI.ExecuteFunction(request,
                                                  (result) =>
            {
                ExecutionCompleted       = true;
                TicTacToeSharedGroupData = JsonUtility.FromJson <TicTacToeSharedGroupData>(result.FunctionResult.ToString());
            },
                                                  (error) =>
            {
                TicTacToeSharedGroupData = null;
                ExecutionCompleted       = true;
                Debug.Log($"StartMatch request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            }
                                                  );

            yield return(WaitForExecution());
        }
        public override IEnumerator ExecuteRequest()
        {
            var request = new ExecuteFunctionRequest
            {
                FunctionName      = Constants.WIN_CHECK_FUNCTION_NAME,
                FunctionParameter = new PlayFabIdRequest
                {
                    PlayFabId = Player.PlayFabId
                },
                AuthenticationContext = new PlayFabAuthenticationContext
                {
                    EntityToken = Player.EntityToken
                }
            };

            PlayFabCloudScriptAPI.ExecuteFunction(request,
                                                  (result) =>
            {
                ExecutionCompleted = true;
                WinCheckResult     = PlayFabSimpleJson.DeserializeObject <WinCheckResult>(result.FunctionResult.ToString());
            },
                                                  (error) =>
            {
                throw new Exception($"WinCheck request failed. Message: ${error.ErrorMessage}, Code: ${error.HttpCode}");
            });

            yield return(WaitForExecution());
        }
Пример #17
0
        public override IEnumerator ExecuteRequest()
        {
            // Create the reset request
            var request = new ExecuteFunctionRequest
            {
                FunctionName      = Constants.RESET_GAME_STATE_FUNCTION_NAME,
                FunctionParameter = new PlayFabIdRequest
                {
                    PlayFabId = Player.PlayFabId
                },
                AuthenticationContext = new PlayFabAuthenticationContext
                {
                    EntityToken = Player.EntityToken
                }
            };

            // Execute the reset request
            PlayFabCloudScriptAPI.ExecuteFunction(request,
                                                  (result) =>
            {
                ExecutionCompleted = true;
            },
                                                  (error) =>
            {
                throw new Exception($"ResetGameState request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            });

            yield return(WaitForExecution());
        }
Пример #18
0
        private static void SendChatMessage(string targetPlayer, string message)
        {
            // Sending a chat message is a simple Azure Function execution where we pass in the target player and message.
            var sendChatRequest = new ExecuteFunctionRequest()
            {
                FunctionName            = "SendChatMessage",
                FunctionParameter       = new { TargetPlayer = targetPlayer, Message = message },
                GeneratePlayStreamEvent = true
            };

            PlayFabCloudScriptAPI.ExecuteFunctionAsync(sendChatRequest);
        }
Пример #19
0
    /*
     *
     *  Execute a PlayFab Cloud Script function to add another PlayFab player to the entity group as a member. This allows the added
     *  player to view the owner's wishlist.
     *
     *  @param playfabid: the PlayFab ID of the player who we want to add to the wish list entity group
     *
     */

    public static void AddPlayFabIdToGroup(string playfabid)
    {
        /*  The Cloud Script function adds the member with the corresponding PlayFab ID to the entity group, so they
         *  can view the wish list. */
        PlayFabCloudScriptAPI.ExecuteEntityCloudScript(new PlayFab.CloudScriptModels.ExecuteEntityCloudScriptRequest()
        {
            // The entity key for the group to whom we want to add a player
            Entity = new PlayFab.CloudScriptModels.EntityKey {
                Id = group_entityKeyId, Type = group_entityKeyType
            },
            // The name of the Cloud Script function we are calling
            FunctionName = "addPlayFabIdToGroup",
            // The parameter provided to your function
            FunctionParameter = new { id = playfabid },
            // Optional - Shows this event in PlayStream; helpful for logging and debugging
            GeneratePlayStreamEvent = true
        }, result => {
        }, error => { Debug.LogError(error.GenerateErrorReport()); });
    }
        public IEnumerator Get()
        {
            var request = GetExecuteFunctionRequest(
                Constants.GET_GAME_STATUS_FUNCTION_NAME,
                new GetGameStatusRequest {
                SharedGroupId = sharedGroupId
            });

            PlayFabCloudScriptAPI.ExecuteFunction(request,
                                                  (result) =>
            {
                ExecutionCompleted = true;
                GameState          = JsonUtility.FromJson <GameState>(result.FunctionResult.ToString());
            },
                                                  (error) =>
            {
                Debug.Log($"GetGameStatus request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}");
            }
                                                  );

            yield return(WaitForExecution());
        }
Пример #21
0
    /*
     *
     *  Execute a PlayFab Cloud Script function to create an entity group for the player's wish list. We use
     *  Cloud Script because title-level data should not be changed directly from the client.
     *
     *  @param group_name: the name of the entity group
     *
     */

    private static void CreateWishlist(string group_name)
    {
        /* Execute Cloud Script function to create the entity group for the wishlist */
        PlayFabCloudScriptAPI.ExecuteEntityCloudScript(new PlayFab.CloudScriptModels.ExecuteEntityCloudScriptRequest()
        {
            /*  The entity is the player who should be the administrator and first member of the entity group; in our case, this is the player who
             *  owns the wish list */
            Entity = new PlayFab.CloudScriptModels.EntityKey {
                Id = LoginClass.getPlayerEntityKeyId(), Type = LoginClass.getPlayerEntityKeyType()
            },
            // The name of the Cloud Script function we are calling
            FunctionName = "createUserWishList",
            // The parameter provided to your function
            FunctionParameter = new { groupName = group_name },
            // Optional - Shows this event in PlayStream; helpful for logging and debugging
            GeneratePlayStreamEvent = true
        }, result => {
            JsonObject jsonResult = (JsonObject)result.FunctionResult;

            WishList.group_entityKeyId   = (string)jsonResult["ek_id"];
            WishList.group_entityKeyType = (string)jsonResult["ek_type"];
        }, error => { Debug.LogError(error.GenerateErrorReport()); });
    }
Пример #22
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
                        });
                    }
                }
            }
        }