今天是農歷五月初五,端午節,在此,祝大家端午安康!
端午節是中華民族古老的傳統節日之一,端午也稱端五,端陽,此外,端午節還有許多別稱,如:午日節、重五節、五月節、浴蘭節、女兒節、天中節、地臘、詩人節、龍日等,
不好意思,跑題了,就此打住,
事情的經過是這樣的,今年端午節公司給每位員工都準備了一個粽子禮盒,本以來就幾個粽子而已,沒想到今年的粽子禮盒內暗藏玄關,內附一個棋盤和五子棋子,



粽子什么的都不重要,主要是這個五子棋我還挺喜歡的,哈哈哈,??
正好這段時間用 Blazor 將之前的博客重構了一遍,于是就想著能否用 Blazor 寫一個五子棋??小游戲呢?
說干就干,本篇主要是分享基于 Blazor 開發的五子棋小游戲,先放試玩地址:https://blazor.meowv.com/gobang ,
大家可以先打開鏈接讓他先加載一會(掛在GitHub,有點慢~??),再繼續回來看文章哈,


剛開始本來我是自己寫的,發現越寫越復雜,遂放棄就在Github上尋找有沒有實作過類似的需求,別說還真有一位大神用 Blazor 實作了,地址:https://github.com/ut32/gobang/ ,所以我的代碼邏輯基本上都參考這位大神的代碼,??????
接下來看看實作程序,新建一個Gobang.razorrazor組件,設定路由:@page "/gobang",
我這里直接放在之前 Blazor 實戰系列的專案中,如果你沒有看過我的 Blazor 實戰系列文章,建議你快去刷一遍,??
相信五子棋大家都玩過,規則我就不說了,
先理一下需求和實作步驟:
- 在頁面上顯示一個 19x19 的棋盤,
- 給兩個選項,電腦先手還是我先手,
- 開始游戲按鈕,結束游戲按鈕,一個按鈕,文字動態顯示,
- 落子問題,黑子始終先手,黑白交替落子,已經落子的地方不允許繼續落子,
- 黑白棋子落子的樣式問題,
- 人機對戰,電腦如何最佳選擇位置進行落子,
- 如何判斷輸贏,四個方向:橫豎撇捺,
- 實作一個簡單的五子棋小游戲,不考慮放棄落子、禁手等問題,
先渲染一個 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 開發五子棋??小游戲的實作程序,功能比較單一,請君賞閱,最后再次祝大家端午節安康!
好了我不能再寫了,我女朋友喊我下五子棋??去了,??????

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/6433.html
標籤:.NET Core
