Skip to content

Commit

Permalink
create immutable X sample game
Browse files Browse the repository at this point in the history
  • Loading branch information
kaihirota committed Oct 20, 2024
1 parent cbe878b commit 1813381
Show file tree
Hide file tree
Showing 9 changed files with 496 additions and 179 deletions.
47 changes: 43 additions & 4 deletions Assets/Shared/Scripts/UI/LevelCompleteScreen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using UnityEngine.UI;
using System;
using System.Collections.Generic;
using Immutable.Passport;

namespace HyperCasual.Runner
{
Expand Down Expand Up @@ -108,19 +109,47 @@ public void OnEnable()
m_NextButton.RemoveListener(OnNextButtonClicked);
m_NextButton.AddListener(OnNextButtonClicked);

// Set listener to "Continue with Passport" button
// Set listener to "Continue with Passport" button
m_ContinuePassportButton.RemoveListener(OnContinueWithPassportButtonClicked);
m_ContinuePassportButton.AddListener(OnContinueWithPassportButtonClicked);

// Set listener to "Try again" button
m_TryAgainButton.RemoveListener(OnTryAgainButtonClicked);
m_TryAgainButton.AddListener(OnTryAgainButtonClicked);

ShowNextButton(true);
// Show 'Next' button if player is already logged into Passport
ShowNextButton(SaveManager.Instance.IsLoggedIn);
// Show "Continue with Passport" button if the player is not logged into Passport
ShowContinueWithPassportButton(!SaveManager.Instance.IsLoggedIn);
}

private void OnContinueWithPassportButtonClicked()
private async void OnContinueWithPassportButtonClicked()
{
try
{
// Show loading
ShowContinueWithPassportButton(false);
ShowLoading(true);

// Log into Passport
await Passport.Instance.Login();

// Successfully logged in
// Save a persistent flag in the game that the player is logged in
SaveManager.Instance.IsLoggedIn = true;
// Show 'Next' button
ShowNextButton(true);
ShowLoading(false);
// Take the player to the Setup Wallet screen
m_SetupWalletEvent.Raise();
}
catch (Exception ex)
{
Debug.Log($"Failed to log into Passport: {ex.Message}");
// Show Continue with Passport button again
ShowContinueWithPassportButton(true);
ShowLoading(false);
}
}

private void OnTryAgainButtonClicked()
Expand All @@ -129,7 +158,17 @@ private void OnTryAgainButtonClicked()

private void OnNextButtonClicked()
{
m_NextLevelEvent.Raise();
// Check if the player is already using a new skin
if (!SaveManager.Instance.UseNewSkin)
{
// Player is not using a new skin, take player to Unlocked Skin screen
m_UnlockedSkinEvent.Raise();
}
else
{
// Player is already using a new skin, take player to the next level
m_NextLevelEvent.Raise();
}
}

private void ShowCompletedContainer(bool show)
Expand Down
34 changes: 32 additions & 2 deletions Assets/Shared/Scripts/UI/MainMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Immutable.Passport;

namespace HyperCasual.Runner
{
Expand All @@ -23,7 +24,9 @@ public class MainMenu : View
[SerializeField]
GameObject m_Loading;

void OnEnable()
Passport passport;

async void OnEnable()
{
ShowLoading(true);

Expand All @@ -34,8 +37,34 @@ void OnEnable()
m_LogoutButton.RemoveListener(OnLogoutButtonClick);
m_LogoutButton.AddListener(OnLogoutButtonClick);

// Initialise Passport
string clientId = "YOUR_IMMUTABLE_CLIENT_ID";
string environment = Immutable.Passport.Model.Environment.SANDBOX;
passport = await Passport.Init(clientId, environment);

// Check if the player is supposed to be logged in and if there are credentials saved
if (SaveManager.Instance.IsLoggedIn && await Passport.Instance.HasCredentialsSaved())
{
// Try to log in using saved credentials
bool success = await Passport.Instance.Login(useCachedSession: true);
// Update the login flag
SaveManager.Instance.IsLoggedIn = success;

// Set up wallet if successful
if (success)
{
await Passport.Instance.ConnectImx();
}
} else {
// No saved credentials to re-login the player, reset the login flag
SaveManager.Instance.IsLoggedIn = false;
}

ShowLoading(false);
ShowStartButton(true);

// Show the logout button if the player is logged in
ShowLogoutButton(SaveManager.Instance.IsLoggedIn);
}

void OnDisable()
Expand All @@ -49,7 +78,7 @@ void OnStartButtonClick()
AudioManager.Instance.PlayEffect(SoundID.ButtonSound);
}

void OnLogoutButtonClick()
async void OnLogoutButtonClick()
{
try
{
Expand All @@ -59,6 +88,7 @@ void OnLogoutButtonClick()
ShowLoading(true);

// Logout
await passport.Logout();

// Reset the login flag
SaveManager.Instance.IsLoggedIn = false;
Expand Down
125 changes: 95 additions & 30 deletions Assets/Shared/Scripts/UI/MintScreen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,19 @@
using UnityEngine.UI;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using Cysharp.Threading.Tasks;
using Immutable.Passport;
using Immutable.Passport.Model;

[Serializable]
public class MintResult
{
public string token_id;
public string contract_address;
public string tx_id;
}

namespace HyperCasual.Runner
{
Expand Down Expand Up @@ -33,6 +45,9 @@ public class MintScreen : View
[SerializeField]
HyperCasualButton m_WalletButton;

// If there's an error minting, these values will be used when the player clicks the "Try again" button
private bool mintedFox = false;

public void OnEnable()
{
// Set listener to 'Next' button
Expand All @@ -47,10 +62,13 @@ public void OnEnable()
m_WalletButton.RemoveListener(OnWalletClicked);
m_WalletButton.AddListener(OnWalletClicked);

// Reset values
mintedFox = false;

Mint();
}

private void Mint()
private async void Mint()
{
try
{
Expand All @@ -59,20 +77,80 @@ private void Mint()
ShowError(false);
ShowNextButton(false);

// Mint
// Mint fox if not minted yet
if (!mintedFox)
{
MintResult mintResult = await MintFox();

ShowMintedMessage();
ShowLoading(false);
ShowError(false);
ShowNextButton(true);
// Show minted message if minted fox successfully
ShowMintedMessage();
}
}
catch (Exception ex)
{
// Failed to mint, let the player try again
Debug.Log($"Failed to mint: {ex.Message}");
ShowLoading(false);
ShowError(true);
ShowNextButton(false);
Debug.Log($"Failed to mint or transfer: {ex.Message}");
}
ShowLoading(false);

// Show error if failed to mint fox
ShowError(!mintedFox);

// Show next button if fox minted successfully
ShowNextButton(mintedFox);
}

/// <summary>
/// Gets the wallet address of the player.
/// </summary>
private async UniTask<string> GetWalletAddress()
{
string address = await Passport.Instance.GetAddress();
return address;
}

/// <summary>
/// Mints a fox (i.e. Immutable Runner Fox) to the player's wallet
/// </summary>
/// <returns>True if minted a fox successfully to player's wallet. Otherwise, false.</returns>
private async UniTask<MintResult> MintFox()
{
Debug.Log("Minting fox...");
try
{
string address = await GetWalletAddress(); // Get the player's wallet address to mint the fox to

if (address != null)
{
var nvc = new List<KeyValuePair<string, string>>
{
// Set 'to' to the player's wallet address
new KeyValuePair<string, string>("to", address)
};
using var client = new HttpClient();
string url = $"http://localhost:3000/mint/fox"; // Endpoint to mint fox
using var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
using var res = await client.SendAsync(req);

// Parse JSON and extract token_id
string content = await res.Content.ReadAsStringAsync();
Debug.Log($"Mint fox response: {content}");

MintResult mintResult = JsonUtility.FromJson<MintResult>(content);
Debug.Log($"Minted fox with token_id: {mintResult.token_id}");

mintedFox = res.IsSuccessStatusCode;
return mintResult;
}

mintedFox = false;
return null;
}
catch (Exception ex)
{
Debug.Log($"Failed to mint fox: {ex.Message}");
mintedFox = false;
return null;
}
}

Expand Down Expand Up @@ -106,16 +184,7 @@ private void ShowCheckoutWallet(bool show)
private void ShowMintingMessage()
{
ShowCheckoutWallet(false);
// Get number of coins col
int numCoins = GetNumCoinsCollected();
if (numCoins > 0)
{
m_Title.text = $"Let's mint the {numCoins} coin{(numCoins > 1 ? "s" : "")} you've collected and a fox to your wallet";
}
else
{
m_Title.text = "Let's mint a fox to your wallet!";
}
m_Title.text = "Let's mint a fox to your wallet!";
}

/// <summary>
Expand All @@ -130,19 +199,15 @@ private int GetNumCoinsCollected()
private void ShowMintedMessage()
{
ShowCheckoutWallet(true);
int numCoins = GetNumCoinsCollected();
if (numCoins > 0)
{
m_Title.text = $"You now own {numCoins} coin{(numCoins > 1 ? "s" : "")} and a fox";
}
else
{
m_Title.text = "You now own a fox!";
}
m_Title.text = "You now own a fox!";
}

private void OnWalletClicked()
private async void OnWalletClicked()
{
// Get the player's wallet address to mint the fox to
string address = await GetWalletAddress();
// Show the player's tokens on the block explorer page.
Application.OpenURL($"https://sandbox.immutascan.io/address/{address}?tab=1");
}
}
}
16 changes: 13 additions & 3 deletions Assets/Shared/Scripts/UI/SetupWalletScreen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.Threading;
using Immutable.Passport;

namespace HyperCasual.Runner
{
Expand Down Expand Up @@ -44,7 +45,7 @@ public void OnEnable()
SetupWallet();
}

private void SetupWallet()
private async void SetupWallet()
{
try
{
Expand All @@ -53,7 +54,16 @@ private void SetupWallet()
ShowError(false);
ShowSuccess(false);

// Set up wallet
// Set up provider
await Passport.Instance.ConnectImx();

Debug.Log("Checking if wallet is registered offchain...");
bool isRegistered = await Passport.Instance.IsRegisteredOffchain();
if (!isRegistered)
{
Debug.Log("Registering wallet offchain...");
await Passport.Instance.RegisterOffchain();
}

m_Title.text = "Your wallet has been successfully set up!";
ShowLoading(false);
Expand All @@ -72,7 +82,7 @@ private void SetupWallet()

private void OnNextButtonClicked()
{
m_NextEvent.Raise();
m_MintEvent.Raise();
}

private void ShowNextButton(bool show)
Expand Down
Loading

0 comments on commit 1813381

Please sign in to comment.