将指令抽象为一组字节码,通过字节码的排列组合定义游戏行为,使得玩家或者策划能够自由设计游戏行为(例如 AI)。
数据驱动
让游戏逻辑脱离编码的限制,赋予数据 行为。
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// 使用这样的一种数据驱动的模式来编程,让游戏逻辑脱离编码的限制,赋予数据 行为 | |
// | |
// 使用堆栈存储指令,每次将堆栈中的指令出栈执行再入栈,直到栈空 | |
var stack = new Stack<int>(); | |
var actlist = new List<int>() { 50, 1, 21, 2, 100,3 }; | |
actlist.ForEach(x => { stack.Push(x); }); | |
var player = new Character(); | |
// 解析字节码 | |
while (stack.Count > 0) | |
{ | |
var act = (ActType)stack.Pop(); | |
switch (act) | |
{ | |
case ActType.AddHp: | |
var parm = stack.Pop(); | |
player.AddHp(parm); | |
//stack.Push(player.Hp); | |
break; | |
case ActType.PlaySound: | |
parm = stack.Pop(); | |
player.PlaySound(parm); | |
break; | |
case ActType.Spell: | |
parm = stack.Pop(); | |
player.Spell(parm); | |
break; | |
default: | |
break; | |
} | |
} | |
} | |
} | |
enum ActType | |
{ | |
AddHp = 1, | |
Spell = 2, | |
PlaySound = 3 | |
} | |
class Character | |
{ | |
public int Hp { get; set; } = 100; | |
public int Mp { get; set; } = 200; | |
public void AddHp(int value) | |
{ | |
Hp += value; | |
Console.WriteLine($"增加生命值:{value}"); | |
} | |
public void Spell(int pos) | |
{ | |
Console.WriteLine($"释放法术:{pos}"); | |
} | |
public void PlaySound(int id) | |
{ | |
Console.WriteLine($"播放音效: {id}"); | |
} | |
} |