天天看點

Unity 3D遊戲開發學習筆記(1) 井字棋

第一次用Unity 3D寫遊戲,做了個井字棋。

Unity 3D遊戲開發學習筆記(1) 井字棋

由于不熟悉onGUI()和C#,參考了師兄的筆記。

代碼實際上很簡單,邏輯也簡單,主要是通過這個小遊戲來熟悉一下Unity 3D的一些基本操作實作,比如OnGUI()的原理,實際上這裡面的Button并不是點選觸發的效果,而是每一幀都在發生改變,是以這裡Button實際上是不斷重疊制造的吧。(顯然變深色了),我感覺這樣的做法不太好,但暫時不知道怎麼去更好實作,就先這樣了。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TicTacToe: MonoBehaviour {
    int turn = ;
    int [,]state = new int[,];
    void Start () {
        Reset();
    }

    void Update () { }

    void OnGUI() {
        if (GUI.Button(new Rect(,,,), "Start Game")) {
            Reset();
        }
        int current = Check();
        if (current == ) GUI.Label(new Rect(,,,),"O wins!");
        if (current == ) GUI.Label(new Rect(,,,),"X wins!");
        if (current == ) GUI.Label(new Rect(,,,),"Tied!");
        for (int i = ; i < ; i++) {
            for (int j = ; j < ; j++) {
                if (state[i, j] == ) {
                    GUI.Button(new Rect(+*i,+*j,,), "O");
                } else if (state[i, j] == ) {
                    GUI.Button(new Rect(+*i,+*j,,), "X");
                } 
                if (GUI.Button(new Rect(+*i,+*j,,), "")) {
                    if (current == ) {
                        if (turn == ) state[i, j] = ;
                        if (turn == -) state[i, j] = ;
                        turn *= -;
                    }
                }
            }
        }
    }

    int Check() {
        for (int i = ; i < ; i++) {
            if (state[i, ] == state[i, ] && state[i, ] == state[i, ] && state[i, ] != ) {
                return state[i, ];
            }
        }

        for (int j = ; j < ; j++) {
            if (state[, j] == state[, j] && state[, j] == state[, j] && state[, j] != ) {
                return state[, j];
            }
        }

        if (state[, ] !=  && state[, ] == state[, ] && state[, ] == state[, ]) {
            return state[, ];
        }

        if (state[, ] !=  && state[, ] == state[, ] && state[, ] == state[, ]) {
            return state[, ];
        }

        for (int i = ; i < ; i++) {
            for (int j = ; j < ; j++) {
                if (state[i, j] == ) return ;
            }
        }

        return ;
    }

    void Reset() {
        turn = ;
        for (int i = ; i < ; i++) {
            for (int j = ; j < ; j++) {
                state[i, j] = ;
            }
        }
    }
}
           

繼續閱讀