Blazor develops Mini games? Strike while the iron is hot!!!

Blazor develops Mini games? Strike while the iron is hot!!!

Blazor has been online for a day. It's really comfortable to start developing. Let's add another tool + a few Mini games.

最后更新 6/23/2023 11:50 PM
沙漠尽头的狼
预计阅读 11 分钟
分类
Blazor
标签
.NET C# Blazor Dotnet9

Hello everyone, I am a wolf at the end of the desert.

网站使用Blazor重构上线一天了,用Blazor开发是真便捷,空闲时间查查gpt和github,又上线一个 正则表达式在线验证工具 和几个在线小游戏,比如 井字棋游戏扫雷 等。

Here is a brief introduction to see if you have any interests or suggestions.

1. New online widgets

1.1. Regular expression online verification tool

Online access: dotnet9.com/tools/regextester

This example demonstrates how to use Blazor Server to develop a simple online regular expression verification tool. Users can enter a regular expression and a test string and click the Test button to test whether the regular expression matches the test string. In addition, this example also provides more than 10 commonly used regular expression tests. Users can click a link to load test data and automatically populate regular expressions and test strings.

The annotations in the above picture simply explain:

  1. Common regular expressions: Click to automatically fill in the corresponding regular expression (Note 2) and test text (Note 3) below, click [Test](Note 4) to verify
  2. Regular expression: Fill in the regular expression you need to use
  3. Test text area: Fill in the string that needs to be verified and extracted here
  4. [Test] button: Click the regular expression (Note 2) above the application and extract the content of the test text area (Note 3), and display the matching result below (Note 5)
  5. Display matching results

There are a total of 123 lines of code, which contains commonly used regular expressions. Make it simple:

@page "/tools/regextester"
@using System.Text.RegularExpressions

<PageTitle>@_title</PageTitle>

<MApp>
    <h2 style="margin-bottom: 30px; margin-top: 10px; text-align: center;">@_title</h2>


    <h3>常用正则表达式测试</h3>

    <p>
        @foreach (var item in _regexPatterns)
        {
            <MButton Color="lime" Class="ma-2" OnClick='() => LoadTest(item.Pattern)'>@item.Name</MButton>
        }
    </p>

    <div>
        <MTextField Label="正则表达式" Type="string" TValue="string" @bind-Value="_regexPattern"/>
    </div>

    <div>
        <MTextarea BackgroundColor="grey lighten-2" Solo
                   Color="orange orange-darken-4" TValue="string" @bind-Value="_testString"
                   Label="测试字符串" Rows="8" style="font-size:12px;" RowHeight="15" AutoGrow/>
    </div>

    <div>
        <MButton Color="success" class="ma-2" OnClick="TestRegex">测试</MButton>
    </div>

    <div>
        @if (string.IsNullOrEmpty(_regexPattern) || string.IsNullOrEmpty(_testString))
        {
            <p>请输入正则表达式和测试字符串并单击“测试”按钮。</p>
        }
        else
        {
            <p>匹配结果: </p>
            <ul>
                @foreach (var match in _matches)
                {
                    <li>@match</li>
                }
            </ul>
        }
    </div>
</MApp>

@code {
        private const string? _title = "工具箱-正则表达式在线验证工具";
    private string? _regexPattern;
    private string? _testString;

    private string? _defaultString = @"下面是一些测试实例:
    history: v1.0 正则表达式测试工具上线
    v1.1 2023-06-23 刚刚上线
    1. 截至目前为止,最长域名后缀 .cancerresearch
    demo@qq.com
    dotnet9-9@vip.qq.com
    dotnet9-9@gmail.com
    demo@live.com
    127.0.0.1
    http://dotnet9.com/
    510112199901013592
    https://dotnet9.com/
    123456789012345
    18628035382
    13493532389
    川AAA008
    京B45698
    14:22:19";

    private readonly List<RegexItem> _regexPatterns = new()
    {
        new("匹配邮箱", @"\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}"),
        new("匹配中文", @"[\u4e00-\u9fa5]+"),
        new("匹配双字节字符(包含汉字)", @"[^\x00-\xff]+"),
        new("匹配时间(时:分:秒)", @"([01]?\d|2[0-3]):[0-5]?\d:[0-5]?\d"),
        new("匹配IP(IPV4)", @"\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}"),
        new("匹配身份证", @"\d{17}[0-9Xx]|\d{15}"),
        new("匹配日期(年-月-日)", @"(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)"),
        new("匹配正整数", @"[1-9]\d*"),
        new("匹配负整数", @"-[1-9]\d*"),
        new("匹配手机号", @"(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}"),
        new("匹配车牌号", @"(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))")
    };

    private readonly List<string> _matches = new();

    private void TestRegex()
    {
        if (string.IsNullOrWhiteSpace(_regexPattern) || string.IsNullOrWhiteSpace(_testString))
        {
            return;
        }
        try
        {
            var regex = new Regex(_regexPattern);
            var match = regex.Match(_testString);
            _matches.Clear();
            while (match.Success)
            {
                _matches.Add(match.Value);
                match = match.NextMatch();
            }
        }
        catch
        {
            _matches.Clear();
        }
    }

    private void LoadTest(string pattern)
    {
        _regexPattern = pattern;
        _testString = _defaultString;
    }

    record RegexItem(string Name, string Pattern);

}

2. Online online Mini games

Let me explain here first that webmasters launch Mini games just to test the pressure on the website server. If you develop Mini games, it is recommended to use client mode (wasm). After all, the pressure on the former lies on the server, and the latter lies on the user.

2.1. guess the number game

Online access: dotnet9.com/games/guessing-numbers

At the beginning of the game, a random number between 1 and 100 is generated as the target number. Players need to enter numbers to guess the target number, and the system will give corresponding prompts based on the player's guess. If the player guesses correctly, the game ends, a congratulatory message is displayed, and a button is provided to start a new game.

This game is simple, with dozens of lines of code:

@page "/games/guessing-numbers"

<PageTitle>@_title</PageTitle>

<MApp>
    <h2 style="margin-bottom: 30px; margin-top: 10px; text-align: center;">@_title</h2>

    @if (_isGameOver)
    {
        <p>@_message</p>
        <p>游戏结束!</p>
        <p>
            <MButton Color="lime" Class="ma-2" OnClick='StartNewGame'>开始新游戏</MButton>
        </p>
    }
    else
    {
        <p>猜一个1到100之间的数字:</p>
        <p>
            <MTextField Label="数字" Type="string" TValue="int" @bind-Value="_guess"/>
        </p>
        <p>
            <MButton Color="success" class="ma-2" OnClick="CheckGuess">猜!</MButton>
        </p>
        <p>@_message</p>
    }
</MApp>


@code {
    readonly string? _title = "猜数字游戏";
    private int _targetNumber;
    private int _guess;
    private string? _message;
    private bool _isGameOver;

    protected override void OnInitialized()
    {
        StartNewGame();
    }

    private void StartNewGame()
    {
        var random = new Random();
        _targetNumber = random.Next(1, 101);
        _guess = 0;
        _message = "";
        _isGameOver = false;
    }

    private void CheckGuess()
    {
        if (_guess == _targetNumber)
        {
            _message = "恭喜你猜对了!";
            _isGameOver = true;
        }
        else if (_guess < _targetNumber)
        {
            _message = "猜小了!";
        }
        else
        {
            _message = "猜大了!";
        }
    }

}

2.2. tic-tac-toe game

Online access: dotnet9.com/games/tictactoe

A simple tic-tac-toe game where players can click on the squares on the board to play chess. The game checks whether a player wins or draws, and displays a corresponding message at the end of the game. Players can click the "Start New Game" button to restart the game.

Line 117 of the code:

@page "/games/tictactoe"

<PageTitle>@_title</PageTitle>

<MApp>
    <h2 style="margin-bottom: 30px; margin-top: 10px; text-align: center;">@_title</h2>

    @if (_isGameOver)
    {
        <p>@_message</p>
        <p>游戏结束!</p>
        <MButton Color="lime" Class="ma-2" OnClick='StartNewGame'>开始新游戏</MButton>
    }
    else
    {
        <div style="text-align: center;">
            @for (var i = 0; i < 3; i++)
            {
                <div>
                    @for (var j = 0; j < 3; j++)
                    {
                        var i1 = i * 3 + j;
                        <MButton Color="lime" OnClick='() => MakeMove(i1)' Disabled='IsCellDisabled(i1)'>@_board[i1]</MButton>
                    }
                </div>
            }
        </div>
        <p>@_message</p>
    }
</MApp>

@code {
    readonly string? _title = "井字棋游戏";
    private string?[] _board = new string[9];
    private string _currentPlayer = "X";
    private string? _message;
    private bool _isGameOver;

    private void MakeMove(int index)
    {
        if (_board[index] != null || _isGameOver)
        {
            return;
        }
        _board[index] = _currentPlayer;
        if (CheckWin(_currentPlayer))
        {
            _message = $"玩家 {_currentPlayer} 获胜!";
            _isGameOver = true;
        }
        else if (_board.All(cell => cell != null))
        {
            _message = "平局!";
            _isGameOver = true;
        }
        else
        {
            _currentPlayer = _currentPlayer == "X" ? "O" : "X";
            if (_currentPlayer == "O")
            {
                MakeComputerMove();
            }
        }
    }

    private void MakeComputerMove()
    {
    // 简单的随机选择一个可用的方格来下棋
        var availableMoves = Enumerable.Range(0, 9).Where(i => _board[i] == null).ToList();
        var random = new Random();
        var randomIndex = random.Next(availableMoves.Count);
        var computerMove = availableMoves[randomIndex];
        _board[computerMove] = _currentPlayer;

        if (CheckWin(_currentPlayer))
        {
            _message = $"电脑获胜!";
            _isGameOver = true;
        }
        else if (_board.All(cell => cell != null))
        {
            _message = "平局!";
            _isGameOver = true;
        }
        else
        {
            _currentPlayer = _currentPlayer == "X" ? "O" : "X";
        }
    }

    private bool CheckWin(string player)
    {
    // 检查所有可能的获胜组合
        return (_board[0] == player && _board[1] == player && _board[2] == player) ||
               (_board[3] == player && _board[4] == player && _board[5] == player) ||
               (_board[6] == player && _board[7] == player && _board[8] == player) ||
               (_board[0] == player && _board[3] == player && _board[6] == player) ||
               (_board[1] == player && _board[4] == player && _board[7] == player) ||
               (_board[2] == player && _board[5] == player && _board[8] == player) ||
               (_board[0] == player && _board[4] == player && _board[8] == player) ||
               (_board[2] == player && _board[4] == player && _board[6] == player);
    }

    private bool IsCellDisabled(int index)
    {
        return _isGameOver || _board[index] != null;
    }

    private void StartNewGame()
    {
        _board = new string[9];
        _currentPlayer = "X";
        _message = null;
        _isGameOver = false;
    }

}

2.3. Online minesweeping games

Online access: dotnet9.com/games/minesweeper

In this example, the player needs to click on the squares to uncover them. If the player steps on a mine, the game ends. If there are mines around the square uncovered by the player, the corresponding number will be displayed on the square, indicating the number of mines around it. If the player successfully uncovers all squares without mines, the game wins.

此游戏高度还原早期Window版本扫雷,代码较多,抄自开源项目:https://github.com/jarDotNet/BlazorMinesweeper, 如果对代码感兴趣可查看该开源项目,或阅读 Dotnet9网站 关于扫雷部分代码:

3. last words

Once again, the Mini games on the website are only for testing. It is not recommended to develop game functions in Server mode. Leave this to Client mode.

Welcome to leave a message if you have any tool needs, and the webmaster will consider adding them when he has time.

I'm here to share today and wish everyone a healthy Dragon Boat Festival.

  • Website address: dotnet9.com/
  • Website source code: github.com/dotnet9/Dotnet9
  • .NET版本: .NET 8.0.0-preview.5.23280.8
  • WeChat technology group: To add webmaster WeChat (codewf), you must note the two words "join the group"
  • QQ technology group: 771992300
Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 6/23/2023

The Dotnet9 website has returned to Blazor reconstruction, making access faster and interaction more convenient!

Originally, webmasters rushed to experience the. NET 8 Blazor Web App and added Razor components to Razor Pages. However, the mixed-mode Razor component cannot interact, and the page also has a reconnection gray UI. They simply use Blazor Server to reconstruct it directly. After several days of hard work, the front desk of the website has completely replaced Razor Pages with Blazor Server, and the annoying reconnection has been solved. Now the website is very fast. I don't know if it's an illusion, but I feel very good.

继续阅读
同分类 / 同标签 11/6/2024

Why is my blog site back in Blazor?

The blog website has gone through hardships in development. It has tried nearly 10 versions such as MVC, Vue, and Go. Now it has returned to Blazor and adopts static SSR. The speed has skyrocketed and it has been successfully launched.

继续阅读
同分类 / 同标签 2/29/2024

Data display can also be done in Winform

In the process of developing winform, data display functions are often needed. I have been using the gridcontrol before. Today, I want to use an example to introduce to you how to use the table component in ant design blazor hybrid to display data.

继续阅读
同分类 / 同标签 2/29/2024

Can Winform's interface become better?

A few days ago, I introduced to you the use of blazor hybrid in winform, and I also said that with blazor's ui, our winform program design can be more beautiful. Next, I want to use an example of drawing in winform blazor hybrid to illustrate it, hoping to be helpful to you.

继续阅读