今天写了个扫雷游戏,程序有bug,当失败后游戏并不能停下来,以下是源码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SaoLei : MonoBehaviour
{
int count = 0;
public bool flag = false;
Texture2D t;
Diamonds[,] dia = new Diamonds[10,10];
Point[] point = new Point[10];
void Start ()
{
Init();
}
void Init()
{
t = new Texture2D(50,50);
t = (Texture2D)Resources.Load("lei");
for(int i = 0;i<10;i++) //初始化10*10方格.
{
point[i] = new Point();
for(int j = 0;j<10;j++)
{
dia[i,j]=new Diamonds();
dia[i,j].rect = new Rect(j*50,i*50,50,50);
}
}
for(int i = 0;i<10;i++)
{
point[i].x = Random.Range(0,10);
point[i].y = Random.Range(0,10);
for(int k = 0;k<i;k++)
{
if(point[i].x == point[k].x && point[i].y == point[k].y)
{
i--;
break;
}
}
dia[point[i].x,point[i].y].number = 9;
Print(point[i].x,point[i].y);
}
}
public void Print(int x,int y)
{
for(int i = x-1;i <= x+1;i++)
{
for(int j = y-1;j <= y+1;j++)
{
if(i>=0&&i<=9&&j>=0&&j<=9&&dia[i,j].number!=9)
{
dia[i,j].number++;
}
}
}
}
void Update ()
{
}
void OnGUI()
{
for(int i = 0;i<10;i++)
{
for(int j = 0;j<10;j++)
{
if(GUI.Button(dia[i,j].rect,""))
{
if(dia[i,j].number == 0)
{
Show(i,j);
}
dia[i,j].show = true;
if(dia[i,j].number == 9)
{
flag = true;
}
}
if(dia[i,j].show)
{
if(dia[i,j].number != 9)
{
GUI.Button(dia[i,j].rect,dia[i,j].number.ToString());
}
else
{
GUI.Button(dia[i,j].rect,t);
}
}
if(flag)
{
GUI.Button(new Rect(550,200,200,50),"You are fail");
if(GUI.Button(new Rect(550,500,200,50),"Again?"))
{
Init();
flag = false;
}
}
}
}
foreach(Diamonds data in dia)
{
if(data.show == false)
{
count++;
}
}
if(count == 10)
{
GUI.Button(new Rect(550,200,200,50),"You are success");
if(GUI.Button(new Rect(550,500,200,50),"Again?"))
{
Init();
count = 0;
}
}
count = 0;
}
void Show(int i,int j)
{
for(int m = i-1;m<=i+1;m++)
{
for(int n = j-1;n<=j+1;n++)
{
if(m>=0 &&m <=9 && n>=0 && n<=9 && dia[m,n].show == false)
{
dia[m,n].show = true;
if(dia[m,n].number == 0)
{
Show(m,n);
}
}
}
}
}
}
public class Diamonds
{
public int number = 0;
public Rect rect;
public bool show = false;
}
public class Point
{
public int x;
public int y;
}