今天是農曆五月初五,端午節。在此,祝你們端午安康!css
端午節是中華民族古老的傳統節日之一。端午也稱端五,端陽。此外,端午節還有許多別稱,如:午日節、重五節、五月節、浴蘭節、女兒節、天中節、地臘、詩人節、龍日等。html
很差意思,跑題了,就此打住。git
事情的通過是這樣的,今年端午節公司給每位員工都準備了一個糉子禮盒,本以來就幾個糉子而已,沒想到今年的糉子禮盒內暗藏玄關,內附一個棋盤和五子棋子。github
糉子什麼的都不重要,主要是這個五子棋我還挺喜歡的,哈哈哈。😎web
正好這段時間用 Blazor 將以前的博客重構了一遍,因而就想着可否用 Blazor 寫一個五子棋⚫⚪小遊戲呢?數組
說幹就幹,本篇主要是分享基於 Blazor 開發的五子棋小遊戲,先放試玩地址:https://blazor.meowv.com/gobang 。async
你們能夠先打開連接讓他先加載一會(掛在GitHub,有點慢~🤪),再繼續回來看文章哈。spa
剛開始原本我是本身寫的,發現越寫越複雜,遂放棄就在Github上尋找有沒有實現過相似的需求,別說還真有一位大神用 Blazor 實現了,地址:https://github.com/ut32/gobang/ ,因此個人代碼邏輯基本上都參考這位大神的代碼。👍👍👍3d
接下來看看實現過程,新建一個Gobang.razor
razor組件,設置路由:@page "/gobang"
。code
我這裏直接放在以前 Blazor 實戰系列的項目中,若是你沒有看過個人 Blazor 實戰系列文章,建議你快去刷一遍。😁
相信五子棋你們都玩過,規則我就不說了。
先理一下需求和實現步驟:
先渲染一個 19x19 的棋盤,直接兩層 for 循環配合 CSS 搞定。
<div class="gobang-box"> <div class="chess"> @for (var i = 0; i < 19; i++) { @for (var j = 0; j < 19; j++) { var _i = i; var _j = j; <div class="cell" @onclick="@(async () => await Playing(_i, _j))"> <span class="chess@(Chess[i, j])"></span> </div> } } </div> </div>
其中的onclick
方法先不看,主要是我方落子的點擊事件。
Chess
是定義的一個二維數組:private int[,] Chess = new int[19, 19];
。
最重要的棋子就是span
標籤,用class來控制黑白,當class = "chess1"
爲黑子,當class = "chess2"
爲白子。
同時在棋盤旁邊添加一些按鈕,選擇誰先手的選項和描述信息。
<div class="chess-info"> <h1>五子棋⚫⚪</h1> <p><b>⚡是時候表演真正的技術了,快來一場人機大戰吧⚡</b></p> <p><label><input type="radio" name="chess" checked="checked" @onclick="@(() => first = "ai")"> 電腦先手</label></p> <p><label><input type="radio" name="chess" @onclick="@(() => first = "me")"> 我先手</label></p> <p><button class="box-btn" @onclick="StartGame">@(IsInGame ? "結束遊戲" : "開始遊戲")</button></p> <div class="chess-msg"> <p><b>@msgs</b></p> <p>遊戲規則:</p> <span>(1)請選擇電腦先手仍是你先手,黑棋始終先手。</span> <span>(2)點擊開始遊戲按鈕開始對局。</span> <span>(3)點擊結束遊戲按鈕結束對局。</span> <span>(4)對局雙方各執一色棋子。</span> <span>(5)空棋盤開局。</span> <span>(6)黑先、白後,交替下子,每次只能下一子。</span> <span>(7)棋子下在棋盤的空白點上,棋子下定後,不得向其它點移動,不得從棋盤上拿掉或拿起另落別處。</span> <span>(8)黑方的第一枚棋子可下在棋盤任意交叉點上。</span> <span>(9)輪流下子是雙方的權利,<del>但容許任何一方放棄下子權(即:PASS權)</del>。</span> <span>(10)<del>五子棋對局,執行黑方指定開局、三手可交換、五手兩打的規定。整個對局過程當中黑方有禁手,白方無禁手。黑方禁手有三三禁手、四四禁手和長連禁手三種。</del></span> </div> </div>
這裏同時把用到的css樣式給到你們。
.gobang-box { width: 1200px; margin: 0 auto; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .chess { width: 760px; height: 760px; float: left; } .chess .cell { float: left; width: 40px; height: 40px; position: relative; cursor: pointer; font-size: 10px; color: #ffd800; } .chess .cell::after { content:' '; position: absolute; height: 2px; display: block; width: 100%; border-bottom: #f5d099 1px solid; background: #c8a06f; top: 50%; left: 0; z-index: 2; } .chess .cell::before { content:' '; position: absolute; height: 100%; display: block; width: 2px; border-right: #f5d099 1px solid; background: #c8a06f; top: 0; left: 50%; z-index: 1; } .chess .cell .chess1 { display: block; width: 30px; height: 30px; border-radius: 15px; text-align: center; line-height: 54px; background: #000000; left: 5px; top: 5px; position: absolute; z-index: 10; background-image: radial-gradient(#444 5%, #111 15%, #000 60%); box-shadow: 0px 0px 3px #333; } .chess .cell .chess2 { display: block; width: 30px; height: 30px; border-radius: 15px; text-align: center; left: 5px; top: 5px; position: absolute; z-index: 10; line-height: 54px; background-image: radial-gradient(#ffffff 5%, #f1f1f1 15%, #f1f1f1 60%); box-shadow: 0px 0px 3px #333; } .chess-info { float: left; width: 400px; height: 760px; padding-left: 20px; margin-left: 40px; } .chess-info input { display: initial; width: initial; height: initial; visibility: initial; } .chess-msg { margin-top: 20px; color: #aaa; } .chess-msg span { display: block; font-size: 12px; }
如今來把用到的一些變量和方法搞進來。
private int[,] Chess = new int[19, 19]; private string first = "ai"; private bool IsInGame = false; private string msgs; private int AIChess = 1; private int MineChess = 2;
Chess
是棋盤的二維數組。
first
爲先手字段,默認電腦先手,我這裏賦值爲"ai",用他來判斷是我先手仍是電腦先手。
IsInGame
用來判斷當前遊戲狀態,是否開始遊戲,能夠根據它來動態控制按鈕文字內容。
msgs
是一個提示信息,告訴玩家雙方執子狀況。
AIChess = 1
和MineChess = 2
就是黑白子,默認電腦爲黑子,我爲白子。
上方兩個radio標籤,用來選擇誰先手,點擊事件分別給first
賦值,按鈕點擊事件StartGame
。
private void StartGame() { // 初始化棋盤 Chess = new int[19, 19]; // 是否開始遊戲,點擊按鈕重置顯示消息 if (IsInGame) { msgs = string.Empty; } else { // 電腦先手 if (first == "ai") { AIChess = 1; MineChess = 2; // 電腦落子正中心天元位置 Chess[9, 9] = AIChess; msgs = "電腦:執黑子 ⚫ 我:執白子 ⚪"; } else { // 我先手的話則我執黑子,電腦執白子 MineChess = 1; AIChess = 2; msgs = "我:執黑子 ⚫ 電腦:執白子 ⚪"; } } // 改變遊戲狀態,用於顯示不一樣文字的按鈕 IsInGame = !IsInGame; }
開始遊戲以前,先初始化一下棋盤,而後判斷當前是否在遊戲中,在遊戲中點了按鈕對應的確定是結束遊戲,那麼此時將提示消息清空。若是未開始遊戲,點了按鈕就是開始對局了,此時就去判斷電腦先手仍是我先手。根據這兩種狀況分別給AIChess
和MineChess
賦值,給出對應的提示消息。若是是電腦先手,那麼自動在棋盤正中心位置落子,查了一下這個位置叫天元。直接將棋盤數組賦值Chess[9, 9] = AIChess;
便可,最後點了按鈕是須要改變狀態的:IsInGame= !IsInGame;
。
那麼若是是我先手或者電腦落子以後,此時須要我方落子,那麼我方落子的方法就是Playing(int row, int cell)
方法。
private async Task Playing(int row, int cell) { // 是否開始遊戲,當前判斷沒開始給出提示 if (!IsInGame) { await Common.InvokeAsync("alert", "\n💪點擊開始遊戲按鈕開啓對局,請閱讀遊戲規則💪"); return; } // 已落子直接返回,不作任何操做 if (Chess[row, cell] != 0) return; // 根據傳進來的座標進行我方落子 Chess[row, cell] = MineChess; if (IsWin(MineChess, row, cell)) { await Common.InvokeAsync("alert", "\n恭喜,你贏了👍"); IsInGame = !IsInGame; return; } // 我方落子以後電腦落子 await AIPlaying(AIChess); }
我放落子以前先判斷是否開始遊戲,若是爲點擊開始遊戲按鈕,則給出彈窗提示,直接返回不作任何操做,接着有一種狀況,我方點擊了已經落子了的位置,也不作任何操做直接返回。
某位置是否落子能夠根據傳進來的座標進行判斷,Chess[row, cell] == 0
表示未落子,Chess[row, cell] != 0
就表示已經落子了,這裏不能夠繼續落子了。
而後就能夠將我方點擊的位置進行落子了,直接給數組賦值便可:Chess[row, cell] = MineChess;
。
落子以後須要判斷輸贏,這裏引入了一個新的方法IsWin(...)
後面說。若是返回true就是贏了,給出提示,改變遊戲狀態。若是沒有贏,我方落子以後就該電腦落子了,這裏也是引入了一個新的方法:AIPlaying(...)
。
private async Task AIPlaying(int chess) { // 我方 var minePoints = new List<ValuedPoint>(); // 電腦 var aiPonints = new List<ValuedPoint>(); for (int i = 0; i < 19; i++) { for (int j = 0; j < 19; j++) { // 還未落子的位置列表 if (Chess[i, j] == 0) { minePoints.Add(GetValuedPoint(chess, i, j)); aiPonints.Add(GetValuedPoint((chess == 1 ? 2 : 1), i, j)); } } } // 獲取最佳位置 var minePoint = minePoints.OrderByDescending(x => x.Score).FirstOrDefault(); var aiPonint = aiPonints.OrderByDescending(x => x.Score).FirstOrDefault(); if (minePoint != null && aiPonint != null) { // 若是某個位置對手分數高於我方,則搶佔位置 if (minePoint.Score > aiPonint.Score) { Chess[minePoint.Point.Row, minePoint.Point.Cell] = chess; if (IsWin(AIChess, minePoint.Point.Row, minePoint.Point.Cell)) { await Common.InvokeAsync("alert", "\n電腦贏了,你個渣渣👎"); IsInGame = !IsInGame; return; } } else { Chess[aiPonint.Point.Row, aiPonint.Point.Cell] = chess; if (IsWin(AIChess, aiPonint.Point.Row, aiPonint.Point.Cell)) { await Common.InvokeAsync("alert", "\n電腦贏了,你個渣渣👎"); IsInGame = !IsInGame; return; } } } }
電腦落子採用的是遍歷計分方式,計算每個空位的分數,分數由高到底,因而先構建一個對象ValuedPoint
。
//ValuedPoint.cs public class ValuedPoint { public Point Point { get; set; } public int Score { get; set; } } //Point.cs public struct Point { public int Row { get; set; } public int Cell { get; set; } }
添加我方和電腦計分對象列表:minePoints
和aiPonints
,遍歷棋盤中未落子的位置進行分數計算,計算分數策略引入一個新的方法:GetValuedPoint(...)
。
而後分別獲取黑子和白子雙方應該落子的最佳位置,即獲取到分數最高的位置座標,就電腦落子來講,若是我分數高於電腦,電腦就會搶佔這個位置進行落子。
落子以後一樣調用IsWin(...)
來判斷電腦是否贏了,贏了給出提示改變狀態結束對局,沒贏就繼續下。
如今來看看計分的策略:GetValuedPoint(...)
。
private ValuedPoint GetValuedPoint(int chess, int row, int cell) { var aiChess = chess == 1 ? 2 : 1; int HScore = 0, VScore = 0, PScore = 0, LScore = 0; #region 橫方向 ➡⬅ { var i = 1; var score = 1; var validPlace = 0; var rightValid = true; var leftValid = true; var rightSpace = 0; var leftSpace = 0; var isDead = false; while (i < 5) { var right = cell + i; if (rightValid && right < 19) { if (Chess[row, right] == chess) { if (rightSpace == 0) score++; validPlace++; } else if (Chess[row, right] == 0) { rightSpace++; validPlace++; } else if (Chess[row, right] == aiChess) { rightValid = false; if (rightSpace == 0) isDead = true; } } var left = cell - i; if (leftValid && left >= 0) { if (Chess[row, left] == chess) { if (leftSpace == 0) score++; validPlace++; } else if (Chess[row, left] == 0) { leftSpace++; validPlace++; } else if (Chess[row, left] == aiChess) { leftValid = false; if (leftSpace == 0) isDead = true; } } i++; } if (score >= 5) HScore = 100000; if (score == 4) { if (!isDead) HScore = 80000; else HScore = validPlace <= 4 ? 0 : 8000; } if (score == 3) { if (!isDead) HScore = validPlace <= 4 ? 0 : 4000; else HScore = validPlace <= 4 ? 0 : 2000; } if (score == 2) { if (!isDead) HScore = validPlace <= 4 ? 0 : 600; else HScore = validPlace <= 4 ? 0 : 300; } } #endregion #region 豎方向 ⬇⬆ { var i = 1; var score = 1; var validPlace = 0; var topValid = true; var bottomValid = true; var topSpace = 0; var bottomSpace = 0; var isDead = false; while (i < 5) { var top = row - i; if (topValid && top >= 0) { if (Chess[top, cell] == chess) { if (topSpace == 0) score++; validPlace++; } else if (Chess[top, cell] == 0) { topSpace++; validPlace++; } else if (Chess[top, cell] == aiChess) { topValid = false; if (topSpace == 0) isDead = true; } } var bottom = row + i; if (bottomValid && bottom < 19) { if (Chess[bottom, cell] == chess) { if (bottomSpace == 0) score++; validPlace++; } else if (Chess[bottom, cell] == 0) { bottomSpace++; validPlace++; } else if (Chess[bottom, cell] == aiChess) { bottomValid = false; if (bottomSpace == 0) isDead = true; } } i++; } if (score >= 5) VScore = 100000; if (score == 4) { if (!isDead) VScore = 80000; else VScore = validPlace <= 4 ? 0 : 8000; } if (score == 3) { if (!isDead) VScore = validPlace <= 4 ? 0 : 4000; else VScore = validPlace <= 4 ? 0 : 2000; } if (score == 2) { if (!isDead) VScore = validPlace <= 4 ? 0 : 600; else VScore = validPlace <= 4 ? 0 : 300; } } #endregion #region 撇方向 ↙↗ { var i = 1; var score = 1; var validPlace = 0; var topValid = true; var bottomValid = true; var topSpace = 0; var bottomSpace = 0; var isDead = false; while (i < 5) { var rightTopRow = row - i; var rightTopCell = cell + i; if (topValid && rightTopRow >= 0 && rightTopCell < 19) { if (Chess[rightTopRow, rightTopCell] == chess) { if (topSpace == 0) score++; validPlace++; } else if (Chess[rightTopRow, rightTopCell] == 0) { topSpace++; validPlace++; } else if (Chess[rightTopRow, rightTopCell] == aiChess) { topValid = false; if (topSpace == 0) isDead = true; } } var leftBottomRow = row + i; var leftBottomCell = cell - i; if (bottomValid && leftBottomRow < 19 && leftBottomCell >= 0) { if (Chess[leftBottomRow, leftBottomCell] == chess) { if (bottomSpace == 0) score++; validPlace++; } else if (Chess[leftBottomRow, leftBottomCell] == 0) { bottomSpace++; validPlace++; } else if (Chess[leftBottomRow, leftBottomCell] == aiChess) { bottomValid = false; if (bottomSpace == 0) isDead = true; } } i++; } if (score >= 5) PScore = 100000; if (score == 4) { if (!isDead) PScore = 80000; else PScore = validPlace <= 4 ? 0 : 9000; } if (score == 3) { if (!isDead) PScore = validPlace <= 4 ? 0 : 4500; else PScore = validPlace <= 4 ? 0 : 3000; } if (score == 2) { if (!isDead) PScore = validPlace <= 4 ? 0 : 800; else PScore = validPlace <= 4 ? 0 : 500; } } #endregion #region 捺方向 ↘↖ { var i = 1; var score = 1; var validPlace = 0; var topSpace = 0; var bottomSpace = 0; var topValid = true; var bottomValid = true; var isDead = false; while (i < 5) { var leftTopRow = row - i; var leftTopCell = cell - i; if (topValid && leftTopRow >= 0 && leftTopCell >= 0) { if (Chess[leftTopRow, leftTopCell] == chess) { if (topSpace == 0) score++; validPlace++; } else if (Chess[leftTopRow, leftTopCell] == 0) { topSpace++; validPlace++; } else if (Chess[leftTopRow, leftTopCell] == aiChess) { topValid = false; if (topSpace == 0) isDead = true; } } var rightBottomRow = row + i; var rightBottomCell = cell + i; if (bottomValid && rightBottomRow < 19 && rightBottomCell < 19) { if (Chess[rightBottomRow, rightBottomCell] == chess) { if (bottomSpace == 0) score++; validPlace++; } else if (Chess[rightBottomRow, rightBottomCell] == 0) { bottomSpace++; validPlace++; } else if (Chess[rightBottomRow, rightBottomCell] == aiChess) { bottomValid = false; if (bottomSpace == 0) isDead = true; } } i++; } if (score >= 5) LScore = 100000; if (score == 4) { if (!isDead) LScore = 80000; else LScore = validPlace <= 4 ? 0 : 9000; } if (score == 3) { if (!isDead) LScore = validPlace <= 4 ? 0 : 4500; else LScore = validPlace <= 4 ? 0 : 3000; } if (score == 2) { if (!isDead) LScore = validPlace <= 4 ? 0 : 800; else LScore = validPlace <= 4 ? 0 : 500; } } #endregion return new ValuedPoint { Score = HScore + VScore + PScore + LScore, Point = new Point { Row = row, Cell = cell } }; }
分別對給定位置的棋子四個方向:橫方向 ➡⬅、豎方向 ⬇⬆、撇方向 ↙↗、捺方向 ↘↖ 進行遍歷,計算每個空位的分數,分數由高到低,最後返回ValuedPoint
對象。
最後判斷是否贏棋五子連珠的方法:IsWin(int chess, int row, int cell)
。
private bool IsWin(int chess, int row, int cell) { #region 橫方向 ➡⬅ { var i = 1; var score = 1; var rightValid = true; var leftValid = true; while (i <= 5) { var right = cell + i; if (rightValid && right < 19) { if (Chess[row, right] == chess) { score++; if (score >= 5) return true; } else rightValid = false; } var left = cell - i; if (leftValid && left >= 0) { if (Chess[row, left] == chess) { score++; if (score >= 5) return true; } else leftValid = false; } i++; } } #endregion #region 豎方向 ⬇⬆ { var i = 1; var score = 1; var topValid = true; var bottomValid = true; while (i < 5) { var top = row - i; if (topValid && top >= 0) { if (Chess[top, cell] == chess) { score++; if (score >= 5) return true; } else topValid = false; } var bottom = row + i; if (bottomValid && bottom < 19) { if (Chess[bottom, cell] == chess) { score++; if (score >= 5) return true; } else { bottomValid = false; } } i++; } } #endregion #region 撇方向 ↙↗ { var i = 1; var score = 1; var topValid = true; var bottomValid = true; while (i < 5) { var rightTopRow = row - i; var rightTopCell = cell + i; if (topValid && rightTopRow >= 0 && rightTopCell < 19) { if (Chess[rightTopRow, rightTopCell] == chess) { score++; if (score >= 5) return true; } else topValid = false; } var leftBottomRow = row + i; var leftBottomCell = cell - i; if (bottomValid && leftBottomRow < 19 && leftBottomCell >= 0) { if (Chess[leftBottomRow, leftBottomCell] == chess) { score++; if (score >= 5) return true; } else bottomValid = false; } i++; } } #endregion #region 捺方向 ↘↖ { var i = 1; var score = 1; var topValid = true; var bottomValid = true; while (i < 5) { var leftTopRow = row - i; var leftTopCell = cell - i; if (topValid && leftTopRow >= 0 && leftTopCell >= 0) { if (Chess[leftTopRow, leftTopCell] == chess) { score++; if (score >= 5) return true; } else topValid = false; } var rightBottomRow = row + i; var rightBottomCell = cell + i; if (bottomValid && rightBottomRow < 19 && rightBottomCell < 19) { if (Chess[rightBottomRow, rightBottomCell] == chess) { score++; if (score >= 5) return true; } else bottomValid = false; } i++; } } #endregion return false; }
當對弈雙方在棋盤落子後,基於落子的座標,在四個方向:橫方向 ➡⬅、豎方向 ⬇⬆、撇方向 ↙↗、捺方向 ↘↖ 找到是否有五個連子,若是能夠找到就返回true,表示贏了,結束本局,沒找到就繼續對弈。
以上即是基於 Blazor 開發五子棋⚫⚪小遊戲的實現過程,功能比較單一,請君賞閱,最後再次祝你們端午節安康!
好了我不能再寫了,我女友喊我下五子棋⚫⚪去了。🤭🤭🤭