Unity3D学习(一)井字棋

来源:互联网 发布:java executor 线程池 编辑:程序博客网 时间:2024/06/06 13:23

Unity3D编程的相关学习

实训终于结束了,可以有时间把前一段时间Unity3D的学习总结一下
在老师的建议下开通了博客,将前几次编程实践复习一下。
首先是一个简单的井字棋游戏:
一个简单的井字棋游戏

下面是代码实现(时间实在隔的有些远,就只贴代码了)

init_TTT.cs:

using System.Collections;using System.Collections.Generic;using UnityEngine;public class init_TTT : MonoBehaviour {    private int[,] plate =  new int[3,3];    private int click = 1;    // Use this for initialization    void Start () {        Debug.Log ("this is a Tic Tac Toe");        reset ();    }    void OnGUI() {        int result = check();        Debug.Log ("enter OnGUI");        if (result == 1) {            GUI.Label (new Rect (100, 220, 100, 50), "X wins");            Debug.Log ("X wins");            //reset ();        }        else if (result == 2) {            GUI.Label (new Rect (100, 220, 100, 50), "O wins");            Debug.Log ("O wins");            //reset ();        }        if (GUI.Button (new Rect (75, 250, 100, 50), "Reset")) {            Debug.Log ("Reset button clicked");            reset ();        }        for (int i = 0; i < 3; i++) {            for (int j = 0; j < 3; j++) {                if (plate[i, j] == 1) {                    GUI.Button (new Rect (50 * (i + 1), 50 * (j + 1), 50, 50), "X");                }                if (plate[i, j] == 2) {                    GUI.Button (new Rect (50 * (i + 1), 50 * (j + 1), 50, 50), "O");                }                if (GUI.Button (new Rect (50*(i+1), 50*(j+1), 50, 50), "")) {                    if (click == 1) {                        plate [i, j] = 1;                    }                    if (click == -1) {                        plate [i, j] = 2;                    }                    click = -click;                }            }        }    }    void reset() {        Debug.Log ("a fake reset");        for (int i = 0; i < 3; i++) {            for (int j = 0; j < 3; j++) {                plate [i, j] = 0;            }        }    }    int check() {        for (int i = 0; i < 3; i++) {            if (plate [i, 0] != 0 && plate [i, 0] == plate [i, 1] && plate [i, 1] == plate [i, 2]) {                return plate [i, 0];            }        }        for (int j = 0; j < 3; j++) {            if (plate [0, j] != 0 && plate [1, j] == plate [0, j] && plate [1, j] == plate [2, j]) {                return plate [0, j];            }        }        if (plate [1, 1] != 0 &&            plate [0, 0] == plate [1, 1] && plate [1, 1] == plate [2, 2] ||            plate [0, 2] == plate [1, 1] && plate [1, 1] == plate [2, 0]) {            return plate [1, 1];        }        return 0;    }    // Update is called once per frame    void Update () {    }}

再将这段代码挂载在一个空对象上,点击运行就可以啦!

0 0