diff --git a/.editorconfig b/.editorconfig index e65297d59..cae76123c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -4,6 +4,5 @@ root = true [*.cs] indent_style = space indent_size = 4 -end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..27ffb31a4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# Auto detect text files and perform LF normalization +* text=auto + +*.cs text diff=csharp +*.csproj text merge=union +*.sln text merge=union eol=crlf + +*.meta text +*.prefab text +*.preset text +*.json text +*.asset text \ No newline at end of file diff --git a/Assets/Scripts/Editor/BuildCGS.cs b/Assets/Editor/BuildCGS.cs similarity index 100% rename from Assets/Scripts/Editor/BuildCGS.cs rename to Assets/Editor/BuildCGS.cs diff --git a/Assets/Scripts/Editor/BuildCGS.cs.meta b/Assets/Editor/BuildCGS.cs.meta similarity index 100% rename from Assets/Scripts/Editor/BuildCGS.cs.meta rename to Assets/Editor/BuildCGS.cs.meta diff --git a/Assets/Prefabs/Card Model.prefab b/Assets/Prefabs/Card Model.prefab index 3b9e2fa81..e0ac6d9e6 100644 --- a/Assets/Prefabs/Card Model.prefab +++ b/Assets/Prefabs/Card Model.prefab @@ -196,7 +196,7 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 7da0cfd7bd166ba43bf3e99b8d74f2e7, type: 3} m_Name: m_EditorClassIdentifier: - localPosition: {x: 0, y: 0} + position: {x: 0, y: 0} rotation: {x: 0, y: 0, z: 0, w: 0} --- !u!114 &114876689799331718 MonoBehaviour: diff --git a/Assets/Prefabs/Menus/Card Search Menu.prefab b/Assets/Prefabs/Menus/Card Search Menu.prefab index a7654df89..1d7a76d32 100644 --- a/Assets/Prefabs/Menus/Card Search Menu.prefab +++ b/Assets/Prefabs/Menus/Card Search Menu.prefab @@ -1380,7 +1380,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 @@ -1804,7 +1804,7 @@ MonoBehaviour: m_PersistentCalls: m_Calls: - m_Target: {fileID: 114126704938545522} - m_MethodName: set_NameFilter + m_MethodName: SetNameFilter m_Mode: 0 m_Arguments: m_ObjectArgument: {fileID: 0} @@ -2022,7 +2022,7 @@ MonoBehaviour: m_PersistentCalls: m_Calls: - m_Target: {fileID: 114126704938545522} - m_MethodName: set_SetCodeFilter + m_MethodName: SetCodeFilter m_Mode: 0 m_Arguments: m_ObjectArgument: {fileID: 0} @@ -2344,7 +2344,7 @@ MonoBehaviour: m_PersistentCalls: m_Calls: - m_Target: {fileID: 114126704938545522} - m_MethodName: set_IdFilter + m_MethodName: SetIdFilter m_Mode: 0 m_Arguments: m_ObjectArgument: {fileID: 0} diff --git a/Assets/Prefabs/Menus/Deck Load Menu.prefab b/Assets/Prefabs/Menus/Deck Load Menu.prefab index 3f028af13..734d69376 100644 --- a/Assets/Prefabs/Menus/Deck Load Menu.prefab +++ b/Assets/Prefabs/Menus/Deck Load Menu.prefab @@ -983,6 +983,7 @@ MonoBehaviour: selectionContent: {fileID: 224937724690924458} selectionTemplate: {fileID: 224513094372486550} scrollRect: {fileID: 114606226609976292} + cancelButton: {fileID: 114440245882454988} shareFileButton: {fileID: 114207059650301704} deleteFileButton: {fileID: 114582670716232018} loadFromFileButton: {fileID: 114827358892291670} @@ -2206,7 +2207,7 @@ MonoBehaviour: m_Calls: [] m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_Sprite: {fileID: 21300000, guid: 967c7b47090d34cf090c40749e45f0b4, type: 3} + m_Sprite: {fileID: 21300000, guid: 935962ddb1e44499dad00e5ca6b38823, type: 3} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 @@ -2253,7 +2254,7 @@ MonoBehaviour: m_HandleRect: {fileID: 224000485604831812} m_Direction: 2 m_Value: 0 - m_Size: 0.99999446 + m_Size: 0.99998367 m_NumberOfSteps: 0 m_OnValueChanged: m_PersistentCalls: @@ -3027,7 +3028,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 @@ -3324,7 +3325,7 @@ RectTransform: m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} - m_AnchorMax: {x: 1, y: 0.99999446} + m_AnchorMax: {x: 1, y: 0.99998367} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 20, y: 20} m_Pivot: {x: 0.5, y: 0.5} @@ -4087,7 +4088,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 1} m_AnchorMax: {x: 1, y: 1} - m_AnchoredPosition: {x: 0, y: -0.000012579555} + m_AnchoredPosition: {x: 0, y: 0.00006396077} m_SizeDelta: {x: 0, y: 150} m_Pivot: {x: 0.5, y: 1} --- !u!224 &224977536836211226 diff --git a/Assets/Prefabs/Menus/Deck Save Menu.prefab b/Assets/Prefabs/Menus/Deck Save Menu.prefab index 4d9cd845f..a5eb7847d 100644 --- a/Assets/Prefabs/Menus/Deck Save Menu.prefab +++ b/Assets/Prefabs/Menus/Deck Save Menu.prefab @@ -1205,7 +1205,7 @@ MonoBehaviour: m_Calls: [] m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_Sprite: {fileID: 21300000, guid: 967c7b47090d34cf090c40749e45f0b4, type: 3} + m_Sprite: {fileID: 21300000, guid: 935962ddb1e44499dad00e5ca6b38823, type: 3} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 diff --git a/Assets/Prefabs/Menus/Dice Menu.prefab b/Assets/Prefabs/Menus/Dice Menu.prefab index 99223aebb..4a9e7a38c 100644 --- a/Assets/Prefabs/Menus/Dice Menu.prefab +++ b/Assets/Prefabs/Menus/Dice Menu.prefab @@ -703,7 +703,7 @@ MonoBehaviour: m_Calls: [] m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_Sprite: {fileID: 21300000, guid: 967c7b47090d34cf090c40749e45f0b4, type: 3} + m_Sprite: {fileID: 21300000, guid: 935962ddb1e44499dad00e5ca6b38823, type: 3} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 diff --git a/Assets/Prefabs/Menus/Lobby Menu.prefab b/Assets/Prefabs/Menus/Lobby Menu.prefab index 277dc8f65..e574e267c 100644 --- a/Assets/Prefabs/Menus/Lobby Menu.prefab +++ b/Assets/Prefabs/Menus/Lobby Menu.prefab @@ -512,7 +512,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 diff --git a/Assets/Prefabs/Menus/Components.meta b/Assets/Prefabs/Menus/Widgets.meta similarity index 100% rename from Assets/Prefabs/Menus/Components.meta rename to Assets/Prefabs/Menus/Widgets.meta diff --git a/Assets/Prefabs/Menus/Components/CGSFooter.prefab b/Assets/Prefabs/Menus/Widgets/CGSFooter.prefab similarity index 100% rename from Assets/Prefabs/Menus/Components/CGSFooter.prefab rename to Assets/Prefabs/Menus/Widgets/CGSFooter.prefab diff --git a/Assets/Prefabs/Menus/Components/CGSFooter.prefab.meta b/Assets/Prefabs/Menus/Widgets/CGSFooter.prefab.meta similarity index 100% rename from Assets/Prefabs/Menus/Components/CGSFooter.prefab.meta rename to Assets/Prefabs/Menus/Widgets/CGSFooter.prefab.meta diff --git a/Assets/Prefabs/Menus/Components/SFButton.preset b/Assets/Prefabs/Menus/Widgets/SFButton.preset similarity index 99% rename from Assets/Prefabs/Menus/Components/SFButton.preset rename to Assets/Prefabs/Menus/Widgets/SFButton.preset index bb7c232a6..2ae0dda67 100644 --- a/Assets/Prefabs/Menus/Components/SFButton.preset +++ b/Assets/Prefabs/Menus/Widgets/SFButton.preset @@ -70,11 +70,11 @@ Preset: objectReference: {fileID: 0} - target: {fileID: 0} propertyPath: m_Colors.m_HighlightedColor.r - value: 0.88235295 + value: 1 objectReference: {fileID: 0} - target: {fileID: 0} propertyPath: m_Colors.m_HighlightedColor.g - value: 0.42745098 + value: 0.4509804 objectReference: {fileID: 0} - target: {fileID: 0} propertyPath: m_Colors.m_HighlightedColor.b diff --git a/Assets/Prefabs/Menus/Components/SFButton.preset.meta b/Assets/Prefabs/Menus/Widgets/SFButton.preset.meta similarity index 100% rename from Assets/Prefabs/Menus/Components/SFButton.preset.meta rename to Assets/Prefabs/Menus/Widgets/SFButton.preset.meta diff --git a/Assets/Prefabs/Menus/Components/SFToggle.preset b/Assets/Prefabs/Menus/Widgets/SFToggle.preset similarity index 99% rename from Assets/Prefabs/Menus/Components/SFToggle.preset rename to Assets/Prefabs/Menus/Widgets/SFToggle.preset index e3bff9f7d..8a795ea63 100644 --- a/Assets/Prefabs/Menus/Components/SFToggle.preset +++ b/Assets/Prefabs/Menus/Widgets/SFToggle.preset @@ -70,11 +70,11 @@ Preset: objectReference: {fileID: 0} - target: {fileID: 0} propertyPath: m_Colors.m_HighlightedColor.r - value: 0.88235295 + value: 1 objectReference: {fileID: 0} - target: {fileID: 0} propertyPath: m_Colors.m_HighlightedColor.g - value: 0.42745098 + value: 0.4509804 objectReference: {fileID: 0} - target: {fileID: 0} propertyPath: m_Colors.m_HighlightedColor.b diff --git a/Assets/Prefabs/Menus/Components/SFToggle.preset.meta b/Assets/Prefabs/Menus/Widgets/SFToggle.preset.meta similarity index 100% rename from Assets/Prefabs/Menus/Components/SFToggle.preset.meta rename to Assets/Prefabs/Menus/Widgets/SFToggle.preset.meta diff --git a/Assets/Resources/Game Selection Menu.prefab b/Assets/Resources/Game Selection Menu.prefab index 6e13ed50e..f7fbf41cb 100644 --- a/Assets/Resources/Game Selection Menu.prefab +++ b/Assets/Resources/Game Selection Menu.prefab @@ -2322,7 +2322,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 diff --git a/Assets/Scenes/DeckEditor.unity b/Assets/Scenes/DeckEditor.unity index 63f3ad74d..b491cabd6 100644 --- a/Assets/Scenes/DeckEditor.unity +++ b/Assets/Scenes/DeckEditor.unity @@ -629,7 +629,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: 0.000034322762, y: 0} + m_AnchoredPosition: {x: -0.000022224247, y: 0} m_SizeDelta: {x: 0, y: 50} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &179835150 @@ -722,7 +722,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: -0.000045761146, y: 0} + m_AnchoredPosition: {x: 0.000002341923, y: 0} m_SizeDelta: {x: 0, y: 50} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &196520020 @@ -2234,7 +2234,7 @@ MonoBehaviour: m_PersistentCalls: m_Calls: - m_Target: {fileID: 62766703} - m_MethodName: Search + m_MethodName: ClearSearchName m_Mode: 1 m_Arguments: m_ObjectArgument: {fileID: 0} @@ -2473,7 +2473,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: -0.000038166, y: 0} + m_AnchoredPosition: {x: -0.00010915344, y: 0} m_SizeDelta: {x: 0, y: 50} m_Pivot: {x: 0.5, y: 0.5} --- !u!1 &796070842 @@ -2598,7 +2598,7 @@ RectTransform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: 0.00003052519, y: 0} + m_AnchoredPosition: {x: -0.000022888184, y: 0} m_SizeDelta: {x: 0, y: 50} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &836546758 @@ -2952,7 +2952,7 @@ MonoBehaviour: m_HandleRect: {fileID: 335690429} m_Direction: 0 m_Value: 0 - m_Size: 0.98539513 + m_Size: 1 m_NumberOfSteps: 0 m_OnValueChanged: m_PersistentCalls: @@ -4623,7 +4623,7 @@ MonoBehaviour: m_PersistentCalls: m_Calls: - m_Target: {fileID: 62766703} - m_MethodName: Search + m_MethodName: ClearSearchName m_Mode: 1 m_Arguments: m_ObjectArgument: {fileID: 0} diff --git a/Assets/Scenes/MainMenu.unity b/Assets/Scenes/MainMenu.unity index a6332363c..7e81cf54c 100644 --- a/Assets/Scenes/MainMenu.unity +++ b/Assets/Scenes/MainMenu.unity @@ -236,7 +236,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 0} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 @@ -876,7 +876,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 0, g: 0.54901963, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 @@ -1233,7 +1233,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 0, g: 0.54901963, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 @@ -1359,7 +1359,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 0, g: 0.54901963, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 @@ -1562,7 +1562,7 @@ MonoBehaviour: m_Transition: 1 m_Colors: m_NormalColor: {r: 0, g: 0.54901963, b: 1, a: 1} - m_HighlightedColor: {r: 0.88235295, g: 0.42745098, b: 0, a: 1} + m_HighlightedColor: {r: 1, g: 0.4509804, b: 0, a: 1} m_PressedColor: {r: 0.38875425, g: 0.28925174, b: 0.78676474, a: 1} m_DisabledColor: {r: 0.2509804, g: 0.2509804, b: 0.2509804, a: 1} m_ColorMultiplier: 1 diff --git a/Assets/Scripts/CGS/CardGameManager.cs b/Assets/Scripts/CGS/CardGameManager.cs index 0483eaf78..93a617fdb 100644 --- a/Assets/Scripts/CGS/CardGameManager.cs +++ b/Assets/Scripts/CGS/CardGameManager.cs @@ -3,298 +3,295 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using CardGameDef; +using CardGameView; +using CGS.Menus; +using CGS.Play; +using CGS.Play.Multiplayer; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; -using CardGameDef; +using UnityEngine.Events; -public delegate void GameSceneDelegate(); - -public class CardGameManager : MonoBehaviour +namespace CGS { - public const string CardGameManagerTag = "CardGameManager"; - public const string BackgroundImageTag = "Background"; - public const string CardCanvasTag = "CardCanvas"; - public const string MenuCanvasTag = "MenuCanvas"; - public const string SelectorPrefabName = "Game Selection Menu"; - public const string PlayerPrefGameName = "DefaultGame"; - public const string FirstGameName = "Standard Playing Cards"; - public const string MessengerPrefabName = "Popup"; - public const string InvalidGameSelectionMessage = "Could not select the card game because the name is not recognized in the list of card games! Try selecting a different card game."; - public const string GameLoadErrorMessage = "Error loading game!: "; - public const string GameDeleteErrorMessage = "Error deleting game!: "; - public const int PixelsPerInch = 100; - - public static string GamesFilePathBase => Application.persistentDataPath + "/games"; - public static CardGame Current { get; private set; } = new CardGame(); - public static bool IsQuitting { get; private set; } - - public SortedDictionary AllCardGames { get; } = new SortedDictionary(); - public List OnSceneActions { get; } = new List(); - - private LobbyDiscovery _discovery; - public LobbyDiscovery Discovery => _discovery ?? - (_discovery = gameObject.GetOrAddComponent()); - - private static CardGameManager _instance; - private GameSelectionMenu _selector; - private Popup _messenger; - private Image _backgroundImage; - - void Awake() + public class CardGameManager : MonoBehaviour { - if (_instance != null && _instance != this) + public const string PlayerPrefGameName = "DefaultGame"; + public const string SelectorPrefabName = "Game Selection Menu"; + public const string MessengerPrefabName = "Popup"; + public const string InvalidGameSelectionMessage = "Could not select the card game because the name is not recognized in the list of card games! Try selecting a different card game."; + public const string GameLoadErrorMessage = "Error loading game!: "; + public const string GameDeleteErrorMessage = "Error deleting game!: "; + public const int PixelsPerInch = 100; + + public static CardGameManager Instance { - Destroy(gameObject); - return; + get + { + if (IsQuitting) return null; + if (_instance != null) return _instance; + GameObject cardGameManager = GameObject.FindGameObjectWithTag(Tags.CardGameManager); + if (cardGameManager == null) + { + cardGameManager = new GameObject(Tags.CardGameManager) { tag = Tags.CardGameManager }; + cardGameManager.transform.position = Vector3.zero; + } + _instance = cardGameManager.GetOrAddComponent(); + return _instance; + } } - _instance = this; - DontDestroyOnLoad(gameObject); - - FindCardGames(); - if (AllCardGames.Count < 1) - CreateDefaultCardGames(); - - CardGame currentGame; - Current = AllCardGames.TryGetValue(PlayerPrefs.GetString(PlayerPrefGameName, FirstGameName), out currentGame) - ? currentGame : new CardGame(); + private static CardGameManager _instance; - if (Debug.isDebugBuild) - Application.logMessageReceived += ShowLogToUser; - SceneManager.sceneLoaded += OnSceneLoaded; - SceneManager.sceneUnloaded += OnSceneUnloaded; - } + public static CardGame Current { get; private set; } = CardGame.Invalid; + public static bool IsQuitting { get; private set; } = false; - private void CreateDefaultCardGames() - { -#if !UNITY_ANDROID || UNITY_EDITOR - UnityExtensionMethods.CopyDirectory(Application.streamingAssetsPath, GamesFilePathBase); -#else - UnityExtensionMethods.ExtractAndroidStreamingAssets(GamesFilePathBase); -#endif - FindCardGames(); - } + public SortedDictionary AllCardGames { get; } = new SortedDictionary(); + public List OnSceneActions { get; } = new List(); - private void FindCardGames() - { - if (!Directory.Exists(GamesFilePathBase)) - return; + public LobbyDiscovery Discovery => _discovery ?? (_discovery = gameObject.GetOrAddComponent()); + private LobbyDiscovery _discovery; - foreach (string gameDirectory in Directory.GetDirectories(GamesFilePathBase)) + public GameSelectionMenu Selector { - string gameName = gameDirectory.Substring(GamesFilePathBase.Length + 1); - AllCardGames[gameName] = new CardGame(gameName, string.Empty); + get + { + if (_selector != null) return _selector; + _selector = Instantiate(Resources.Load(SelectorPrefabName)).GetOrAddComponent(); + _selector.transform.SetParent(null); + return _selector; + } } - } + private GameSelectionMenu _selector; - void ShowLogToUser(string logString, string stackTrace, LogType type) - { - Messenger.Show(logString); - } - - void OnSceneLoaded(Scene scene, LoadSceneMode mode) - { - DoGameSceneActions(); - } - - void OnSceneUnloaded(Scene scene) - { - OnSceneActions.Clear(); - } + public Popup Messenger + { + get + { + if (_messenger != null) return _messenger; + _messenger = Instantiate(Resources.Load(MessengerPrefabName)).GetOrAddComponent(); + _messenger.transform.SetParent(transform); + return _messenger; + } + } + private Popup _messenger; - public IEnumerator DownloadCardGame(string gameUrl) - { - //Messenger.Show("Game download has started"); - CardGame newGame = new CardGame(Set.DefaultCode, gameUrl) { AutoUpdate = true }; - Current = newGame; - yield return newGame.Download(); - if (string.IsNullOrEmpty(newGame.Error)) - AllCardGames[newGame.Name] = newGame; - else - Debug.LogError(GameLoadErrorMessage + newGame.Error); - SelectCardGame(newGame.Name); - //Messenger.Show("Game download has finished"); - } + public Image BackgroundImage + { + get + { + if (_backgroundImage == null && GameObject.FindGameObjectWithTag(Tags.BackgroundImage) != null) + _backgroundImage = GameObject.FindGameObjectWithTag(Tags.BackgroundImage).GetOrAddComponent(); + return _backgroundImage; + } + } + private Image _backgroundImage; - public void SelectLeft() - { - string prevGameName = AllCardGames.Keys.Last(); - SortedDictionary.Enumerator allCardGamesEnum = AllCardGames.GetEnumerator(); - bool found = false; - while (!found && allCardGamesEnum.MoveNext()) + public static Canvas TopCardCanvas { - if (!allCardGamesEnum.Current.Key.Equals(Current.Name)) - prevGameName = allCardGamesEnum.Current.Key; - else - found = true; + get + { + Canvas topCanvas = null; + foreach (GameObject canvas in GameObject.FindGameObjectsWithTag(Tags.CardCanvas)) + if (canvas.activeSelf && (topCanvas == null || canvas.GetComponent().sortingOrder > topCanvas.sortingOrder)) + topCanvas = canvas.GetComponent(); + return topCanvas; + } } - SelectCardGame(prevGameName); - } - public void SelectRight() - { - string nextGameName = Current.Name; - SortedDictionary.Enumerator allCardGamesEnum = AllCardGames.GetEnumerator(); - bool found = false; - while (!found && allCardGamesEnum.MoveNext()) - if (allCardGamesEnum.Current.Key.Equals(Current.Name)) - found = true; - if (allCardGamesEnum.MoveNext()) - nextGameName = allCardGamesEnum.Current.Key; - else if (found) - nextGameName = AllCardGames.Keys.First(); - SelectCardGame(nextGameName); - } + public static Canvas TopMenuCanvas + { + get + { + Canvas topCanvas = null; + foreach (GameObject canvas in GameObject.FindGameObjectsWithTag(Tags.MenuCanvas)) + if (canvas.activeSelf && (topCanvas == null || canvas.GetComponent().sortingOrder > topCanvas.sortingOrder)) + topCanvas = canvas.GetComponent(); + return topCanvas; + } + } - public void SelectCardGame(string gameName, string gameUrl) - { - if (string.IsNullOrEmpty(gameName) || !AllCardGames.ContainsKey(gameName)) + void Awake() { - StartCoroutine(DownloadCardGame(gameUrl)); - return; + if (_instance != null && _instance != this) + { + Destroy(gameObject); + return; + } + _instance = this; + CardGame.Invalid.CoroutineRunner = this; + DontDestroyOnLoad(gameObject); + + if (!Directory.Exists(CardGame.GamesDirectoryPath)) + CreateDefaultCardGames(); + LookupCardGames(); + + CardGame currentGame; + Current = AllCardGames.TryGetValue(PlayerPrefs.GetString(PlayerPrefGameName), out currentGame) + ? currentGame : AllCardGames.First().Value; + + if (Debug.isDebugBuild) + Application.logMessageReceived += ShowLogToUser; + SceneManager.sceneLoaded += OnSceneLoaded; + SceneManager.sceneUnloaded += OnSceneUnloaded; } - SelectCardGame(gameName); - } - public void SelectCardGame(string gameName) - { - if (string.IsNullOrEmpty(gameName) || !AllCardGames.ContainsKey(gameName)) + private void CreateDefaultCardGames() { - Debug.LogError(InvalidGameSelectionMessage); - Selector.Show(); - return; +#if UNITY_ANDROID && !UNITY_EDITOR + UnityExtensionMethods.ExtractAndroidStreamingAssets(CardGame.GamesDirectoryPath); +#else + UnityExtensionMethods.CopyDirectory(Application.streamingAssetsPath, CardGame.GamesDirectoryPath); +#endif } - CardGame currentGame; - Current = AllCardGames.TryGetValue(gameName, out currentGame) ? currentGame : new CardGame(); + private void LookupCardGames() + { + if (!Directory.Exists(CardGame.GamesDirectoryPath) || Directory.GetDirectories(CardGame.GamesDirectoryPath).Length < 1) + CreateDefaultCardGames(); - DoGameSceneActions(); - } + foreach (string gameDirectory in Directory.GetDirectories(CardGame.GamesDirectoryPath)) + { + string gameName = gameDirectory.Substring(CardGame.GamesDirectoryPath.Length + 1); + AllCardGames[gameName] = new CardGame(this, gameName, string.Empty); + } + } - public IEnumerator LoadCards() - { - //Messenger.Show("Cards are loading in the background. Performance may be affected in the meantime."); - yield return Current.LoadAllCards(); - if (!string.IsNullOrEmpty(Current.Error)) - Debug.LogError(GameLoadErrorMessage + Current.Error); - //Messenger.Show("All cards have finished loading."); - } + void ShowLogToUser(string logString, string stackTrace, LogType type) + { + Messenger.Show(logString); + } - public void DoGameSceneActions() - { - if (!Current.IsLoaded) - Current.Load(); - - if (!string.IsNullOrEmpty(Current.Error)) - Debug.LogError(GameLoadErrorMessage + Current.Error); - else - PlayerPrefs.SetString(PlayerPrefGameName, Current.Name); - - if (BackgroundImage != null) - BackgroundImage.sprite = Current.BackgroundImageSprite; - CardInfoViewer.Instance?.ResetInfo(); - - for (int i = OnSceneActions.Count - 1; i >= 0; i--) - if (OnSceneActions[i] == null) - OnSceneActions.RemoveAt(i); - foreach (GameSceneDelegate action in OnSceneActions) - action(); - } + void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + DoGameSceneActions(); + } - public void DeleteGame() - { - try + void OnSceneUnloaded(Scene scene) { - Directory.Delete(Current.FilePathBase, true); - AllCardGames.Remove(Current.Name); - SelectCardGame(AllCardGames.Keys.First()); - Selector.Show(); + OnSceneActions.Clear(); } - catch (Exception ex) + + public IEnumerator DownloadCardGame(string gameUrl) { - Debug.LogError(GameDeleteErrorMessage + ex.Message); + //Messenger.Show("Game download has started"); + CardGame newGame = new CardGame(this, Set.DefaultCode, gameUrl) { AutoUpdate = true }; + Current = newGame; + yield return newGame.Download(); + if (string.IsNullOrEmpty(newGame.Error)) + AllCardGames[newGame.Name] = newGame; + else + Debug.LogError(GameLoadErrorMessage + newGame.Error); + SelectCardGame(newGame.Name); + //Messenger.Show("Game download has finished"); } - } - void OnDisable() - { - SceneManager.sceneLoaded -= OnSceneLoaded; - } + public void SelectLeft() + { + string prevGameName = AllCardGames.Keys.Last(); + SortedDictionary.Enumerator allCardGamesEnum = AllCardGames.GetEnumerator(); + bool found = false; + while (!found && allCardGamesEnum.MoveNext()) + { + if (!allCardGamesEnum.Current.Key.Equals(Current.Name)) + prevGameName = allCardGamesEnum.Current.Key; + else + found = true; + } + SelectCardGame(prevGameName); + } - void OnApplicationQuit() - { - IsQuitting = true; - } + public void SelectRight() + { + string nextGameName = Current.Name; + SortedDictionary.Enumerator allCardGamesEnum = AllCardGames.GetEnumerator(); + bool found = false; + while (!found && allCardGamesEnum.MoveNext()) + if (allCardGamesEnum.Current.Key.Equals(Current.Name)) + found = true; + if (allCardGamesEnum.MoveNext()) + nextGameName = allCardGamesEnum.Current.Key; + else if (found) + nextGameName = AllCardGames.Keys.First(); + SelectCardGame(nextGameName); + } - public static CardGameManager Instance - { - get + public void SelectCardGame(string gameName, string gameUrl) { - if (IsQuitting) return null; - if (_instance != null) return _instance; - GameObject cardGameManager = GameObject.FindGameObjectWithTag(CardGameManagerTag); - if (cardGameManager == null) + if (string.IsNullOrEmpty(gameName) || !AllCardGames.ContainsKey(gameName)) { - cardGameManager = new GameObject(CardGameManagerTag) { tag = CardGameManagerTag }; - cardGameManager.transform.position = Vector3.zero; + StartCoroutine(DownloadCardGame(gameUrl)); + return; } - _instance = cardGameManager.GetOrAddComponent(); - return _instance; + SelectCardGame(gameName); } - } - public GameSelectionMenu Selector - { - get + public void SelectCardGame(string gameName) { - if (_selector != null) return _selector; - _selector = Instantiate(Resources.Load(SelectorPrefabName)).GetOrAddComponent(); - _selector.transform.SetParent(null); - return _selector; + if (string.IsNullOrEmpty(gameName) || !AllCardGames.ContainsKey(gameName)) + { + Debug.LogError(InvalidGameSelectionMessage); + Selector.Show(); + return; + } + + Current = AllCardGames[gameName]; + DoGameSceneActions(); } - } - public Popup Messenger - { - get + public void DoGameSceneActions() { - if (_messenger != null) return _messenger; - _messenger = Instantiate(Resources.Load(MessengerPrefabName)).GetOrAddComponent(); - _messenger.transform.SetParent(transform); - return _messenger; + if (!Current.IsLoaded) + Current.Load(); + + if (!string.IsNullOrEmpty(Current.Error)) + Debug.LogError(GameLoadErrorMessage + Current.Error); + else + PlayerPrefs.SetString(PlayerPrefGameName, Current.Name); + + if (BackgroundImage != null) + BackgroundImage.sprite = Current.BackgroundImageSprite; + CardInfoViewer.Instance?.ResetInfo(); + + for (int i = OnSceneActions.Count - 1; i >= 0; i--) + if (OnSceneActions[i] == null) + OnSceneActions.RemoveAt(i); + foreach (UnityAction action in OnSceneActions) + action(); } - } - public Image BackgroundImage - { - get + + public IEnumerator LoadCards() { - if (_backgroundImage == null && GameObject.FindGameObjectWithTag(BackgroundImageTag) != null) - _backgroundImage = GameObject.FindGameObjectWithTag(BackgroundImageTag).GetOrAddComponent(); - return _backgroundImage; + //Messenger.Show("Cards are loading in the background. Performance may be affected in the meantime."); + yield return Current.LoadAllCards(); + if (!string.IsNullOrEmpty(Current.Error)) + Debug.LogError(GameLoadErrorMessage + Current.Error); + //Messenger.Show("All cards have finished loading."); } - } - public static Canvas TopCardCanvas - { - get + public void DeleteGame() { - Canvas topCanvas = null; - foreach (GameObject canvas in GameObject.FindGameObjectsWithTag(CardCanvasTag)) - if (canvas.activeSelf && (topCanvas == null || canvas.GetComponent().sortingOrder > topCanvas.sortingOrder)) - topCanvas = canvas.GetComponent(); - return topCanvas; + try + { + Directory.Delete(Current.GameFolderPath, true); + AllCardGames.Remove(Current.Name); + SelectCardGame(AllCardGames.Keys.First()); + Selector.Show(); + } + catch (Exception ex) + { + Debug.LogError(GameDeleteErrorMessage + ex.Message); + } } - } - public static Canvas TopMenuCanvas - { - get + void OnDisable() + { + SceneManager.sceneLoaded -= OnSceneLoaded; + } + + void OnApplicationQuit() { - Canvas topCanvas = null; - foreach (GameObject canvas in GameObject.FindGameObjectsWithTag(MenuCanvasTag)) - if (canvas.activeSelf && (topCanvas == null || canvas.GetComponent().sortingOrder > topCanvas.sortingOrder)) - topCanvas = canvas.GetComponent(); - return topCanvas; + IsQuitting = true; } } } diff --git a/Assets/Scripts/CGS/CardInfoViewer.cs b/Assets/Scripts/CGS/CardInfoViewer.cs deleted file mode 100644 index 65eb47c1c..000000000 --- a/Assets/Scripts/CGS/CardInfoViewer.cs +++ /dev/null @@ -1,241 +0,0 @@ -using System.Collections.Generic; -using CardGameDef; -using UnityEngine; -using UnityEngine.UI; -using UnityEngine.EventSystems; - -public class CardInfoViewer : MonoBehaviour, IPointerDownHandler, ISelectHandler, IDeselectHandler -{ - public const string CardInfoViewerTag = "CardInfoViewer"; - public const string SetLabel = "Set"; - public const float VisibleYMin = 0.625f; - public const float VisibleYMax = 1; - public const float HiddenYmin = 1.025f; - public const float HiddenYMax = 1.4f; - public const float AnimationSpeed = 5.0f; - - public RectTransform infoPanel; - public RectTransform zoomPanel; - public Image cardImage; - public Image zoomImage; - public Text nameText; - public Text idText; - public Dropdown propertySelection; - public Text labelText; - public Text contentText; - - public List PropertyOptions { get; } = new List(); - public Dictionary DisplayNameLookup { get; } = new Dictionary(); - - private static CardInfoViewer _instance; - private CardModel _selectedCardModel; - private int _selectedPropertyIndex; - private bool _isVisible; - - void Start() - { - ResetInfo(); - } - - void Update() - { - infoPanel.anchorMin = IsVisible ? - new Vector2(infoPanel.anchorMin.x, Mathf.Lerp(infoPanel.anchorMin.y, VisibleYMin, AnimationSpeed * Time.deltaTime)) : - new Vector2(infoPanel.anchorMin.x, Mathf.Lerp(infoPanel.anchorMin.y, HiddenYmin, AnimationSpeed * Time.deltaTime)); - infoPanel.anchorMax = IsVisible ? - new Vector2(infoPanel.anchorMax.x, Mathf.Lerp(infoPanel.anchorMax.y, VisibleYMax, AnimationSpeed * Time.deltaTime)) : - new Vector2(infoPanel.anchorMax.x, Mathf.Lerp(infoPanel.anchorMax.y, HiddenYMax, AnimationSpeed * Time.deltaTime)); - } - - void LateUpdate() - { - if (!IsVisible || SelectedCardModel == null || !Input.anyKeyDown || CardGameManager.TopMenuCanvas != null) - return; - - if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && SelectedCardModel.DoubleClickAction != null) - SelectedCardModel.DoubleClickAction(SelectedCardModel); - else if (Input.GetButtonDown(Inputs.Page)) - { - if (Input.GetAxis(Inputs.Page) > 0) - IncrementProperty(); - else - DecrementProperty(); - } - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - SelectedCardModel = null; - } - - public void ResetInfo() - { - cardImage.gameObject.GetOrAddComponent().aspectRatio = CardGameManager.Current.CardAspectRatio; - zoomPanel.GetChild(0).gameObject.GetOrAddComponent().aspectRatio = CardGameManager.Current.CardAspectRatio; - - int selectedPropertyIndex = 0; - PropertyOptions.Clear(); - PropertyOptions.Add(new Dropdown.OptionData() { text = SetLabel }); - DisplayNameLookup.Clear(); - foreach (PropertyDef propDef in CardGameManager.Current.CardProperties) - { - string displayName = !string.IsNullOrEmpty(propDef.Display) ? propDef.Display : propDef.Name; - PropertyOptions.Add(new Dropdown.OptionData() { text = displayName }); - DisplayNameLookup[displayName] = propDef.Name; - if (propDef.Name.Equals(CardGameManager.Current.CardPrimaryProperty)) - selectedPropertyIndex = PropertyOptions.Count - 1; - } - propertySelection.options = PropertyOptions; - propertySelection.value = selectedPropertyIndex; - propertySelection.onValueChanged.Invoke(selectedPropertyIndex); - } - - public void DecrementProperty() - { - SelectedPropertyIndex--; - } - - public void IncrementProperty() - { - SelectedPropertyIndex++; - } - - public void SetContentText() - { - Set currentSet = null; - if (SelectedCardModel != null) - contentText.text = SelectedPropertyIndex != 0 ? - SelectedCardModel.Value.GetPropertyValueString(SelectedPropertyName) - : (CardGameManager.Current.Sets.TryGetValue(SelectedCardModel.Value.SetCode, out currentSet) - ? currentSet : Set.Default).ToString(); - else - contentText.text = string.Empty; - } - - public void OnPointerDown(PointerEventData eventData) - { - EventSystem.current.SetSelectedGameObject(gameObject, eventData); - } - - public void OnSelect(BaseEventData eventData) - { - IsVisible = true; - } - - public void OnDeselect(BaseEventData eventData) - { - if (!zoomPanel.gameObject.activeSelf) - IsVisible = false; - } - - public void ShowCardZoomed(CardModel cardModel) - { - SelectedCardModel = cardModel; - ShowCardZoomed(); - } - - public void ShowCardZoomed() - { - zoomPanel.gameObject.SetActive(true); - } - - public void HideCardZoomed() - { - if (SwipeManager.IsSwiping()) - return; - zoomPanel.gameObject.SetActive(false); - } - - public static CardInfoViewer Instance - { - get - { - if (_instance != null) - return _instance; - - GameObject cardInfoViewer = GameObject.FindWithTag(CardInfoViewerTag); - _instance = cardInfoViewer?.GetOrAddComponent(); - return _instance; - } - } - - public string SelectedPropertyName - { - get - { - string selectedName = SetLabel; - if (SelectedPropertyIndex >= 1 && SelectedPropertyIndex < PropertyOptions.Count) - DisplayNameLookup.TryGetValue(SelectedPropertyDisplay, out selectedName); - return selectedName; - } - } - - public string SelectedPropertyDisplay - { - get - { - string selectedDisplay = SetLabel; - if (SelectedPropertyIndex >= 1 && SelectedPropertyIndex < PropertyOptions.Count) - selectedDisplay = PropertyOptions[SelectedPropertyIndex].text; - return selectedDisplay; - } - } - - public int SelectedPropertyIndex - { - get { return _selectedPropertyIndex; } - set - { - _selectedPropertyIndex = value; - if (_selectedPropertyIndex < 0) - _selectedPropertyIndex = PropertyOptions.Count - 1; - if (_selectedPropertyIndex >= PropertyOptions.Count) - _selectedPropertyIndex = 0; - propertySelection.value = _selectedPropertyIndex; - labelText.text = SelectedPropertyDisplay; - SetContentText(); - } - } - - public CardModel SelectedCardModel - { - get { return _selectedCardModel; } - set - { - if (_selectedCardModel != null) - _selectedCardModel.HideHighlight(); - - _selectedCardModel = value; - - if (_selectedCardModel == null) - { - IsVisible = false; - return; - } - cardImage.sprite = _selectedCardModel.GetComponent().sprite; - zoomImage.sprite = cardImage.sprite; - nameText.text = _selectedCardModel.Value.Name; - idText.text = _selectedCardModel.Value.Id; - SetContentText(); - - IsVisible = true; - } - } - - public bool IsVisible - { - get { return _isVisible; } - set - { - _isVisible = value; - if (!_isVisible && zoomPanel != null) - zoomPanel.gameObject.SetActive(false); - - if (SelectedCardModel == null) - return; - - if (_isVisible) - SelectedCardModel.ShowHighlight(); - else - SelectedCardModel.HideHighlight(); - } - } - public bool WasVisible => infoPanel.anchorMax.y < (HiddenYMax + VisibleYMax) / 2.0f; -} diff --git a/Assets/Scripts/CGS/CardInfoViewerSelectable.cs b/Assets/Scripts/CGS/CardInfoViewerSelectable.cs deleted file mode 100644 index 9d6d49bc7..000000000 --- a/Assets/Scripts/CGS/CardInfoViewerSelectable.cs +++ /dev/null @@ -1,27 +0,0 @@ -using UnityEngine; -using UnityEngine.EventSystems; - -public class CardInfoViewerSelectable : MonoBehaviour, IPointerDownHandler, ISelectHandler, IDeselectHandler -{ - public bool ignoreDeselect = false; - - public void OnPointerDown(PointerEventData eventData) - { - EventSystem.current.SetSelectedGameObject(gameObject, eventData); - } - - public void OnSelect(BaseEventData eventData) - { - if (CardInfoViewer.Instance.WasVisible) - CardInfoViewer.Instance.IsVisible = true; - } - - public void OnDeselect(BaseEventData eventData) - { - if (ignoreDeselect) - return; - - if (!CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf) - CardInfoViewer.Instance.IsVisible = false; - } -} diff --git a/Assets/Scripts/CGS/CardModel.cs b/Assets/Scripts/CGS/CardModel.cs deleted file mode 100644 index fca17fb47..000000000 --- a/Assets/Scripts/CGS/CardModel.cs +++ /dev/null @@ -1,582 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEngine.UI; -using UnityEngine.EventSystems; -using UnityEngine.Networking; -using CardGameDef; - -public delegate void OnDoubleClickDelegate(CardModel cardModel); -public delegate void SecondaryDragDelegate(); - -public enum DragPhase -{ - Begin, - Drag, - End -} - -[RequireComponent(typeof(Image), typeof(CanvasGroup), typeof(Outline))] -public class CardModel : NetworkBehaviour, IPointerDownHandler, IPointerUpHandler, ISelectHandler, IDeselectHandler, IBeginDragHandler, IDragHandler, IEndDragHandler -{ - public const float MovementSpeed = 600f; - public static readonly Color SelectedHighlightColor = new Color(0.39f, 0.29f, 0.79f); - public static readonly Vector2 OutlineHighlightDistance = new Vector2(10, 10); - - public bool IsOnline => CGSNetManager.Instance != null && CGSNetManager.Instance.isNetworkActive - && transform.parent == CGSNetManager.Instance.playController.playAreaContent; - public bool IsProcessingSecondaryDragAction => PointerPositions.Count > 1 || (CurrentPointerEventData != null && - (CurrentPointerEventData.button == PointerEventData.InputButton.Middle || CurrentPointerEventData.button == PointerEventData.InputButton.Right)); - public CardStack ParentCardStack => transform.parent.GetComponent(); - - public bool DoesCloneOnDrag { get; set; } - public OnDoubleClickDelegate DoubleClickAction { get; set; } - public SecondaryDragDelegate SecondaryDragAction { get; set; } - public CardDropZone DropTarget { get; set; } - - public bool DidSelectOnDown { get; private set; } - public PointerEventData CurrentPointerEventData { get; private set; } - public DragPhase CurrentDragPhase { get; private set; } - - public Dictionary PointerPositions { get; } = new Dictionary(); - protected Dictionary PointerDragOffsets { get; } = new Dictionary(); - - [SyncVar(hook = "OnChangePosition")] - public Vector2 position; - - [SyncVar(hook = "OnChangeRotation")] - public Quaternion rotation; - - [SyncVar] - private string _id; - public string Id => _id; - public Card Value - { - get - { - Card cardValue; - if (string.IsNullOrEmpty(_id) || !CardGameManager.Current.Cards.TryGetValue(_id, out cardValue)) - return Card.Blank; - return cardValue; - } - set - { - _id = value != null ? value.Id : string.Empty; - gameObject.name = value != null ? "[" + value.Id + "] " + value.Name : string.Empty; - CardGameManager.Current.PutCardImage(this); - } - } - - [SyncVar] - private bool _isFacedown; - public bool IsFacedown - { - get { return _isFacedown; } - set - { - if (value == _isFacedown) - return; - _isFacedown = value; - if (_isFacedown) - { - HideNameLabel(); - image.sprite = CardGameManager.Current.CardBackImageSprite; - } - else - CardGameManager.Current.PutCardImage(this); - - if (IsOnline && hasAuthority) - CmdUpdateIsFacedown(_isFacedown); - } - } - - private Image _image; - public Image image => _image ?? (_image = GetComponent()); - public bool HasImage => image.sprite != CardGameManager.Current.CardBackImageSprite; - - private Outline _outline; - private Text _nameText; - - private RectTransform _placeHolder; - private CardStack _placeHolderCardStack; - - void Start() - { - ((RectTransform)transform).sizeDelta = CardGameManager.PixelsPerInch * CardGameManager.Current.CardSize; - - if (IsOnline) - { - if (Vector2.zero != position) - ((RectTransform)transform).anchoredPosition = position; - if (Quaternion.identity != rotation) - transform.rotation = rotation; - } - - if (!IsFacedown) - CardGameManager.Current.PutCardImage(this); - else - image.sprite = CardGameManager.Current.CardBackImageSprite; - - _outline = GetComponent(); - _nameText = GetComponentInChildren(); - } - - public void OnPointerDown(PointerEventData eventData) - { - DidSelectOnDown = eventData.button != PointerEventData.InputButton.Middle && eventData.button != PointerEventData.InputButton.Right - && CardInfoViewer.Instance.SelectedCardModel != this && CardInfoViewer.Instance.WasVisible; - if (DidSelectOnDown) - EventSystem.current.SetSelectedGameObject(gameObject, eventData); - - CurrentPointerEventData = eventData; - - PointerPositions[eventData.pointerId] = eventData.position; - PointerDragOffsets[eventData.pointerId] = ((Vector2)transform.position) - eventData.position; - } - - public void OnPointerUp(PointerEventData eventData) - { - if (CurrentPointerEventData != null && CurrentPointerEventData.pointerId == eventData.pointerId && !eventData.dragging - && eventData.button != PointerEventData.InputButton.Middle && eventData.button != PointerEventData.InputButton.Right) - { - if (!DidSelectOnDown && EventSystem.current.currentSelectedGameObject == gameObject && DoubleClickAction != null) - DoubleClickAction(this); - else if (PlaceHolder == null) - EventSystem.current.SetSelectedGameObject(gameObject, eventData); - } - - CurrentPointerEventData = eventData; - if (CurrentDragPhase == DragPhase.Drag) - return; - - PointerPositions.Remove(eventData.pointerId); - PointerDragOffsets.Remove(eventData.pointerId); - } - - public void OnSelect(BaseEventData eventData) - { - if (!IsFacedown) - CardInfoViewer.Instance.SelectedCardModel = this; - } - - public void OnDeselect(BaseEventData eventData) - { - if (!CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf) - CardInfoViewer.Instance.IsVisible = false; - } - - public void OnBeginDrag(PointerEventData eventData) - { - if (IsOnline && !hasAuthority) - return; - - if (DoesCloneOnDrag) - { - GameObject newGameObject = Instantiate(gameObject, transform.position, transform.rotation, gameObject.FindInParents().transform); - eventData.pointerPress = newGameObject; - eventData.pointerDrag = newGameObject; - newGameObject.GetComponent().blocksRaycasts = false; - CardModel cardModel = newGameObject.GetOrAddComponent(); - cardModel.HideHighlight(); - cardModel.Value = Value; - cardModel.DoesCloneOnDrag = false; - cardModel.PointerDragOffsets[eventData.pointerId] = (Vector2)transform.position - eventData.position; - cardModel.OnBeginDrag(eventData); - return; - } - - EventSystem.current.SetSelectedGameObject(null, eventData); - CurrentPointerEventData = eventData; - CurrentDragPhase = DragPhase.Begin; - PointerPositions[eventData.pointerId] = eventData.position; - - UpdatePosition(); - if (SecondaryDragAction != null && IsProcessingSecondaryDragAction) - SecondaryDragAction(); - } - - public void OnDrag(PointerEventData eventData) - { - if (IsOnline && !hasAuthority) - return; - - CurrentPointerEventData = eventData; - CurrentDragPhase = DragPhase.Drag; - PointerPositions[eventData.pointerId] = eventData.position; - - UpdatePosition(); - if (SecondaryDragAction != null && IsProcessingSecondaryDragAction) - SecondaryDragAction(); - } - - public void OnEndDrag(PointerEventData eventData) - { - if (IsOnline && !hasAuthority) - return; - - CurrentPointerEventData = eventData; - CurrentDragPhase = DragPhase.End; - - UpdatePosition(); - if (SecondaryDragAction != null && IsProcessingSecondaryDragAction) - SecondaryDragAction(); - - Vector2 removedOffset = Vector2.zero; - Vector2 pointerDragOffset; - if (PointerDragOffsets.TryGetValue(eventData.pointerId, out pointerDragOffset)) - removedOffset = (Vector2)transform.position - eventData.position - pointerDragOffset; - PointerPositions.Remove(eventData.pointerId); - PointerDragOffsets.Remove(eventData.pointerId); - Vector2 otherOffset; - foreach (int offsetKey in PointerDragOffsets.Keys.ToList()) - if (PointerDragOffsets.TryGetValue(offsetKey, out otherOffset)) - PointerDragOffsets[offsetKey] = otherOffset - removedOffset; - - if (IsProcessingSecondaryDragAction) - return; - - if (PlaceHolder != null) - StartCoroutine(MoveToPlaceHolder()); - else if (ParentCardStack == null) - Discard(); - } - - public static CardModel GetPointerDrag(PointerEventData eventData) - { - if (eventData.pointerDrag == null) - return null; - return eventData.pointerDrag.GetComponent(); - } - - public void UpdatePosition() - { -#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR - if (SecondaryDragAction != Rotate && IsProcessingSecondaryDragAction) - return; -#else - if (Input.GetMouseButton(1) || Input.GetMouseButtonUp(1) || Input.GetMouseButton(2) || Input.GetMouseButtonUp(2)) - return; -#endif - if (PointerPositions.Count < 1 || PointerDragOffsets.Count < 1 || (IsOnline && !hasAuthority)) - return; - - Vector2 targetPosition = UnityExtensionMethods.CalculateMean(PointerPositions.Values.ToList()); - targetPosition = targetPosition + UnityExtensionMethods.CalculateMean(PointerDragOffsets.Values.ToList()); - if (ParentCardStack != null) - UpdateCardStackPosition(targetPosition); - else - transform.position = targetPosition; - - if (PlaceHolderCardStack != null) - PlaceHolderCardStack.UpdateLayout(PlaceHolder, targetPosition); - - if (IsOnline) - CmdUpdatePosition(((RectTransform)transform).anchoredPosition); - } - - public void UpdateCardStackPosition(Vector2 targetPosition) - { - CardStack cardStack = ParentCardStack; - if (cardStack == null || (IsOnline && !hasAuthority)) - return; - - if (!cardStack.DoesImmediatelyRelease && (cardStack.type == CardStackType.Vertical || cardStack.type == CardStackType.Horizontal)) - cardStack.UpdateScrollRect(CurrentDragPhase, CurrentPointerEventData); - else - cardStack.UpdateLayout(transform as RectTransform, targetPosition); - - if (cardStack.type == CardStackType.Area) - transform.SetAsLastSibling(); - - Vector3[] stackCorners = new Vector3[4]; - ((RectTransform)cardStack.transform).GetWorldCorners(stackCorners); - bool isOutYBounds = targetPosition.y < stackCorners[0].y || targetPosition.y > stackCorners[1].y; - bool isOutXBounds = targetPosition.x < stackCorners[0].x || targetPosition.y > stackCorners[2].x; - if ((cardStack.DoesImmediatelyRelease && !IsProcessingSecondaryDragAction) - || (cardStack.type == CardStackType.Full && CurrentDragPhase == DragPhase.Begin) - || (cardStack.type == CardStackType.Vertical && isOutXBounds) - || (cardStack.type == CardStackType.Horizontal && isOutYBounds) - || (cardStack.type == CardStackType.Area - && (isOutYBounds || (PlaceHolder != null && PlaceHolder.parent != transform.parent)))) - ParentToCanvas(targetPosition); - } - - [Command] - void CmdUpdatePosition(Vector2 position) - { - this.position = position; - } - - public void OnChangePosition(Vector2 position) - { - if (!hasAuthority) - ((RectTransform)transform).anchoredPosition = position; - } - - public void ParentToCanvas(Vector3 targetPosition) - { - if (IsOnline && hasAuthority) - CmdUnspawnCard(); - CardStack prevParentStack = ParentCardStack; - if (CurrentDragPhase == DragPhase.Drag) - prevParentStack.UpdateScrollRect(DragPhase.End, CurrentPointerEventData); - transform.SetParent(CardGameManager.TopCardCanvas.transform); - transform.SetAsLastSibling(); - if (prevParentStack != null) - prevParentStack.OnRemove(this); - GetComponent().blocksRaycasts = false; - ((RectTransform)transform).anchorMax = 0.5f * Vector2.one; - ((RectTransform)transform).anchorMin = 0.5f * Vector2.one; - ((RectTransform)transform).pivot = 0.5f * Vector2.one; - transform.position = targetPosition; - transform.localScale = Vector3.one; - } - - [Command] - void CmdUnspawnCard() - { - RpcUnspawnCard(); - } - - [ClientRpc] - public void RpcUnspawnCard() - { - if (!isServer && !hasAuthority) - Discard(); - else if (isServer) - NetworkServer.UnSpawn(gameObject); - } - - public IEnumerator MoveToPlaceHolder() - { - while (PlaceHolder != null && Vector3.Distance(transform.position, PlaceHolder.position) > 1) - { - float step = MovementSpeed * Time.deltaTime; - transform.position = Vector3.MoveTowards(transform.position, PlaceHolder.position, step); - yield return null; - } - - if (PlaceHolder == null) - { - Discard(); - yield break; - } - - CardStack prevParentStack = ParentCardStack; - transform.SetParent(PlaceHolder.parent); - transform.SetSiblingIndex(PlaceHolder.GetSiblingIndex()); - if (prevParentStack != null) - prevParentStack.OnRemove(this); - if (ParentCardStack != null) - ParentCardStack.OnAdd(this); - PlaceHolder = null; - GetComponent().blocksRaycasts = true; - } - - public void UpdateParentCardStackScrollRect() - { - CardStack cardStack = ParentCardStack; - if (cardStack != null) - cardStack.UpdateScrollRect(CurrentDragPhase, CurrentPointerEventData); - } - - public void Rotate() - { - Vector2 referencePoint = transform.position; - foreach (KeyValuePair pointerDragPosition in PointerPositions) - if (pointerDragPosition.Key != CurrentPointerEventData.pointerId) - referencePoint = pointerDragPosition.Value; - Vector2 prevDir = (CurrentPointerEventData.position - CurrentPointerEventData.delta) - referencePoint; - Vector2 currDir = CurrentPointerEventData.position - referencePoint; - transform.Rotate(0, 0, Vector2.SignedAngle(prevDir, currDir)); - - if (IsOnline) - CmdUpdateRotation(transform.rotation); - } - - [Command] - public void CmdUpdateRotation(Quaternion rotation) - { - this.rotation = rotation; - } - - public void OnChangeRotation(Quaternion rotation) - { - if (!hasAuthority) - transform.rotation = rotation; - } - - public static void Rotate90(CardModel cardModel) - { - if (cardModel == null || (cardModel.IsOnline && !cardModel.hasAuthority)) - return; - - cardModel.transform.rotation *= Quaternion.Euler(0, 0, -90); - if (cardModel.IsOnline) - cardModel.CmdUpdateRotation(cardModel.transform.rotation); - } - - public static void ToggleRotation90(CardModel cardModel) - { - if (cardModel == null || (cardModel.IsOnline && !cardModel.hasAuthority)) - return; - - bool isVertical = cardModel.transform.rotation.Equals(Quaternion.identity); - cardModel.transform.rotation = isVertical ? - Quaternion.AngleAxis(90, Vector3.back) : Quaternion.identity; - if (cardModel.IsOnline) - cardModel.CmdUpdateRotation(cardModel.transform.rotation); - } - - public static void ResetRotation(CardStack cardStack, CardModel cardModel) - { - if (cardModel == null || (cardModel.IsOnline && !cardModel.hasAuthority)) - return; - - cardModel.transform.rotation = Quaternion.identity; - if (cardModel.IsOnline) - cardModel.CmdUpdateRotation(cardModel.transform.rotation); - } - - public static void ShowCard(CardStack cardStack, CardModel cardModel) - { - if (cardModel == null || (cardModel.IsOnline && !cardModel.hasAuthority)) - return; - - cardModel.IsFacedown = false; - } - - public static void HideCard(CardStack cardStack, CardModel cardModel) - { - if (cardModel == null || (cardModel.IsOnline && !cardModel.hasAuthority)) - return; - - cardModel.IsFacedown = true; - EventSystem.current.SetSelectedGameObject(null, cardModel.CurrentPointerEventData); - } - - public static void ToggleFacedown(CardModel cardModel) - { - if (cardModel == null || (cardModel.IsOnline && !cardModel.hasAuthority)) - return; - - cardModel.IsFacedown = !cardModel.IsFacedown; - EventSystem.current.SetSelectedGameObject(null, cardModel.CurrentPointerEventData); - } - - [Command] - void CmdUpdateIsFacedown(bool isFacedown) - { - RpcUpdateIsFacedown(isFacedown); - } - - [ClientRpc] - void RpcUpdateIsFacedown(bool isFacedown) - { - if (!hasAuthority) - IsFacedown = isFacedown; - } - - public void ShowHighlight() - { - if (_outline == null) - _outline = GetComponent(); - _outline.effectColor = SelectedHighlightColor; - _outline.effectDistance = OutlineHighlightDistance; - } - - public void WarnHighlight() - { - if (_outline == null) - _outline = GetComponent(); - _outline.effectColor = Color.red; - _outline.effectDistance = OutlineHighlightDistance; - } - - public void HideHighlight() - { - if (_outline == null) - _outline = GetComponent(); - bool isOthers = IsOnline && !hasAuthority; - _outline.effectColor = isOthers ? Color.yellow : Color.black; - _outline.effectDistance = isOthers ? OutlineHighlightDistance : Vector2.zero; - } - - [ClientRpc] - public void RpcHideHighlight() - { - HideHighlight(); - } - - public void ShowNameLabel() - { - transform.GetChild(0).gameObject.SetActive(true); - if (_nameText == null) - _nameText = GetComponentInChildren(); - _nameText.text = Value.Name; - } - - public void HideNameLabel() - { - transform.GetChild(0).gameObject.SetActive(false); - } - - public void Discard() - { - if (DropTarget == null && CardGameManager.Current.GameCatchesDiscard && CGSNetManager.Instance != null) - CGSNetManager.Instance.playController.CatchDiscard(Value); - Destroy(gameObject); - } - - void OnDestroy() - { - if (CardGameManager.IsQuitting) - return; - - CardGameManager.Current.RemoveCardImage(this); - if (PlaceHolder != null) - Destroy(PlaceHolder.gameObject); - } - - public RectTransform PlaceHolder - { - get { return _placeHolder; } - private set - { - if (_placeHolder != null) - Destroy(_placeHolder.gameObject); - _placeHolder = value; - if (_placeHolder == null) - { - if (ParentCardStack == null && DropTarget == null) - WarnHighlight(); - _placeHolderCardStack = null; - } - else - HideHighlight(); - } - } - - public CardStack PlaceHolderCardStack - { - get { return _placeHolderCardStack; } - set - { - _placeHolderCardStack = value; - - if (_placeHolderCardStack == null) - { - PlaceHolder = null; - return; - } - DropTarget = null; - - GameObject placeholder = new GameObject(gameObject.name + "(PlaceHolder)", typeof(RectTransform)); - PlaceHolder = (RectTransform)placeholder.transform; - PlaceHolder.SetParent(_placeHolderCardStack.transform); - PlaceHolder.sizeDelta = ((RectTransform)transform).sizeDelta; - PlaceHolder.anchoredPosition = Vector2.zero; - } - } -} diff --git a/Assets/Scripts/CGS/CardStack.cs b/Assets/Scripts/CGS/CardStack.cs deleted file mode 100644 index 504b68272..000000000 --- a/Assets/Scripts/CGS/CardStack.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.UI; -using UnityEngine.EventSystems; - -public delegate void OnAddCardDelegate(CardStack cardStack,CardModel cardModel); -public delegate void OnRemoveCardDelegate(CardStack cardStack,CardModel cardModel); - -public enum CardStackType -{ - Full, - Vertical, - Horizontal, - Area -} - -public class CardStack : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler -{ - public CardStackType type; - public ScrollRect scrollRectContainer; - - public bool DoesImmediatelyRelease { get; set; } - - public List OnAddCardActions { get; } = new List(); - public List OnRemoveCardActions { get; } = new List(); - - public void OnPointerEnter(PointerEventData eventData) - { - CardModel cardModel = CardModel.GetPointerDrag(eventData); - if (cardModel != null && (type != CardStackType.Area || cardModel.transform.parent != transform)) - cardModel.PlaceHolderCardStack = this; - } - - public void OnPointerExit(PointerEventData eventData) - { - CardModel cardModel = CardModel.GetPointerDrag(eventData); - if (cardModel != null && cardModel.PlaceHolderCardStack == this) - cardModel.PlaceHolderCardStack = null; - } - - public void OnAdd(CardModel cardModel) - { - if (cardModel == null) - return; - - foreach (OnAddCardDelegate cardAddAction in OnAddCardActions) - cardAddAction(this, cardModel); - } - - public void OnRemove(CardModel cardModel) - { - if (cardModel == null) - return; - - foreach (OnRemoveCardDelegate cardRemoveAction in OnRemoveCardActions) - cardRemoveAction(this, cardModel); - } - - public void UpdateLayout(RectTransform child, Vector2 targetPosition) - { - if (child == null) - return; - - switch (type) { - case CardStackType.Full: - break; - case CardStackType.Vertical: - case CardStackType.Horizontal: - int newSiblingIndex = transform.childCount; - for (int i = 0; i < transform.childCount; i++) { - if (type == CardStackType.Vertical ? targetPosition.y < transform.GetChild(i).position.y : targetPosition.x > transform.GetChild(i).position.x) - continue; - newSiblingIndex = i; - if (child.GetSiblingIndex() < newSiblingIndex) - newSiblingIndex--; - break; - } - child.SetSiblingIndex(newSiblingIndex); - break; - case CardStackType.Area: - default: - child.position = targetPosition; - break; - } - } - - public void UpdateScrollRect(DragPhase dragPhase, PointerEventData eventData) - { - if (scrollRectContainer == null) - return; - - switch (dragPhase) { - case DragPhase.Begin: - scrollRectContainer.OnBeginDrag(eventData); - break; - case DragPhase.Drag: - scrollRectContainer.OnDrag(eventData); - break; - case DragPhase.End: - default: - scrollRectContainer.OnEndDrag(eventData); - break; - } - } -} diff --git a/Assets/Scripts/CGS/DeckEditor/CardSelector.cs b/Assets/Scripts/CGS/DeckEditor/CardSelector.cs deleted file mode 100644 index 394657986..000000000 --- a/Assets/Scripts/CGS/DeckEditor/CardSelector.cs +++ /dev/null @@ -1,269 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.EventSystems; - -public class CardSelector : MonoBehaviour -{ - public DeckEditor editor; - public SearchResults results; - - void Update() - { - if (CardGameManager.TopMenuCanvas != null || editor.searchResults.nameInputField.isFocused) - return; - - if (CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf && SwipeManager.DetectSwipe()) - { - if (SwipeManager.IsSwipingDown()) - SelectUp(); - else if (SwipeManager.IsSwipingUp()) - SelectDown(); - else if (SwipeManager.IsSwipingRight()) - SelectLeft(); - else if (SwipeManager.IsSwipingLeft()) - SelectRight(); - } - - if (Input.anyKeyDown) - { - if (Input.GetButtonDown(Inputs.Vertical)) - { - if (Input.GetAxis(Inputs.Vertical) > 0) - SelectUp(); - else - SelectDown(); - } - else if (Input.GetButtonDown(Inputs.Horizontal)) - { - if (Input.GetAxis(Inputs.Horizontal) > 0) - SelectRight(); - else - SelectLeft(); - } - else if (Input.GetButtonDown(Inputs.Column)) - { - if (Input.GetAxis(Inputs.Column) > 0) - ShiftRight(); - else - ShiftLeft(); - } - else if (Input.GetButtonDown(Inputs.Page) && !CardInfoViewer.Instance.IsVisible) - { - if (Input.GetAxis(Inputs.Page) > 0) - PageRight(); - else - PageLeft(); - } - } - } - - public void SelectDown() - { - if (EventSystem.current.alreadySelecting) - return; - - List editorCards = editor.CardModels; - if (editorCards.Count < 1) - { - EventSystem.current.SetSelectedGameObject(null); - return; - } - - for (int i = 0; i < editorCards.Count; i++) - { - if (editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) - continue; - i++; - if (i == editorCards.Count) - i = 0; - EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); - return; - } - EventSystem.current.SetSelectedGameObject(editorCards[0].gameObject); - } - - public void SelectUp() - { - if (EventSystem.current.alreadySelecting) - return; - - List editorCards = editor.CardModels; - if (editorCards.Count < 1) - { - EventSystem.current.SetSelectedGameObject(null); - return; - } - - for (int i = editorCards.Count - 1; i >= 0; i--) - { - if (editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) - continue; - i--; - if (i < 0) - i = editorCards.Count - 1; - EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); - return; - } - EventSystem.current.SetSelectedGameObject(editorCards[editorCards.Count - 1].gameObject); - } - - public void SelectLeft() - { - if (EventSystem.current.alreadySelecting) - return; - - if (results.layoutArea.childCount < 1) - { - EventSystem.current.SetSelectedGameObject(null); - return; - } - - for (int i = results.layoutArea.childCount - 1; i >= 0; i--) - { - if (results.layoutArea.GetChild(i).GetComponent() != CardInfoViewer.Instance.SelectedCardModel) - continue; - i--; - if (i < 0) - { - results.PageLeft(); - i = results.layoutArea.childCount - 1; - } - EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(i).gameObject); - return; - } - EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(0).gameObject); - } - - public void SelectRight() - { - if (EventSystem.current.alreadySelecting) - return; - - if (results.layoutArea.childCount < 1) - { - EventSystem.current.SetSelectedGameObject(null); - return; - } - - for (int i = 0; i < results.layoutArea.childCount; i++) - { - if (results.layoutArea.GetChild(i).GetComponent() != CardInfoViewer.Instance.SelectedCardModel) - continue; - i++; - if (i == results.layoutArea.childCount) - { - results.PageRight(); - i = 0; - } - EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(i).gameObject); - return; - } - EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(0).gameObject); - } - - public void ShiftLeft() - { - if (EventSystem.current.alreadySelecting) - return; - - List editorCards = editor.CardModels; - if (editorCards.Count < 1) - { - EventSystem.current.SetSelectedGameObject(null); - return; - } - - Transform startParent = null; - for (int i = editorCards.Count - 1; i >= 0; i--) - { - if (startParent == null && editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) - continue; - if (editorCards[i] == CardInfoViewer.Instance.SelectedCardModel) - startParent = editorCards[i].transform.parent; - if (startParent != editorCards[i].transform.parent) - { - editor.scrollRect.horizontalNormalizedPosition = editorCards[i].transform.parent.GetSiblingIndex() / (editorCards[i].transform.parent.parent.childCount - 1f); - EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); - return; - } - } - editor.scrollRect.horizontalNormalizedPosition = 1; - EventSystem.current.SetSelectedGameObject(editorCards[editorCards.Count - 1].gameObject); - } - - public void ShiftRight() - { - if (EventSystem.current.alreadySelecting) - return; - - List editorCards = editor.CardModels; - if (editorCards.Count < 1) - { - EventSystem.current.SetSelectedGameObject(null); - return; - } - - Transform startParent = null; - for (int i = 0; i < editorCards.Count; i++) - { - if (startParent == null && editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) - continue; - if (editorCards[i] == CardInfoViewer.Instance.SelectedCardModel) - startParent = editorCards[i].transform.parent; - if (startParent != editorCards[i].transform.parent) - { - editor.scrollRect.horizontalNormalizedPosition = editorCards[i].transform.parent.GetSiblingIndex() / (editorCards[i].transform.parent.parent.childCount - 1f); - EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); - return; - } - } - editor.scrollRect.horizontalNormalizedPosition = 0; - EventSystem.current.SetSelectedGameObject(editorCards[0].gameObject); - } - - public void PageLeft() - { - results.PageLeft(); - } - - public void PageRight() - { - results.PageRight(); - } - - public void GoLeft() - { - RectTransform rt = GetComponent(); - if (rt.rect.width > rt.rect.height) - ShiftLeft(); - else - PageLeft(); - } - - public void GoRight() - { - RectTransform rt = GetComponent(); - if (rt.rect.width > rt.rect.height) - ShiftRight(); - else - PageRight(); - } - - public void MoveLeft() - { - RectTransform rt = GetComponent(); - if (rt.rect.width > rt.rect.height) - PageLeft(); - else - SelectLeft(); - } - - public void MoveRight() - { - RectTransform rt = GetComponent(); - if (rt.rect.width > rt.rect.height) - PageRight(); - else - SelectRight(); - } -} diff --git a/Assets/Scripts/CGS/DeckEditor/DeckEditor.cs b/Assets/Scripts/CGS/DeckEditor/DeckEditor.cs deleted file mode 100644 index 685b5395b..000000000 --- a/Assets/Scripts/CGS/DeckEditor/DeckEditor.cs +++ /dev/null @@ -1,312 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.UI; -using UnityEngine.EventSystems; -using UnityEngine.SceneManagement; -using CardGameDef; - -public delegate string OnDeckNameChangeDelegate(string newName); - -public class DeckEditor : MonoBehaviour, ICardDropHandler -{ - public const string NewDeckPrompt = "Clear the editor and start a new Untitled deck?"; - public const string SaveChangesPrompt = "You have unsaved changes. Would you like to save?"; - public const string ChangeIndicator = "*"; - - public float PreHeight => cardModelPrefab.GetComponent().rect.height; - public int CardsPerStack => Mathf.FloorToInt(8 * (CardGameManager.PixelsPerInch * CardGameManager.Current.CardSize.y / PreHeight)); - public int CardStackCount => Mathf.CeilToInt((float)CardGameManager.Current.DeckMaxCount / CardsPerStack); - public List CardStacks => _cardStacks ?? (_cardStacks = new List()); - public int CurrentCardStackIndex - { - get - { - if (_currentCardStackIndex < 0 || _currentCardStackIndex >= CardStacks.Count) - _currentCardStackIndex = 0; - return _currentCardStackIndex; - } - set { _currentCardStackIndex = value; } - } - public DeckLoadMenu DeckLoader => _deckLoader ?? (_deckLoader = Instantiate(deckLoadMenuPrefab).GetOrAddComponent()); - public DeckSaveMenu DeckSaver => _deckSaver ?? (_deckSaver = Instantiate(deckSaveMenuPrefab).GetOrAddComponent()); - - public List CardModels - { - get - { - List cardModels = new List(); - foreach (CardStack stack in CardStacks) - foreach (CardModel cardModel in stack.GetComponentsInChildren()) - cardModels.Add(cardModel); - return cardModels; - } - } - public Deck CurrentDeck - { - get - { - Deck deck = new Deck(SavedDeck != null ? SavedDeck.Name : Deck.DefaultName, CardGameManager.Current.DeckFileType); - foreach (CardStack stack in CardStacks) - foreach (CardModel card in stack.GetComponentsInChildren()) - deck.Cards.Add(card.Value); - return deck; - } - } - public Deck SavedDeck { get; private set; } - public bool HasChanged - { - get - { - Deck currentDeck = CurrentDeck; - if (currentDeck.Cards.Count < 1) - return false; - return !currentDeck.Equals(SavedDeck); - } - } - - public GameObject cardViewerPrefab; - public GameObject cardModelPrefab; - public GameObject cardStackPrefab; - public GameObject deckLoadMenuPrefab; - public GameObject deckSaveMenuPrefab; - public RectTransform layoutContent; - public CardDropZone dropZone; - public ScrollRect scrollRect; - public Text nameText; - public Text countText; - public SearchResults searchResults; - - private List _cardStacks; - private int _currentCardStackIndex; - private DeckLoadMenu _deckLoader; - private DeckSaveMenu _deckSaver; - - void OnEnable() - { - Instantiate(cardViewerPrefab); - CardGameManager.Instance.OnSceneActions.Add(ResetCardStacks); - } - - void Start() - { - dropZone.dropHandler = this; - } - - void Update() - { - if (!CardGameManager.Current.CardNameIsAtTop) - LabelCardsInStacks(); - - if (CardInfoViewer.Instance.IsVisible || !Input.anyKeyDown || CardGameManager.TopMenuCanvas != null || searchResults.nameInputField.isFocused) - return; - - if (Input.GetButtonDown(Inputs.Sort)) - Sort(); - else if (Input.GetButtonDown(Inputs.New)) - PromptForClear(); - else if (Input.GetButtonDown(Inputs.Load)) - ShowDeckLoadMenu(); - else if (Input.GetButtonDown(Inputs.Save)) - ShowDeckSaveMenu(); - else if (Input.GetButtonDown(Inputs.FocusName)) - searchResults.nameInputField.ActivateInputField(); - else if (Input.GetButtonDown(Inputs.Filter)) - searchResults.ShowSearchMenu(); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - CheckBackToMainMenu(); - } - - public void LabelCardsInStacks() - { - foreach (CardStack cardStack in CardStacks) - foreach (CardModel cardModel in cardStack.GetComponentsInChildren()) - cardModel.ShowNameLabel(); - } - - public void ResetCardStacks() - { - Clear(); - layoutContent.DestroyAllChildren(); - CardStacks.Clear(); - for (int i = 0; i < CardStackCount; i++) - { - CardStack newCardStack = Instantiate(cardStackPrefab, layoutContent).GetOrAddComponent(); - newCardStack.type = CardStackType.Vertical; - newCardStack.scrollRectContainer = scrollRect; - newCardStack.DoesImmediatelyRelease = true; - newCardStack.OnAddCardActions.Add(OnAddCardModel); - newCardStack.OnRemoveCardActions.Add(OnRemoveCardModel); - CardStacks.Add(newCardStack); - newCardStack.GetComponent().spacing = cardStackPrefab.GetComponent().spacing - * (CardGameManager.PixelsPerInch * CardGameManager.Current.CardSize.y / PreHeight); - } - layoutContent.sizeDelta = new Vector2(cardStackPrefab.GetComponent().rect.width * CardStacks.Count, - layoutContent.sizeDelta.y); - } - - public void OnDrop(CardModel cardModel) - { - AddCardModel(cardModel); - } - - public void AddCardModel(CardModel cardModel) - { - if (cardModel == null || CardStacks.Count < 1) - return; - - EventSystem.current.SetSelectedGameObject(null, cardModel.CurrentPointerEventData); - - AddCard(cardModel.Value); - } - - public void AddCard(Card card) - { - if (card == null || CardStacks.Count < 1) - return; - - int maxCopiesInStack = CardsPerStack; - CardModel newCardModel = null; - while (newCardModel == null) - { - if (CardStacks[CurrentCardStackIndex].transform.childCount < maxCopiesInStack) - { - newCardModel = Instantiate(cardModelPrefab, CardStacks[CurrentCardStackIndex].transform).GetOrAddComponent(); - newCardModel.Value = card; - } - else - { - CurrentCardStackIndex++; - if (CurrentCardStackIndex == 0) - maxCopiesInStack++; - } - } - scrollRect.horizontalNormalizedPosition = CardStacks.Count > 1 ? - CurrentCardStackIndex / (CardStacks.Count - 1f) : 0f; - - OnAddCardModel(CardStacks[CurrentCardStackIndex], newCardModel); - } - - public void OnAddCardModel(CardStack cardStack, CardModel cardModel) - { - if (cardStack == null || cardModel == null) - return; - - CurrentCardStackIndex = CardStacks.IndexOf(cardStack); - cardModel.SecondaryDragAction = cardModel.UpdateParentCardStackScrollRect; - cardModel.DoubleClickAction = DestroyCardModel; - - UpdateDeckStats(); - } - - public void OnRemoveCardModel(CardStack cardStack, CardModel cardModel) - { - if (cardModel.HasImage) - cardModel.HideNameLabel(); - UpdateDeckStats(); - } - - public void DestroyCardModel(CardModel cardModel) - { - if (cardModel == null) - return; - - cardModel.transform.SetParent(null); - Destroy(cardModel.gameObject); - CardInfoViewer.Instance.IsVisible = false; - - UpdateDeckStats(); - } - - public void Sort() - { - Deck sortedDeck = CurrentDeck; - sortedDeck.Sort(); - foreach (CardStack stack in CardStacks) - stack.transform.DestroyAllChildren(); - CurrentCardStackIndex = 0; - foreach (Card card in sortedDeck.Cards) - AddCard(card); - } - - public void PromptForClear() - { - CardGameManager.Instance.Messenger.Prompt(NewDeckPrompt, Clear); - } - - public void Clear() - { - foreach (CardStack stack in CardStacks) - stack.transform.DestroyAllChildren(); - CurrentCardStackIndex = 0; - scrollRect.horizontalNormalizedPosition = 0; - - CardInfoViewer.Instance.IsVisible = false; - SavedDeck = null; - UpdateDeckStats(); - } - - public string UpdateDeckName(string newName) - { - if (newName == null) - newName = string.Empty; - newName = UnityExtensionMethods.GetSafeFileName(newName); - nameText.text = newName + (HasChanged ? ChangeIndicator : string.Empty); - return newName; - } - - public void UpdateDeckStats() - { - string deckName = Deck.DefaultName; - if (SavedDeck != null) - deckName = SavedDeck.Name; - nameText.text = deckName + (HasChanged ? ChangeIndicator : string.Empty); - countText.text = CurrentDeck.Cards.Count.ToString(); - } - - public void ShowDeckLoadMenu() - { - Deck currentDeck = CurrentDeck; - DeckLoader.Show(LoadDeck, currentDeck.Name, currentDeck.Cards.Count > 0 ? currentDeck.ToString() : null); - } - - public void LoadDeck(Deck newDeck) - { - if (newDeck == null) - return; - - Clear(); - foreach (Card card in newDeck.Cards) - AddCard(card); - SavedDeck = newDeck; - UpdateDeckStats(); - } - - public void ShowDeckSaveMenu() - { - Deck deckToSave = CurrentDeck; - bool overwrite = SavedDeck != null && deckToSave.Name.Equals(SavedDeck.Name); - DeckSaver.Show(deckToSave, UpdateDeckName, OnSaveDeck, overwrite); - } - - public void OnSaveDeck(Deck savedDeck) - { - SavedDeck = savedDeck; - UpdateDeckStats(); - } - - public void CheckBackToMainMenu() - { - if (HasChanged) - { - CardGameManager.Instance.Messenger.Ask(SaveChangesPrompt, BackToMainMenu, ShowDeckSaveMenu); - return; - } - - BackToMainMenu(); - } - - public void BackToMainMenu() - { - SceneManager.LoadScene(MainMenu.MainMenuSceneIndex); - } -} diff --git a/Assets/Scripts/CGS/DeckEditor/DeckEditorLayout.cs b/Assets/Scripts/CGS/DeckEditor/DeckEditorLayout.cs deleted file mode 100644 index 700c0e1e9..000000000 Binary files a/Assets/Scripts/CGS/DeckEditor/DeckEditorLayout.cs and /dev/null differ diff --git a/Assets/Scripts/CGS/DeckEditor/SearchResults.cs b/Assets/Scripts/CGS/DeckEditor/SearchResults.cs deleted file mode 100644 index d398539fa..000000000 --- a/Assets/Scripts/CGS/DeckEditor/SearchResults.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System.Collections.Generic; -using CardGameDef; -using UnityEngine; -using UnityEngine.UI; - -public class SearchResults : MonoBehaviour -{ - public const string EmptyFilterText = "*"; - - public GameObject cardSearchMenuPrefab; - public DeckEditor deckEditor; - public RectTransform layoutArea; - public InputField nameInputField; - public Text filtersText; - public Text countText; - - public int CardsPerPage => Mathf.FloorToInt(layoutArea.rect.width / (CardGameManager.PixelsPerInch * CardGameManager.Current.CardSize.x + layoutArea.gameObject.GetOrAddComponent().spacing)); - public int TotalPageCount => CardsPerPage == 0 ? 0 : (AllResults.Count / CardsPerPage) + ((AllResults.Count % CardsPerPage) == 0 ? -1 : 0); - - public CardSearchMenu CardSearcher => _cardSearcher ?? - (_cardSearcher = Instantiate(cardSearchMenuPrefab).GetOrAddComponent()); - - public int CurrentPageIndex { get; set; } - - private CardSearchMenu _cardSearcher; - private List _allResults; - - void OnEnable() - { - CardSearcher.SearchCallback = ShowResults; - CardGameManager.Instance.OnSceneActions.Add(CardSearcher.ClearSearch); - } - - public string SetNameInputField(string nameFilter) - { - nameInputField.text = nameFilter; - return nameInputField.text; - } - - public void SetNameFilter(string nameFilter) - { - CardSearcher.NameFilter = nameFilter; - } - - public void Search() - { - CardSearcher.Search(); - } - - public void PageLeft() - { - if (!CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf) - CardInfoViewer.Instance.SelectedCardModel = null; - CurrentPageIndex--; - if (CurrentPageIndex < 0) - CurrentPageIndex = TotalPageCount; - UpdateSearchResultsPanel(); - } - - public void PageRight() - { - if (!CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf) - CardInfoViewer.Instance.SelectedCardModel = null; - CurrentPageIndex++; - if (CurrentPageIndex > TotalPageCount) - CurrentPageIndex = 0; - UpdateSearchResultsPanel(); - } - - public void UpdateSearchResultsPanel() - { - layoutArea.DestroyAllChildren(); - - for (int i = 0; i < CardsPerPage && CurrentPageIndex >= 0 && CurrentPageIndex * CardsPerPage + i < AllResults.Count; i++) - { - string cardId = AllResults[CurrentPageIndex * CardsPerPage + i].Id; - if (!CardGameManager.Current.Cards.ContainsKey(cardId)) - continue; - Card cardToShow = CardGameManager.Current.Cards[cardId]; - CardModel cardModelToShow = Instantiate(deckEditor.cardModelPrefab, layoutArea).GetOrAddComponent(); - cardModelToShow.Value = cardToShow; - cardModelToShow.DoesCloneOnDrag = true; - if (((RectTransform)deckEditor.transform).rect.width > ((RectTransform)deckEditor.transform).rect.height) - cardModelToShow.DoubleClickAction = deckEditor.AddCardModel; - else - cardModelToShow.DoubleClickAction = CardInfoViewer.Instance.ShowCardZoomed; - } - - countText.text = (CurrentPageIndex + 1) + "/" + (TotalPageCount + 1); - } - - public void ShowSearchMenu() - { - CardSearcher.Show(SetNameInputField, ShowResults); - } - - public void ShowResults(string filters, List results) - { - if (string.IsNullOrEmpty(filters)) - filters = EmptyFilterText; - filtersText.text = filters; - - AllResults = results; - } - - public List AllResults - { - get { return _allResults ?? (_allResults = new List()); } - set - { - _allResults = value; - CurrentPageIndex = 0; - UpdateSearchResultsPanel(); - } - } -} diff --git a/Assets/Scripts/CGS/DeckEditor.meta b/Assets/Scripts/CGS/EditDeck.meta similarity index 100% rename from Assets/Scripts/CGS/DeckEditor.meta rename to Assets/Scripts/CGS/EditDeck.meta diff --git a/Assets/Scripts/CGS/EditDeck/CardSelector.cs b/Assets/Scripts/CGS/EditDeck/CardSelector.cs new file mode 100644 index 000000000..d93c57524 --- /dev/null +++ b/Assets/Scripts/CGS/EditDeck/CardSelector.cs @@ -0,0 +1,273 @@ +using System.Collections.Generic; +using CardGameView; +using UnityEngine; +using UnityEngine.EventSystems; + +namespace CGS.EditDeck +{ + public class CardSelector : MonoBehaviour + { + public DeckEditor editor; + public SearchResults results; + + void Update() + { + if (CardGameManager.TopMenuCanvas != null || editor.searchResults.nameInputField.isFocused) + return; + + if (CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf && SwipeManager.DetectSwipe()) + { + if (SwipeManager.IsSwipingDown()) + SelectUp(); + else if (SwipeManager.IsSwipingUp()) + SelectDown(); + else if (SwipeManager.IsSwipingRight()) + SelectLeft(); + else if (SwipeManager.IsSwipingLeft()) + SelectRight(); + } + + if (Input.anyKeyDown) + { + if (Input.GetButtonDown(Inputs.Vertical)) + { + if (Input.GetAxis(Inputs.Vertical) > 0) + SelectUp(); + else + SelectDown(); + } + else if (Input.GetButtonDown(Inputs.Horizontal)) + { + if (Input.GetAxis(Inputs.Horizontal) > 0) + SelectRight(); + else + SelectLeft(); + } + else if (Input.GetButtonDown(Inputs.Column)) + { + if (Input.GetAxis(Inputs.Column) > 0) + ShiftRight(); + else + ShiftLeft(); + } + else if (Input.GetButtonDown(Inputs.Page) && !CardInfoViewer.Instance.IsVisible) + { + if (Input.GetAxis(Inputs.Page) > 0) + PageRight(); + else + PageLeft(); + } + } + } + + public void SelectDown() + { + if (EventSystem.current.alreadySelecting) + return; + + List editorCards = editor.CardModels; + if (editorCards.Count < 1) + { + EventSystem.current.SetSelectedGameObject(null); + return; + } + + for (int i = 0; i < editorCards.Count; i++) + { + if (editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) + continue; + i++; + if (i == editorCards.Count) + i = 0; + EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); + return; + } + EventSystem.current.SetSelectedGameObject(editorCards[0].gameObject); + } + + public void SelectUp() + { + if (EventSystem.current.alreadySelecting) + return; + + List editorCards = editor.CardModels; + if (editorCards.Count < 1) + { + EventSystem.current.SetSelectedGameObject(null); + return; + } + + for (int i = editorCards.Count - 1; i >= 0; i--) + { + if (editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) + continue; + i--; + if (i < 0) + i = editorCards.Count - 1; + EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); + return; + } + EventSystem.current.SetSelectedGameObject(editorCards[editorCards.Count - 1].gameObject); + } + + public void SelectLeft() + { + if (EventSystem.current.alreadySelecting) + return; + + if (results.layoutArea.childCount < 1) + { + EventSystem.current.SetSelectedGameObject(null); + return; + } + + for (int i = results.layoutArea.childCount - 1; i >= 0; i--) + { + if (results.layoutArea.GetChild(i).GetComponent() != CardInfoViewer.Instance.SelectedCardModel) + continue; + i--; + if (i < 0) + { + results.PageLeft(); + i = results.layoutArea.childCount - 1; + } + EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(i).gameObject); + return; + } + EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(0).gameObject); + } + + public void SelectRight() + { + if (EventSystem.current.alreadySelecting) + return; + + if (results.layoutArea.childCount < 1) + { + EventSystem.current.SetSelectedGameObject(null); + return; + } + + for (int i = 0; i < results.layoutArea.childCount; i++) + { + if (results.layoutArea.GetChild(i).GetComponent() != CardInfoViewer.Instance.SelectedCardModel) + continue; + i++; + if (i == results.layoutArea.childCount) + { + results.PageRight(); + i = 0; + } + EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(i).gameObject); + return; + } + EventSystem.current.SetSelectedGameObject(results.layoutArea.GetChild(0).gameObject); + } + + public void ShiftLeft() + { + if (EventSystem.current.alreadySelecting) + return; + + List editorCards = editor.CardModels; + if (editorCards.Count < 1) + { + EventSystem.current.SetSelectedGameObject(null); + return; + } + + Transform startParent = null; + for (int i = editorCards.Count - 1; i >= 0; i--) + { + if (startParent == null && editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) + continue; + if (editorCards[i] == CardInfoViewer.Instance.SelectedCardModel) + startParent = editorCards[i].transform.parent; + if (startParent != editorCards[i].transform.parent) + { + editor.scrollRect.horizontalNormalizedPosition = editorCards[i].transform.parent.GetSiblingIndex() / (editorCards[i].transform.parent.parent.childCount - 1f); + EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); + return; + } + } + editor.scrollRect.horizontalNormalizedPosition = 1; + EventSystem.current.SetSelectedGameObject(editorCards[editorCards.Count - 1].gameObject); + } + + public void ShiftRight() + { + if (EventSystem.current.alreadySelecting) + return; + + List editorCards = editor.CardModels; + if (editorCards.Count < 1) + { + EventSystem.current.SetSelectedGameObject(null); + return; + } + + Transform startParent = null; + for (int i = 0; i < editorCards.Count; i++) + { + if (startParent == null && editorCards[i] != CardInfoViewer.Instance.SelectedCardModel) + continue; + if (editorCards[i] == CardInfoViewer.Instance.SelectedCardModel) + startParent = editorCards[i].transform.parent; + if (startParent != editorCards[i].transform.parent) + { + editor.scrollRect.horizontalNormalizedPosition = editorCards[i].transform.parent.GetSiblingIndex() / (editorCards[i].transform.parent.parent.childCount - 1f); + EventSystem.current.SetSelectedGameObject(editorCards[i].gameObject); + return; + } + } + editor.scrollRect.horizontalNormalizedPosition = 0; + EventSystem.current.SetSelectedGameObject(editorCards[0].gameObject); + } + + public void PageLeft() + { + results.PageLeft(); + } + + public void PageRight() + { + results.PageRight(); + } + + public void GoLeft() + { + RectTransform rt = GetComponent(); + if (rt.rect.width > rt.rect.height) + ShiftLeft(); + else + PageLeft(); + } + + public void GoRight() + { + RectTransform rt = GetComponent(); + if (rt.rect.width > rt.rect.height) + ShiftRight(); + else + PageRight(); + } + + public void MoveLeft() + { + RectTransform rt = GetComponent(); + if (rt.rect.width > rt.rect.height) + PageLeft(); + else + SelectLeft(); + } + + public void MoveRight() + { + RectTransform rt = GetComponent(); + if (rt.rect.width > rt.rect.height) + PageRight(); + else + SelectRight(); + } + } +} diff --git a/Assets/Scripts/CGS/DeckEditor/CardSelector.cs.meta b/Assets/Scripts/CGS/EditDeck/CardSelector.cs.meta similarity index 100% rename from Assets/Scripts/CGS/DeckEditor/CardSelector.cs.meta rename to Assets/Scripts/CGS/EditDeck/CardSelector.cs.meta diff --git a/Assets/Scripts/CGS/EditDeck/DeckEditor.cs b/Assets/Scripts/CGS/EditDeck/DeckEditor.cs new file mode 100644 index 000000000..c0b0ab55c --- /dev/null +++ b/Assets/Scripts/CGS/EditDeck/DeckEditor.cs @@ -0,0 +1,304 @@ +using System.Collections.Generic; +using CardGameDef; +using CardGameView; +using CGS.Menus; +using CGS.Play.Zones; +using UnityEngine; +using UnityEngine.UI; +using UnityEngine.EventSystems; +using UnityEngine.SceneManagement; + +namespace CGS.EditDeck +{ + public class DeckEditor : MonoBehaviour, ICardDropHandler + { + public const string NewDeckPrompt = "Clear the editor and start a new Untitled deck?"; + public const string SaveChangesPrompt = "You have unsaved changes. Would you like to save?"; + public const string ChangeIndicator = "*"; + + public float PreHeight => cardModelPrefab.GetComponent().rect.height; + public int CardsPerStack => Mathf.FloorToInt(8 * (CardGameManager.PixelsPerInch * CardGameManager.Current.CardSize.y / PreHeight)); + public int CardStackCount => Mathf.CeilToInt((float)CardGameManager.Current.DeckMaxCount / CardsPerStack); + public List CardStacks => _cardStacks ?? (_cardStacks = new List()); + public int CurrentCardStackIndex + { + get + { + if (_currentCardStackIndex < 0 || _currentCardStackIndex >= CardStacks.Count) + _currentCardStackIndex = 0; + return _currentCardStackIndex; + } + set { _currentCardStackIndex = value; } + } + public DeckLoadMenu DeckLoader => _deckLoader ?? (_deckLoader = Instantiate(deckLoadMenuPrefab).GetOrAddComponent()); + public DeckSaveMenu DeckSaver => _deckSaver ?? (_deckSaver = Instantiate(deckSaveMenuPrefab).GetOrAddComponent()); + + public List CardModels + { + get + { + List cardModels = new List(); + foreach (CardStack stack in CardStacks) + foreach (CardModel cardModel in stack.GetComponentsInChildren()) + cardModels.Add(cardModel); + return cardModels; + } + } + public Deck CurrentDeck + { + get + { + Deck deck = new Deck(CardGameManager.Current, SavedDeck?.Name ?? Deck.DefaultName, CardGameManager.Current.DeckFileType); + foreach (CardStack stack in CardStacks) + foreach (CardModel card in stack.GetComponentsInChildren()) + deck.Cards.Add(card.Value); + return deck; + } + } + public Deck SavedDeck { get; private set; } + public bool HasChanged + { + get + { + Deck currentDeck = CurrentDeck; + if (currentDeck.Cards.Count < 1) + return false; + return !currentDeck.Equals(SavedDeck); + } + } + + public GameObject cardViewerPrefab; + public GameObject cardModelPrefab; + public GameObject cardStackPrefab; + public GameObject deckLoadMenuPrefab; + public GameObject deckSaveMenuPrefab; + public RectTransform layoutContent; + public CardDropZone dropZone; + public ScrollRect scrollRect; + public Text nameText; + public Text countText; + public SearchResults searchResults; + + private List _cardStacks; + private int _currentCardStackIndex; + private DeckLoadMenu _deckLoader; + private DeckSaveMenu _deckSaver; + + void OnEnable() + { + Instantiate(cardViewerPrefab); + CardGameManager.Instance.OnSceneActions.Add(ResetCardStacks); + } + + void Start() + { + dropZone.dropHandler = this; + } + + void Update() + { + if (CardInfoViewer.Instance.IsVisible || CardGameManager.TopMenuCanvas != null || searchResults.nameInputField.isFocused) + return; + + if (Input.GetButtonDown(Inputs.Sort)) + Sort(); + else if (Input.GetButtonDown(Inputs.New)) + PromptForClear(); + else if (Input.GetButtonDown(Inputs.Load)) + ShowDeckLoadMenu(); + else if (Input.GetButtonDown(Inputs.Save)) + ShowDeckSaveMenu(); + else if (Input.GetButtonDown(Inputs.FocusName)) + searchResults.nameInputField.ActivateInputField(); + else if (Input.GetButtonDown(Inputs.Filter)) + searchResults.ShowSearchMenu(); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + CheckBackToMainMenu(); + } + + public void ResetCardStacks() + { + Clear(); + layoutContent.DestroyAllChildren(); + CardStacks.Clear(); + for (int i = 0; i < CardStackCount; i++) + { + CardStack newCardStack = Instantiate(cardStackPrefab, layoutContent).GetOrAddComponent(); + newCardStack.type = CardStackType.Vertical; + newCardStack.scrollRectContainer = scrollRect; + newCardStack.DoesImmediatelyRelease = true; + newCardStack.OnAddCardActions.Add(OnAddCardModel); + newCardStack.OnRemoveCardActions.Add(OnRemoveCardModel); + CardStacks.Add(newCardStack); + newCardStack.GetComponent().spacing = cardStackPrefab.GetComponent().spacing + * (CardGameManager.PixelsPerInch * CardGameManager.Current.CardSize.y / PreHeight); + } + layoutContent.sizeDelta = new Vector2(cardStackPrefab.GetComponent().rect.width * CardStacks.Count, + layoutContent.sizeDelta.y); + } + + public void OnDrop(CardModel cardModel) + { + AddCardModel(cardModel); + } + + public void AddCardModel(CardModel cardModel) + { + if (cardModel == null || CardStacks.Count < 1) + return; + + EventSystem.current.SetSelectedGameObject(null, cardModel.CurrentPointerEventData); + + AddCard(cardModel.Value); + } + + public void AddCard(Card card) + { + if (card == null || CardStacks.Count < 1) + return; + + int maxCopiesInStack = CardsPerStack; + CardModel newCardModel = null; + while (newCardModel == null) + { + if (CardStacks[CurrentCardStackIndex].transform.childCount < maxCopiesInStack) + { + newCardModel = Instantiate(cardModelPrefab, CardStacks[CurrentCardStackIndex].transform).GetOrAddComponent(); + newCardModel.Value = card; + } + else + { + CurrentCardStackIndex++; + if (CurrentCardStackIndex == 0) + maxCopiesInStack++; + } + } + scrollRect.horizontalNormalizedPosition = CardStacks.Count > 1 ? + CurrentCardStackIndex / (CardStacks.Count - 1f) : 0f; + + OnAddCardModel(CardStacks[CurrentCardStackIndex], newCardModel); + } + + public void OnAddCardModel(CardStack cardStack, CardModel cardModel) + { + if (cardStack == null || cardModel == null) + return; + + CurrentCardStackIndex = CardStacks.IndexOf(cardStack); + cardModel.SecondaryDragAction = cardModel.UpdateParentCardStackScrollRect; + cardModel.DoubleClickAction = DestroyCardModel; + + UpdateDeckStats(); + } + + public void OnRemoveCardModel(CardStack cardStack, CardModel cardModel) + { + UpdateDeckStats(); + } + + public void DestroyCardModel(CardModel cardModel) + { + if (cardModel == null) + return; + + cardModel.transform.SetParent(null); + Destroy(cardModel.gameObject); + CardInfoViewer.Instance.IsVisible = false; + + UpdateDeckStats(); + } + + public void Sort() + { + Deck sortedDeck = CurrentDeck; + sortedDeck.Sort(); + foreach (CardStack stack in CardStacks) + stack.transform.DestroyAllChildren(); + CurrentCardStackIndex = 0; + foreach (Card card in sortedDeck.Cards) + AddCard(card); + } + + public void PromptForClear() + { + CardGameManager.Instance.Messenger.Prompt(NewDeckPrompt, Clear); + } + + public void Clear() + { + foreach (CardStack stack in CardStacks) + stack.transform.DestroyAllChildren(); + CurrentCardStackIndex = 0; + scrollRect.horizontalNormalizedPosition = 0; + + CardInfoViewer.Instance.IsVisible = false; + SavedDeck = null; + UpdateDeckStats(); + } + + public string UpdateDeckName(string newName) + { + if (newName == null) + newName = string.Empty; + newName = UnityExtensionMethods.GetSafeFileName(newName); + nameText.text = newName + (HasChanged ? ChangeIndicator : string.Empty); + return newName; + } + + public void UpdateDeckStats() + { + string deckName = Deck.DefaultName; + if (SavedDeck != null) + deckName = SavedDeck.Name; + nameText.text = deckName + (HasChanged ? ChangeIndicator : string.Empty); + countText.text = CurrentDeck.Cards.Count.ToString(); + } + + public void ShowDeckLoadMenu() + { + Deck currentDeck = CurrentDeck; + DeckLoader.Show(LoadDeck, currentDeck.Name, currentDeck.Cards.Count > 0 ? currentDeck.ToString() : null); + } + + public void LoadDeck(Deck newDeck) + { + if (newDeck == null) + return; + + Clear(); + foreach (Card card in newDeck.Cards) + AddCard(card); + SavedDeck = newDeck; + UpdateDeckStats(); + } + + public void ShowDeckSaveMenu() + { + Deck deckToSave = CurrentDeck; + bool overwrite = SavedDeck != null && deckToSave.Name.Equals(SavedDeck.Name); + DeckSaver.Show(deckToSave, UpdateDeckName, OnSaveDeck, overwrite); + } + + public void OnSaveDeck(Deck savedDeck) + { + SavedDeck = savedDeck; + UpdateDeckStats(); + } + + public void CheckBackToMainMenu() + { + if (HasChanged) + { + CardGameManager.Instance.Messenger.Ask(SaveChangesPrompt, BackToMainMenu, ShowDeckSaveMenu); + return; + } + + BackToMainMenu(); + } + + public void BackToMainMenu() + { + SceneManager.LoadScene(MainMenu.MainMenuSceneIndex); + } + } +} diff --git a/Assets/Scripts/CGS/DeckEditor/DeckEditor.cs.meta b/Assets/Scripts/CGS/EditDeck/DeckEditor.cs.meta similarity index 100% rename from Assets/Scripts/CGS/DeckEditor/DeckEditor.cs.meta rename to Assets/Scripts/CGS/EditDeck/DeckEditor.cs.meta diff --git a/Assets/Scripts/CGS/EditDeck/DeckEditorLayout.cs b/Assets/Scripts/CGS/EditDeck/DeckEditorLayout.cs new file mode 100644 index 000000000..819399445 Binary files /dev/null and b/Assets/Scripts/CGS/EditDeck/DeckEditorLayout.cs differ diff --git a/Assets/Scripts/CGS/DeckEditor/DeckEditorLayout.cs.meta b/Assets/Scripts/CGS/EditDeck/DeckEditorLayout.cs.meta similarity index 100% rename from Assets/Scripts/CGS/DeckEditor/DeckEditorLayout.cs.meta rename to Assets/Scripts/CGS/EditDeck/DeckEditorLayout.cs.meta diff --git a/Assets/Scripts/CGS/EditDeck/SearchResults.cs b/Assets/Scripts/CGS/EditDeck/SearchResults.cs new file mode 100644 index 000000000..6c4c05076 --- /dev/null +++ b/Assets/Scripts/CGS/EditDeck/SearchResults.cs @@ -0,0 +1,127 @@ +using System.Collections.Generic; +using CardGameDef; +using CardGameView; +using CGS.Menus; +using UnityEngine; +using UnityEngine.UI; + +namespace CGS.EditDeck +{ + public class SearchResults : MonoBehaviour + { + public const string EmptyFilterText = "*"; + + public GameObject cardSearchMenuPrefab; + public DeckEditor deckEditor; + public RectTransform layoutArea; + public InputField nameInputField; + public Text filtersText; + public Text countText; + + public int CardsPerPage => Mathf.FloorToInt(layoutArea.rect.width / + (CardGameManager.PixelsPerInch * CardGameManager.Current.CardSize.x + layoutArea.gameObject.GetOrAddComponent().spacing)); + public int TotalPageCount => CardsPerPage == 0 ? 0 : (AllResults.Count / CardsPerPage) + ((AllResults.Count % CardsPerPage) == 0 ? -1 : 0); + + public CardSearchMenu CardSearcher => _cardSearcher ?? + (_cardSearcher = Instantiate(cardSearchMenuPrefab).GetOrAddComponent()); + + public int CurrentPageIndex { get; set; } + + private CardSearchMenu _cardSearcher; + private List _allResults; + + void OnEnable() + { + CardSearcher.SearchCallback = ShowResults; + CardGameManager.Instance.OnSceneActions.Add(CardSearcher.ClearSearch); + } + + public string SetNameInputField(string nameFilter) + { + nameInputField.text = nameFilter; + return nameInputField.text; + } + + public void SetNameFilter(string nameFilter) + { + CardSearcher.SetNameFilter(nameFilter); + } + + public void ClearSearchName() + { + CardSearcher.ClearSearchName(); + } + + public void Search() + { + CardSearcher.Search(); + } + + public void PageLeft() + { + if (!CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf) + CardInfoViewer.Instance.SelectedCardModel = null; + CurrentPageIndex--; + if (CurrentPageIndex < 0) + CurrentPageIndex = TotalPageCount; + UpdateSearchResultsPanel(); + } + + public void PageRight() + { + if (!CardInfoViewer.Instance.zoomPanel.gameObject.activeSelf) + CardInfoViewer.Instance.SelectedCardModel = null; + CurrentPageIndex++; + if (CurrentPageIndex > TotalPageCount) + CurrentPageIndex = 0; + UpdateSearchResultsPanel(); + } + + public void UpdateSearchResultsPanel() + { + layoutArea.DestroyAllChildren(); + + for (int i = 0; i < CardsPerPage && CurrentPageIndex >= 0 && CurrentPageIndex * CardsPerPage + i < AllResults.Count; i++) + { + string cardId = AllResults[CurrentPageIndex * CardsPerPage + i].Id; + if (!CardGameManager.Current.Cards.ContainsKey(cardId)) + continue; + Card cardToShow = CardGameManager.Current.Cards[cardId]; + CardModel cardModelToShow = Instantiate(deckEditor.cardModelPrefab, layoutArea).GetOrAddComponent(); + cardModelToShow.Value = cardToShow; + cardModelToShow.DoesCloneOnDrag = true; + if (((RectTransform)deckEditor.transform).rect.width > ((RectTransform)deckEditor.transform).rect.height) + cardModelToShow.DoubleClickAction = deckEditor.AddCardModel; + else + cardModelToShow.DoubleClickAction = CardInfoViewer.Instance.ShowCardZoomed; + } + + countText.text = (CurrentPageIndex + 1) + "/" + (TotalPageCount + 1); + } + + public void ShowSearchMenu() + { + CardSearcher.Show(SetNameInputField, ShowResults); + } + + public void ShowResults(string filters, List results) + { + if (string.IsNullOrEmpty(filters)) + filters = EmptyFilterText; + filtersText.text = filters; + + AllResults = results; + } + + public List AllResults + { + get { return _allResults ?? (_allResults = new List()); } + set + { + _allResults = value; + CurrentPageIndex = 0; + UpdateSearchResultsPanel(); + } + } + } +} diff --git a/Assets/Scripts/CGS/DeckEditor/SearchResults.cs.meta b/Assets/Scripts/CGS/EditDeck/SearchResults.cs.meta similarity index 100% rename from Assets/Scripts/CGS/DeckEditor/SearchResults.cs.meta rename to Assets/Scripts/CGS/EditDeck/SearchResults.cs.meta diff --git a/Assets/Scripts/CGS/Inputs.cs b/Assets/Scripts/CGS/Inputs.cs index fb1f9c588..13b370fdf 100644 --- a/Assets/Scripts/CGS/Inputs.cs +++ b/Assets/Scripts/CGS/Inputs.cs @@ -1,27 +1,30 @@ using UnityEngine; -public static class Inputs +namespace CGS { - public const KeyCode BluetoothReturn = (KeyCode)10; - public const string Cancel = "Cancel"; - public const string Column = "Column"; - public const string Delete = "Delete"; - public const string Filter = "Filter"; - public const string FocusName = "FocusName"; - public const string FocusText = "FocusText"; - public const string Horizontal = "Horizontal"; - public const string Load = "Load"; - public const string New = "New"; - public const string Page = "Page"; - public const string Save = "Save"; - public const string Sort = "Sort"; - public const string Submit = "Submit"; - public const string Vertical = "Vertical"; - - public static char FilterFocusNameInput(char charToValidate) + public static class Inputs { - if (charToValidate == '`') - charToValidate = '\0'; - return charToValidate; + public const KeyCode BluetoothReturn = (KeyCode)10; + public const string Cancel = "Cancel"; + public const string Column = "Column"; + public const string Delete = "Delete"; + public const string Filter = "Filter"; + public const string FocusName = "FocusName"; + public const string FocusText = "FocusText"; + public const string Horizontal = "Horizontal"; + public const string Load = "Load"; + public const string New = "New"; + public const string Page = "Page"; + public const string Save = "Save"; + public const string Sort = "Sort"; + public const string Submit = "Submit"; + public const string Vertical = "Vertical"; + + public static char FilterFocusNameInput(char charToValidate) + { + if (charToValidate == '`') + charToValidate = '\0'; + return charToValidate; + } } } diff --git a/Assets/Scripts/CGS/Menus/CardSearchMenu.cs b/Assets/Scripts/CGS/Menus/CardSearchMenu.cs index 5fb70f115..8d3df2d4a 100644 --- a/Assets/Scripts/CGS/Menus/CardSearchMenu.cs +++ b/Assets/Scripts/CGS/Menus/CardSearchMenu.cs @@ -5,506 +5,462 @@ using UnityEngine.EventSystems; using UnityEngine.UI; -public delegate void OnSearchDelegate(string filters, List searchResults); - -public class CardSearchMenu : MonoBehaviour +namespace CGS.Menus { - public const string ClearFiltersPrompt = "Clear Filters?"; - public float PropertyPanelHeight => ((RectTransform)stringPropertyPanel.transform).rect.height; - - public Scrollbar scrollbar; - public InputField nameInputField; - public InputField idInputField; - public InputField setCodeInputField; - public RectTransform propertyFiltersContent; - public SearchPropertyPanel stringPropertyPanel; - public SearchPropertyPanel integerPropertyPanel; - public SearchPropertyPanel enumPropertyPanel; - - public OnDeckNameChangeDelegate NameChangeCallback { get; set; } - public OnSearchDelegate SearchCallback { get; set; } - - public List FilterPanels { get; } = new List(); - public List InputFields { get; } = new List(); - public List Toggles { get; } = new List(); - - public Dictionary StringPropertyFilters { get; } = new Dictionary(); - public Dictionary IntMinPropertyFilters { get; } = new Dictionary(); - public Dictionary IntMaxPropertyFilters { get; } = new Dictionary(); - public Dictionary EnumPropertyFilters { get; } = new Dictionary(); - public List Results { get; } = new List(); - - private string _nameFilter; - private string _idFilter; - private string _setCodeFilter; - - void LateUpdate() + public delegate void OnSearchDelegate(string filters, List searchResults); + + public class CardSearchMenu : MonoBehaviour { - if (!Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) - return; + public const string ClearFiltersPrompt = "Clear Filters?"; + public float PropertyPanelHeight => ((RectTransform)stringPropertyPanel.transform).rect.height; - if (Input.GetButtonDown(Inputs.FocusName) || Input.GetButtonDown(Inputs.FocusText)) - { - FocusInputField(); - return; - } + public Scrollbar scrollbar; + public InputField nameInputField; + public InputField idInputField; + public InputField setCodeInputField; + public RectTransform propertyFiltersContent; + public SearchPropertyPanel stringPropertyPanel; + public SearchPropertyPanel integerPropertyPanel; + public SearchPropertyPanel enumPropertyPanel; - if (ActiveInputField != null && ActiveInputField.isFocused) - return; + public OnNameChangeDelegate NameChangeCallback { get; set; } + public OnSearchDelegate SearchCallback { get; set; } - if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) - { - Search(); - Hide(); - } - else if (Input.GetButtonDown(Inputs.Page)) - scrollbar.value = Mathf.Clamp01(scrollbar.value + (Input.GetAxis(Inputs.Page) < 0 ? 0.1f : -0.1f)); - else if (Input.GetButtonDown(Inputs.Vertical) || Input.GetButtonDown(Inputs.Horizontal)) - FocusToggle(); - else if (Input.GetButtonDown(Inputs.New) && ActiveToggle != null) - ToggleEnum(); - else if (Input.GetButtonDown(Inputs.Delete) && ActiveInputField == null) - ClearFilters(); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - Hide(); - } + public List FilterPanels { get; } = new List(); + public List InputFields { get; } = new List(); + public List Toggles { get; } = new List(); - public void FocusInputField() - { - if (ActiveInputField == null || InputFields.Count < 1) + public CardSearchFilters Filters { get; } = new CardSearchFilters(); + public List Results { get; } = new List(); + + public InputField ActiveInputField { - InputFields.FirstOrDefault()?.ActivateInputField(); - ActiveInputField = InputFields.FirstOrDefault(); - return; + get + { + return EventSystem.current.currentSelectedGameObject != null + ? EventSystem.current.currentSelectedGameObject?.GetComponent() : null; + } + set + { + if (!EventSystem.current.alreadySelecting) + EventSystem.current.SetSelectedGameObject(value.gameObject); + } } - if (Input.GetButtonDown(Inputs.FocusName)) - { // up - InputField previous = InputFields.Last(); - for (int i = 0; i < InputFields.Count; i++) + public Toggle ActiveToggle + { + get { - if (ActiveInputField == InputFields[i]) - { - previous.ActivateInputField(); - ActiveInputField = previous; - break; - } - previous = InputFields[i]; + return EventSystem.current.currentSelectedGameObject != null + ? EventSystem.current.currentSelectedGameObject.GetComponent() : null; } - } - else - { // down - InputField next = InputFields.First(); - for (int i = InputFields.Count - 1; i >= 0; i--) + set { - if (ActiveInputField == InputFields[i]) - { - next.ActivateInputField(); - ActiveInputField = next; - break; - } - next = InputFields[i]; + if (!EventSystem.current.alreadySelecting) + EventSystem.current.SetSelectedGameObject(value.gameObject); } } - } - public void FocusToggle() - { - if (ActiveToggle == null || Toggles.Count < 1) + void LateUpdate() { - ActiveToggle = Toggles.FirstOrDefault(); - return; + if (!Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) + return; + + if (Input.GetButtonDown(Inputs.FocusName) || Input.GetButtonDown(Inputs.FocusText)) + { + FocusInputField(); + return; + } + + if (ActiveInputField != null && ActiveInputField.isFocused) + return; + + if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) + { + Search(); + Hide(); + } + else if (Input.GetButtonDown(Inputs.Page)) + scrollbar.value = Mathf.Clamp01(scrollbar.value + (Input.GetAxis(Inputs.Page) < 0 ? 0.1f : -0.1f)); + else if (Input.GetButtonDown(Inputs.Vertical) || Input.GetButtonDown(Inputs.Horizontal)) + FocusToggle(); + else if (Input.GetButtonDown(Inputs.New) && ActiveToggle != null) + ToggleEnum(); + else if (Input.GetButtonDown(Inputs.Delete) && ActiveInputField == null) + ClearFilters(); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + Hide(); } - if (Input.GetButtonDown(Inputs.Vertical)) + public void FocusInputField() { - Transform currentPanel = ActiveToggle.transform.parent; - if (Input.GetAxis(Inputs.Vertical) > 0) + if (ActiveInputField == null || InputFields.Count < 1) + { + InputFields.FirstOrDefault()?.ActivateInputField(); + ActiveInputField = InputFields.FirstOrDefault(); + return; + } + + if (Input.GetButtonDown(Inputs.FocusName)) { // up - Toggle previous = Toggles.Last(); - for (int i = 0; i < Toggles.Count; i++) + InputField previous = InputFields.Last(); + for (int i = 0; i < InputFields.Count; i++) { - if (ActiveToggle == Toggles[i]) + if (ActiveInputField == InputFields[i]) { - ActiveToggle = previous; + previous.ActivateInputField(); + ActiveInputField = previous; break; } - if (Toggles[i].transform.parent != ActiveToggle.transform.parent) - previous = Toggles[i]; + previous = InputFields[i]; } } else { // down - Toggle next = Toggles.First(); - for (int i = Toggles.Count - 1; i >= 0; i--) + InputField next = InputFields.First(); + for (int i = InputFields.Count - 1; i >= 0; i--) { - if (ActiveToggle == Toggles[i]) + if (ActiveInputField == InputFields[i]) { - ActiveToggle = next; + next.ActivateInputField(); + ActiveInputField = next; break; } - if (Toggles[i].transform.parent != ActiveToggle.transform.parent) - next = Toggles[i]; + next = InputFields[i]; } } } - else if (Input.GetButton(Inputs.Horizontal)) + + public void FocusToggle() { - if (Input.GetAxis(Inputs.Horizontal) > 0) - { // right - Toggle next = Toggles.First(); - for (int i = Toggles.Count - 1; i >= 0; i--) - { - if (ActiveToggle == Toggles[i]) + if (ActiveToggle == null || Toggles.Count < 1) + { + ActiveToggle = Toggles.FirstOrDefault(); + return; + } + + if (Input.GetButtonDown(Inputs.Vertical)) + { + Transform currentPanel = ActiveToggle.transform.parent; + if (Input.GetAxis(Inputs.Vertical) > 0) + { // up + Toggle previous = Toggles.Last(); + for (int i = 0; i < Toggles.Count; i++) { - ActiveToggle = next; - break; + if (ActiveToggle == Toggles[i]) + { + ActiveToggle = previous; + break; + } + if (Toggles[i].transform.parent != ActiveToggle.transform.parent) + previous = Toggles[i]; + } + } + else + { // down + Toggle next = Toggles.First(); + for (int i = Toggles.Count - 1; i >= 0; i--) + { + if (ActiveToggle == Toggles[i]) + { + ActiveToggle = next; + break; + } + if (Toggles[i].transform.parent != ActiveToggle.transform.parent) + next = Toggles[i]; } - next = Toggles[i]; } } - else - { // left - Toggle previous = Toggles.Last(); - for (int i = 0; i < Toggles.Count; i++) - { - if (ActiveToggle == Toggles[i]) + else if (Input.GetButton(Inputs.Horizontal)) + { + if (Input.GetAxis(Inputs.Horizontal) > 0) + { // right + Toggle next = Toggles.First(); + for (int i = Toggles.Count - 1; i >= 0; i--) { - ActiveToggle = previous; - break; + if (ActiveToggle == Toggles[i]) + { + ActiveToggle = next; + break; + } + next = Toggles[i]; + } + } + else + { // left + Toggle previous = Toggles.Last(); + for (int i = 0; i < Toggles.Count; i++) + { + if (ActiveToggle == Toggles[i]) + { + ActiveToggle = previous; + break; + } + previous = Toggles[i]; } - previous = Toggles[i]; } } } - } - - public void ToggleEnum() - { - if (ActiveToggle == null) - return; - ActiveToggle.isOn = !ActiveToggle.isOn; - } - public void Show(OnDeckNameChangeDelegate nameChangeCallback, OnSearchDelegate searchCallback) - { - gameObject.SetActive(true); - transform.SetAsLastSibling(); - NameChangeCallback = nameChangeCallback; - SearchCallback = searchCallback; - - stringPropertyPanel.gameObject.SetActive(false); - integerPropertyPanel.gameObject.SetActive(false); - enumPropertyPanel.gameObject.SetActive(false); - for (int i = FilterPanels.Count - 1; i >= 0; i--) + public void ToggleEnum() { - Destroy(FilterPanels[i].gameObject); - FilterPanels.RemoveAt(i); + if (ActiveToggle == null) + return; + ActiveToggle.isOn = !ActiveToggle.isOn; } - InputFields.Clear(); - Toggles.Clear(); - - nameInputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; - InputFields.Add(nameInputField); - idInputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; - InputFields.Add(idInputField); - setCodeInputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; - InputFields.Add(setCodeInputField); - - propertyFiltersContent.sizeDelta = new Vector2(propertyFiltersContent.sizeDelta.x, PropertyPanelHeight * CardGameManager.Current.CardProperties.Count + (PropertyPanelHeight * 3)); - foreach (PropertyDef property in CardGameManager.Current.CardProperties) + + public void Show(OnNameChangeDelegate nameChangeCallback, OnSearchDelegate searchCallback) { - GameObject newPanel; - if (EnumDef.IsEnumProperty(property.Name)) - newPanel = CreateEnumPropertyFilterPanel(property); - else if (property.Type == PropertyType.Integer) - newPanel = CreateIntegerPropertyFilterPanel(property.Name, property.Display); - else //if (property.Type == PropertyType.String) - newPanel = CreateStringPropertyFilterPanel(property.Name, property.Display); - FilterPanels.Add(newPanel); - foreach (InputField inputField in newPanel.GetComponentsInChildren()) + gameObject.SetActive(true); + transform.SetAsLastSibling(); + NameChangeCallback = nameChangeCallback; + SearchCallback = searchCallback; + + stringPropertyPanel.gameObject.SetActive(false); + integerPropertyPanel.gameObject.SetActive(false); + enumPropertyPanel.gameObject.SetActive(false); + for (int i = FilterPanels.Count - 1; i >= 0; i--) { - inputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; - InputFields.Add(inputField); + Destroy(FilterPanels[i].gameObject); + FilterPanels.RemoveAt(i); } - foreach (Toggle toggle in newPanel.GetComponentsInChildren()) - Toggles.Add(toggle); - } - } + InputFields.Clear(); + Toggles.Clear(); - public GameObject CreateStringPropertyFilterPanel(string propertyName, string displayName) - { - GameObject newPanel = Instantiate(stringPropertyPanel.gameObject, propertyFiltersContent); - newPanel.gameObject.SetActive(true); - - SearchPropertyPanel config = newPanel.GetComponent(); - config.nameLabelText.text = !string.IsNullOrEmpty(displayName) ? displayName : propertyName; - string storedFilter; - if (StringPropertyFilters.TryGetValue(propertyName, out storedFilter)) - config.stringInputField.text = storedFilter; - config.stringPlaceHolderText.text = "Enter " + propertyName + "..."; - config.stringInputField.onValueChanged.AddListener(text => SetStringPropertyFilter(propertyName, text)); - - return newPanel; - } + nameInputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; + InputFields.Add(nameInputField); + idInputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; + InputFields.Add(idInputField); + setCodeInputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; + InputFields.Add(setCodeInputField); - public GameObject CreateIntegerPropertyFilterPanel(string propertyName, string displayName) - { - GameObject newPanel = Instantiate(integerPropertyPanel.gameObject, propertyFiltersContent); - newPanel.gameObject.SetActive(true); + propertyFiltersContent.sizeDelta = new Vector2(propertyFiltersContent.sizeDelta.x, PropertyPanelHeight * CardGameManager.Current.CardProperties.Count + (PropertyPanelHeight * 3)); + foreach (PropertyDef property in CardGameManager.Current.CardProperties) + { + GameObject newPanel; + if (CardGameManager.Current.IsEnumProperty(property.Name)) + newPanel = CreateEnumPropertyFilterPanel(property); + else if (property.Type == PropertyType.Integer) + newPanel = CreateIntegerPropertyFilterPanel(property.Name, property.Display); + else //if (property.Type == PropertyType.String) + newPanel = CreateStringPropertyFilterPanel(property.Name, property.Display); + FilterPanels.Add(newPanel); + foreach (InputField inputField in newPanel.GetComponentsInChildren()) + { + inputField.onValidateInput += delegate (string input, int charIndex, char addedChar) { return Inputs.FilterFocusNameInput(addedChar); }; + InputFields.Add(inputField); + } + foreach (Toggle toggle in newPanel.GetComponentsInChildren()) + Toggles.Add(toggle); + } + } - SearchPropertyPanel config = newPanel.GetComponent(); - config.nameLabelText.text = !string.IsNullOrEmpty(displayName) ? displayName : propertyName; - int storedFilter; + public GameObject CreateStringPropertyFilterPanel(string propertyName, string displayName) + { + GameObject newPanel = Instantiate(stringPropertyPanel.gameObject, propertyFiltersContent); + newPanel.gameObject.SetActive(true); + + SearchPropertyPanel config = newPanel.GetComponent(); + config.nameLabelText.text = !string.IsNullOrEmpty(displayName) ? displayName : propertyName; + string storedFilter; + if (Filters.StringProperties.TryGetValue(propertyName, out storedFilter)) + config.stringInputField.text = storedFilter; + config.stringPlaceHolderText.text = "Enter " + propertyName + "..."; + config.stringInputField.onValueChanged.AddListener(text => SetStringPropertyFilter(propertyName, text)); + + return newPanel; + } - if (IntMinPropertyFilters.TryGetValue(propertyName, out storedFilter)) - config.integerMinInputField.text = storedFilter.ToString(); - config.integerMinInputField.onValueChanged.AddListener(text => SetIntMinPropertyFilter(propertyName, text)); + public GameObject CreateIntegerPropertyFilterPanel(string propertyName, string displayName) + { + GameObject newPanel = Instantiate(integerPropertyPanel.gameObject, propertyFiltersContent); + newPanel.gameObject.SetActive(true); - if (IntMaxPropertyFilters.TryGetValue(propertyName, out storedFilter)) - config.integerMaxInputField.text = storedFilter.ToString(); - config.integerMaxInputField.onValueChanged.AddListener(text => SetIntMaxPropertyFilter(propertyName, text)); + SearchPropertyPanel config = newPanel.GetComponent(); + config.nameLabelText.text = !string.IsNullOrEmpty(displayName) ? displayName : propertyName; + int storedFilter; - return newPanel; - } + if (Filters.IntMinProperties.TryGetValue(propertyName, out storedFilter)) + config.integerMinInputField.text = storedFilter.ToString(); + config.integerMinInputField.onValueChanged.AddListener(text => SetIntMinPropertyFilter(propertyName, text)); - public GameObject CreateEnumPropertyFilterPanel(PropertyDef property) - { - GameObject newPanel = Instantiate(enumPropertyPanel.gameObject, propertyFiltersContent); - newPanel.gameObject.SetActive(true); - - SearchPropertyPanel config = newPanel.GetComponent(); - config.nameLabelText.text = !string.IsNullOrEmpty(property.Display) ? property.Display : property.Name; - int storedFilter; - EnumPropertyFilters.TryGetValue(property.Name, out storedFilter); - - EnumDef enumDef = CardGameManager.Current.Enums.First(def => def.Property.Equals(property.Name)); - Vector3 localPosition = config.enumToggle.transform.localPosition; - float panelWidth = 0; - foreach (KeyValuePair enumValue in enumDef.Values) - { - int lookupKey; - if (!enumDef.Lookup.TryGetValue(enumValue.Key, out lookupKey)) - lookupKey = enumDef.CreateLookup(enumValue.Key); - Toggle newToggle = Instantiate(config.enumToggle.gameObject, config.enumContent).GetOrAddComponent(); - newToggle.isOn = (storedFilter & lookupKey) != 0; - newToggle.onValueChanged.AddListener(isOn => SetEnumPropertyFilter(property.Name, lookupKey, isOn)); - newToggle.GetComponentInChildren().text = enumValue.Value; - newToggle.transform.localPosition = localPosition; - float width = newToggle.GetComponentInChildren().preferredWidth + 25; - RectTransform imageTransform = (RectTransform)newToggle.GetComponentInChildren().transform; - imageTransform.sizeDelta = new Vector2(width, imageTransform.sizeDelta.y); - localPosition.x += width; - panelWidth += width; + if (Filters.IntMaxProperties.TryGetValue(propertyName, out storedFilter)) + config.integerMaxInputField.text = storedFilter.ToString(); + config.integerMaxInputField.onValueChanged.AddListener(text => SetIntMaxPropertyFilter(propertyName, text)); + + return newPanel; } - if (!string.IsNullOrEmpty(property.Empty)) + public GameObject CreateEnumPropertyFilterPanel(PropertyDef property) { - int lookupKey; - if (!enumDef.Lookup.TryGetValue(property.Empty, out lookupKey)) - lookupKey = enumDef.CreateLookup(property.Empty); - Toggle newToggle = Instantiate(config.enumToggle.gameObject, config.enumContent).GetOrAddComponent(); - newToggle.isOn = (storedFilter & lookupKey) != 0; - newToggle.onValueChanged.AddListener(isOn => SetEnumPropertyFilter(property.Name, lookupKey, isOn)); - newToggle.GetComponentInChildren().text = property.Empty; - newToggle.transform.localPosition = localPosition; - float width = newToggle.GetComponentInChildren().preferredWidth + 25; - RectTransform imageTransform = (RectTransform)newToggle.GetComponentInChildren().transform; - imageTransform.sizeDelta = new Vector2(width, imageTransform.sizeDelta.y); - localPosition.x += width; - panelWidth += width; - } - config.enumToggle.gameObject.SetActive(false); - config.enumContent.sizeDelta = new Vector2(panelWidth, config.enumContent.sizeDelta.y); + GameObject newPanel = Instantiate(enumPropertyPanel.gameObject, propertyFiltersContent); + newPanel.gameObject.SetActive(true); + + SearchPropertyPanel config = newPanel.GetComponent(); + config.nameLabelText.text = !string.IsNullOrEmpty(property.Display) ? property.Display : property.Name; + int storedFilter; + Filters.EnumProperties.TryGetValue(property.Name, out storedFilter); + + EnumDef enumDef = CardGameManager.Current.Enums.First(def => def.Property.Equals(property.Name)); + Vector3 localPosition = config.enumToggle.transform.localPosition; + float panelWidth = 0; + foreach (KeyValuePair enumValue in enumDef.Values) + { + int lookupKey; + if (!enumDef.Lookup.TryGetValue(enumValue.Key, out lookupKey)) + lookupKey = enumDef.CreateLookup(enumValue.Key); + Toggle newToggle = Instantiate(config.enumToggle.gameObject, config.enumContent).GetOrAddComponent(); + newToggle.isOn = (storedFilter & lookupKey) != 0; + newToggle.onValueChanged.AddListener(isOn => SetEnumPropertyFilter(property.Name, lookupKey, isOn)); + newToggle.GetComponentInChildren().text = enumValue.Value; + newToggle.transform.localPosition = localPosition; + float width = newToggle.GetComponentInChildren().preferredWidth + 25; + RectTransform imageTransform = (RectTransform)newToggle.GetComponentInChildren().transform; + imageTransform.sizeDelta = new Vector2(width, imageTransform.sizeDelta.y); + localPosition.x += width; + panelWidth += width; + } - return newPanel; - } + if (!string.IsNullOrEmpty(property.Empty)) + { + int lookupKey; + if (!enumDef.Lookup.TryGetValue(property.Empty, out lookupKey)) + lookupKey = enumDef.CreateLookup(property.Empty); + Toggle newToggle = Instantiate(config.enumToggle.gameObject, config.enumContent).GetOrAddComponent(); + newToggle.isOn = (storedFilter & lookupKey) != 0; + newToggle.onValueChanged.AddListener(isOn => SetEnumPropertyFilter(property.Name, lookupKey, isOn)); + newToggle.GetComponentInChildren().text = property.Empty; + newToggle.transform.localPosition = localPosition; + float width = newToggle.GetComponentInChildren().preferredWidth + 25; + RectTransform imageTransform = (RectTransform)newToggle.GetComponentInChildren().transform; + imageTransform.sizeDelta = new Vector2(width, imageTransform.sizeDelta.y); + localPosition.x += width; + panelWidth += width; + } + config.enumToggle.gameObject.SetActive(false); + config.enumContent.sizeDelta = new Vector2(panelWidth, config.enumContent.sizeDelta.y); - public void SetStringPropertyFilter(string propertyName, string filterValue) - { - if (string.IsNullOrEmpty(filterValue)) - { - if (StringPropertyFilters.ContainsKey(propertyName)) - StringPropertyFilters.Remove(propertyName); - return; + return newPanel; } - StringPropertyFilters[propertyName] = filterValue; - } - - public void SetIntMinPropertyFilter(string propertyName, string filterValue) - { - int intValue; - if (!int.TryParse(filterValue, out intValue)) + public void SetNameFilter(string name) { - if (IntMinPropertyFilters.ContainsKey(propertyName)) - IntMinPropertyFilters.Remove(propertyName); - return; - } + Filters.Name = NameChangeCallback != null ? NameChangeCallback(name) : name; - IntMinPropertyFilters[propertyName] = intValue; - } + if (!nameInputField.text.Equals(Filters.Name)) + nameInputField.text = Filters.Name; + } - public void SetIntMaxPropertyFilter(string propertyName, string filterValue) - { - int intValue; - if (!int.TryParse(filterValue, out intValue)) + public void SetIdFilter(string id) { - if (IntMaxPropertyFilters.ContainsKey(propertyName)) - IntMaxPropertyFilters.Remove(propertyName); - return; + Filters.Id = id; } - IntMaxPropertyFilters[propertyName] = intValue; - } + public void SetCodeFilter(string code) + { + Filters.SetCode = code; + } - public void SetEnumPropertyFilter(string propertyName, int filterValue, bool isOn) - { - if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) - return; + public void SetStringPropertyFilter(string propertyName, string filterValue) + { + if (string.IsNullOrEmpty(filterValue)) + { + if (Filters.StringProperties.ContainsKey(propertyName)) + Filters.StringProperties.Remove(propertyName); + return; + } - bool isStored = EnumPropertyFilters.ContainsKey(propertyName); - int storedFilter = 0; - if (isStored) - storedFilter = EnumPropertyFilters[propertyName]; + Filters.StringProperties[propertyName] = filterValue; + } - int newFilter = isOn ? storedFilter | filterValue : storedFilter & ~filterValue; - if (newFilter == 0) + public void SetIntMinPropertyFilter(string propertyName, string filterValue) { - if (isStored) - EnumPropertyFilters.Remove(propertyName); + int intValue; + if (!int.TryParse(filterValue, out intValue)) + { + if (Filters.IntMinProperties.ContainsKey(propertyName)) + Filters.IntMinProperties.Remove(propertyName); + return; + } + + Filters.IntMinProperties[propertyName] = intValue; } - else - EnumPropertyFilters[propertyName] = newFilter; - } - public void ClearFilters() - { - foreach (InputField input in GetComponentsInChildren()) - input.text = string.Empty; - foreach (Toggle toggle in GetComponentsInChildren()) - toggle.isOn = false; - - StringPropertyFilters.Clear(); - IntMinPropertyFilters.Clear(); - IntMaxPropertyFilters.Clear(); - EnumPropertyFilters.Clear(); - } + public void SetIntMaxPropertyFilter(string propertyName, string filterValue) + { + int intValue; + if (!int.TryParse(filterValue, out intValue)) + { + if (Filters.IntMaxProperties.ContainsKey(propertyName)) + Filters.IntMaxProperties.Remove(propertyName); + return; + } - public void ClearSearch() - { - ClearFilters(); - Search(); - } + Filters.IntMaxProperties[propertyName] = intValue; + } - public void Search() - { - Results.Clear(); - IEnumerable cardSearcher = CardGameManager.Current.FilterCards(IdFilter, NameFilter, SetCodeFilter, StringPropertyFilters, IntMinPropertyFilters, IntMaxPropertyFilters, EnumPropertyFilters); - foreach (Card card in cardSearcher) - Results.Add(card); - SearchCallback?.Invoke(Filters, Results); - } + public void SetEnumPropertyFilter(string propertyName, int filterValue, bool isOn) + { + if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) + return; - public void Hide() - { - gameObject.SetActive(false); - } + bool isStored = Filters.EnumProperties.ContainsKey(propertyName); + int storedFilter = 0; + if (isStored) + storedFilter = Filters.EnumProperties[propertyName]; - public string Filters - { - get - { - string filters = string.Empty; - if (!string.IsNullOrEmpty(IdFilter)) - filters += "id:" + IdFilter + "; "; - if (!string.IsNullOrEmpty(SetCodeFilter)) - filters += "set:" + SetCodeFilter + "; "; - foreach (PropertyDef property in CardGameManager.Current.CardProperties) + int newFilter = isOn ? storedFilter | filterValue : storedFilter & ~filterValue; + if (newFilter == 0) { - switch (property.Type) - { - case PropertyType.ObjectEnum: - case PropertyType.ObjectEnumList: - case PropertyType.StringEnum: - case PropertyType.StringEnumList: - if (!EnumPropertyFilters.ContainsKey(property.Name)) - break; - EnumDef enumDef = CardGameManager.Current.Enums.FirstOrDefault(def => def.Property.Equals(property.Name)); - if (enumDef != null) - filters += property.Name + ":=" + EnumPropertyFilters[property.Name] + "; "; - break; - case PropertyType.Integer: - if (IntMinPropertyFilters.ContainsKey(property.Name)) - filters += property.Name + ">=" + IntMinPropertyFilters[property.Name] + "; "; - if (IntMaxPropertyFilters.ContainsKey(property.Name)) - filters += property.Name + "<=" + IntMaxPropertyFilters[property.Name] + "; "; - break; - case PropertyType.Object: - case PropertyType.ObjectList: - case PropertyType.Number: - case PropertyType.Boolean: - case PropertyType.StringList: - case PropertyType.EscapedString: - case PropertyType.String: - default: - if (StringPropertyFilters.ContainsKey(property.Name)) - filters += property.Name + ":" + StringPropertyFilters[property.Name] + "; "; - break; - } + if (isStored) + Filters.EnumProperties.Remove(propertyName); } - return filters; + else + Filters.EnumProperties[propertyName] = newFilter; } - } - public string NameFilter - { - get { return _nameFilter ?? (_nameFilter = string.Empty); } - set + public void ClearFilters() { - _nameFilter = value; - NameChangeCallback?.Invoke(_nameFilter); - if (nameInputField != null) - nameInputField.text = _nameFilter; + foreach (InputField input in GetComponentsInChildren()) + input.text = string.Empty; + foreach (Toggle toggle in GetComponentsInChildren()) + toggle.isOn = false; + + Filters.Name = string.Empty; + Filters.Id = string.Empty; + Filters.SetCode = string.Empty; + Filters.StringProperties.Clear(); + Filters.IntMinProperties.Clear(); + Filters.IntMaxProperties.Clear(); + Filters.EnumProperties.Clear(); } - } - public string IdFilter - { - get { return _idFilter ?? (_idFilter = string.Empty); } - set { _idFilter = value; } - } - - public string SetCodeFilter - { - get { return _setCodeFilter ?? (_setCodeFilter = string.Empty); } - set { _setCodeFilter = value; } - } - public InputField ActiveInputField - { - get + public void ClearSearch() { - return EventSystem.current.currentSelectedGameObject != null - ? EventSystem.current.currentSelectedGameObject?.GetComponent() : null; + ClearFilters(); + Search(); } - set + + public void ClearSearchName() { - if (!EventSystem.current.alreadySelecting) - EventSystem.current.SetSelectedGameObject(value.gameObject); + string name = Filters.Name; + ClearFilters(); + SetNameFilter(name); + Search(); } - } - public Toggle ActiveToggle - { - get + public void Search() { - return EventSystem.current.currentSelectedGameObject != null - ? EventSystem.current.currentSelectedGameObject.GetComponent() : null; + Results.Clear(); + IEnumerable cardSearcher = CardGameManager.Current.FilterCards(Filters); + foreach (Card card in cardSearcher) + Results.Add(card); + SearchCallback?.Invoke(Filters.ToString(CardGameManager.Current), Results); } - set + + public void Hide() { - if (!EventSystem.current.alreadySelecting) - EventSystem.current.SetSelectedGameObject(value.gameObject); + gameObject.SetActive(false); } } } diff --git a/Assets/Scripts/CGS/Menus/DeckLoadMenu.cs b/Assets/Scripts/CGS/Menus/DeckLoadMenu.cs index 43c2de2a5..1c3b1027c 100644 --- a/Assets/Scripts/CGS/Menus/DeckLoadMenu.cs +++ b/Assets/Scripts/CGS/Menus/DeckLoadMenu.cs @@ -8,262 +8,272 @@ using UnityEngine.EventSystems; using UnityEngine.UI; -public delegate void OnDeckLoadedDelegate(Deck loadedDeck); - -public class DeckLoadMenu : SelectionPanel +namespace CGS.Menus { - public const string DecInstructions = "//On each line, enter:\n// \n//For example:\n4 Super Awesome Card\n3 Less Awesome Card I Still Like\n1 Card That Is Situational"; - public const string HsdInstructions = "#Paste the deck string/code here"; - public const string TxtInstructions = "### Instructions\n#On each line, enter:\n# \n#For example:\n4 Super Awesome Card\n3 Less Awesome Card I Still Like\n1 Card That Is Situational"; - public const string YdkInstructions = "#On each line, enter \n#Copy/Paste recommended"; - - public const string DeletePrompt = "Are you sure you would like to delete this deck?"; - public const string DeckDeleteErrorMessage = "There was an error while attempting to delete the deck: "; - public const string DeckLoadErrorMessage = "There was an error while loading the deck: "; - public const string DeckSaveErrorMessage = "There was an error saving the deck to file: "; - - public Button shareFileButton; - public Button deleteFileButton; - public Button loadFromFileButton; - - public RectTransform newDeckPanel; - public InputField nameInputField; - public TMPro.TextMeshProUGUI instructionsText; - public TMPro.TMP_InputField textInputField; - - public OnDeckLoadedDelegate LoadCallback { get; private set; } - public string SelectedFileName { get; private set; } - public SortedDictionary DeckFiles { get; } = new SortedDictionary(); - - void LateUpdate() - { - if (nameInputField.isFocused || !Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) - return; + public delegate void OnDeckLoadedDelegate(Deck loadedDeck); - if (newDeckPanel.gameObject.activeSelf) - { - if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && EventSystem.current.currentSelectedGameObject == null) - DoSaveDontOverwrite(); - else if (Input.GetButtonDown(Inputs.New) && EventSystem.current.currentSelectedGameObject == null) - textInputField.text = string.Empty; - else if (Input.GetButtonDown(Inputs.FocusName) && EventSystem.current.currentSelectedGameObject == null) - nameInputField.ActivateInputField(); - else if (Input.GetButtonDown(Inputs.FocusText) && EventSystem.current.currentSelectedGameObject == null) - textInputField.ActivateInputField(); - else if (Input.GetButtonDown(Inputs.Save) && EventSystem.current.currentSelectedGameObject == null) - PasteClipboardIntoText(); - else if (Input.GetButtonDown(Inputs.Delete) && EventSystem.current.currentSelectedGameObject == null) - textInputField.text = string.Empty; - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - HideNewDeckPanel(); - } - else + public class DeckLoadMenu : SelectionPanel + { + public const string DecInstructions = "//On each line, enter:\n// \n//For example:\n4 Super Awesome Card\n3 Less Awesome Card I Still Like\n1 Card That Is Situational"; + public const string HsdInstructions = "#Paste the deck string/code here"; + public const string TxtInstructions = "### Instructions\n#On each line, enter:\n# \n#For example:\n4 Super Awesome Card\n3 Less Awesome Card I Still Like\n1 Card That Is Situational"; + public const string YdkInstructions = "#On each line, enter \n#Copy/Paste recommended"; + + public const string DeletePrompt = "Are you sure you would like to delete this deck?"; + public const string DeckDeleteErrorMessage = "There was an error while attempting to delete the deck: "; + public const string DeckLoadErrorMessage = "There was an error while loading the deck: "; + public const string DeckSaveErrorMessage = "There was an error saving the deck to file: "; + + public Button shareFileButton; + public Button deleteFileButton; + public Button loadFromFileButton; + + public RectTransform newDeckPanel; + public InputField nameInputField; + public TMPro.TextMeshProUGUI instructionsText; + public TMPro.TMP_InputField textInputField; + + public OnDeckLoadedDelegate LoadCallback { get; private set; } + public string SelectedFileName { get; private set; } + public SortedDictionary DeckFiles { get; } = new SortedDictionary(); + + void LateUpdate() { - if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && loadFromFileButton.interactable) - LoadFromFileAndHide(); - else if (Input.GetKeyDown(Inputs.BluetoothReturn) && Toggles.Contains(EventSystem.current.currentSelectedGameObject)) - EventSystem.current.currentSelectedGameObject.GetComponent().isOn = true; - else if (Input.GetButtonDown(Inputs.Sort) && shareFileButton.interactable) - Share(); - else if (Input.GetButtonDown(Inputs.New)) - ShowNewDeckPanel(); - else if (Input.GetButtonDown(Inputs.Delete) && deleteFileButton.interactable) - PromptForDeleteFile(); - else if (Input.GetButtonDown(Inputs.Vertical)) - ScrollToggles(Input.GetAxis(Inputs.Vertical) > 0); - else if (Input.GetButtonDown(Inputs.Page)) - ScrollPage(Input.GetAxis(Inputs.Page) < 0); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - Hide(); + if (nameInputField.isFocused || !Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) + return; + + if (newDeckPanel.gameObject.activeSelf) + { + if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && EventSystem.current.currentSelectedGameObject == null) + DoSaveDontOverwrite(); + else if (Input.GetButtonDown(Inputs.New) && EventSystem.current.currentSelectedGameObject == null) + textInputField.text = string.Empty; + else if (Input.GetButtonDown(Inputs.FocusName) && EventSystem.current.currentSelectedGameObject == null) + nameInputField.ActivateInputField(); + else if (Input.GetButtonDown(Inputs.FocusText) && EventSystem.current.currentSelectedGameObject == null) + textInputField.ActivateInputField(); + else if (Input.GetButtonDown(Inputs.Save) && EventSystem.current.currentSelectedGameObject == null) + PasteClipboardIntoText(); + else if (Input.GetButtonDown(Inputs.Delete) && EventSystem.current.currentSelectedGameObject == null) + textInputField.text = string.Empty; + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + HideNewDeckPanel(); + } + else + { + if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && loadFromFileButton.interactable) + LoadFromFileAndHide(); + else if (Input.GetKeyDown(Inputs.BluetoothReturn) && Toggles.Contains(EventSystem.current.currentSelectedGameObject)) + EventSystem.current.currentSelectedGameObject.GetComponent().isOn = true; + else if (Input.GetButtonDown(Inputs.Sort) && shareFileButton.interactable) + Share(); + else if (Input.GetButtonDown(Inputs.New)) + ShowNewDeckPanel(); + else if (Input.GetButtonDown(Inputs.Delete) && deleteFileButton.interactable) + PromptForDeleteFile(); + else if (Input.GetButtonDown(Inputs.Vertical)) + ScrollToggles(Input.GetAxis(Inputs.Vertical) > 0); + else if (Input.GetButtonDown(Inputs.Page)) + ScrollPage(Input.GetAxis(Inputs.Page) < 0); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + Hide(); + } } - } - - public void Show(OnDeckLoadedDelegate loadCallback = null, string originalName = null, string originalText = null) - { - gameObject.SetActive(true); - transform.SetAsLastSibling(); - LoadCallback = loadCallback; - SelectedFileName = string.Empty; - - BuildDeckFileSelectionOptions(); - nameInputField.text = originalName ?? Deck.DefaultName; - textInputField.text = originalText ?? string.Empty; - switch (CardGameManager.Current.DeckFileType) + public void Show(OnDeckLoadedDelegate loadCallback = null, string originalName = null, string originalText = null) { - case DeckFileType.Dec: - instructionsText.text = DecInstructions; - break; - case DeckFileType.Hsd: - instructionsText.text = HsdInstructions; - break; - case DeckFileType.Ydk: - instructionsText.text = YdkInstructions; - break; - case DeckFileType.Txt: - default: - instructionsText.text = TxtInstructions; - break; + gameObject.SetActive(true); + transform.SetAsLastSibling(); + LoadCallback = loadCallback; + SelectedFileName = string.Empty; + + BuildDeckFileSelectionOptions(); + + nameInputField.text = originalName ?? Deck.DefaultName; + textInputField.text = originalText ?? string.Empty; + switch (CardGameManager.Current.DeckFileType) + { + case DeckFileType.Dec: + instructionsText.text = DecInstructions; + break; + case DeckFileType.Hsd: + instructionsText.text = HsdInstructions; + break; + case DeckFileType.Ydk: + instructionsText.text = YdkInstructions; + break; + case DeckFileType.Txt: + default: + instructionsText.text = TxtInstructions; + break; + } } - } - public void BuildDeckFileSelectionOptions() - { - DeckFiles.Clear(); - string[] files = Directory.Exists(CardGameManager.Current.DecksFilePath) ? Directory.GetFiles(CardGameManager.Current.DecksFilePath) : new string[0]; - foreach (string file in files) - if (GetFileTypeFromPath(file) == CardGameManager.Current.DeckFileType) - DeckFiles[GetNameFromPath((file))] = file; + public void BuildDeckFileSelectionOptions() + { + DeckFiles.Clear(); + string[] files = Directory.Exists(CardGameManager.Current.DecksFilePath) ? Directory.GetFiles(CardGameManager.Current.DecksFilePath) : new string[0]; + foreach (string file in files) + if (GetFileTypeFromPath(file) == CardGameManager.Current.DeckFileType) + DeckFiles[GetNameFromPath((file))] = file; - Rebuild(DeckFiles.Keys.ToList(), SelectFile, SelectedFileName); + Rebuild(DeckFiles.Keys.ToList(), SelectFile, SelectedFileName); - shareFileButton.interactable = !string.IsNullOrEmpty(SelectedFileName); - deleteFileButton.interactable = !string.IsNullOrEmpty(SelectedFileName); - loadFromFileButton.interactable = !string.IsNullOrEmpty(SelectedFileName); - } + shareFileButton.interactable = !string.IsNullOrEmpty(SelectedFileName); + deleteFileButton.interactable = !string.IsNullOrEmpty(SelectedFileName); + loadFromFileButton.interactable = !string.IsNullOrEmpty(SelectedFileName); + } - public void SelectFile(bool isOn, string deckFileName) - { - if (string.IsNullOrEmpty(deckFileName)) + public void SelectFile(Toggle toggle, string deckFileName) { - SelectedFileName = string.Empty; - shareFileButton.interactable = false; - deleteFileButton.interactable = false; - loadFromFileButton.interactable = false; - return; + if (string.IsNullOrEmpty(deckFileName)) + { + SelectedFileName = string.Empty; + shareFileButton.interactable = false; + deleteFileButton.interactable = false; + loadFromFileButton.interactable = false; + return; + } + + if (toggle.isOn) + { + SelectedFileName = deckFileName; + shareFileButton.interactable = true; + deleteFileButton.interactable = true; + loadFromFileButton.interactable = true; + } + else if (!toggle.group.AnyTogglesOn() && SelectedFileName.Equals(deckFileName)) + LoadFromFileAndHide(); } - if (isOn) + public string GetNameFromPath(string filePath) { - SelectedFileName = deckFileName; - shareFileButton.interactable = true; - deleteFileButton.interactable = true; - loadFromFileButton.interactable = true; + int startName = filePath.LastIndexOf(Path.DirectorySeparatorChar) + 1; + int endName = filePath.LastIndexOf('.'); + return filePath.Substring(startName, endName > 0 ? endName - startName : 0); } - else if (SelectedFileName.Equals(deckFileName)) - LoadFromFileAndHide(); - } - - public string GetNameFromPath(string filePath) - { - int startName = filePath.LastIndexOf(Path.DirectorySeparatorChar) + 1; - int endName = filePath.LastIndexOf('.'); - return filePath.Substring(startName, endName > 0 ? endName - startName : 0); - } - public DeckFileType GetFileTypeFromPath(string filePath) - { - DeckFileType fileType = DeckFileType.Txt; - string extension = filePath.Substring(filePath.LastIndexOf('.') + 1); - if (extension.ToLower().Equals(DeckFileType.Dec.ToString().ToLower())) - fileType = DeckFileType.Dec; - else if (extension.ToLower().Equals(DeckFileType.Hsd.ToString().ToLower())) - fileType = DeckFileType.Hsd; - else if (extension.ToLower().Equals(DeckFileType.Ydk.ToString().ToLower())) - fileType = DeckFileType.Ydk; - return fileType; - } - - public void Share() - { - CardGameManager.Instance.Messenger.Show("Share functionality is coming soon."); - } - - public void PromptForDeleteFile() - { - CardGameManager.Instance.Messenger.Prompt(DeletePrompt, DeleteFile); - } - - public void DeleteFile() - { - try + public DeckFileType GetFileTypeFromPath(string filePath) { - File.Delete(DeckFiles[SelectedFileName]); + DeckFileType fileType = DeckFileType.Txt; + string extension = filePath.Substring(filePath.LastIndexOf('.') + 1); + if (extension.ToLower().Equals(DeckFileType.Dec.ToString().ToLower())) + fileType = DeckFileType.Dec; + else if (extension.ToLower().Equals(DeckFileType.Hsd.ToString().ToLower())) + fileType = DeckFileType.Hsd; + else if (extension.ToLower().Equals(DeckFileType.Ydk.ToString().ToLower())) + fileType = DeckFileType.Ydk; + return fileType; } - catch (Exception e) + + public void Share() { - Debug.LogError(DeckDeleteErrorMessage + e.Message); + CardGameManager.Instance.Messenger.Show("Share functionality is coming soon."); } - SelectedFileName = string.Empty; - BuildDeckFileSelectionOptions(); - } - public void LoadFromFileAndHide() - { - string deckText = string.Empty; - try + public void PromptForDeleteFile() { - deckText = File.ReadAllText(DeckFiles[SelectedFileName]); + CardGameManager.Instance.Messenger.Prompt(DeletePrompt, DeleteFile); } - catch (Exception e) + + public void DeleteFile() { - Debug.LogError(DeckLoadErrorMessage + e.Message); + try + { + File.Delete(DeckFiles[SelectedFileName]); + } + catch (Exception e) + { + Debug.LogError(DeckDeleteErrorMessage + e.Message); + } + SelectedFileName = string.Empty; + BuildDeckFileSelectionOptions(); } - Deck newDeck = Deck.Parse(SelectedFileName, CardGameManager.Current.DeckFileType, deckText); - LoadCallback?.Invoke(newDeck); - Hide(); - } + public void LoadFromFileAndHide() + { + string deckText = string.Empty; + try + { + deckText = File.ReadAllText(DeckFiles[SelectedFileName]); + } + catch (Exception e) + { + Debug.LogError(DeckLoadErrorMessage + e.Message); + } + + Deck newDeck = Deck.Parse(CardGameManager.Current, SelectedFileName, CardGameManager.Current.DeckFileType, deckText); + LoadCallback?.Invoke(newDeck); + ResetCancelButton(); + Hide(); + } - public void ShowNewDeckPanel() - { - newDeckPanel.gameObject.SetActive(true); - } + public void ShowNewDeckPanel() + { + newDeckPanel.gameObject.SetActive(true); + } - public void ValidateDeckName(string deckName) - { - nameInputField.text = UnityExtensionMethods.GetSafeFileName(deckName); - } + public void ValidateDeckName(string deckName) + { + nameInputField.text = UnityExtensionMethods.GetSafeFileName(deckName); + } - public void Clear() - { - textInputField.text = string.Empty; - } + public void Clear() + { + textInputField.text = string.Empty; + } - public void PasteClipboardIntoText() - { - textInputField.text = UniClipboard.GetText(); - } + public void PasteClipboardIntoText() + { + textInputField.text = UniClipboard.GetText(); + } - public void DoSaveDontOverwrite() - { - Deck filePathFinder = new Deck(nameInputField.text, CardGameManager.Current.DeckFileType); - if (File.Exists(filePathFinder.FilePath)) - CardGameManager.Instance.StartCoroutine(WaitToPromptOverwrite()); - else - DoSave(); - } + public void DoSaveDontOverwrite() + { + Deck filePathFinder = new Deck(CardGameManager.Current, nameInputField.text, CardGameManager.Current.DeckFileType); + if (File.Exists(filePathFinder.FilePath)) + CardGameManager.Instance.StartCoroutine(WaitToPromptOverwrite()); + else + DoSave(); + } - public IEnumerator WaitToPromptOverwrite() - { - yield return null; - CardGameManager.Instance.Messenger.Ask(DeckSaveMenu.OverWriteDeckPrompt, null, DoSave); - } + public IEnumerator WaitToPromptOverwrite() + { + yield return null; + CardGameManager.Instance.Messenger.Ask(DeckSaveMenu.OverWriteDeckPrompt, null, DoSave); + } - public void DoSave() - { - Deck filePathFinder = new Deck(nameInputField.text, CardGameManager.Current.DeckFileType); - try + public void DoSave() { - if (!Directory.Exists(CardGameManager.Current.DecksFilePath)) - Directory.CreateDirectory(CardGameManager.Current.DecksFilePath); - File.WriteAllText(filePathFinder.FilePath, textInputField.text); + Deck filePathFinder = new Deck(CardGameManager.Current, nameInputField.text, CardGameManager.Current.DeckFileType); + try + { + if (!Directory.Exists(CardGameManager.Current.DecksFilePath)) + Directory.CreateDirectory(CardGameManager.Current.DecksFilePath); + File.WriteAllText(filePathFinder.FilePath, textInputField.text); + } + catch (Exception e) + { + Debug.LogError(DeckSaveErrorMessage + e.Message); + } + BuildDeckFileSelectionOptions(); + HideNewDeckPanel(); } - catch (Exception e) + + public void HideNewDeckPanel() { - Debug.LogError(DeckSaveErrorMessage + e.Message); + newDeckPanel.gameObject.SetActive(false); } - BuildDeckFileSelectionOptions(); - HideNewDeckPanel(); - } - public void HideNewDeckPanel() - { - newDeckPanel.gameObject.SetActive(false); - } + public void ResetCancelButton() + { + cancelButton.onClick.RemoveAllListeners(); + cancelButton.onClick.AddListener(Hide); + } - public void Hide() - { - gameObject.SetActive(false); + public void Hide() + { + gameObject.SetActive(false); + } } } diff --git a/Assets/Scripts/CGS/Menus/DeckSaveMenu.cs b/Assets/Scripts/CGS/Menus/DeckSaveMenu.cs index e01977d1a..b33e09eba 100644 --- a/Assets/Scripts/CGS/Menus/DeckSaveMenu.cs +++ b/Assets/Scripts/CGS/Menus/DeckSaveMenu.cs @@ -5,106 +5,109 @@ using UnityEngine.EventSystems; using UnityEngine.UI; -public delegate void OnDeckSavedDelegate(Deck savedDeck); - -public class DeckSaveMenu : MonoBehaviour +namespace CGS.Menus { - public const string DeckCopiedMessage = "The text for this deck has been copied to the clipboard."; - public const string OverWriteDeckPrompt = "A deck with that name already exists. Overwrite?"; - public const string DeckSaveErrorMessage = "There was an error saving the deck to file: "; + public delegate void OnDeckSavedDelegate(Deck savedDeck); - public InputField nameInputField; - public TMPro.TMP_Text textOutputArea; + public class DeckSaveMenu : MonoBehaviour + { + public const string DeckCopiedMessage = "The text for this deck has been copied to the clipboard."; + public const string OverWriteDeckPrompt = "A deck with that name already exists. Overwrite?"; + public const string DeckSaveErrorMessage = "There was an error saving the deck to file: "; - public Deck CurrentDeck { get; private set; } - public OnDeckNameChangeDelegate NameChangeCallback { get; private set; } - public OnDeckSavedDelegate DeckSaveCallback { get; private set; } - public bool DoesAutoOverwrite { get; private set; } + public InputField nameInputField; + public TMPro.TMP_Text textOutputArea; - void LateUpdate() - { - if (nameInputField.isFocused || !Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) - return; + public Deck CurrentDeck { get; private set; } + public OnNameChangeDelegate NameChangeCallback { get; private set; } + public OnDeckSavedDelegate DeckSaveCallback { get; private set; } + public bool DoesAutoOverwrite { get; private set; } - if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && EventSystem.current.currentSelectedGameObject == null) - AttemptSaveAndHide(); - else if (Input.GetButtonDown(Inputs.FocusName)) - nameInputField.ActivateInputField(); - else if (Input.GetButtonDown(Inputs.Load) && EventSystem.current.currentSelectedGameObject == null) - CopyTextToClipboard(); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - Hide(); - } + void LateUpdate() + { + if (nameInputField.isFocused || !Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) + return; - public void Show(Deck deckToShow, OnDeckNameChangeDelegate nameChangeCallback = null, OnDeckSavedDelegate deckSaveCallback = null, bool overwrite = false) - { - gameObject.SetActive(true); - transform.SetAsLastSibling(); - CurrentDeck = deckToShow ?? new Deck(); - NameChangeCallback = nameChangeCallback; - DeckSaveCallback = deckSaveCallback; - DoesAutoOverwrite = overwrite; - nameInputField.text = CurrentDeck.Name; - textOutputArea.text = CurrentDeck.ToString(); - } + if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && EventSystem.current.currentSelectedGameObject == null) + AttemptSaveAndHide(); + else if (Input.GetButtonDown(Inputs.FocusName)) + nameInputField.ActivateInputField(); + else if (Input.GetButtonDown(Inputs.Load) && EventSystem.current.currentSelectedGameObject == null) + CopyTextToClipboard(); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + Hide(); + } - public void ChangeName(string newName) - { - if (NameChangeCallback != null) - newName = NameChangeCallback(newName); - if (!string.IsNullOrEmpty(newName)) - nameInputField.text = newName; - Deck newDeck = new Deck(newName, CardGameManager.Current.DeckFileType); - newDeck.Cards.AddRange(CurrentDeck.Cards); - textOutputArea.text = newDeck.ToString(); - } + public void Show(Deck deckToShow, OnNameChangeDelegate nameChangeCallback = null, OnDeckSavedDelegate deckSaveCallback = null, bool overwrite = false) + { + gameObject.SetActive(true); + transform.SetAsLastSibling(); + CurrentDeck = deckToShow ?? new Deck(CardGameManager.Current); + NameChangeCallback = nameChangeCallback; + DeckSaveCallback = deckSaveCallback; + DoesAutoOverwrite = overwrite; + nameInputField.text = CurrentDeck.Name; + textOutputArea.text = CurrentDeck.ToString(); + } - public void CopyTextToClipboard() - { - UniClipboard.SetText(textOutputArea.text); - CardGameManager.Instance.Messenger.Show(DeckCopiedMessage); - } + public void ChangeName(string newName) + { + if (NameChangeCallback != null) + newName = NameChangeCallback(newName); + if (!string.IsNullOrEmpty(newName)) + nameInputField.text = newName; + Deck newDeck = new Deck(CardGameManager.Current, newName, CardGameManager.Current.DeckFileType); + newDeck.Cards.AddRange(CurrentDeck.Cards); + textOutputArea.text = newDeck.ToString(); + } - public void AttemptSaveAndHide() - { - Deck filePathFinder = new Deck(nameInputField.text, CardGameManager.Current.DeckFileType); - if (!DoesAutoOverwrite && File.Exists(filePathFinder.FilePath)) - CardGameManager.Instance.Messenger.Prompt(OverWriteDeckPrompt, SaveToFile); - else - SaveToFile(); + public void CopyTextToClipboard() + { + UniClipboard.SetText(textOutputArea.text); + CardGameManager.Instance.Messenger.Show(DeckCopiedMessage); + } - Hide(); - } + public void AttemptSaveAndHide() + { + Deck filePathFinder = new Deck(CardGameManager.Current, nameInputField.text, CardGameManager.Current.DeckFileType); + if (!DoesAutoOverwrite && File.Exists(filePathFinder.FilePath)) + CardGameManager.Instance.Messenger.Prompt(OverWriteDeckPrompt, SaveToFile); + else + SaveToFile(); - public void SaveToFile() - { - CurrentDeck.Name = nameInputField.text; - SaveToFile(CurrentDeck, DeckSaveCallback); - } + Hide(); + } - public static void SaveToFile(Deck deck, OnDeckSavedDelegate deckSaveCallback = null) - { - try + public void SaveToFile() { - if (!Directory.Exists(CardGameManager.Current.DecksFilePath)) - Directory.CreateDirectory(CardGameManager.Current.DecksFilePath); - File.WriteAllText(deck.FilePath, deck.ToString()); + CurrentDeck.Name = nameInputField.text; + SaveToFile(CurrentDeck, DeckSaveCallback); } - catch (Exception e) + + public static void SaveToFile(Deck deck, OnDeckSavedDelegate deckSaveCallback = null) { - Debug.LogError(DeckSaveErrorMessage + e.Message); + try + { + if (!Directory.Exists(CardGameManager.Current.DecksFilePath)) + Directory.CreateDirectory(CardGameManager.Current.DecksFilePath); + File.WriteAllText(deck.FilePath, deck.ToString()); + } + catch (Exception e) + { + Debug.LogError(DeckSaveErrorMessage + e.Message); + } + deckSaveCallback?.Invoke(deck); } - deckSaveCallback?.Invoke(deck); - } - public void CancelAndHide() - { - NameChangeCallback?.Invoke(CurrentDeck.Name); - Hide(); - } + public void CancelAndHide() + { + NameChangeCallback?.Invoke(CurrentDeck.Name); + Hide(); + } - public void Hide() - { - gameObject.SetActive(false); + public void Hide() + { + gameObject.SetActive(false); + } } } diff --git a/Assets/Scripts/CGS/Menus/DiceMenu.cs b/Assets/Scripts/CGS/Menus/DiceMenu.cs index a14f13d9e..9d90f8e44 100644 --- a/Assets/Scripts/CGS/Menus/DiceMenu.cs +++ b/Assets/Scripts/CGS/Menus/DiceMenu.cs @@ -1,95 +1,98 @@ -using UnityEngine; +using CGS.Play; +using UnityEngine; using UnityEngine.UI; -public class DiceMenu : MonoBehaviour +namespace CGS.Menus { - public const int DefaultMin = 1; - public const int DefaultMax = 6; - - public GameObject diePrefab; - public Text minText; - public Text maxText; + public class DiceMenu : MonoBehaviour + { + public const int DefaultMin = 1; + public const int DefaultMax = 6; - protected RectTransform Target { get; set; } + public GameObject diePrefab; + public Text minText; + public Text maxText; - private int _min; - private int _max; + public int Min + { + get { return _min; } + set + { + _min = value; + minText.text = _min.ToString(); + } + } + private int _min; - void Start() - { - Min = DefaultMin; - Max = DefaultMax; - } + public int Max + { + get { return _max; } + set + { + _max = value; + maxText.text = _max.ToString(); + } + } + private int _max; - void LateUpdate() - { - if (!Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) - return; + protected RectTransform Target { get; set; } - if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) - CreateAndHide(); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - Hide(); - } + void Start() + { + Min = DefaultMin; + Max = DefaultMax; + } - public void Show(RectTransform playArea) - { - gameObject.SetActive(true); - transform.SetAsLastSibling(); - Target = playArea; - } + void LateUpdate() + { + if (!Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) + return; - public void DecrementMin() - { - Min--; - } + if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) + CreateAndHide(); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + Hide(); + } - public void IncrementMin() - { - Min++; - } + public void Show(RectTransform playArea) + { + gameObject.SetActive(true); + transform.SetAsLastSibling(); + Target = playArea; + } - public void DecrementMax() - { - Max--; - } + public void DecrementMin() + { + Min--; + } - public void IncrementMax() - { - Max++; - } + public void IncrementMin() + { + Min++; + } - public void CreateAndHide() - { - Die die = Instantiate(diePrefab, Target.parent).GetOrAddComponent(); - die.transform.SetParent(Target); - die.Min = Min; - die.Max = Max; - Hide(); - } + public void DecrementMax() + { + Max--; + } - public void Hide() - { - gameObject.SetActive(false); - } + public void IncrementMax() + { + Max++; + } - public int Min - { - get { return _min; } - set + public void CreateAndHide() { - _min = value; - minText.text = _min.ToString(); + Die die = Instantiate(diePrefab, Target.parent).GetOrAddComponent(); + die.transform.SetParent(Target); + die.Min = Min; + die.Max = Max; + Hide(); } - } - public int Max - { - get { return _max; } - set + public void Hide() { - _max = value; - maxText.text = _max.ToString(); + gameObject.SetActive(false); } } } diff --git a/Assets/Scripts/CGS/Menus/GameSelectionMenu.cs b/Assets/Scripts/CGS/Menus/GameSelectionMenu.cs index 574cda591..67837196f 100644 --- a/Assets/Scripts/CGS/Menus/GameSelectionMenu.cs +++ b/Assets/Scripts/CGS/Menus/GameSelectionMenu.cs @@ -6,164 +6,163 @@ using UnityEngine.EventSystems; using UnityEngine.UI; -public class GameSelectionMenu : SelectionPanel +namespace CGS.Menus { - public const string DeleteMessage = "Please download additional card games before deleting."; - public const string DeletePrompt = "Deleting a card game also deletes all decks saved for that card game. Are you sure you would like to delete this card game?"; - public const string DominoesUrl = "https://cardgamesim.finoldigital.com/games/Dominoes/Dominoes.json"; - public const string StandardUrl = "https://cardgamesim.finoldigital.com/games/Standard/Standard.json"; - public const string MahjongUrl = "https://cardgamesim.finoldigital.com/games/Mahjong/Mahjong.json"; - - public RectTransform downloadPanel; - public InputField urlInput; - public Button cancelButton; - public Button downloadButton; - - void Update() + public class GameSelectionMenu : SelectionPanel { - if (urlInput.isFocused || !Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) - return; - - if (downloadPanel.gameObject.activeSelf) - { - if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && downloadButton.interactable) - StartDownload(); - else if ((Input.GetButtonDown(Inputs.New) || Input.GetButtonDown(Inputs.Load)) && urlInput.interactable) - Clear(); - else if (Input.GetButtonDown(Inputs.Save) && urlInput.interactable) - Paste(); - else if (Input.GetButtonDown(Inputs.FocusName) && urlInput.interactable) - urlInput.ActivateInputField(); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - HideDownloadPanel(); - } - else - { - if (Input.GetKeyDown(Inputs.BluetoothReturn) && Toggles.Contains(EventSystem.current.currentSelectedGameObject)) - EventSystem.current.currentSelectedGameObject.GetComponent().isOn = true; - else if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) - Hide(); - else if (Input.GetButtonDown(Inputs.Sort)) - Share(); - else if (Input.GetButtonDown(Inputs.New) || Input.GetButtonDown(Inputs.Load)) - ShowDownloadPanel(); - else if (Input.GetButtonDown(Inputs.Delete)) - Delete(); - else if (Input.GetButtonDown(Inputs.Horizontal)) + public const string DeleteMessage = "Please download additional card games before deleting."; + public const string DeletePrompt = "Deleting a card game also deletes all decks saved for that card game. Are you sure you would like to delete this card game?"; + public const string DominoesUrl = "https://cardgamesim.finoldigital.com/games/Dominoes/Dominoes.json"; + public const string StandardUrl = "https://cardgamesim.finoldigital.com/games/Standard/Standard.json"; + public const string MahjongUrl = "https://cardgamesim.finoldigital.com/games/Mahjong/Mahjong.json"; + + public RectTransform downloadPanel; + public InputField urlInput; + public Button downloadButton; + + void Update() + { + if (urlInput.isFocused || !Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) + return; + + if (downloadPanel.gameObject.activeSelf) { - if (Input.GetAxis(Inputs.Horizontal) < 0) - CardGameManager.Instance.SelectLeft(); - else - CardGameManager.Instance.SelectRight(); - Rebuild(CardGameManager.Instance.AllCardGames.Keys.ToList(), SelectGame, CardGameManager.Current.Name); + if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && downloadButton.interactable) + StartDownload(); + else if ((Input.GetButtonDown(Inputs.New) || Input.GetButtonDown(Inputs.Load)) && urlInput.interactable) + Clear(); + else if (Input.GetButtonDown(Inputs.Save) && urlInput.interactable) + Paste(); + else if (Input.GetButtonDown(Inputs.FocusName) && urlInput.interactable) + urlInput.ActivateInputField(); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + HideDownloadPanel(); + } + else + { + if (Input.GetKeyDown(Inputs.BluetoothReturn) && Toggles.Contains(EventSystem.current.currentSelectedGameObject)) + EventSystem.current.currentSelectedGameObject.GetComponent().isOn = true; + else if (Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) + Hide(); + else if (Input.GetButtonDown(Inputs.Sort)) + Share(); + else if (Input.GetButtonDown(Inputs.New) || Input.GetButtonDown(Inputs.Load)) + ShowDownloadPanel(); + else if (Input.GetButtonDown(Inputs.Delete)) + Delete(); + else if (Input.GetButtonDown(Inputs.Horizontal)) + { + if (Input.GetAxis(Inputs.Horizontal) < 0) + CardGameManager.Instance.SelectLeft(); + else + CardGameManager.Instance.SelectRight(); + Rebuild(CardGameManager.Instance.AllCardGames.Keys.ToList(), SelectGame, CardGameManager.Current.Name); + } + else if (Input.GetButtonDown(Inputs.Vertical)) + ScrollToggles(Input.GetAxis(Inputs.Vertical) > 0); + else if (Input.GetButtonDown(Inputs.Page)) + ScrollPage(Input.GetAxis(Inputs.Page) < 0); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + Hide(); } - else if (Input.GetButtonDown(Inputs.Vertical)) - ScrollToggles(Input.GetAxis(Inputs.Vertical) > 0); - else if (Input.GetButtonDown(Inputs.Page)) - ScrollPage(Input.GetAxis(Inputs.Page) < 0); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - Hide(); } - } - public void Show() - { - gameObject.SetActive(true); - transform.SetAsLastSibling(); - Rebuild(CardGameManager.Instance.AllCardGames.Keys.ToList(), SelectGame, CardGameManager.Current.Name); - } - - public void SelectGame(bool isOn, string gameName) - { - if (isOn) + public void Show() { gameObject.SetActive(true); - CardGameManager.Instance.SelectCardGame(gameName); + transform.SetAsLastSibling(); + Rebuild(CardGameManager.Instance.AllCardGames.Keys.ToList(), SelectGame, CardGameManager.Current.Name); } - else - Hide(); - } - public void Share() - { - CardGameManager.Instance.Messenger.Show("Share functionality is coming soon."); - } + public void SelectGame(Toggle toggle, string gameName) + { + if (toggle.isOn) + CardGameManager.Instance.SelectCardGame(gameName); + else if (!toggle.group.AnyTogglesOn()) + Hide(); + } - public void Delete() - { - if (CardGameManager.Instance.AllCardGames.Count > 1) - CardGameManager.Instance.Messenger.Prompt(DeletePrompt, CardGameManager.Instance.DeleteGame); - else - CardGameManager.Instance.Messenger.Show(DeleteMessage); - } + public void Share() + { + CardGameManager.Instance.Messenger.Show("Share functionality is coming soon."); + } - public void ShowDownloadPanel() - { - downloadPanel.gameObject.SetActive(true); - } + public void Delete() + { + if (CardGameManager.Instance.AllCardGames.Count > 1) + CardGameManager.Instance.Messenger.Prompt(DeletePrompt, CardGameManager.Instance.DeleteGame); + else + CardGameManager.Instance.Messenger.Show(DeleteMessage); + } - public void ApplyDominoes() - { - if (urlInput.interactable) - urlInput.text = DominoesUrl; - } + public void ShowDownloadPanel() + { + downloadPanel.gameObject.SetActive(true); + } - public void ApplyStandard() - { - if (urlInput.interactable) - urlInput.text = StandardUrl; - } + public void ApplyDominoes() + { + if (urlInput.interactable) + urlInput.text = DominoesUrl; + } - public void ApplyMahjong() - { - if (urlInput.interactable) - urlInput.text = MahjongUrl; - } + public void ApplyStandard() + { + if (urlInput.interactable) + urlInput.text = StandardUrl; + } - public void Paste() - { - if (urlInput.interactable) - urlInput.text = UniClipboard.GetText(); - } + public void ApplyMahjong() + { + if (urlInput.interactable) + urlInput.text = MahjongUrl; + } - public void Clear() - { - urlInput.text = string.Empty; - } + public void Paste() + { + if (urlInput.interactable) + urlInput.text = UniClipboard.GetText(); + } - public void CheckDownloadUrl(string url) - { - downloadButton.interactable = System.Uri.IsWellFormedUriString(url.Trim(), System.UriKind.Absolute); - } + public void Clear() + { + urlInput.text = string.Empty; + } - public void StartDownload() - { - CardGameManager.Instance.StartCoroutine(DownloadGame()); - } + public void CheckDownloadUrl(string url) + { + downloadButton.interactable = System.Uri.IsWellFormedUriString(url.Trim(), System.UriKind.Absolute); + } - public IEnumerator DownloadGame() - { - string gameUrl = urlInput.text.Trim(); + public void StartDownload() + { + CardGameManager.Instance.StartCoroutine(DownloadGame()); + } - urlInput.text = string.Empty; - urlInput.interactable = false; - cancelButton.interactable = false; + public IEnumerator DownloadGame() + { + string gameUrl = urlInput.text.Trim(); - yield return CardGameManager.Instance.DownloadCardGame(gameUrl); + urlInput.text = string.Empty; + urlInput.interactable = false; + cancelButton.interactable = false; - cancelButton.interactable = true; - urlInput.interactable = true; - HideDownloadPanel(); - } + yield return CardGameManager.Instance.DownloadCardGame(gameUrl); - public void HideDownloadPanel() - { - Show(); - downloadPanel.gameObject.SetActive(false); - } + cancelButton.interactable = true; + urlInput.interactable = true; + HideDownloadPanel(); + } - public void Hide() - { - gameObject.SetActive(false); + public void HideDownloadPanel() + { + Show(); + downloadPanel.gameObject.SetActive(false); + } + + public void Hide() + { + gameObject.SetActive(false); + } } } diff --git a/Assets/Scripts/CGS/Menus/LobbyMenu.cs b/Assets/Scripts/CGS/Menus/LobbyMenu.cs index 769632c1d..90566131a 100644 --- a/Assets/Scripts/CGS/Menus/LobbyMenu.cs +++ b/Assets/Scripts/CGS/Menus/LobbyMenu.cs @@ -1,104 +1,113 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using CGS.Play.Multiplayer; using UnityEngine; +using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.Networking; using UnityEngine.UI; -public class LobbyMenu : SelectionPanel +namespace CGS.Menus { - public Button cancelButton; - public Button joinButton; - - public List HostNames { get; private set; } = new List(); - public string SelectedHost { get; private set; } = ""; - - void Update() + public class LobbyMenu : SelectionPanel { - if (!Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) - return; - - if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && joinButton.interactable) - Join(); - else if (Input.GetKeyDown(Inputs.BluetoothReturn) && Toggles.Contains(EventSystem.current.currentSelectedGameObject)) - EventSystem.current.currentSelectedGameObject.GetComponent().isOn = true; - else if (Input.GetButtonDown(Inputs.New)) - Host(); - else if (Input.GetButtonDown(Inputs.Vertical)) - ScrollToggles(Input.GetAxis(Inputs.Vertical) > 0); - else if (Input.GetButtonDown(Inputs.Page)) - ScrollPage(Input.GetAxis(Inputs.Page) < 0); - else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) - Hide(); - } + public Button joinButton; - public void Show() - { - gameObject.SetActive(true); - transform.SetAsLastSibling(); + public List HostNames { get; private set; } = new List(); + public string SelectedHost { get; private set; } = ""; - HostNames.Clear(); - SelectedHost = string.Empty; - Rebuild(HostNames, SelectHost, SelectedHost); + void Update() + { + if (!Input.anyKeyDown || gameObject != CardGameManager.TopMenuCanvas?.gameObject) + return; + + if ((Input.GetKeyDown(Inputs.BluetoothReturn) || Input.GetButtonDown(Inputs.Submit)) && joinButton.interactable) + Join(); + else if (Input.GetKeyDown(Inputs.BluetoothReturn) && Toggles.Contains(EventSystem.current.currentSelectedGameObject)) + EventSystem.current.currentSelectedGameObject.GetComponent().isOn = true; + else if (Input.GetButtonDown(Inputs.New)) + Host(); + else if (Input.GetButtonDown(Inputs.Vertical)) + ScrollToggles(Input.GetAxis(Inputs.Vertical) > 0); + else if (Input.GetButtonDown(Inputs.Page)) + ScrollPage(Input.GetAxis(Inputs.Page) < 0); + else if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown(Inputs.Cancel)) + Hide(); + } - CardGameManager.Instance.Discovery.lobby = this; - CardGameManager.Instance.Discovery.SearchForHost(); - } + public void Show(UnityAction cancelAction) + { + gameObject.SetActive(true); + transform.SetAsLastSibling(); - public void DisplayHosts(List hostNames) - { - if (hostNames == null || hostNames.Equals(HostNames)) - return; + cancelButton.onClick.RemoveAllListeners(); + cancelButton.onClick.AddListener(cancelAction); - HostNames.Clear(); - foreach (string hostname in hostNames) - HostNames.Add(hostname.Split(':').Last()); - if (!HostNames.Contains(SelectedHost)) - { + HostNames.Clear(); SelectedHost = string.Empty; - joinButton.interactable = false; - } + Rebuild(HostNames, SelectHost, SelectedHost); - Rebuild(HostNames, SelectHost, SelectedHost); - } + CardGameManager.Instance.Discovery.lobby = this; + CardGameManager.Instance.Discovery.SearchForHost(); + } - public void Host() - { - NetworkManager.singleton.StartHost(); - NetworkManager.singleton.StartCoroutine(WaitToShowDeckLoader()); - Hide(); - } + public void DisplayHosts(List hostNames) + { + if (hostNames == null || hostNames.Equals(HostNames)) + return; + + HostNames.Clear(); + foreach (string hostname in hostNames) + HostNames.Add(hostname.Split(':').Last()); + if (!HostNames.Contains(SelectedHost)) + { + SelectedHost = string.Empty; + joinButton.interactable = false; + } + + Rebuild(HostNames, SelectHost, SelectedHost); + } - public IEnumerator WaitToShowDeckLoader() - { - yield return null; - CGSNetManager.Instance.playController.ShowDeckMenu(); - } + public void Host(UnityAction cancelAction = null) + { + NetworkManager.singleton.StartHost(); + NetworkManager.singleton.StartCoroutine(WaitToShowDeckLoader(cancelAction)); + Hide(); + } - public void SelectHost(bool isOn, string hostName) - { - if (string.IsNullOrEmpty(hostName)) - return; + public IEnumerator WaitToShowDeckLoader(UnityAction cancelAction) + { + yield return null; + CGSNetManager.Instance.playController.ShowDeckMenu(); + CGSNetManager.Instance.playController.DeckLoader.cancelButton.onClick.RemoveAllListeners(); + CGSNetManager.Instance.playController.DeckLoader.cancelButton.onClick.AddListener(cancelAction); + } - if (isOn) + public void SelectHost(Toggle toggle, string hostName) { - SelectedHost = hostName; - joinButton.interactable = true; + if (string.IsNullOrEmpty(hostName)) + return; + + if (toggle.isOn) + { + SelectedHost = hostName; + joinButton.interactable = true; + } + else if (!toggle.group.AnyTogglesOn() && SelectedHost.Equals(hostName)) + Join(); } - else if (SelectedHost.Equals(hostName)) - Join(); - } - public void Join() - { - NetworkManager.singleton.networkAddress = SelectedHost; - NetworkManager.singleton.StartClient(); - Hide(); - } + public void Join() + { + NetworkManager.singleton.networkAddress = SelectedHost; + NetworkManager.singleton.StartClient(); + Hide(); + } - public void Hide() - { - gameObject.SetActive(false); + public void Hide() + { + gameObject.SetActive(false); + } } } diff --git a/Assets/Scripts/CGS/Menus/MainMenu.cs b/Assets/Scripts/CGS/Menus/MainMenu.cs index c3db2dc15..ca9e6498b 100644 --- a/Assets/Scripts/CGS/Menus/MainMenu.cs +++ b/Assets/Scripts/CGS/Menus/MainMenu.cs @@ -6,115 +6,118 @@ using UnityEngine.SceneManagement; using UnityEngine.UI; -public class MainMenu : MonoBehaviour +namespace CGS.Menus { - public const int MainMenuSceneIndex = 1; - public const int PlayModeSceneIndex = 2; - public const int DeckEditorSceneIndex = 3; - public const int OptionsMenuSceneIndex = 4; - public const string VersionMessage = "Ver. "; + public class MainMenu : MonoBehaviour + { + public const int MainMenuSceneIndex = 1; + public const int PlayModeSceneIndex = 2; + public const int DeckEditorSceneIndex = 3; + public const int OptionsMenuSceneIndex = 4; + public const string VersionMessage = "Ver. "; - public List buttons; - public GameObject quitButton; - public Text versionText; + public List buttons; + public GameObject quitButton; + public Text versionText; - void Start() - { + void Start() + { #if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR quitButton.SetActive(false); #endif - versionText.text = VersionMessage + Application.version; - - if (CardGameManager.Instance.Discovery.running) - CardGameManager.Instance.Discovery.StopBroadcast(); - CardGameManager.Instance.Discovery.HasReceivedBroadcast = false; - CardGameManager.Instance.Discovery.SearchForHost(); - } + versionText.text = VersionMessage + Application.version; - void Update() - { - if (!Input.anyKeyDown || CardGameManager.TopMenuCanvas != null) - return; + if (CardGameManager.Instance.Discovery.running) + CardGameManager.Instance.Discovery.StopBroadcast(); + CardGameManager.Instance.Discovery.HasReceivedBroadcast = false; + CardGameManager.Instance.Discovery.SearchForHost(); + } - if (Input.GetKeyDown(Inputs.BluetoothReturn)) - EventSystem.current.currentSelectedGameObject?.GetComponent