計算機科学のブログ

ASP.NET Core Blazor projects - Visual Studio for Mac Learner's Guide

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のappendix ⅰ(ASP.NET Core Blazor projects - Visual Studio for Mac Learner’s Guide)、p.699(Exercise)の解答を求めてみる。

BlazorMatchGame

コード

index.razor

@page "/"

<style>
    .container {
        width:400px;
    }
    button {
        width: 100px;
        height:100px;
        font-size:50px;
    }
</style>
<div class="container">
    <div class="row">
        @for (var animalNumber = 0; animalNumber < shffueldAnimals.Count; animalNumber++)
        {
            var animal = shffueldAnimals[animalNumber];
            var animalDescription = $"Button #{animalNumber}";
            <div class="col-3">
                <button @onclick="@(() => ButtonClick(animal, animalDescription))"
                        type="button" class="btn btn-outline-dark">
                    <h1>@animal</h1>
                </button>
            </div>
        }
    </div>
    <div class="row">
        <hy2>Matches found: @matchesFound</hy2>
    </div>
</div>

@code {
    List<string> animalEmoji = new List<string>()
    {
        "🐶","🐶",
        "🐴","🐴",
        "🐮","🐮",
        "🐱","🐱",
        "🐰","🐰",
        "🦁","🦁",
        "🐯","🐯",
        "🐻","🐻",
    };
    List<string> shffueldAnimals = new List<string>();
    int matchesFound = 0;
    protected override void OnInitialized()
    {
        SetUpGame();
    }
    private void SetUpGame()
    {
        Random random = new Random();
        shffueldAnimals = animalEmoji
            .OrderBy(item => random.Next())
            .ToList();
        matchesFound = 0;
    }
    string lastAnimalFound = string.Empty;
    string lastDescription = string.Empty;
    private void ButtonClick(string animal, string animalDescription)
    {
        if (lastAnimalFound == string.Empty)
        {
            lastAnimalFound = animal;
            lastDescription = animalDescription;
        }
        else if (lastAnimalFound == animal &&
            lastDescription != animalDescription)
        {
            lastAnimalFound = string.Empty;
            shffueldAnimals = shffueldAnimals
                .Select(a => a.Replace(animal, string.Empty))
                .ToList();
            matchesFound++;
            if (matchesFound == animalEmoji.Count / 2)
            {
                SetUpGame();
            }
        }
        else
        {
            lastAnimalFound = string.Empty;
        }
    }
}