專案程式碼可以從Github下載:https://github.com/zhenl/ZL.Shudu 。程式碼隨專案進度更新。
我們已經建立了可以執行數獨遊戲的基本介面,現在為遊戲增加一些功能,首先是計時功能,數獨作為一種智力遊戲,完成時間是重要的指標。還有就是回退功能,在很多情況下,遊戲過程中需要試錯,如果進入死局,需要能夠回到上幾步,再試一個新的路徑,如果沒有這個功能,只能重新開始,降低遊戲的吸引力。
計時功能的實現比較簡單,只要在開始和完成時記錄時間,計算出時間差並顯示就可以了。回退功能可以使用堆疊完成,將每一操作步驟放入堆疊,從堆疊中彈出一條記錄,就是回退的一步。
首先增加兩個變數,記錄開始時間和回退過程:
private DateTime dtBegin;
private Stack<string> steps = new Stack<string>();
然後,在開始遊戲的時候,記錄開始時間,並將堆疊清零:
steps.Clear();
dtBegin = DateTime.Now;
this.lbFinish.IsVisible = false;
this.lbTime.IsVisible = false;
this.lbMessage.IsVisible = false;
在輸入數字後,記錄下輸入的位置和值,存入堆疊:
if (!checkval(x, y, num))
{
return;
}
steps.Push(x + "," + y + "," + num);
currentButton.Text = currentNumBtn.Text;
增加響應回退的事件:
private void btn_Reset_Clicked(object sender, EventArgs e)
{
if (steps.Count > 0)
{
var laststep = steps.Pop();
var arr = laststep.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
int x = int.Parse(arr[0]), y = int.Parse(arr[1]), num = int.Parse(arr[2]);
buttons[x, y].Text = "";
}
}
在完成的時候,顯示耗時時間:
if (IsFinish())
{
lbFinish.IsVisible = true;
lbTime.IsVisible = true;
rowResult.Height = 40;
var diff = (DateTime.Now.Ticks - dtBegin.Ticks) / 10000 / 1000 / 60;
lbTime.Text = diff + "分鐘";
}
還需要增加新遊戲的功能,目前只有一個遊戲,再多增加一些,現在只簡單實現這個功能,將一些遊戲儲存在陣列中,開始遊戲時隨機抽取一個。程式碼如下:
private static int[,,] chesses = {
{
{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0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,0,0}
},{
{0,7,0,0,9,0,2,0,0},
{0,0,0,0,0,7,0,0,5},
{2,0,4,3,5,0,7,0,0},
{0,5,0,0,4,0,9,0,0},
{9,0,3,5,0,1,4,0,8},
{0,0,7,0,6,0,0,1,0},
{0,0,8,0,1,9,3,0,2},
{7,0,0,2,0,0,0,0,0},
{0,0,2,0,3,0,0,9,0}
},{
{3,0,2,4,0,7,9,0,1},
{0,0,7,1,3,8,5,0,0},
{6,0,0,0,0,0,0,0,4},
{0,0,0,0,4,0,0,0,0},
{0,9,4,0,0,0,1,5,0},
{0,0,0,0,9,0,0,0,0},
{4,0,0,0,0,0,0,0,5},
{0,0,8,9,1,5,6,0,0},
{5,0,9,6,0,4,7,0,2}
}
};
修改生成新遊戲的函式:
private void SetNewGame()
{
int k;
var lst = chesses;
var leng = lst.GetLength(0);
if (ra == null)
{
ra = new Random();
}
k = ra.Next(0, leng);
var mychess = new int[9, 9];
for (var i = 0; i < 9; i++)
for (var j = 0; j < 9; j++)
{
mychess[i, j] = chesses[k, i, j];
}
SetGame(mychess);
}
好了,到這裡遊戲基本上已經初步完成了,專案程式碼可以從Github下載:https://github.com/zhenl/ZL.Shudu 。程式碼隨專案進度更新。
現在可以在手機上啟動一個新的遊戲試試了,當你玩了一會兒,忽然有個電話進來,接完電話,再回到遊戲,What?原來的進度都丟了!下一步我們需要在本地儲存當前的進度。