让我们使用Blazor,C#和.NET Core构建经典的儿童游戏!
我们需要下载最新版的 Visual Studio 2019,并将其更新到最新版(比如16.6版本)
写代码之前,我们要确定一下我们这个游戏所要用到的对象:
X
和O
表示 public enum PieceStyle
{
X,
O,
Blank
}
public enum EvaluationDirection
{
Up,
UpRight,
Right,
DownRight
}
public class GamePiece
{
public PieceStyle Style;
public GamePiece()
{
Style = PieceStyle.Blank;
}
}
public class WinningPlay
{
public List<string> WinningMoves { get; set; }
public EvaluationDirection WinningDirection { get; set; }
public PieceStyle WinningStyle { get; set; }
}
public class GameBoard
{
public GamePiece[,] Board { get; set; }
public PieceStyle CurrentTurn = PieceStyle.X;
public bool GameComplete => GetWinner() != null || IsADraw();
public GameBoard()
{
Reset();
}
public void Reset()
{
Board = new GamePiece[3, 3];
//将棋子转换成空白
for (int i = 0; i <= 2; i++)
{
for (int j = 0; j <= 2; j++)
{
Board[i, j] = new GamePiece();
}
}
}
private void SwitchTurns()
{
//This is equivalent to: if currently X's turn,
// make it O's turn, and vice-versa
CurrentTurn = CurrentTurn == PieceStyle.X ? PieceStyle.O : PieceStyle.X;
}
public void PieceClicked(int x, int y)
{
//If the game is complete, do nothing
if (GameComplete) { return; }
//If the space is not already claimed...
GamePiece clickedSpace = Board[x, y];
if (clickedSpace.Style == PieceStyle.Blank)
{
//Set the marker to the current turn marker (X or O), then make it the other player's turn
clickedSpace.Style = CurrentTurn;
SwitchTurns();
}
}
@page "/tictactoe"
@using BlazorWasmTicTacToe.Models;
<h1>井字棋游戏</h1>
@code { GameBoard board = new GameBoard(); }
@if (!board.GameComplete)
{
<h2>@board.CurrentTurn's Turn!</h2> }
else
{
<h2>@board.GetGameCompleteMessage() <button class="btn btn-success" @onclick="@(() => board.Reset())">Reset</button></h2>}
<div class="board">
@for (int i = 0; i < 3; i++)
{
<div class="column">
@for (int j = 0; j < 3; j++)
{
int x = i;
int y = j;
<div class="gamepiece
@board.Board[i,j].Style.ToString().ToLower()" @onclick="@(() => board.PieceClicked(x,y))"
style="@(board.IsGamePieceAWinningPiece(i, j)? "opacity: 0.6" : "")"></div>}
</div>}
</div>
完整代码请到GitHub仓库下载:
井字棋游戏[1]
今天给大家分享了如何使用 Blazor 构建井字棋游戏;大家都学会了吗?
联系客服