using System; using EscapeRoomEngine.Engine.Runtime.Measurements; using UnityEngine; using UnityEngine.UI; namespace EscapeRoomEngine.Engine.Runtime { public enum GameState { Stopped, Paused, Running } public class GameControl : MonoBehaviour { public static GameControl Instance { get { if (_foundGameControl == null) { _foundGameControl = FindObjectOfType(); } return _foundGameControl; } } private static GameControl _foundGameControl; [SerializeField] private Button startButton, stopButton, pauseButton, resumeButton, addMinuteButton, removeMinuteButton; [SerializeField] private Text timeText; [HideInInspector] public GameState gameState = GameState.Stopped; private float _timeElapsed; private void Start() { SetGamemasterTimeText(_timeElapsed); } private void Update() { // Update time if (gameState == GameState.Running) { _timeElapsed += Time.deltaTime; SetGamemasterTimeText(_timeElapsed); } // Enable or disable buttons startButton.interactable = gameState == GameState.Stopped; stopButton.interactable = gameState != GameState.Stopped; pauseButton.interactable = gameState == GameState.Running; resumeButton.interactable = gameState == GameState.Paused; addMinuteButton.interactable = gameState != GameState.Stopped; removeMinuteButton.interactable = gameState != GameState.Stopped && _timeElapsed >= 10; } #region Time Controls public void StartGame() { gameState = GameState.Running; _timeElapsed = 0; // generate the first room if it hasn't been generated yet Engine.DefaultEngine.CurrentRoom.Match(none: () => Engine.DefaultEngine.GenerateRoom()); // start a new session Measure.StartSession(); } public void StopGame() { if (gameState != GameState.Stopped) { // was running Measure.EndSession(_timeElapsed); } gameState = GameState.Stopped; } public void PauseGame() { gameState = GameState.Paused; } public void ResumeGame() { gameState = GameState.Running; } /// /// Change the allowed time by a specified amount of seconds. /// /// The amount of seconds that will be added to the time. Can be negative to remove time. public void ChangeTime(int seconds) { if (_timeElapsed + seconds >= 0) { _timeElapsed += seconds; } } private void SetGamemasterTimeText(float time) { if (timeText != null) { timeText.text = TimeToText(time); } } private static string TimeToText(float time) { var minutes = (int) (time / 60); var seconds = (int) Math.Ceiling(time - minutes * 60); if (seconds == 60) { minutes += 1; seconds = 0; } return $"{minutes:D2}:{seconds:D2}"; } #endregion public void ExitGame() { StopGame(); #if UNITY_STANDALONE Application.Quit(); #endif #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #endif } } }