How to lock TicTacToe matchfield after a player won?

lukas9669

Member
Joined
Feb 7, 2022
Messages
9
Programming Experience
1-3
I am actually programming a tic tac toe game with the blazor framework and I have already a function to lock the button if it was clicked. It looks like this:
The Class which contains the button:
public class ElementOfMatchField
    {
        public int Row { get; set; }

        public int Column { get; set; }


        public string Symbol { get; set; }

        public bool WasClicked => !string.IsNullOrEmpty(Symbol);

        public ElementOfMatchField(int row, int column)
        {
            this.Row = row;
            this.Column = column;
            
        }
    }

and the html:
@if (MatchField != null)
    {
        @foreach (var field in MatchField)
        {
            <div>
                <button class='space' @onclick="() => PrintSymbolOnButton(field)" disabled="@field.WasClicked">
                        @field.Symbol
                </button>
            </div>
        }
    }


How can I write the funtion? the code to check if any player has won looks like this:
C#:
public void CalculatePlayerWon()
    {
        foreach (var player in players)
        {
            for (int i = 0; i < FieldCount; i++)
            {
                var allRow1 = MatchField.Where(x => x.Row == i && x.Symbol == player.Symbol);
                var allRow2 = MatchField.Where(x => x.Column == i && x.Symbol == player.Symbol);

                if (allRow1.Count() == FieldCount || allRow2.Count() == FieldCount)
                {
                    playerWon = player.Symbol + " has won.";
                    break;
                }
            }

            var diagonale1 = MatchField.Where(x => (x.Row == 0 && x.Column == 0) || (x.Row == 1 && x.Column == 1) || (x.Row == 2 && x.Column == 2));
            var diagonale2 = MatchField.Where(x => (x.Row == 0 && x.Column == 2) || (x.Row == 1 && x.Column == 1) || (x.Row == 2 && x.Column == 0));

            bool hasWonDiag1 = diagonale1.All(x => x.Symbol == player.Symbol);
            bool hasWonDiag2 = diagonale2.All(x => x.Symbol == player.Symbol);

            if (hasWonDiag1 || hasWonDiag2)
            {
                playerWon = player.Symbol + " has won.";
                break;
            }
        }
      
    }
 
It looks like you have this:
C#:
disabled="@field.WasClicked"

Why not something like:
C#:
disabled="@field.Disabled"

And have the Disabled property depend on WasClicked OR IsLocked , then add a IsLocked property.
 
Back
Top Bottom