Realtime Blazor Tic-Tac-Toe game - Bot vs Multiplayer using signalR
Posted onEdited onDisqus:
In this article, we will see how to create a bot vs. multiplayer tic-tac-toe game in blazor. Blazor is an open source .NET web front-end framework that allows us to create client-side applications using C# and HTML. This is a simple asp.net core hosted server-side blazor front-end application with Game UI razor component and signalR game hub to connect players with the bot to play the game. The Game Bot is created with .Net Core Background Service with core game engine to identify the best move against a player using minimax recursive algorithm. The entire source code is uploaded in my github repository.
Architecture
Tic-Tac-Toe Blazor App - This is a server-side Blazor App with Tic-Tac-Toe UI razor component. The razor component will have the game board design and its logic.
SignalR Game Hub - This hub holds the signalR methods to send messages between player and bot.
Tic-Tac-Toe Bot Client - Bot client is based on .Net Core background service and contains the core game engine using the minimax algorithm. Whenever the player sends the move details to signalR hub, it will send it to bot with the current board state and bot will get the next best spot available using core game engine and send it back to hub with the bot move. The hub will send back to the caller, and the player UI will get updated the move details in real time.
How It Works - Demo
Steps
TicTacToe Blazor App
As a first step, Launch the Latest Visual Studio 2019 and create a new blazor project by selecting Asp.net Core web application and select the Blazor Server App.
I used the Blazor Server Side app for this example, but you can use client-side Blazor as well. Right now, client-side blazor app doesn’t have any official blazor signalR client due to the dependency of web socket support in the runtime. However, there are community version of the blazor signalR client is available.
In the solution explorer, add a new Razor component called TicTacToe.razor file and put the Tic-Tac-Toe board design and logic in the component. It also initializes the signalR hub client.
In this component, we have three layouts. The main layout will render the tic-tac-toe board. The other two layouts will show the result of the winner or draw panel. The main layout is using the bootstrap container to design the board, and each cell is associated with onclick event method to notify the hub with the selected cell value.
privatevoidRestartGame() { playerWon = null; isDraw = false; for (var i = 0; i < 9; i++) { board[i] = i.ToString(); } StateHasChanged(); }
}
In OnInitAsync Method, We initialize the board with the default index values. By default, the player will use X symbol and the bot will use O symbol to play.
We will also initialize signalR hub in OnInitAsync method. On click of the Cell, OnSelect method gets executed, and board item array will now have the data with the player move and send the entire board array as a parameter to hub method OnUserMoveReceived. It also listens to NotifyUser Hub method which is invoked by a bot with its move.
This hub class will hold the following signalR methods.
OnBotConnected - This method gets executed when the bot connected to signalR hub. It also adds the bot client into BOT group. This group is used to communicate with BOT only to send the message with the latest move from the player.
OnBotDisconnected - This method gets executed when the bot disconnected from signalR hub. It also removes the bot from BOT group.
OnBotMoveReceived - This method is used to notify the player (caller) after bot finish with the move and ready for the player to respond.
OnUserMoveReceived - This method is used to notify the bot after the player finish with the move and ready for a bot to respond.
async Task NotifyBot(string[] board, string connectionID) { GameEngine engine = new GameEngine(); _logger.LogInformation($"Move received from {connectionID}"); Move move = engine.GetBestSpot(board, engine.botPlayer); board[int.Parse(move.index)] = engine.botPlayer; _logger.LogInformation($"Bot Move with the index of {move.index} send to {connectionID}"); await connection.InvokeAsync("OnBotMoveReceived", board, connectionID); }
protectedoverrideasync Task ExecuteAsync(CancellationToken stoppingToken) { connection = new HubConnectionBuilder() .WithUrl("https://localhost:5001/gamehub") .Build(); connection.On<string[], string>("NotifyBot", NotifyBot); await connection.StartAsync(); // Start the connection.
//Add to BOT Group When Bot Connected await connection.InvokeAsync("OnBotConnected"); _logger.LogInformation("Bot connected");
The game bot is developed using .Net Core background service; when it started, it will connect to signalR hub. When it joins, it invokes OnBotConnected method to add it into the BOT signalR group. When it receives the message from hub with the board array data, it calculates the next best move by calling GetBestSpot method from the game engine and sends it back to the caller with its move.
When the background service is stopped, it disposes the signalR connection and remove it from BOT group.
Core Game Engine
publicclassGameEngine { publicreadonlystring botPlayer = "O"; publicreadonlystring humanPlayer = "X"; public Move GetBestSpot(string[] board, string player) { Move bestMove = null; var availableSpots = GetAvailableSpots(board); foreach (var spot in availableSpots) { string[] newboard = (string[])board.Clone(); var newMove = new Move(); newMove.index = spot; newboard[int.Parse(spot)] = player;
if (!IsWon(newboard, player) && GetAvailableSpots(newboard).Length > 0) { if (player == botPlayer) { var result = GetBestSpot(newboard, humanPlayer); newMove.index = result.index; newMove.score = result.score; } else { var result = GetBestSpot(newboard, botPlayer); newMove.index = result.index; newMove.score = result.score; } } else { if (IsWon(newboard, botPlayer)) newMove.score = 1; elseif (IsWon(newboard, humanPlayer)) newMove.score = -1; else newMove.score = 0; }
I used minimax algorithm in the game engine to find the best available spot. Minimax algorithm is a recursive algorithm which will play all possible movement by itself and as opponent until it reaches the terminal state (win or draw) and then decides the best move from those all possible iteration. You can refer this article to understand more details about minimax algorithm.
Conclusion
Blazor is super useful for .NET developers who are not interested in learning javascript for front-end development. This article shows how easy to develop real time blazor application with signalR. I have used minimax algorithm to identify the best spot available. It will be more interesting to use reinforcement machine learning algorithm for AI to learn and identify based on rewards instead of recursive minimax algorithm. This will be a good use case to try when ML.NET introduce reinforcement learning library.
The entire source code is uploaded in my github repository. Happy Coding.