using System;
using UnityEngine;
///
/// Behaviour to show the amount of bombs left
///
public class BombNumberScript : MonoBehaviour {
#region Types
///
/// Digit number X from a number where the rightmost is considered as the first
///
public enum EDigit {
First,
Second,
Third
}
#endregion
#region Fields
///
/// Which digit this script is attached to
///
public EDigit Digit;
///
/// The collection of all the number sprites (must be ordered)
///
public Sprite[] NumberSprites;
private int _number;
private ControlScript _parent;
private bool _leftDown, _rightDown;
#endregion
#region Properties
///
/// The control script of the game
///
public ControlScript Parent {
set { _parent = value; }
}
#endregion
#region Unity events
///
/// LateUpdate is called at the end of every frame.
///
void LateUpdate() {
if (Input.GetMouseButtonUp(0))
_leftDown = false;
if (Input.GetMouseButtonUp(1))
_rightDown = false;
}
///
/// OnMouseOver is called every frame as long as the mouse is hovering over this objects bounding box
///
void OnMouseOver() {
if (_parent.GameState != EGameState.Uninitialized)
return;
if (Input.GetMouseButtonDown(0))
_leftDown = true;
if (Input.GetMouseButtonUp(0) && _leftDown)
_parent.OnBombNumberClick(Digit);
if (Input.GetMouseButtonDown(1))
_rightDown = true;
if (Input.GetMouseButtonUp(1) && _rightDown)
_parent.OnBombNumberRightClick(Digit);
}
#endregion
#region Methods
///
/// Sets the number for this digit based on the total amount of bombs
///
///
public void SetNumber(int number) {
_number = number;
ChangeSprite();
}
#endregion
#region Helper methods
///
/// Updates the sprite so that it matches the number.
///
///
/// This works for whatever number was given. Negative numbers are set to 9 so that it easily loops:
///
/// 1 -> 2 -> ... -> 9 -> 0 -> 1 -> ...
/// 2 -> 1 -> 0 -> 9 -> 8 -> ...
///
///
private void ChangeSprite() {
int index;
switch (Digit) {
case EDigit.First:
index = Math.Abs(_number) % 10;
break;
case EDigit.Second:
if (-10 < _number && _number < 0)
index = 10;
else
index = (Math.Abs(_number) / 10) % 10;
break;
case EDigit.Third:
if (-100 < _number && _number < -9)
index = 10;
else
index = Math.Abs(_number) / 100;
break;
default:
throw new ArgumentOutOfRangeException();
}
GetComponent().sprite = NumberSprites[index];
// set layer to 5
GetComponent().sortingOrder = 5;
}
#endregion
}