Skip to content

CloudBread를 사용하여 Flappy Bird 게임에 서버 구축 3. API 사용하기

YoonSeok Hong edited this page Oct 22, 2016 · 6 revisions

7. CloudBread 에 회원가입하기

  1. Facebook에서 UserID와 이름을 가져와서 CloudBread 서버에 등록하기 CBInsRegMember API 호출 (PostMan 참고)

  2. 유효한 사용자이면, 게임 화면으로 넘어가기

  • CBInsRegMember API호출 시, 새로 가입 된 사용자 응답
{
  "result": "2"
}
  • CBInsRegMember API호출 시, 중복된 사용자(이미 가입된 사용자)
status : 500 Internal Server Error

CloudBread.cs 파일에 CloudBread 서버에 회원 등록을 하기 위해 CBInsRegMember API 를 호출하도록 구현

public void CBInsRegMember(Action<string, WWW> callback)
{
    var ServerEndPoint = ServerAddress + "api/CBInsRegMember";

   WWWHelper helper = WWWHelper.Instance;
   helper.OnHttpRequest += OnHttpRequest;

   MemberData memberData = new MemberData
   {
        MemberID_Members = (string)PlayerPrefs.GetString("userId"),
        EmailAddress_Members = (string)PlayerPrefs.GetString("userId"),
        Name1_Members = (string)PlayerPrefs.GetString("nickName")
   };

   JsonWriter jsonWriter = new JsonWriter();
   string jsonBody = jsonWriter.Write(memberData);

   helper.POST("CBInsRegMember", ServerEndPoint, jsonBody);

   Callback = callback;
}

FacebookLoginScript.cs 의 Login 콜백 함수에서 바로 CBInsRegMember 호출

private void Callback_login(string id, WWW www)
{
    print(www.text);
    string resultJson = www.text;

    JsonReader jsonReader = new JsonReader();
    AuthData resultData = jsonReader.Read<AuthData>(resultJson);

    // Azure 인증을 위해 발급받은 Azure Token 을 헤더에 추가
    AzureMobileAppRequestHelper.AuthToken = resultData.authenticationToken;

    // 게임에서 사용 할 userId 를 PlayerPrefs 에 저장
    PlayerPrefs.SetString("userId", resultData.user.userId);

    // CBInsRegMember 함수를 사용하여 CloudBread 에 memberId 등록하기
    CloudBread cb = new CloudBread();
    cb.CBInsRegMember(Callback_CBInsRegMember);
}
    public void Callback_CBInsRegMember(string id, WWW www)
    {
        if (www.error != null) //새로 회원 가입
        {
            print("이미 가입된 회원");
            StartGame();


        }
        else //이미 가입된 회원
        {
            print("새로 가입한 회원");
            StartGame();
        }
    }

FacebookLoginScript.cs 스크립트 완성

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using Assets.Scripts.CloudBread;
using JsonFx.Json;
using UnityEngine.SceneManagement;

public class FacebookLoginScript : MonoBehaviour {

// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}

    // Awake function from Unity's MonoBehavior
    void Awake()
    {
        if (!FB.IsInitialized)
        {
            // Initialize the Facebook SDK
            FB.Init(InitCallback, OnHideUnity);
        }
        else {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp();
        }
    }

    private void InitCallback()
    {
        if (FB.IsInitialized)
        {
            // Signal an app activation App Event
            FB.ActivateApp();
            // Continue with Facebook SDK
            // ...
        }
        else {
            Debug.Log("Failed to Initialize the Facebook SDK");
        }
    }

    private void LoginwithPermissions()
    {
        var perms = new List<string>() { "public_profile", "email", "user_friends" };
        FB.LogInWithReadPermissions(perms, AuthCallback);
    }

    private void AuthCallback(ILoginResult result)
    {
        if (FB.IsLoggedIn)
        {
            // AccessToken class will have session details
            var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
            // Print current access token's User ID
            Debug.Log(aToken.UserId);
            // Print current access token's granted permissions
            foreach (string perm in aToken.Permissions)
            {
                Debug.Log(perm);
            }

            // 유저 이름(닉네임) 불러오기
            FB.API("me?fields=name", HttpMethod.GET, NameCallBack);


            // 인증 토큰 가져오기
            CloudBread cb = new CloudBread();
            cb.Login(AzureAuthentication.AuthenticationProvider.Facebook, aToken.TokenString, Callback_login);
        }
        else {
            Debug.Log("User cancelled login");
        }
    }

    private void Callback_login(string id, WWW www)
    {
        print(www.text);
        string resultJson = www.text;

        JsonReader jsonReader = new JsonReader();
        AuthData resultData = jsonReader.Read<AuthData>(resultJson);

        AzureMobileAppRequestHelper.AuthToken = resultData.authenticationToken;



        PlayerPrefs.SetString("userId", resultData.user.userId);

        CloudBread cb = new CloudBread();
        cb.CBInsRegMember(Callback_CBInsRegMember);

    }

    public void Callback_CBInsRegMember(string id, WWW www)
    {
        if (www.error != null) //새로 회원 가입
        {
            print("이미 가입된 회원");
            StartGame();


        }
        else //이미 가입된 회원
        {
            print("새로 가입한 회원");
            StartGame();
        }
    }

    public void StartGame()
    {
        SceneManager.LoadScene("mainGame");
    }

    private void NameCallBack(IGraphResult result)
    {
        string userName = (string)result.ResultDictionary["name"];
        print(userName + "님 안녕하세요^^");
        PlayerPrefs.SetString("nickName", userName);
    }

    private void OnHideUnity(bool isGameShown)
    {
        if (!isGameShown)
        {
            // Pause the game - we will need to hide
            Time.timeScale = 0;
        }
        else {
            // Resume the game - we're getting focus again
            Time.timeScale = 1;
        }
    }

    public void FacebookLoginBtnClick()
    {
        if (!FB.IsLoggedIn)
            LoginwithPermissions();
    }
}

8. CloudBread에 게임 기록 저장하기

  1. ScoreManagerScript.cs 파일 열기

  2. 게임 끝났을 때, CBComUdtMmberGameInfoes 호출을 위해, GameState가 Dead 일 때 추가하기

  3. CBComUdtMmberGameInfoes API 호출을 위해 MemberGameInfo 클래스 생성 (PostMan 참조)

  4. CloudBread 클래스에 CBComUDTMemberGameInofes 호출 구현

        public void CBComUdtMemberGameInfoes(Action<string, WWW> callback)
        {
            var ServerEndPoint = ServerAddress + "api/CBComUdtMemberGameInfoes";

            WWWHelper helper = WWWHelper.Instance;
            helper.OnHttpRequest += OnHttpRequest;

            MemberGameInfo gameinfoData = new MemberGameInfo
            {
                MemberID = (string)PlayerPrefs.GetString("userId"),

                Level = 2,
                Points = PlayerPrefs.GetInt("bestScore")
            };

            JsonWriter jsonWriter = new JsonWriter();
            string jsonBody = jsonWriter.Write(gameinfoData);

            helper.POST("CBComUdtMemberGameInfoes", ServerEndPoint, jsonBody);

            Callback = callback;
        }

        class MemberGameInfo
        {
            public string MemberID;
            public int Level = 0;
            public int Exps = 0;
            public int Points = 0;
            public string UserSTAT1;
            public string UserSTAT2;
            public string UserSTAT3;
            public string UserSTAT4;
            public string UserSTAT5;
            public string UserSTAT6;
            public string UserSTAT7;
            public string UserSTAT8;
            public string UserSTAT9;
            public string UserSTAT10;
            public string sCol1;
            public string sCol2;
            public string sCol3;
            public string sCol4;
            public string sCol5;
            public string sCol6;
            public string sCol7;
            public string sCol8;
            public string sCol9;
            public string sCol10;

        }
  1. ScoreManagerScript 에서 CBComDUTMemberGameInfoes 호출하기

기존에는 항상 게임 상태와 상관없이 항상 Update 되던 함수를 게임 플레이 중인 모드와 게임이 죽었을 때 모드로 분리

    if (GameStateManager.GameState == GameState.Playing)
       {
           if (previousScore != Score) //save perf from non needed calculations
           {
               if (Score < 10)
               {
                   //just draw units
                   Units.sprite = numberSprites[Score];
               }
               else if (Score >= 10 && Score < 100)
               {
                   (Tens.gameObject as GameObject).SetActive(true);
                   Tens.sprite = numberSprites[Score / 10];
                   Units.sprite = numberSprites[Score % 10];
               }
               else if (Score >= 100)
               {
                   (Hundreds.gameObject as GameObject).SetActive(true);
                   Hundreds.sprite = numberSprites[Score / 100];
                   int rest = Score % 100;
                   Tens.sprite = numberSprites[rest / 10];
                   Units.sprite = numberSprites[rest % 10];
               }
           }

       }
       else if (GameStateManager.GameState == GameState.Dead)
       {
       }

게임 상태가 죽었을 때(GmaeStateManage.Gamestate == Gamestate.Dead) CB CBComUdtMemberGameInfoes 호출하기

else if (GameStateManager.GameState == GameState.Dead)
{
      if (flag){
          flag = false;
          PlayerPrefs.SetInt("bestScore", Score);
          CloudBread cb = new CloudBread();
          cb.CBComUdtMemberGameInfoes(Callback_Success);
      }
}
public void Callback_Success(string id, WWW www)
{
    print("[" + id + "] Success");
}
Clone this wiki locally