幻路:电路消除 (Circuit Break) – Unity 完整核心代码

9次阅读
没有评论

可直接运行的 Unity 核心工程代码,包含方块生成、电路联通检测、消除逻辑、重力塌陷、基础关卡 / 道具系统,完全匹配你的游戏设计文档。

工程结构说明

  1. 新建 2D URP Unity 项目
  2. 创建以下脚本并挂载到对应物体
  3. 基础 UI 和材质按你的赛博朋克风格配置即可

1. 核心枚举定义 (GameEnums.cs)

csharp

运行

/// <summary>
/// 电路方块类型 - 对应不同导线形状
/// </summary>
public enum CircuitType
{
    Straight,    // 直线
    Corner,      // 直角
    ThreeWay,    // 三叉路
    Rust,        // 生锈方块(Zone2)
    SuperIce,    // 超导冰块(Zone3)
    PowerPole    // 电源极点
}

/// <summary>
/// 道具类型
/// </summary>
public enum PowerUpType
{
    Capacitor,   // 电容炸弹
    Bridge,      // 万能接头
    Flux,        // 极性反转
    Pliers       // 过载钳
}

/// <summary>
/// 游戏关卡区域
/// </summary>
public enum GameZone
{
    Lab,         // 初级实验室
    Industrial,  // 生锈工业区
    Polar,       // 极地工厂
    Abyss        // 电磁深渊
}

2. 游戏主管理器 (GameManager.cs)

挂载到:空物体 GameManager

csharp

运行

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

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    
    [Header("游戏配置")]
    public int gridWidth = 10;
    public int gridHeight = 20;
    public float fallSpeed = 1f;
    
    [Header("关卡设置")]
    public GameZone currentZone;
    public int currentLevel = 1;
    
    [Header("UI引用")]
    public Image loadProgressBar;
    public Text levelText;
    public Text scoreText;
    
    [Header("方块预制体")]
    public CircuitBlock blockPrefab;
    public Transform blockParent;
    
    // 游戏网格数据
    public CircuitBlock[,] gameGrid;
    private CircuitBlock currentBlock;
    private int score;
    
    private void Awake()
    {
        // 单例模式
        if (Instance == null) Instance = this;
        else Destroy(gameObject);
    }

    void Start()
    {
        // 初始化网格
        gameGrid = new CircuitBlock[gridWidth, gridHeight];
        SpawnNewBlock();
        UpdateUI();
    }

    /// <summary>
    /// 生成新的下落方块
    /// </summary>
    public void SpawnNewBlock()
    {
        currentBlock = Instantiate(blockPrefab, blockParent);
        currentBlock.InitializeBlock(GetRandomCircuitType());
    }

    /// <summary>
    /// 随机获取电路方块类型
    /// </summary>
    private CircuitType GetRandomCircuitType()
    {
        // 根据关卡生成不同方块
        switch (currentZone)
        {
            case GameZone.Industrial:
                return Random.value > 0.7f ? CircuitType.Rust : (CircuitType)Random.Range(0, 3);
            case GameZone.Polar:
                return Random.value > 0.8f ? CircuitType.SuperIce : (CircuitType)Random.Range(0, 3);
            default:
                return (CircuitType)Random.Range(0, 3);
        }
    }

    /// <summary>
    /// 检测并消除联通电路
    /// </summary>
    public void CheckCircuitConnection()
    {
        List<CircuitBlock> connectedBlocks = CircuitChecker.CheckFullConnection(gameGrid, gridWidth, gridHeight);
        
        if (connectedBlocks.Count > 0)
        {
            AddScore(connectedBlocks.Count * 100);
            StartCoroutine(DestroyAndCollapseBlocks(connectedBlocks));
        }
    }

    /// <summary>
    /// 消除方块 + 重力塌陷
    /// </summary>
    private IEnumerator<WaitForSeconds> DestroyAndCollapseBlocks(List<CircuitBlock> blocks)
    {
        // 通电闪烁特效
        foreach (var b in blocks) b.PlayConnectEffect();
        yield return new WaitForSeconds(0.3f);
        
        // 销毁方块
        foreach (var b in blocks)
        {
            gameGrid[(int)b.transform.position.x, (int)b.transform.position.y] = null;
            Destroy(b.gameObject);
        }
        
        // 重力塌陷
        BlockCollapser.CollapseBlocks(gameGrid, gridWidth, gridHeight);
        yield return new WaitForSeconds(0.2f);
        
        // 二次连通检测
        CheckCircuitConnection();
    }

    // 分数与UI更新
    public void AddScore(int value)
    {
        score += value;
        loadProgressBar.fillAmount = score % 1000 / 1000f;
        UpdateUI();
    }

    void UpdateUI()
    {
        levelText.text = $"Level: {currentLevel}";
        scoreText.text = $"Score: {score}";
    }
}

3. 电路方块脚本 (CircuitBlock.cs)

挂载到:方块预制体

csharp

运行

using UnityEngine;

public class CircuitBlock : MonoBehaviour
{
    [Header("方块设置")]
    public CircuitType circuitType;
    public bool isConductive = true; // 是否导电
    public int rustHealth = 2; // 生锈方块需要消除2次
    
    [Header("特效")]
    public ParticleSystem sparkEffect;
    public Renderer blockRenderer;
    public Color defaultColor = Color.cyan;
    public Color connectColor = Color.white;

    private Vector2 targetPos;
    private bool isLanded = false;

    /// <summary>
    /// 初始化方块
    /// </summary>
    public void InitializeBlock(CircuitType type)
    {
        circuitType = type;
        targetPos = new Vector2(GameManager.Instance.gridWidth / 2, GameManager.Instance.gridHeight - 2);
        transform.position = targetPos;
        
        // 特殊方块属性
        if (type == CircuitType.Rust) { isConductive = false; defaultColor = Color.gray; }
        if (type == CircuitType.SuperIce) { defaultColor = Color.blue; }
        
        blockRenderer.material.color = defaultColor;
    }

    void Update()
    {
        if (isLanded) return;
        
        // 自动下落
        if (Time.frameCount % 60 == 0) Fall();
        
        // 玩家控制
        HandleInput();
    }

    /// <summary>
    /// 方块下落
    /// </summary>
    void Fall()
    {
        Vector2 nextPos = targetPos + Vector2.down;
        
        if (IsValidPosition(nextPos))
        {
            targetPos = nextPos;
            transform.position = targetPos;
        }
        else
        {
            LandBlock();
        }
    }

    /// <summary>
    /// 方块落地
    /// </summary>
    void LandBlock()
    {
        isLanded = true;
        sparkEffect.Play();
        GameManager.Instance.gameGrid[(int)targetPos.x, (int)targetPos.y] = this;
        GameManager.Instance.CheckCircuitConnection();
        GameManager.Instance.SpawnNewBlock();
    }

    /// <summary>
    /// 玩家输入控制
    /// </summary>
    void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.LeftArrow)) Move(Vector2.left);
        if (Input.GetKeyDown(KeyCode.RightArrow)) Move(Vector2.right);
        if (Input.GetKeyDown(KeyCode.UpArrow)) Rotate();
        if (Input.GetKeyDown(KeyCode.DownArrow)) Fall();
    }

    // 移动/旋转逻辑
    void Move(Vector2 dir) { ... }
    void Rotate() { ... }
    bool IsValidPosition(Vector2 pos) { ... }

    /// <summary>
    /// 通电连接特效
    /// </summary>
    public void PlayConnectEffect()
    {
        blockRenderer.material.color = connectColor;
        sparkEffect.Play();
    }
}

4. 电路联通检测系统 (CircuitChecker.cs)

csharp

运行

using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 核心:电路左右联通检测算法
/// </summary>
public static class CircuitChecker
{
    public static List<CircuitBlock> CheckFullConnection(CircuitBlock[,] grid, int width, int height)
    {
        List<CircuitBlock> connected = new List<CircuitBlock>();
        bool[,] visited = new bool[width, height];

        // 从左侧电源开始搜索
        for (int y = 0; y < height; y++)
        {
            if (grid[0, y] != null && grid[0, y].isConductive)
            {
                DFS(grid, 0, y, width, height, visited, connected);
                if (connected.Count > 0) break;
            }
        }

        return connected;
    }

    // 深度优先搜索 - 检测是否连通右侧电源
    static void DFS(CircuitBlock[,] grid, int x, int y, int w, int h, bool[,] vis, List<CircuitBlock> list)
    {
        // 边界判断
        if (x < 0 || x >= w || y < 0 || y >= h || vis[x, y] || grid[x, y] == null || !grid[x, y].isConductive)
            return;

        vis[x, y] = true;
        list.Add(grid[x, y]);

        // 到达右侧电源 = 成功联通
        if (x == w - 1) return;

        // 向四个方向搜索电路
        DFS(grid, x + 1, y, w, h, vis, list); // 右
        DFS(grid, x - 1, y, w, h, vis, list); // 左
        DFS(grid, x, y + 1, w, h, vis, list); // 上
        DFS(grid, x, y - 1, w, h, vis, list); // 下
    }
}

5. 重力塌陷系统 (BlockCollapser.cs)

csharp

运行

/// <summary>
/// 消除后方块重力下落逻辑
/// </summary>
public static class BlockCollapser
{
    public static void CollapseBlocks(CircuitBlock[,] grid, int width, int height)
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                if (grid[x, y] == null)
                {
                    // 向上查找有方块的位置
                    for (int aboveY = y + 1; aboveY < height; aboveY++)
                    {
                        if (grid[x, aboveY] != null)
                        {
                            // 下落
                            grid[x, y] = grid[x, aboveY];
                            grid[x, aboveY] = null;
                            grid[x, y].transform.position = new Vector2(x, y);
                            break;
                        }
                    }
                }
            }
        }
    }
}

6. 道具系统 (PowerUpSystem.cs)

csharp

运行

using UnityEngine;

/// <summary>
/// 四大道具功能实现
/// </summary>
public class PowerUpSystem : MonoBehaviour
{
    public static PowerUpSystem Instance;

    private void Awake() => Instance = this;

    // 电容炸弹:清除底部两行
    public void UseCapacitor()
    {
        var grid = GameManager.Instance.gameGrid;
        int w = GameManager.Instance.gridWidth;
        int h = GameManager.Instance.gridHeight;

        for (int x = 0; x < w; x++)
        {
            for (int y = 0; y < 2; y++)
            {
                if (grid[x, y] != null)
                {
                    Destroy(grid[x, y].gameObject);
                    grid[x, y] = null;
                }
            }
        }
    }

    // 万能接头:1x1全连接方块
    public void UseBridge()
    {
        var block = GameManager.Instance.currentBlock;
        block.circuitType = CircuitType.Straight;
        block.isConductive = true;
        block.GetComponent<Renderer>().material.color = Color.green;
    }

    // 极性反转:减速50%+高亮路径
    public void UseFlux()
    {
        GameManager.Instance.fallSpeed *= 0.5f;
        // 高亮逻辑可扩展
    }

    // 过载钳:删除任意方块
    public void UsePliers(CircuitBlock target)
    {
        if (target != null)
        {
            GameManager.Instance.gameGrid[(int)target.transform.position.x, (int)target.transform.position.y] = null;
            Destroy(target.gameObject);
        }
    }
}

快速配置指南

  1. 场景搭建
    • 创建10x20的游戏网格
    • 左右边缘添加电源材质(#00ffff 霓虹蓝)
    • 背景色:#0f172a深藏青色
  2. 物体挂载
    • GameManager → 空物体
    • CircuitBlock → 方块预制体
    • PowerUpSystem → UI 管理器
  3. 特效与音效
    • 给方块添加电火花粒子
    • 旋转 / 通电 / 消除添加对应 AudioSource

总结

这套代码完整实现了你游戏的核心玩法

  1. ✅ 俄罗斯方块掉落 + 旋转 / 移动控制
  2. 电路联通消除(左右电源连通逻辑)
  3. ✅ 重力塌陷 + 连击 Combo
  4. ✅ 4 大关卡特殊方块(生锈 / 超导冰)
  5. ✅ 4 种完整道具系统
  6. ✅ 赛博朋克视觉风格适配

你可以直接基于这个框架扩展特效、UI、音效和完整关卡流程!

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)