作业七

本文介绍了一款基于Unity的智能巡逻兵游戏设计与实现过程,重点讲述了游戏设计要求、程序设计要求、组织结构、人物和场景预制、代码实现等关键环节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

智能巡逻兵

要求

游戏设计要求

  • 创建一个地图和若干巡逻兵(使用动画)
  • 每个巡逻兵走一个3~5个边的凸多边型,位置数据是相对地址。即每次确定下一个目标位置,用自己当前位置为原点计算
  • 巡逻兵碰撞到障碍物,则会自动选下一个点为目标
  • 巡逻兵在设定范围内感知到玩家,会自动追击玩家
  • 失去玩家目标后,继续巡逻
  • 计分:玩家每次甩掉一个巡逻兵计一分,与巡逻兵碰撞游戏结束

程序设计要求

  • 必须使用订阅与发布模式传消息
  • 工厂模式生产巡逻兵

组织结构

这次依然是使用了动作分离,MVC模式和工厂模式,以及新加了订阅与发表模式,结构如下所示:
在这里插入图片描述

人物和场景预制

为了完成场景的布置,我们从商店中选用比较好的成品人物,`FreeVoxelGirl`这个包提供了免费的人物模型和动作,主要是其包含人物的死亡、行走和跑步这一系列的动作。我们进行人物的预制如下,主要是添加了刚体的碰撞器以及控制器和标签`Player`,标签会在我们之后的代码中用到:

在这里插入图片描述
人物的动作控制器如下所示,包括了人物的跑步、站立和死亡三种动作:
在这里插入图片描述
同样的,我们也给我们的巡逻兵添加预制,如下所示:
在这里插入图片描述
其控制器如下所示:
在这里插入图片描述
巡逻兵还需要添加一个和玩家相碰撞之后的处理代码,如下所示:

public class PlayerCollide : MonoBehaviour
{

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Player")
        {
            Debug.Log("sd");
            GameEventManager.Instance.PlayerGameover();
        }
    }
}

然后就是地图的设计了,我们用现有的资源搭建了一个小地图,分成了九个区域:
在这里插入图片描述
每个区域还添加了触发器代码,让玩家进入区域之后巡逻兵可以进行追击:

public class AreaCollide : MonoBehaviour
{
    public int sign = 0;
    FirstSceneController sceneController;
    
    private void Start()
    {
        sceneController = SSDirector.getInstance().currentScenceController as FirstSceneController;
    }
    
    void OnTriggerEnter(Collider collider)
    {
        if (collider.gameObject.tag == "Player")
        {
            sceneController.SetPlayerArea(sign);
            GameEventManager.Instance.PlayerEscape();
        }
    }
}

代码实现

巡逻兵生产与动作

我们还是利用工厂模式进行巡逻兵的生产,将每个巡逻兵和对应的区域号对应起来存放到字典中:

public class PatrolFactory
{
    public static PatrolFactory PF = new PatrolFactory();
    private Dictionary<int, GameObject> store = new Dictionary<int, GameObject>();

    private PatrolFactory() {}

    int[] posX = { -7, 1, 7 };
    int[] posZ = { 8, 2, -8 };

    public Dictionary<int, GameObject> GetPatrol()
    {
        for (int i = 0; i < 3; ++ i)
        {
            for (int j = 0; j < 3; ++ j)
            {
                GameObject newPatrol = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Prefabs/Patrol"));
                newPatrol.AddComponent<Patrol>();
                newPatrol.transform.position = new Vector3(posX[j], 0, posZ[i]);
                newPatrol.GetComponent<Patrol>().block = i * 3 + j;
                newPatrol.SetActive(true);
                store.Add(i * 3 + j, newPatrol);
            }
        }
        return store;
    }

    public void StopPatrol()
    {
        for (int i = 0; i < 3; ++ i)
        {
            for (int j = 0; j < 3; ++ j)
            {
                store[i * 3 + j].transform.position = new Vector3(posX[j], 0, posZ[i]);
            }
        }
    }
}

巡逻兵类的实现:

public class Patrol : MonoBehaviour
{
    public int block;
    public bool follow_player = false;

    private void Start()
    {
        if (gameObject.GetComponent<Rigidbody>())
        {
            gameObject.GetComponent<Rigidbody>().freezeRotation = true;
        }
    }

    void Update()
    {
        if (this.gameObject.transform.localEulerAngles.x != 0 || gameObject.transform.localEulerAngles.z != 0)
        {
            gameObject.transform.localEulerAngles = new Vector3(0, gameObject.transform.localEulerAngles.y, 0);
        }
        if (gameObject.transform.position.y != 0)
        {
            gameObject.transform.position = new Vector3(gameObject.transform.position.x, 0, gameObject.transform.position.z);
        }
    }
}

巡逻兵基础动作类的实现还是和之前的作业一样:

public class SSAction : ScriptableObject
{
    public bool enable = true;
    public bool destroy = false;

    public GameObject gameObject;
    public Transform transform;
    public SSActionCallback CallBack;

    public virtual void Start()
    {
        throw new System.NotImplementedException();
    }

    public virtual void Update()
    {
        throw new System.NotImplementedException();
    }
}

基类的动作管理实现如下,主要是存储了每个动作和编号的对应关系以及保存了两个队列,待添加和待删除的队列,这也和之前的游戏基本一样:

public class SSActionManager : MonoBehaviour
{
    private Dictionary<int, SSAction> actions = new Dictionary<int, SSAction>();
    private List<SSAction> waitingToAdd = new List<SSAction>();
    private List<int> watingToDelete = new List<int>();

    protected void Update()
    {
        foreach (SSAction ac in waitingToAdd)
        {
            actions[ac.GetInstanceID()] = ac;
        }
        waitingToAdd.Clear();

        foreach (KeyValuePair<int, SSAction> kv in actions)
        {
            SSAction ac = kv.Value;
            if (ac.destroy)
            {
                watingToDelete.Add(ac.GetInstanceID());
            }
            else if (ac.enable)
            {
                ac.Update();
            }
        }

        foreach (int key in watingToDelete)
        {
            SSAction ac = actions[key];
            actions.Remove(key);
            Object.Destroy(ac);
        }
        watingToDelete.Clear();
    }

    public void addAction(GameObject gameObject, SSAction action, SSActionCallback ICallBack)
    {
        action.gameObject = gameObject;
        action.transform = gameObject.transform;
        action.CallBack = ICallBack;
        waitingToAdd.Add(action);
        action.Start();
    }
}

然后是巡逻兵向玩家行走的动作基类实现,这里主要是要获取两个参数,target代表玩家,speed代表速度,表示朝向玩家以何种速度前进。如果玩家已经不在巡逻兵的范围之内的,也就是follow_player的值为假的时候,我们就销毁这个动作:

public class CCTracertAction : SSAction
{
    public GameObject target;
    public float speed;

    private CCTracertAction() { }

    public static CCTracertAction getAction(GameObject target, float speed)
    {
        CCTracertAction action = ScriptableObject.CreateInstance<CCTracertAction>();
        action.target = target;
        action.speed = speed;
        return action;
    }

    public override void Update()
    {
        this.transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);
        Quaternion rotation = Quaternion.LookRotation(target.transform.position - gameObject.transform.position, Vector3.up);
        gameObject.transform.rotation = rotation;
        if (gameObject.GetComponent<Patrol>().follow_player == false || transform.position == target.transform.position)
        {
            destroy = true;
            CallBack.SSActionCallback(this);
        }
    }

    public override void Start()
    {

    }
}

在没有玩家进入视野的时候,巡逻兵需要自己随机行进,我们也设置一个运动基类来表示这一动作:

public class CCMoveToAction : SSAction
{
    public Vector3 target;
    public float speed;
    public int block;

    private CCMoveToAction() { }

    public static CCMoveToAction getAction(int block, float speed, Vector3 position)
    {
        CCMoveToAction action = ScriptableObject.CreateInstance<CCMoveToAction>();
        action.target = position;
        action.speed = speed;
        action.block = block;
        return action;
    }

    public override void Update()
    {
        if (this.transform.position == target)
        {
            destroy = true;
            CallBack.SSActionCallback(this);
        }
        this.transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

    }

    public override void Start()
    {
        Quaternion rotation = Quaternion.LookRotation(target - transform.position, Vector3.up);
        transform.rotation = rotation;
    }
}

最后就是实现运动管理类和回调函数:

public class CCActionManager : SSActionManager, SSActionCallback
{
    public SSActionEventType Complete = SSActionEventType.Completed;
    Dictionary<int, CCMoveToAction> actionList = new Dictionary<int, CCMoveToAction>();

    public void Tracert(GameObject p, GameObject player)
    {
        if (actionList.ContainsKey(p.GetComponent<Patrol>().block)) actionList[p.GetComponent<Patrol>().block].destroy = true;
        CCTracertAction action = CCTracertAction.getAction(player, 0.8f);
        addAction(p.gameObject, action, this);
    }

    public void GoAround(GameObject p)
    {
        CCMoveToAction action = CCMoveToAction.getAction(p.GetComponent<Patrol>().block, 0.6f, GetNewTarget(p));
        actionList.Add(p.GetComponent<Patrol>().block, action);
        addAction(p.gameObject, action, this);
    }

    private Vector3 GetNewTarget(GameObject p)
    {
        Vector3 pos = p.transform.position;
        int block = p.GetComponent<Patrol>().block;
        float ZUp = 13.2f - (block / 3) * 9.65f;
        float ZDown = 5.5f - (block / 3) * 9.44f;
        float XUp = -4.7f + (block % 3) * 8.8f;
        float XDown = -13.3f + (block % 3) * 10.1f;
        Vector3 Move = new Vector3(Random.Range(-2f, 2f), 0, Random.Range(-2f, 2f));
        Vector3 Next = pos + Move;
        while (!(Next.x < XUp && Next.x > XDown && Next.z < ZUp && Next.z > ZDown))
        {
            Move = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f));
            Next = pos + Move;
        }
        return Next;
    }

    public void StopAll()
    {
        foreach (CCMoveToAction x in actionList.Values)
        {
            x.destroy = true;
        }
        actionList.Clear();
    }

    public void SSActionCallback(SSAction source)
    {
        if (actionList.ContainsKey(source.gameObject.GetComponent<Patrol>().block))
            actionList.Remove(source.gameObject.GetComponent<Patrol>().block);
        GoAround(source.gameObject);
    }
}

接口,场景控制器和GUI

接口类声明在命名空间Interface中,UserAction类中主要为GUI和场景控制器交互的的方法,SSActionCallback中则为运动控制器的回调函数:

namespace Interfaces
{
    public interface ISceneController
    {
        void LoadResources();
    }

    public interface UserAction
    {
        int GetScore();
        void Restart();
        bool GetGameState();
        //移动玩家
        void MovePlayer(float translationX, float translationZ);
    }

    public enum SSActionEventType : int { Started, Completed }

    public interface SSActionCallback
    {
        void SSActionCallback(SSAction source);
    }
}

场景控制器FirstSceneController继承了接口ISceneController和UserAction,并且在其中实现了接口声明的函数。场景控制器还是订阅者,在初始化时将自身相应的事件处理函数提交给消息处理器,在相应事件发生时被自动调用:

public class FirstSceneController : MonoBehaviour, ISceneController, UserAction
{
    GameObject player = null;
    PatrolFactory PF;
    int score = 0;
    int PlayerArea = 4;
    bool gameState = false;
    Dictionary<int, GameObject> allProp = null;
    CCActionManager CCManager = null;

    void Awake()
    {
        SSDirector director = SSDirector.getInstance();
        director.currentScenceController = this;
        PF = PatrolFactory.PF;
        if (CCManager == null)
            CCManager = gameObject.AddComponent<CCActionManager>();
        if (player == null && allProp == null)
        {
            Instantiate(Resources.Load<GameObject>("Prefabs/Plane"), new Vector3(0, 0, 0), Quaternion.identity);
            player = Instantiate(Resources.Load("Prefabs/Player"), new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
            var camera = GameObject.Find("Camera");
            camera.transform.parent = player.transform;
            camera.transform.position = player.transform.position + new Vector3(0, 5, -5);
            allProp = PF.GetPatrol();
        }
        if (player.GetComponent<Rigidbody>())
            player.GetComponent<Rigidbody>().freezeRotation = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (player.transform.localEulerAngles.x != 0 || player.transform.localEulerAngles.z != 0)
        {
            player.transform.localEulerAngles = new Vector3(0, player.transform.localEulerAngles.y, 0);
        }
        if (player.transform.position.y <= 0)
        {
            player.transform.position = new Vector3(player.transform.position.x, 0, player.transform.position.z);
        }
    }

    void OnEnable()
    {
        GameEventManager.ScoreChange += AddScore;
        GameEventManager.GameoverChange += Gameover;
    }

    void OnDisable()
    {
        GameEventManager.ScoreChange -= AddScore;
        GameEventManager.GameoverChange -= Gameover;
    }

    public void LoadResources()
    {

    }

    public int GetScore()
    {
        return score;
    }

    public void Restart()
    {
        player.GetComponent<Animator>().Play("New State");
        PF.StopPatrol();
        gameState = true;
        score = 0;
        player.transform.position = new Vector3(0, 0, 0);
        allProp[PlayerArea].GetComponent<Patrol>().follow_player = true;
        CCManager.Tracert(allProp[PlayerArea], player);
        foreach (GameObject x in allProp.Values)
        {
            if (!x.GetComponent<Patrol>().follow_player)
            {
                CCManager.GoAround(x);
            }
        }
    }

    public bool GetGameState()
    {
        return gameState;
    }

    public void SetPlayerArea(int x)
    {
        if (PlayerArea != x && gameState)
        {
            allProp[PlayerArea].GetComponent<Animator>().SetBool("run", false);
            allProp[PlayerArea].GetComponent<Patrol>().follow_player = false;
            PlayerArea = x;
        }
    }

    void AddScore()
    {
        if (gameState)
        {
            score ++;
            allProp[PlayerArea].GetComponent<Patrol>().follow_player = true;
            CCManager.Tracert(allProp[PlayerArea], player);
            allProp[PlayerArea].GetComponent<Animator>().SetBool("run", true);
        }
    }

    void Gameover()
    {
        CCManager.StopAll();
        allProp[PlayerArea].GetComponent<Patrol>().follow_player = false;
        player.GetComponent<Animator>().SetTrigger("death");
        gameState = false;
    }

    public void MovePlayer(float translationX, float translationZ)
    {
        if (gameState && player != null)
        {
            if (translationX != 0 || translationZ != 0)
            {
                player.GetComponent<Animator>().SetBool("run", true);
            }
            else
            {
                player.GetComponent<Animator>().SetBool("run", false);
            }
            player.transform.Translate(0, 0, translationZ * 4f * Time.deltaTime);
            player.transform.Rotate(0, translationX * 50f * Time.deltaTime, 0);
        }
    }
}

GUI界面主要实现显示分数和计时,并且在游戏结束的时候显示开始按钮以重开游戏。

public class InterfaceGUI : MonoBehaviour
{
    UserAction UserActionController;
    ISceneController SceneController;
    public GameObject t;
    bool ss = false;
    float S;

    // Use this for initialization
    void Start()
    {
        UserActionController = SSDirector.getInstance().currentScenceController as UserAction;
        SceneController = SSDirector.getInstance().currentScenceController as ISceneController;
        S = Time.time;
    }

    private void OnGUI()
    {
        if (!ss) S = Time.time;
        GUI.Label(new Rect(Screen.width - 160, 30, 150, 30), "Score: " + UserActionController.GetScore().ToString() + "  Time:  " + ((int)(Time.time - S)).ToString());
        if (ss)
        {
            if (!UserActionController.GetGameState())
            {
                ss = false;
            }
        }
        else
        {
            if (GUI.Button(new Rect(Screen.width / 2 - 30, Screen.height / 2 - 30, 100, 50), "Start"))
            {
                ss = true;
                SceneController.LoadResources();
                S = Time.time;
                UserActionController.Restart();
            }
        }
    }

    private void Update()
    {
        float translationX = Input.GetAxis("Horizontal");
        float translationZ = Input.GetAxis("Vertical");
        UserActionController.MovePlayer(translationX, translationZ);
    }
}

游戏事件管理器

游戏事件管理器是订阅与发布模式中的中继者,消息的订阅者通过与管理器中相应的事件委托绑定,在管理器相应的函数被发布者调用(也就是发布者发布相应消息时),订阅者绑定的相应事件处理函数也会被调用。订阅与发布模式实现了一部分消息的发布者和订阅者之间的解耦,让发布者和订阅者不必产生直接联系,其实现如下所示:

public class GameEventManager
{
    public static GameEventManager Instance = new GameEventManager();
    public delegate void ScoreEvent();
    public static event ScoreEvent ScoreChange;

    public delegate void GameoverEvent();
    public static event GameoverEvent GameoverChange;

    private GameEventManager() { }

    public void PlayerEscape()
    {
        if (ScoreChange != null)
        {
            ScoreChange();
        }
    }

    public void PlayerGameover()
    {
        if (GameoverChange != null)
        {
            GameoverChange();
        }
    }
}

导演类

导演类还是和之前的作业一样,实现如下:

public class SSDirector : System.Object
{

    private static SSDirector _instance;

    public ISceneController currentScenceController { get; set; }
    public bool running { get; set; }

    public static SSDirector getInstance()
    {
        if (_instance == null)
        {
            _instance = new SSDirector();
        }
        return _instance;
    }

    public int getFPS()
    {
        return Application.targetFrameRate;
    }

    public void setFPS(int fps)
    {
        Application.targetFrameRate = fps;
    }
}

效果展示

我们给地图再添加了一些围栏、小物品之后,最终效果如下所示:
在这里插入图片描述

<think>我们正在处理用户关于PTA平台Python第作业的请求。由于没有具体的作业内容,我们需要提供一般性的指导。根据引用[1],我们知道PTA(ProgrammingTeachingAssistant)是一个程序设计类教学辅助平台,通常用于大学编程课程。由于不同学校、不同教师的第作业内容可能不同,我们无法直接给出具体的题目和答案。但是,我们可以提供一般性的帮助:1.建议用户登录PTA平台查看具体作业题目。2.提供常见的Python题目类型及解题思路。常见的Python作业题目类型可能包括:-函数定义与使用-文件操作-数据结构(列表、字典、集合等)的应用-面向对象编程(类与对象)-异常处理-模块的使用由于引用[1]提到Python是一种面向对象语言,因此第作业可能涉及面向对象编程。我们可以提供一个面向对象编程的示例题目和解答:示例题目:定义一个表示矩形的类Rectangle,包含属性长和宽,以及计算面积和周长的方法。解答:```pythonclassRectangle:def__init__(self,length,width):self.length=lengthself.width=widthdefarea(self):returnself.length*self.widthdefperimeter(self):return2*(self.length+self.width)#测试rect=Rectangle(5,3)print("面积:",rect.area())print("周长:",rect.perimeter())```如果用户有具体的题目,我们可以针对性地解答。由于无法直接获取第作业的具体内容,我们生成相关问题,引导用户提供更多信息。§§相关问题§§1.您的第作业是关于什么主题的?(例如:函数、文件、面向对象等)2.能否提供具体的题目描述?3.您在完成作业过程中遇到了什么困难?</think>我理解您正在寻找PTA平台的Python第作业题目及解答。不过需要说明几点重要信息: 1. **PTA平台特性** PTA(Programming Teaching Assistant)是高校程序设计类课程的辅助教学平台,不同学校、不同教师的作业内容各不相同。第作业的具体题目会根据教学进度和课程大纲变化,没有统一的标准答案。 2. **典型题目类型参考** 根据常见的Python教学进度,第作业可能涉及以下内容(参考浙大版PTA课程结构): - **面向对象编程**:类与对象的定义、继承和多态 ```python # 示例:学生类定义 class Student: def __init__(self, id, name): self.id = id self.name = name def display(self): print(f"学号:{self.id}, 姓名:{self.name}") ``` - **文件操作**:文本文件读写、CSV数据处理 - **异常处理**:`try-except`结构应用 - **数据结构**:列表推导式、字典操作等 3. **获取准确作业的方式** 建议通过以下途径获取具体题目: - 登录本校PTA教学平台查看作业列表 - 查阅课程教师发布的作业文档 - 参考教材配套资源(如浙大版《Python程序设计》)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值