game: overcomplicated interim 2
This commit is contained in:
parent
c5402178f0
commit
4e6c7db3f1
|
@ -166,7 +166,7 @@ Transform:
|
|||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 133964670}
|
||||
serializedVersion: 2
|
||||
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
|
||||
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
|
||||
m_LocalPosition: {x: 0, y: 0, z: 0}
|
||||
m_LocalScale: {x: 1, y: 1, z: 1}
|
||||
m_ConstrainProportionsScale: 0
|
||||
|
@ -459,6 +459,8 @@ MonoBehaviour:
|
|||
m_Script: {fileID: 11500000, guid: 0cfc0b50e9003a0468ebdc186439c53b, type: 3}
|
||||
m_Name:
|
||||
m_EditorClassIdentifier:
|
||||
state: 0
|
||||
uiGameObject: {fileID: 133964670}
|
||||
--- !u!4 &1204483826
|
||||
Transform:
|
||||
m_ObjectHideFlags: 0
|
||||
|
@ -480,6 +482,6 @@ SceneRoots:
|
|||
m_Roots:
|
||||
- {fileID: 963194228}
|
||||
- {fileID: 705507995}
|
||||
- {fileID: 133964672}
|
||||
- {fileID: 447905427}
|
||||
- {fileID: 133964672}
|
||||
- {fileID: 1204483826}
|
||||
|
|
|
@ -78,11 +78,20 @@ public class AccountUI : MonoBehaviour
|
|||
/// </summary>
|
||||
private Button _usernameUpdateButton;
|
||||
|
||||
public void Start()
|
||||
/// <summary>
|
||||
/// start function to initialise the account view
|
||||
/// </summary>
|
||||
/// <exception cref="Exception"></exception>
|
||||
private void Start()
|
||||
{
|
||||
TransitionStateTo(State.NotSignedIn);
|
||||
if (state == State.UnassociatedState) throw new Exception("unreachable state");
|
||||
|
||||
// GameManager.Instance.Backend.RegisterOnSignInCallback(OnSignInCallback);
|
||||
GameManager.Instance.Backend.RegisterOnSignInCallback(OnSignInCallback);
|
||||
GameManager.Instance.RegisterOnLocalPlayerDataUpdate(data =>
|
||||
{
|
||||
Debug.Log("local player data update callback, populating AccountView fields");
|
||||
PopulateFields(data.LastKnownUsername, data.LastKnownEmail);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -114,15 +123,11 @@ public void OnEnable()
|
|||
|
||||
_secondaryActionButton = ui.Q<Button>("SecondaryActionButton");
|
||||
_secondaryActionButton.clicked += OnSecondaryActionButtonClick;
|
||||
|
||||
TransitionStateTo(State.NotSignedIn);
|
||||
GameManager.Instance.Backend.RegisterOnSignInCallback(OnSignInCallback);
|
||||
}
|
||||
|
||||
private void OnSignInCallback(FirebaseUser user)
|
||||
{
|
||||
Debug.Log("sign in account ui callback");
|
||||
|
||||
Debug.Log("post-auth callback, updating account view text");
|
||||
var username = GameManager.Instance.Backend.GetUsername();
|
||||
_usernameField.value = username;
|
||||
_emailField.value = GameManager.Instance.Backend.GetUser().Email;
|
||||
|
@ -216,12 +221,12 @@ private void TransitionStateTo(State newState, bool keepAccompanyingText = false
|
|||
state = newState;
|
||||
}
|
||||
|
||||
private void ValidateUsername()
|
||||
private void ValidateUsername(TextField usernameField)
|
||||
{
|
||||
// just has to be min. 5 characters
|
||||
_usernameField.style.color = _defaultInputFieldValueTextColour;
|
||||
if (_usernameField.value.Length >= 5) return;
|
||||
_usernameField.style.color = _errorInputFieldValueTextColour;
|
||||
usernameField.style.color = _defaultInputFieldValueTextColour;
|
||||
if (usernameField.value.Length >= 5) return;
|
||||
usernameField.style.color = _errorInputFieldValueTextColour;
|
||||
throw new Exception("Username must be at least 5 characters long.");
|
||||
}
|
||||
|
||||
|
@ -279,18 +284,18 @@ private void ValidateFields(TextField emailField, TextField passwordField)
|
|||
|
||||
try
|
||||
{
|
||||
ValidateEmailField(_emailField);
|
||||
ValidateEmailField(emailField);
|
||||
}
|
||||
catch (Exception _)
|
||||
catch (Exception)
|
||||
{
|
||||
invalidEmail = true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ValidatePasswordField(_passwordField);
|
||||
ValidatePasswordField(passwordField);
|
||||
}
|
||||
catch (Exception _)
|
||||
catch (Exception)
|
||||
{
|
||||
invalidPassword = true;
|
||||
}
|
||||
|
@ -321,27 +326,27 @@ private void ValidateFields(TextField emailField, TextField passwordField, TextF
|
|||
|
||||
try
|
||||
{
|
||||
ValidateEmailField(_emailField);
|
||||
ValidateEmailField(emailField);
|
||||
}
|
||||
catch (Exception _)
|
||||
catch (Exception)
|
||||
{
|
||||
invalidEmail = true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ValidatePasswordField(_passwordField);
|
||||
ValidatePasswordField(passwordField);
|
||||
}
|
||||
catch (Exception _)
|
||||
catch (Exception)
|
||||
{
|
||||
invalidPassword = true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ValidateUsername();
|
||||
ValidateUsername(usernameField);
|
||||
}
|
||||
catch (Exception _)
|
||||
catch (Exception)
|
||||
{
|
||||
invalidUsername = true;
|
||||
}
|
||||
|
@ -369,7 +374,7 @@ private void OnUsernameUpdateButtonClick()
|
|||
{
|
||||
try
|
||||
{
|
||||
ValidateUsername();
|
||||
ValidateUsername(_usernameField);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
|
|
@ -57,16 +57,6 @@ public enum UserAccountDetailTargetEnum
|
|||
Password
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// callback functions to be invoked when the user signs in
|
||||
/// </summary>
|
||||
private readonly List<Action<FirebaseUser>> _onSignInCallback = new();
|
||||
|
||||
/// <summary>
|
||||
/// callback functions to be invoked when the user signs out
|
||||
/// </summary>
|
||||
private readonly List<Action<FirebaseUser>> _onSignOutCallback = new();
|
||||
|
||||
/// <summary>
|
||||
/// the firebase authentication object
|
||||
/// </summary>
|
||||
|
@ -77,6 +67,16 @@ public enum UserAccountDetailTargetEnum
|
|||
/// </summary>
|
||||
private DatabaseReference _db;
|
||||
|
||||
/// <summary>
|
||||
/// callback functions to be invoked when the user signs in
|
||||
/// </summary>
|
||||
private readonly List<Action<FirebaseUser>> _onSignInCallbacks = new();
|
||||
|
||||
/// <summary>
|
||||
/// callback functions to be invoked when the user signs out
|
||||
/// </summary>
|
||||
private readonly List<Action<FirebaseUser>> _onSignOutCallbacks = new();
|
||||
|
||||
/// <summary>
|
||||
/// the current user object, if authenticated
|
||||
/// </summary>
|
||||
|
@ -95,9 +95,9 @@ public enum UserAccountDetailTargetEnum
|
|||
/// <summary>
|
||||
/// variable initialisation function
|
||||
/// </summary>
|
||||
public void Initialise()
|
||||
public void Initialise(Action<FirebaseConnectionStatus> callback)
|
||||
{
|
||||
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
|
||||
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
|
||||
{
|
||||
// cher is this robust enough
|
||||
switch (task.Result)
|
||||
|
@ -107,6 +107,7 @@ public void Initialise()
|
|||
_auth.StateChanged += AuthStateChanged;
|
||||
_db = FirebaseDatabase.DefaultInstance.RootReference;
|
||||
Status = FirebaseConnectionStatus.Connected;
|
||||
callback(Status);
|
||||
break;
|
||||
|
||||
case DependencyStatus.UnavailableDisabled:
|
||||
|
@ -114,21 +115,25 @@ public void Initialise()
|
|||
case DependencyStatus.UnavilableMissing:
|
||||
case DependencyStatus.UnavailablePermission:
|
||||
Status = FirebaseConnectionStatus.ExternalError;
|
||||
callback(Status);
|
||||
break;
|
||||
|
||||
case DependencyStatus.UnavailableUpdating:
|
||||
Status = FirebaseConnectionStatus.Updating;
|
||||
RetryInitialiseAfterDelay();
|
||||
callback(Status);
|
||||
RetryInitialiseAfterDelay(callback);
|
||||
break;
|
||||
|
||||
case DependencyStatus.UnavailableUpdaterequired:
|
||||
Status = FirebaseConnectionStatus.UpdateRequired;
|
||||
callback(Status);
|
||||
break;
|
||||
|
||||
case DependencyStatus.UnavailableOther:
|
||||
default:
|
||||
Status = FirebaseConnectionStatus.InternalError;
|
||||
Debug.LogError("firebase ??? blew up or something," + task.Result);
|
||||
callback(Status);
|
||||
break;
|
||||
}
|
||||
|
||||
|
@ -139,10 +144,10 @@ public void Initialise()
|
|||
/// <summary>
|
||||
/// async function to retry initialisation after a delay
|
||||
/// </summary>
|
||||
private async void RetryInitialiseAfterDelay()
|
||||
private async void RetryInitialiseAfterDelay(Action<FirebaseConnectionStatus> callback)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
Initialise();
|
||||
Initialise(callback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -172,7 +177,7 @@ private void AuthStateChanged(object sender, EventArgs eventArgs)
|
|||
if (!signedIn && _user != null)
|
||||
{
|
||||
Debug.Log($"signed out successfully as {_user.UserId}");
|
||||
foreach (var callback in _onSignOutCallback)
|
||||
foreach (var callback in _onSignOutCallbacks)
|
||||
callback(_user);
|
||||
}
|
||||
|
||||
|
@ -183,26 +188,29 @@ private void AuthStateChanged(object sender, EventArgs eventArgs)
|
|||
Debug.Log($"signed in successfully as {_user.UserId}");
|
||||
RetrieveUsernameWithCallback((_, _) =>
|
||||
{
|
||||
foreach (var callback in _onSignInCallback) callback(_user);
|
||||
Debug.Log($"retrieved username post-authentication, calling {_onSignInCallbacks.Count} callbacks");
|
||||
foreach (var callback in _onSignInCallbacks) callback(_user);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// function to register a callback for when the user signs in
|
||||
/// </summary>
|
||||
/// <param name="callback">callback function that takes in a FirebaseUser argument</param>
|
||||
/// <param name="callback">callback function that takes in a <c>FirebaseUser</c> object</param>
|
||||
public void RegisterOnSignInCallback(Action<FirebaseUser> callback)
|
||||
{
|
||||
_onSignInCallback.Add(callback);
|
||||
_onSignInCallbacks.Add(callback);
|
||||
Debug.Log($"registering on sign in callback, there are now {_onSignInCallbacks.Count} callbacks");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// function to register a callback for when the user signs out
|
||||
/// </summary>
|
||||
/// <param name="callback">callback function that takes in a FirebaseUser argument</param>
|
||||
/// <param name="callback">callback function that takes in a <c>FirebaseUser</c> object</param>
|
||||
public void RegisterOnSignOutCallback(Action<FirebaseUser> callback)
|
||||
{
|
||||
_onSignOutCallback.Add(callback);
|
||||
Debug.Log($"registering on sign out callback, there are now {_onSignOutCallbacks.Count} callbacks");
|
||||
_onSignOutCallbacks.Add(callback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -364,21 +372,18 @@ private void RetrieveUsernameWithCallback(Action<DatabaseTransactionResult, stri
|
|||
|
||||
_db.Child("users").Child(_user.UserId).Child("username").GetValueAsync().ContinueWithOnMainThread(task =>
|
||||
{
|
||||
DatabaseTransactionResult result;
|
||||
if (task.IsCompletedSuccessfully)
|
||||
{
|
||||
result = DatabaseTransactionResult.Ok;
|
||||
_username = task.Result.Value.ToString();
|
||||
Debug.Log($"our username is {_username}");
|
||||
callback(DatabaseTransactionResult.Ok, _username);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = DatabaseTransactionResult.Error;
|
||||
_username = "Unknown";
|
||||
Debug.LogError("failed to get username");
|
||||
callback(DatabaseTransactionResult.Error, _username);
|
||||
}
|
||||
|
||||
callback(result, _username);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -429,8 +434,8 @@ public void ForgotPassword(string email, Action<bool> callback)
|
|||
/// abstraction function to get the user's recent scores from the database
|
||||
/// </summary>
|
||||
/// <param name="callback">
|
||||
/// callback function that takes in a DatabaseTransactionResult and List of LocalPlayerData.Score
|
||||
/// argument
|
||||
/// callback function that takes in a <c>DatabaseTransactionResult</c> enum
|
||||
/// and a <c>List<LocalPlayerData.Score></c>argument
|
||||
/// </param>
|
||||
public void GetRecentScores(Action<DatabaseTransactionResult, List<LocalPlayerData.Score>> callback)
|
||||
{
|
||||
|
|
|
@ -62,6 +62,7 @@ public static RGB gamut_clip_preserve_chroma(RGB rgb)
|
|||
/// a and b must be normalized so a^2 + b^2 == 1
|
||||
/// </summary>
|
||||
// https://bottosson.github.io/posts/gamutclipping/ (MIT)
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public static float find_gamut_intersection(
|
||||
float a,
|
||||
float b,
|
||||
|
@ -164,6 +165,7 @@ public static RGB gamut_clip_preserve_chroma(RGB rgb)
|
|||
/// a and b must be normalized so a^2 + b^2 == 1
|
||||
/// </summary>
|
||||
// https://bottosson.github.io/posts/gamutclipping/ (MIT)
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public static LC find_cusp(float a, float b)
|
||||
{
|
||||
// First, find the maximum saturation (saturation S = C/L)
|
||||
|
@ -178,7 +180,7 @@ public static LC find_cusp(float a, float b)
|
|||
}
|
||||
|
||||
// https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab (public domain)
|
||||
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public static Lab linear_srgb_to_oklab(RGB c)
|
||||
{
|
||||
var l = 0.4122214708f * c.r + 0.5363325363f * c.g + 0.0514459929f * c.b;
|
||||
|
@ -220,6 +222,7 @@ public static RGB oklab_to_linear_srgb(Lab c)
|
|||
/// a and b must be normalized so a^2 + b^2 == 1
|
||||
/// </summary>
|
||||
// https://bottosson.github.io/posts/gamutclipping/ (MIT)
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public static float compute_max_saturation(float a, float b)
|
||||
{
|
||||
// Max saturation will be when one of r, g or b goes below zero.
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Serialization;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
/// <summary>
|
||||
|
@ -12,24 +13,45 @@ public class GameManager : MonoBehaviour
|
|||
/// </summary>
|
||||
public enum DisplayState
|
||||
{
|
||||
UnassociatedState, // initial state, then we transition to Nothing to initialise the ui
|
||||
Nothing,
|
||||
PlayView,
|
||||
GameView,
|
||||
LeaderboardView,
|
||||
AccountView,
|
||||
AccountView
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// singleton pattern: define instance field for accessing the singleton elsewhere
|
||||
/// </summary>
|
||||
public static GameManager Instance;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// the current display state of the game
|
||||
/// </summary>
|
||||
[SerializeField] private DisplayState state = DisplayState.Nothing;
|
||||
[SerializeField] private DisplayState state = DisplayState.UnassociatedState;
|
||||
|
||||
/// <summary>
|
||||
/// the visual element object for game ui (hud/prompts/tooltips)
|
||||
/// the game object for the ui
|
||||
/// </summary>
|
||||
[SerializeField] private GameObject uiGameObject;
|
||||
|
||||
// /// <summary>
|
||||
// /// callback functions to be invoked when the display state changes
|
||||
// /// </summary>
|
||||
// private readonly List<Action<DisplayState>> _onDisplayStateChange = new();
|
||||
|
||||
/// <summary>
|
||||
/// callback functions to be invoked when the local player data is updated
|
||||
/// </summary>
|
||||
private readonly List<Action<LocalPlayerData>> _onLocalPlayerDataUpdateCallbacks = new();
|
||||
|
||||
/// <summary>
|
||||
/// the local player data object for storing player data
|
||||
/// </summary>
|
||||
private LocalPlayerData _data;
|
||||
|
||||
/// <summary>
|
||||
/// the visual element for the ui
|
||||
/// </summary>
|
||||
private VisualElement _ui;
|
||||
|
||||
|
@ -37,11 +59,6 @@ public enum DisplayState
|
|||
/// backend object for handling communication with the firebase backend
|
||||
/// </summary>
|
||||
public Backend Backend;
|
||||
|
||||
/// <summary>
|
||||
/// the local player data object for storing player data
|
||||
/// </summary>
|
||||
private LocalPlayerData _localPlayerData;
|
||||
|
||||
/// <summary>
|
||||
/// enforces singleton behaviour; sets doesn't destroy on load and checks for multiple instances
|
||||
|
@ -61,30 +78,65 @@ private void Awake()
|
|||
Debug.Log("awake as non-singleton instance, destroying self");
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
SetDisplayState(DisplayState.PlayView);
|
||||
|
||||
// load the local player data and refresh the ui
|
||||
_localPlayerData = new LocalPlayerData();
|
||||
_localPlayerData.LoadFromTheWorld();
|
||||
|
||||
// register a callback to refresh the ui when the player signs in
|
||||
Backend.RegisterOnSignInCallback(_ =>
|
||||
{
|
||||
_localPlayerData.LoadFromTheWorld();
|
||||
});
|
||||
if (uiGameObject == null)
|
||||
throw new NullReferenceException("a reference UI GameObject is not set in the inspector");
|
||||
|
||||
_ui = uiGameObject.GetComponent<UIDocument>()?.rootVisualElement;
|
||||
if (_ui == null)
|
||||
throw new NullReferenceException("could not grab the UIDocument in the reference UI GameObject");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// called when the game object is enabled
|
||||
/// called before the first frame update
|
||||
/// </summary>
|
||||
private void OnEnable()
|
||||
private void Start()
|
||||
{
|
||||
// transition to the initial state
|
||||
SetDisplayState(DisplayState.Nothing);
|
||||
|
||||
// initialise the backend
|
||||
Backend = new Backend();
|
||||
Backend.Initialise();
|
||||
Backend.Initialise(status =>
|
||||
{
|
||||
Debug.Log("initialised backend, setting connection status text");
|
||||
|
||||
_ui.Q<Label>("ConnectionStatusText").text = status switch
|
||||
{
|
||||
Backend.FirebaseConnectionStatus.Connected => "Status: Connected",
|
||||
Backend.FirebaseConnectionStatus.Updating => "Status: Updating... (Retrying in a bit!)",
|
||||
Backend.FirebaseConnectionStatus.NotConnected => "Status: Disconnected",
|
||||
Backend.FirebaseConnectionStatus.UpdateRequired =>
|
||||
"Status: Disconnected (Device Component Update Required)",
|
||||
Backend.FirebaseConnectionStatus.ExternalError => "Status: Disconnected (External/Device Error)",
|
||||
Backend.FirebaseConnectionStatus.InternalError => "Status: Disconnected (Internal Error)",
|
||||
_ => "Status: Disconnected (unknown fcs state, this is unreachable and a bug)"
|
||||
};
|
||||
|
||||
if (status == Backend.FirebaseConnectionStatus.Connected) return;
|
||||
|
||||
// if we're not connected, hide any online 'features'
|
||||
_ui.Q<Button>("LeaderboardButton").style.display = DisplayStyle.None;
|
||||
_ui.Q<Button>("AccountButton").style.display = DisplayStyle.None;
|
||||
});
|
||||
|
||||
// load the local player data and refresh the ui
|
||||
_data = new LocalPlayerData();
|
||||
_data.LoadFromTheWorld(data =>
|
||||
{
|
||||
foreach (var callback in _onLocalPlayerDataUpdateCallbacks) callback(data);
|
||||
});
|
||||
|
||||
// register a callback to refresh the ui when the player signs in
|
||||
Backend.RegisterOnSignInCallback(_ =>
|
||||
{
|
||||
Debug.Log("post-auth callback, refreshing player data from the world");
|
||||
_data.LoadFromTheWorld(data =>
|
||||
{
|
||||
Debug.Log("firing lpdata update callbacks");
|
||||
foreach (var callback in _onLocalPlayerDataUpdateCallbacks) callback(data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -95,6 +147,26 @@ private void OnDestroy()
|
|||
Backend.Cleanup();
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// function to register a callback for when the display state changes
|
||||
// /// </summary>
|
||||
// /// <param name="callback">callback function that takes in a <c>DisplayState</c> enum</param>
|
||||
// public void RegisterOnDisplayStateChange(Action<DisplayState> callback)
|
||||
// {
|
||||
// _onDisplayStateChange.Add(callback);
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// function to register a callback for when the local player data is updated
|
||||
/// </summary>
|
||||
/// <param name="callback">callback function that takes in a <c>LocalPlayerData</c> object</param>
|
||||
public void RegisterOnLocalPlayerDataUpdate(Action<LocalPlayerData> callback)
|
||||
{
|
||||
_onLocalPlayerDataUpdateCallbacks.Add(callback);
|
||||
Debug.Log(
|
||||
$"registering on lpdata update callback, there are now {_onLocalPlayerDataUpdateCallbacks.Count} callbacks");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// function to show a menu based on the enum passed,
|
||||
/// and any other necessary actions
|
||||
|
@ -102,7 +174,50 @@ private void OnDestroy()
|
|||
/// <param name="newDisplayState">the game menu to show</param>
|
||||
public void SetDisplayState(DisplayState newDisplayState)
|
||||
{
|
||||
var currentDisplayState = St;
|
||||
var currentDisplayState = state;
|
||||
|
||||
// if the new state is the same as the current state, do nothing
|
||||
if (currentDisplayState == newDisplayState)
|
||||
{
|
||||
Debug.Log($"staying at {currentDisplayState} (illogical transition)");
|
||||
return;
|
||||
}
|
||||
|
||||
Debug.Log($"switching from {currentDisplayState} to {newDisplayState}");
|
||||
|
||||
var gameView = _ui.Q<VisualElement>("GameView");
|
||||
var leaderboardView = _ui.Q<VisualElement>("LeaderboardView");
|
||||
var accountView = _ui.Q<VisualElement>("AccountView");
|
||||
|
||||
switch (newDisplayState)
|
||||
{
|
||||
case DisplayState.Nothing:
|
||||
gameView.style.display = DisplayStyle.None;
|
||||
leaderboardView.style.display = DisplayStyle.None;
|
||||
accountView.style.display = DisplayStyle.None;
|
||||
break;
|
||||
|
||||
case DisplayState.GameView:
|
||||
gameView.style.display = DisplayStyle.Flex;
|
||||
leaderboardView.style.display = DisplayStyle.None;
|
||||
accountView.style.display = DisplayStyle.None;
|
||||
break;
|
||||
|
||||
case DisplayState.LeaderboardView:
|
||||
gameView.style.display = DisplayStyle.None;
|
||||
leaderboardView.style.display = DisplayStyle.Flex;
|
||||
accountView.style.display = DisplayStyle.None;
|
||||
break;
|
||||
|
||||
case DisplayState.AccountView:
|
||||
gameView.style.display = DisplayStyle.None;
|
||||
leaderboardView.style.display = DisplayStyle.None;
|
||||
accountView.style.display = DisplayStyle.Flex;
|
||||
break;
|
||||
|
||||
case DisplayState.UnassociatedState:
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(newDisplayState), newDisplayState, null);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -4,7 +4,7 @@ MonoImporter:
|
|||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
executionOrder: -10
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
|
|
|
@ -1,42 +1,44 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Unity.VisualScripting;
|
||||
using UnityEngine;
|
||||
|
||||
public class LocalPlayerData
|
||||
{
|
||||
/// <summary>
|
||||
/// last known email used
|
||||
/// </summary>
|
||||
public string LastKnownEmail = "";
|
||||
|
||||
/// <summary>
|
||||
/// last known username used
|
||||
/// </summary>
|
||||
public string LastKnownUsername = "Guest";
|
||||
|
||||
/// <summary>
|
||||
/// queue of the 10 most recent local scores
|
||||
/// </summary>
|
||||
public Queue<Score> RecentLocalScores = new(10);
|
||||
|
||||
/// <summary>
|
||||
/// queue of the 10 most recent online scores,
|
||||
/// used in user rating calculation and accuracy display stats
|
||||
/// </summary>
|
||||
public Queue<Score> RecentOnlineScores = new(10);
|
||||
|
||||
/// <summary>
|
||||
/// queue of the best online scores,
|
||||
/// used in user rating calculation and accuracy display stats
|
||||
/// </summary>
|
||||
public Queue<Score> BestOnlineScores = new(30);
|
||||
|
||||
/// <summary>
|
||||
/// last known email used
|
||||
/// </summary>
|
||||
public string LastKnownEmail = "";
|
||||
|
||||
/// <summary>
|
||||
/// last known username used
|
||||
/// </summary>
|
||||
public string LastKnownUsername = "Guest";
|
||||
|
||||
/// <summary>
|
||||
/// queue of the 10 most recent local scores
|
||||
/// </summary>
|
||||
public Queue<Score> RecentLocalScores = new(10);
|
||||
|
||||
/// <summary>
|
||||
/// queue of the 10 most recent online scores,
|
||||
/// used in user rating calculation and accuracy display stats
|
||||
/// </summary>
|
||||
public Queue<Score> RecentOnlineScores = new(10);
|
||||
|
||||
/// <summary>
|
||||
/// loads player data from player prefs and database
|
||||
/// </summary>
|
||||
public void LoadFromTheWorld()
|
||||
public void LoadFromTheWorld(Action<LocalPlayerData> callback)
|
||||
{
|
||||
|
||||
// load user data, possibly from the backend
|
||||
var possibleUser = GameManager.Instance.Backend.GetUser();
|
||||
var currentKnownEmail = string.Empty;
|
||||
|
@ -46,6 +48,7 @@ public void LoadFromTheWorld()
|
|||
currentKnownEmail = possibleUser.Email;
|
||||
currentKnownUsername = GameManager.Instance.Backend.GetUsername();
|
||||
}
|
||||
|
||||
var lastStoredEmail = PlayerPrefs.GetString("LastKnownEmail", "");
|
||||
var lastStoredUsername = PlayerPrefs.GetString("LastKnownUsername", "Guest");
|
||||
LastKnownEmail = string.IsNullOrEmpty(currentKnownEmail) ? lastStoredEmail : currentKnownEmail;
|
||||
|
@ -75,30 +78,24 @@ public void LoadFromTheWorld()
|
|||
|
||||
// if any of the values are invalid, don't add the score
|
||||
if (noOfRounds < 0 || l < 0 || c < 0 || h < 0) continue;
|
||||
|
||||
RegisterLocalScore(new Score(timestamp, noOfRounds, l, c, h));
|
||||
RecentLocalScores.Enqueue(new Score(timestamp, noOfRounds, l, c, h));
|
||||
}
|
||||
|
||||
|
||||
// load online scores
|
||||
RecentOnlineScores.Clear();
|
||||
GameManager.Instance.Backend.GetRecentScores((dtr, recentOnlineScores) =>
|
||||
GameManager.Instance.Backend.GetRecentScores((_, recentOnlineScores) =>
|
||||
{
|
||||
foreach (var onlineScore in recentOnlineScores)
|
||||
{
|
||||
if (RecentOnlineScores.Count > 10) RecentOnlineScores.Dequeue();
|
||||
RecentOnlineScores.Enqueue(onlineScore);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// registers a score to the player's local data
|
||||
/// </summary>
|
||||
/// <param name="score">the score to register</param>
|
||||
public void RegisterLocalScore(Score score)
|
||||
{
|
||||
if (RecentLocalScores.Count > 10) RecentLocalScores.Dequeue();
|
||||
RecentLocalScores.Enqueue(score);
|
||||
Debug.Log("firing late post-load lpdata callback");
|
||||
callback(this);
|
||||
});
|
||||
|
||||
Debug.Log("loaded player data from the world");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -120,10 +117,22 @@ public void SaveToTheWorld()
|
|||
PlayerPrefs.SetFloat($"RecentLocalScores_{idx}_AvgHueAccuracy", score.AvgHueAccuracy);
|
||||
idx++;
|
||||
}
|
||||
|
||||
Debug.Log("saved player data to the world");
|
||||
|
||||
// online scores are already saved in the backend
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// registers a score to the player's local data
|
||||
/// </summary>
|
||||
/// <param name="score">the score to register</param>
|
||||
public void RegisterLocalScore(Score score)
|
||||
{
|
||||
if (RecentLocalScores.Count > 10) RecentLocalScores.Dequeue();
|
||||
RecentLocalScores.Enqueue(score);
|
||||
}
|
||||
|
||||
public struct Score
|
||||
{
|
||||
/// <summary>
|
||||
|
@ -169,4 +178,12 @@ public struct Score
|
|||
AvgHueAccuracy = h;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// function to save the player data when the application quits
|
||||
/// </summary>
|
||||
private void OnApplicationQuit()
|
||||
{
|
||||
SaveToTheWorld();
|
||||
}
|
||||
}
|
|
@ -7,45 +7,55 @@
|
|||
public class SideViewUI : MonoBehaviour
|
||||
{
|
||||
/// <summary>
|
||||
/// settings button for showing the settings menu
|
||||
/// button to change to transition to the account view
|
||||
/// </summary>
|
||||
private Button _accountButton;
|
||||
|
||||
/// <summary>
|
||||
/// settings button for showing the settings menu
|
||||
/// text that displays the users stable chroma accuracy
|
||||
/// </summary>
|
||||
private Label _chromaAccuracyText;
|
||||
|
||||
/// <summary>
|
||||
/// settings button for showing the settings menu
|
||||
/// text that displays the connection status to the backend
|
||||
/// </summary>
|
||||
private Label _connectionStatusText;
|
||||
|
||||
/// <summary>
|
||||
/// text that displays the users stable hue accuracy
|
||||
/// </summary>
|
||||
private Label _hueAccuracyText;
|
||||
|
||||
/// <summary>
|
||||
/// leaderboard button for showing the leaderboard
|
||||
/// button to transition to the leaderboard view
|
||||
/// </summary>
|
||||
private Button _leaderboardButton;
|
||||
|
||||
/// <summary>
|
||||
/// settings button for showing the settings menu
|
||||
/// text that displays the users stable lightness accuracy
|
||||
/// </summary>
|
||||
private Label _lightnessAccuracyText;
|
||||
|
||||
/// <summary>
|
||||
/// play button for starting the game
|
||||
/// button to transition to the game view
|
||||
/// </summary>
|
||||
private Button _playButton;
|
||||
|
||||
/// <summary>
|
||||
/// settings button for showing the settings menu
|
||||
/// text that displays the username
|
||||
/// </summary>
|
||||
private Label _playerNameText;
|
||||
|
||||
/// <summary>
|
||||
/// settings button for showing the settings menu
|
||||
/// text that displays the users' rating
|
||||
/// </summary>
|
||||
private Label _playerRatingText;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
GameManager.Instance.RegisterOnLocalPlayerDataUpdate(RenderFromPlayerData);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// function to subscribe button events to their respective functions
|
||||
/// </summary>
|
||||
|
@ -67,14 +77,15 @@ private void OnEnable()
|
|||
_chromaAccuracyText = ui.Q<Label>("ChromaAccuracyText");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// function to update the ui with the latest data
|
||||
/// </summary>
|
||||
/// <param name="localPlayerData"></param>
|
||||
/// <param name="localPlayerData">the local player data to render the ui from</param>
|
||||
private void RenderFromPlayerData(LocalPlayerData localPlayerData)
|
||||
{
|
||||
// calculate averages from both recent local scores and online scores
|
||||
var totalLightessAcc = 0f;
|
||||
var totalLightness = 0f;
|
||||
var totalChromaAcc = 0f;
|
||||
var totalHueAcc = 0f;
|
||||
var totalRounds = 0;
|
||||
|
@ -83,7 +94,7 @@ private void RenderFromPlayerData(LocalPlayerData localPlayerData)
|
|||
|
||||
foreach (var localScore in localPlayerData.RecentLocalScores)
|
||||
{
|
||||
totalLightessAcc += localScore.AvgLightnessAccuracy;
|
||||
totalLightness += localScore.AvgLightnessAccuracy;
|
||||
totalChromaAcc += localScore.AvgChromaAccuracy;
|
||||
totalHueAcc += localScore.AvgHueAccuracy;
|
||||
totalRounds += localScore.NoOfRounds;
|
||||
|
@ -91,26 +102,26 @@ private void RenderFromPlayerData(LocalPlayerData localPlayerData)
|
|||
|
||||
foreach (var onlineScore in localPlayerData.RecentOnlineScores)
|
||||
{
|
||||
totalLightessAcc += onlineScore.AvgLightnessAccuracy;
|
||||
totalLightness += onlineScore.AvgLightnessAccuracy;
|
||||
totalChromaAcc += onlineScore.AvgChromaAccuracy;
|
||||
totalHueAcc += onlineScore.AvgHueAccuracy;
|
||||
totalRounds += onlineScore.NoOfRounds;
|
||||
}
|
||||
|
||||
|
||||
foreach (var onlineScore in localPlayerData.BestOnlineScores)
|
||||
{
|
||||
totalLightessAcc += onlineScore.AvgLightnessAccuracy;
|
||||
totalLightness += onlineScore.AvgLightnessAccuracy;
|
||||
totalChromaAcc += onlineScore.AvgChromaAccuracy;
|
||||
totalHueAcc += onlineScore.AvgHueAccuracy;
|
||||
totalRounds += onlineScore.NoOfRounds;
|
||||
}
|
||||
|
||||
|
||||
// finally, set the labels
|
||||
_playerNameText.text = GameManager.Instance.Backend.GetUsername();
|
||||
_lightnessAccuracyText.text = $"{(totalLightessAcc / totalRounds):F}";
|
||||
_hueAccuracyText.text = $"{(totalHueAcc / totalRounds):F}";
|
||||
_chromaAccuracyText.text = $"{(totalChromaAcc / totalRounds):F}";
|
||||
|
||||
_lightnessAccuracyText.text = $"{totalLightness / totalRounds:F}";
|
||||
_hueAccuracyText.text = $"{totalHueAcc / totalRounds:F}";
|
||||
_chromaAccuracyText.text = $"{totalChromaAcc / totalRounds:F}";
|
||||
|
||||
// and set the player rating, but after we get it from the backend
|
||||
// (god I LOVE async (I am LYING out of my teeth))
|
||||
GameManager.Instance.Backend.CalculateUserRating((dtr, rating) =>
|
||||
|
@ -125,7 +136,7 @@ private void RenderFromPlayerData(LocalPlayerData localPlayerData)
|
|||
/// </summary>
|
||||
private static void OnPlayButtonClicked()
|
||||
{
|
||||
GameManager.Instance.SetDisplayState(GameManager.DisplayState.PlayView);
|
||||
GameManager.Instance.SetDisplayState(GameManager.DisplayState.GameView);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
@ -25,7 +25,7 @@
|
|||
<ui:Button text="Account ↗" parse-escape-sequences="true" display-tooltip-when-elided="true"
|
||||
name="AccountButton"/>
|
||||
<ui:VisualElement name="AccountSection"
|
||||
style="flex-grow: 0; border-top-color: rgb(208, 152, 194); margin-top: 0; border-top-width: 1px; margin-right: 0; margin-bottom: 0; margin-left: 0; border-bottom-color: rgb(208, 152, 194); border-bottom-width: 1px; padding-bottom: 12px;">
|
||||
style="flex-grow: 0; border-top-color: rgb(208, 152, 194); margin-top: 0; border-top-width: 1px; margin-right: 0; margin-bottom: 0; margin-left: 0; border-bottom-color: rgb(208, 152, 194); padding-bottom: 12px;">
|
||||
<ui:VisualElement name="PlayerDetails"
|
||||
style="flex-grow: 1; flex-direction: row; align-items: stretch; justify-content: space-between; font-size: 10px; align-self: stretch;">
|
||||
<ui:VisualElement name="PlayerNameDetail" style="flex-grow: 1;">
|
||||
|
@ -73,6 +73,12 @@
|
|||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement name="ConnectionStatusText"
|
||||
style="flex-grow: 0; border-top-color: rgb(208, 152, 194); margin-top: 0; border-top-width: 1px; margin-right: 0; margin-bottom: 0; margin-left: 0; border-bottom-color: rgb(208, 152, 194); border-bottom-width: 1px; padding-bottom: 12px;">
|
||||
<ui:Label tabindex="-1" text="Status: Unknown" parse-escape-sequences="true"
|
||||
display-tooltip-when-elided="true" name="ConnectionStatusText"
|
||||
style="-unity-font-style: normal; font-size: 14px; padding-bottom: 0; -unity-text-align: lower-left;"/>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement name="MainView"
|
||||
|
@ -113,16 +119,14 @@
|
|||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement name="LeaderboardView"
|
||||
style="flex-grow: 1; display: none; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; margin-top: 3.25%; margin-right: 3.25%; margin-bottom: 3.25%; margin-left: 3.25%; flex-direction: column; justify-content: space-between;">
|
||||
<ui:VisualElement name="LeaderboardHeader" style="flex-grow: 0;">
|
||||
<ui:Label tabindex="-1" text="Leaderboard" parse-escape-sequences="true"
|
||||
display-tooltip-when-elided="true" name="RoundText"
|
||||
style="font-size: 58px; -unity-font-style: bold;"/>
|
||||
</ui:VisualElement>
|
||||
style="flex-grow: 1; display: flex; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; margin-top: 3.25%; margin-right: 3.25%; margin-bottom: 3.25%; margin-left: 3.25%; flex-direction: column; justify-content: space-between;">
|
||||
<ui:Label tabindex="-1" text="Leaderboard" parse-escape-sequences="true"
|
||||
display-tooltip-when-elided="true" name="RoundText"
|
||||
style="font-size: 58px; -unity-font-style: normal;"/>
|
||||
<ui:ListView name="LeaderboardListView"/>
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement name="AccountView"
|
||||
style="flex-grow: 1; display: flex; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; margin-top: 3.25%; margin-right: 3.25%; margin-bottom: 3.25%; margin-left: 3.25%; flex-direction: column; justify-content: space-between;">
|
||||
style="flex-grow: 1; display: none; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; margin-top: 3.25%; margin-right: 3.25%; margin-bottom: 3.25%; margin-left: 3.25%; flex-direction: column; justify-content: space-between;">
|
||||
<ui:Label tabindex="-1" text="You are not signed in." parse-escape-sequences="true"
|
||||
display-tooltip-when-elided="true" name="AccountHeader"
|
||||
style="font-size: 58px; -unity-font-style: normal;"/>
|
||||
|
|
|
@ -4,5 +4,8 @@
|
|||
EditorBuildSettings:
|
||||
m_ObjectHideFlags: 0
|
||||
serializedVersion: 2
|
||||
m_Scenes: []
|
||||
m_Scenes:
|
||||
- enabled: 1
|
||||
path: Assets/Scenes/GameScene.unity
|
||||
guid: 9fc0d4010bbf28b4594072e72b8655ab
|
||||
m_configObjects: {}
|
||||
|
|
|
@ -161,7 +161,8 @@ PlayerSettings:
|
|||
resetResolutionOnWindowResize: 0
|
||||
androidSupportedAspectRatio: 1
|
||||
androidMaxAspectRatio: 2.1
|
||||
applicationIdentifier: {}
|
||||
applicationIdentifier:
|
||||
Standalone: com.DefaultCompany.ColourMeOKLABGame
|
||||
buildNumber:
|
||||
Standalone: 0
|
||||
VisionOS: 0
|
||||
|
|
Reference in a new issue