using System; using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class CableMiniGame : MonoBehaviour, ITask { [System.Serializable] public class Cable { public string colorName; public Button sourceButton; public Button targetButton; public Image cableImage; [HideInInspector] public bool connected; } public string TaskID { get; set; } public TaskType TaskType { get; set; } public string TaskName { get; set; } public (double, double) TaskLocation { get; set; } public bool IsCompleted { get; private set; } private Action _onCompleted; private Action _onExit; [Header("MiniGame Settings")] public Cable[] cables; public string previousSceneName; public Color wrongAttemptColor = Color.white; public float blinkDuration = 0.2f; private string selectedColor = null; public void Initialize(Action onCompleted) { IsCompleted = false; _onCompleted = onCompleted; foreach (var cable in cables) cable.connected = false; } public void Complete() { if (IsCompleted) return; IsCompleted = true; _onCompleted?.Invoke(this); ExitTask(_onExit); } public void ExitTask(Action onExit) { onExit?.Invoke(this); } void Start() { foreach (var cable in cables) { Cable localCable = cable; cable.sourceButton.onClick.AddListener(() => OnSourceClicked(localCable)); cable.targetButton.onClick.AddListener(() => OnTargetClicked(localCable)); } } void OnSourceClicked(Cable cable) { if (cable.connected) return; selectedColor = cable.colorName; } void OnTargetClicked(Cable cable) { if (selectedColor == null || cable.connected) return; if (selectedColor == cable.colorName) { cable.cableImage.color = GetColorFromName(selectedColor); cable.connected = true; CheckCompletion(); } else { StartCoroutine(BlinkAndExit(cable.cableImage)); } selectedColor = null; } void CheckCompletion() { foreach (var cable in cables) { if (!cable.connected) return; } Complete(); } Color GetColorFromName(string name) { switch (name.ToLower()) { case "red": return Color.red; case "blue": return Color.blue; case "green": return Color.green; case "yellow": return Color.yellow; case "purple": return new Color(0.5f, 0, 0.5f); default: return Color.white; } } IEnumerator BlinkAndExit(Image img) { Color original = img.color; img.color = wrongAttemptColor; yield return new WaitForSeconds(blinkDuration); img.color = original; ExitTask(_onExit); SceneManager.LoadScene(previousSceneName); } }