Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class TicTacToe : MonoBehaviour {
- public TicTacToeCell cell;
- bool isPlayerTurnRed;
- bool inGame;
- private TicTacToeCell[,] cells;
- private void Start() {
- cells = new TicTacToeCell[3, 3];
- inGame = true;
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- cells[i, j] = Instantiate(cell, new Vector3(i, j, 0), Quaternion.identity);
- cells[i, j].Init(this, i, j);
- }
- }
- }
- public void CellPressed(int x, int y) {
- if (!inGame) {
- return;
- }
- cells[x, y].Claim(isPlayerTurnRed);
- isPlayerTurnRed = !isPlayerTurnRed;
- int[] lines = new int[8];
- lines[0] = cells[0, 0].GetNumber() + cells[1, 0].GetNumber() + cells[2, 0].GetNumber();
- lines[1] = cells[0, 1].GetNumber() + cells[1, 1].GetNumber() + cells[2, 1].GetNumber();
- lines[2] = cells[0, 2].GetNumber() + cells[1, 2].GetNumber() + cells[2, 2].GetNumber();
- lines[3] = cells[0, 0].GetNumber() + cells[0, 1].GetNumber() + cells[0, 2].GetNumber();
- lines[4] = cells[1, 0].GetNumber() + cells[1, 1].GetNumber() + cells[1, 2].GetNumber();
- lines[5] = cells[2, 0].GetNumber() + cells[2, 1].GetNumber() + cells[2, 2].GetNumber();
- lines[6] = cells[0, 0].GetNumber() + cells[1, 1].GetNumber() + cells[2, 2].GetNumber();
- lines[7] = cells[2, 0].GetNumber() + cells[1, 1].GetNumber() + cells[0, 2].GetNumber();
- for (int i = 0; i < 8; i++) {
- if (lines[i] == 3) {
- Debug.Log("Red Player WIN!");
- inGame = false;
- } else if (lines[i] == -3) {
- Debug.Log("Green Player WIN!");
- inGame = false;
- }
- }
- if (!HasZero()) {
- Debug.Log("Tie!");
- inGame = false;
- }
- }
- private bool HasZero() {
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- if (cells[i, j].GetNumber() == 0) {
- return true;
- }
- }
- }
- return false;
- }
- private void Update() {
- if (Input.GetKeyDown(KeyCode.R)) {
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- cells[i, j].Restart();
- inGame = true;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement