页数:30页文件大小:295.4 KB来源: 设计模式ppt课件
本课件以大富翁游戏为综合案例,展示如何用中介者串起模型与视图,并用单件、模板方法、策略、状态、命令、构造器、原型与访问者等模式分别处理对象唯一性、流程骨架、AI策略、玩家状态与操作请求。
综合举例
游戏的变化
Model与View
应用中介者和MVC模式
Gamepublic class Game{private static Game instance = new Game();private List<ModelElement> model;private View view;private Game() { }public static Game GetInstance(){return instance;}public bool Init(){}public bool Run(){}public bool Term(){}//其它操作}如何创建Element,以后再说View部分
主要循环结构:public void Loop(){while (running){ProcessInput();UpdateView();WaitMessage();}}Process与UpdateView的原始编码public void ProcessInput(){if (scene == 1) {int key = GetKeyBoard();if (key == 'A' ) {//do ....} else if (key == MOUSE_CLICK ) {//do ....} else {//do ....}}else if (scene == 2) {int key = GetKeyBoard();if (key == 'D' ) {//do ....} else if (key == MOUSE_CLICK ) {//do ....} else {//do ....}} else {}}public void UpdateView(){if (scene == 1) {//do ....} else if (scene == 2) {//do ....} else {//do ....}}用模式改进View
使用模版方法模式
使用策略模式基本上与应用模版方法模式,有类似的效果不足:场景切换
应用状态模式
续
View与DX的交互
View修改Model的请求public void ProcessInput(){if (scene == 1) {DoChange1(ModelElement2 ele);DoChange2(ModelElement1 ele);}else if (scene == 2) {DoChange3(ModelElement2 ele);DoChange4(ModelElement4 ele);}应用命令模式
Game中使用命令模式
Model部分
Model的构造
Game中构造地图
Builder中构造Block、House等
使用原型方法
public class MapBuilder
玩家的处理public abstract class Player{public void CastDices(intdiceCount,int fixedValue){}public void MoveOnMap(){}public void UseCard();protected Block currentPosition;}MoveOnMap()注意双派分的使用public abstract class Player{public int CastDices(int diceCount,int fixedValue){}public void MoveOnMap(){int step = CastDices(2, 0);for (int i = 0; i < steps; i++){if (currentPosition.NextBlock() == false) break;}}public void UseCard(Player);public void UseCard(House);protected Block currentPosition;}Blockclass Blcok{public void NextBlock(){int dir[] = {0,1,2,3,4,5,6,7};ShuffleDir();for(int i=0;i<8;i++) {if (neighbors[dir[i]] == this) continue;SetCurrent(neighbors[dir[i]]);//其它处理,如撞上栏杆等return true;}return false;}private Block[] neighbors = new Block[8];}UseCard中的卡片子系统
public class MoneyCard : PlayerCard{public void ApplyPlayer(Player fromPlayer,Player toPlayer){toPlayer.SetMoney(toPlayer.GetMoney() / 2);}}public abstract class Player{public void UsePlayerCard(this,Player otherPlayer,PlayerCard card){card.ApplyPlayer(this,otherPlayer);}}下载地址:{{downurl}}
{{{a}}}
{{#b}}{{{b}}}
{{/b}} {{/title}} {{#nolog}}登陆注册
{{/nolog}} {{#djsx}}点我刷新
{{/djsx}} {{#gocz}} {{/gocz}} {{#ffqr}} {{/ffqr}}