前言
大一學(xué)期末的時候株汉,用Winform做過一個2048??傳送門,移動時沒有動畫歌殃,游戲界面還算美觀乔妈,但核心邏輯嘛线罕,嘿嘿
最近工作不忙豪娜,閑來無事枫甲,打算重構(gòu)一個帶動畫的。
魯迅說過握童,生命在于折騰烘绽,廢話不多說呢燥,開搞班缎!
構(gòu)思一下
框框先搭起來,后面再實(shí)現(xiàn)揣非。
將一局游戲簡單抽象為一個類
class G2048
抡医,所有邏輯在這個類里實(shí)現(xiàn)。
屬性
用一個二維數(shù)組來存儲基本的信息
int[,] Map
- 后續(xù)要加上動畫效果早敬,所以加一個移動路徑的字典
Dictionary<Point,Point>
忌傻,用來存儲每一步操作后產(chǎn)生變化的坐標(biāo),key中存原始坐標(biāo)搞监,value中存移動后坐標(biāo)水孩。 - 兩種方案:①直接設(shè)為屬性,每次操作后更新琐驴。②在每一步操作時返回一個路徑字典俘种。
- 第二種看起來合理一些,但我選擇第一種绝淡,是的宙刘,這就是任性。
/// <summary>
/// 存儲每個方塊內(nèi)容
/// </summary>
public int[,] Map { get; private set; }
/// <summary>
/// Log牢酵,用來存儲一步操作后每個方塊的變化
/// </summary>
public Dictionary<Point, Point> Moved = new Dictionary<Point, Point>();
/// <summary>
/// 行數(shù)
/// </summary>
public int Row { get; private set; }
/// <summary>
/// 列數(shù)
/// </summary>
public int Colum { get; private set; }
/// <summary>
/// 得分
/// </summary>
public int Score { get; set; }
/// <summary>
/// 步數(shù)
/// </summary>
public int StepNum { get; set; }
/// <summary>
/// 新增加的方塊坐標(biāo)
/// </summary>
public Point LastBlockPoint { get; private set; }
/// <summary>
/// 目前Map中不為0的方塊數(shù)量
/// </summary>
private int blockCount = 0;
構(gòu)造函數(shù)
不局限于4*4的棋盤悬包,添加一個帶參的構(gòu)造函數(shù)來定義棋盤
public G2048()
{
Row = 4;
Colum = 4;
Map = new int[4, 4];
this.newBlock();
}
public G2048(int i, int j)
{
Row = i;
Colum = j;
Map = new int[i, j];
this.newBlock();
}
枚舉
移動方向弄個枚舉,讓代碼看起來舒服一些
public enum Direction
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
方法的定義
/// <summary>
/// 生成一個新的方塊
/// </summary>
private void newBlock()
/// <summary>
/// 向某個方向移動
/// </summary>
/// <param name="direction"></param>
/// <returns>是否是有效的操作(游戲是否產(chǎn)生了變化)</returns>
public bool Operate(Direction direction)
/// <summary>
/// 一行或一列坐標(biāo)的移動
/// </summary>
/// <param name="points"></param>
private void singleMove(Point[] points)
/// <summary>
/// 是否GameOver
/// </summary>
/// <returns>res</returns>
private bool isGameOver()
/// <summary>
/// 打印游戲
/// </summary>
/// <returns>格式化字符串</returns>
public override string ToString()
{
string res = "";
foreach (var v in Moved)
{
res+=v.Key.ToString() + "-->" + v.Value.ToString()+"\n";
}
res += "blockCount:" + blockCount + "\t" +"newBlockPoint:"+ LastBlockPoint.ToString()+"\n";
res += "StepNum:"+StepNum+"\t"+"Score:" + Score + "\n";
res += "isGameOver:" + isGameOver() + "\n";
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Colum; j++)
{
res += Map[i, j] + "\t";
}
res += "\n";
}
return res;
}
委托
加個游戲結(jié)束的委托
public delegate void GameOverDelegate();
/// <summary>
/// 委托 游戲結(jié)束后
/// </summary>
public GameOverDelegate GameOvered;
具體實(shí)現(xiàn)
經(jīng)過了上面的梳理馍乙,發(fā)現(xiàn)基本上已經(jīng)完成了嘛布近,只需要稍稍補(bǔ)充一下細(xì)節(jié),嘿嘿嘿
陷入沉思
聽說PDD又開直播了丝格?撑瞧!
溜了溜了,改日吧铁追。