unity-towers-of-hanoi/Assets/Controls.cs

149 lines
4.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Controls : MonoBehaviour
{
public Light control;
public GameObject column1;
public GameObject column2;
public GameObject column3;
private List<GameObject> columns;
public GameObject selectedDisc;
public List<GameObject> discs;
public GameObject winnerMessage;
// Start is called before the first frame update
void Start()
{
this.columns = new List<GameObject> { this.column1, this.column2, this.column3 };
this.ResetGame();
}
void ResetGame()
{
this.winnerMessage.SetActive(false);
List<GameObject> reversedDiscs = this.discs;
reversedDiscs.Reverse();
int i = 1;
foreach (GameObject disc in reversedDiscs)
{
this.column1.GetComponent<Cylinder>().discs.Add(disc);
i++;
}
this.column1.GetComponent<Cylinder>().selected = true;
this.column2.GetComponent<Cylinder>().selected = false;
this.column3.GetComponent<Cylinder>().selected = false;
this.selectedDisc = null;
}
GameObject GetSelectedColumn()
{
if (this.column1.GetComponent<Cylinder>().selected)
{
return this.column1;
}
if (this.column2.GetComponent<Cylinder>().selected)
{
return this.column2;
}
return this.column3;
}
void RenderDisc()
{
if (this.selectedDisc)
{
this.selectedDisc.transform.position = this.control.transform.position;
}
}
void CheckGameFinished()
{
if (this.IsGameFinished())
{
this.winnerMessage.SetActive(true);
}
}
bool IsGameFinished() {
if (this.selectedDisc) return false;
foreach (GameObject column in this.columns.GetRange(1, 2))
{
if (column.GetComponent<Cylinder>().discs.Count == this.discs.Count)
{
return true;
}
}
return false;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp("r"))
{
SceneManager.LoadScene("Main");
}
if (this.IsGameFinished())
{
return;
}
this.RenderDisc();
GameObject selectedColumn = this.GetSelectedColumn();
if (Input.GetKeyUp("a") && selectedColumn != this.column1)
{
selectedColumn.GetComponent<Cylinder>().selected = false;
if (selectedColumn == this.column3)
{
this.column2.GetComponent<Cylinder>().selected = true;
}
else
{
this.column1.GetComponent<Cylinder>().selected = true;
}
}
if (Input.GetKeyUp("d") && selectedColumn != this.column3)
{
selectedColumn.GetComponent<Cylinder>().selected = false;
if (selectedColumn == this.column1)
{
this.column2.GetComponent<Cylinder>().selected = true;
} else
{
this.column3.GetComponent<Cylinder>().selected = true;
}
}
if (Input.GetKeyUp("w") && !this.selectedDisc)
{
this.selectedDisc = selectedColumn.GetComponent<Cylinder>().GetTopDisc();
}
if (Input.GetKeyUp("s") && this.selectedDisc != null)
{
if (selectedColumn.GetComponent<Cylinder>().CanPutDisc(this.selectedDisc)) {
selectedColumn.GetComponent<Cylinder>().discs.Add(this.selectedDisc);
this.selectedDisc = null;
this.CheckGameFinished();
}
}
if (Input.GetKeyUp("r"))
{
this.ResetGame();
}
}
}