using System;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Controller : MonoBehaviour
{
Button[,] buttons;
Image[] images;
GAME game;
void Start()
{
game = new GAME(ShowBox);
InitButtons();
InitImage();
ShowBox(1, 1, 1);
ShowBox(1, 2, 1);
ShowBox(1, 3, 1);
ShowBox(1, 4, 1);
ShowBox(2, 5, 1);
ShowBox(3, 3, 1);
ShowBox(3, 4, 1);
ShowBox(4, 5, 1);
ShowBox(5, 1, 1);
ShowBox(5, 2, 1);
ShowBox(5, 3, 1);
ShowBox(5, 4, 1);
game.Start();
}
public void ShowBox(int x, int y, int cube)
{
buttons[x, y].GetComponent<Image>().sprite = images[cube].sprite;
}
public void Click()
{
string name = EventSystem.current.currentSelectedGameObject.name;
int nr = GetNumber(name);
int x = nr % GAME.SIZE;
int y = nr / GAME.SIZE;
Debug.Log($"clicked {name} {x} {y}");
game.Click(x, y);
}
private void InitButtons()
{
buttons = new Button[GAME.SIZE, GAME.SIZE];
for (int nr = 0; nr < GAME.SIZE * GAME.SIZE; nr++)
buttons[nr % GAME.SIZE, nr / GAME.SIZE] = GameObject.Find($"Button ({nr})").GetComponent<Button>();
}
private void InitImage()
{
images = new Image[GAME.CUBE];
for (int j = 0; j < GAME.CUBE; j++)
images[j] = GameObject.Find($"Image ({j})").GetComponent<Image>();
}
private int GetNumber(string name)
{
Regex regex = new Regex("\\((\\d+)\\)");
Match match = regex.Match(name);
if (!match.Success)
throw new System.Exception("Unrecognized object name");
Group group = match.Groups[1];
string number = group.Value;
return Convert.ToInt32(number);
}
}