本系列第七篇,介紹 Common/Step.cs,定義移動方向、設計模式列舉,以及核心結構 Step:以單一 char 高效編碼「方向、是否推箱、是否停留」三資訊,支援隱性雙向轉換。
namespace Skyiv.Ben.PushBox.Common
{
enum Direction { None, East, South, West, North }
public enum Action { None, Create, Edit, Delete }
public struct Step
{
Direction direct;
bool isBox;
bool isStop;
public Direction Direct => direct;
public bool IsBox => isBox;
public bool IsStop => isStop;
public Step(Direction direct, bool isBox, bool isStop)
{
this.direct = direct;
this.isBox = isBox;
this.isStop = isStop;
}
// 編碼對照表:
// A B C D E (方向 None~North, 無推箱、無停留)
// F G H I J (推箱)
// K L M N O (停留)
// P Q R S T (推箱+停留)
public static implicit operator char(Step step)
{
char c = "ABCDE"[step.direct - Direction.None];
if (step.isBox) c = (char)(c + 5);
if (step.isStop) c = (char)(c + 10);
return c;
}
public static implicit operator Step(char c)
{
int n = c - 'A';
return new Step(
(Direction)(n % 5),
(n % 10 >= 5),
(n >= 10)
);
}
}
}
| 字元 | 方向 | 推箱 | 停留 | 索引 n |
|---|---|---|---|---|
| A | None | 否 | 否 | 0 |
| B | East | 否 | 否 | 1 |
| C | South | 否 | 否 | 2 |
| D | West | 否 | 否 | 3 |
| E | North | 否 | 否 | 4 |
| F~J | 同上 | 是 | 否 | 5~9 |
| K~O | 同上 | 否 | 是 | 10~14 |
| P~T | 同上 | 是 | 是 | 15~19 |
Step → char 序列化,char → Step 反序列化,程式碼簡潔:string s = string.Concat(steps.Select(st => (char)st));.bxs):每關通關步驟存為單行字串。Stack 直接 Push/Pop。Step 執行動畫。Step 結構展示了「領域建模 + 位元級編碼 + 隱性轉換」的優雅結合。此模式廣泛適用於任何需高效序列化的離散狀態序列。