目录
前言
这是中山大学软件工程学院2023年3D游戏编程与设计的第三次作业,也欢迎大家学习参考交流
github个人主页: innitinnit (github.com)
游戏效果展示:
游戏规则:
在4*4的方格中将随机出现O,点击后O消失,玩家得1分,得10分者获胜。若在规定时间内未点击O,则判定玩家失败,游戏结束。
代码展示:
使用了MVC结构进行划分
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//1
public class hitTheMole : MonoBehaviour
{
// Entities and their states / Model
private bool[,] grid = new bool[4, 4];
private float timer = 0f;
private int score = 0;
private bool gameOver = false;
private bool clickedOnMole = false;
private int ifWin = 0;
// System Handlers
void Start()
{
Init();
}
private void Update()
{
if (!gameOver)
{
timer += Time.deltaTime;
if (timer >= 1f)
{
timer = 0f;
if (!clickedOnMole)
{
gameOver = true;
ifWin = 2;
}
clickedOnMole = false;
GenerateRandomMole();
}
}
}
//2
// View to render entities / models
private void OnGUI()
{
if (ifWin == 1 && gameOver)
{
GUI.Label(new Rect(10, 10, 100, 20), "You win!");
return;
}
if (ifWin == 2 && gameOver)
{
GUI.Label(new Rect(10, 10, 100, 20), "You lose!");
return;
}
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
string label = grid[row, col] ? "O" : "";
if (GUI.Button(new Rect(10 + col * 70, 40 + row * 70, 60, 60), label))
{
if (grid[row, col])
{
grid[row, col] = false;
timer = 0f;
score++;
clickedOnMole = true;
if (score >= 10)
{
gameOver = true;
ifWin = 1;
}
}
}
}
}
GUI.Label(new Rect(10, 10, 100, 20), "Score: " + score);
}
//3
// Components /controls
private void Init()
{
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
grid[row, col] = false;
}
}
GenerateRandomMole();
}
private void GenerateRandomMole()
{
int randRow = Random.Range(0, 4);
int randCol = Random.Range(0, 4);
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
if (row == randRow && col == randCol)
{
grid[row, col] = true;
}
else
{
grid[row, col] = false;
}
}
}
}
}