Skip to content
This repository was archived by the owner on May 12, 2026. It is now read-only.

Commit a4aed70

Browse files
Add check for invalid move
1 parent 76e1487 commit a4aed70

2 files changed

Lines changed: 39 additions & 7 deletions

File tree

Home/Pages/Games/Nim/Index.razor.cs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,16 @@ private void TakeCoinsOnClick(int row, int col)
5656
return;
5757
}
5858

59-
State.TakeCoins(row, col);
60-
StateHasChanged();
61-
62-
if (!State.IsGameOver)
59+
bool successfulMove = State.TakeCoins(row, col);
60+
if (successfulMove)
6361
{
64-
State.ChangePlayer(StateHasChanged);
62+
StateHasChanged();
63+
64+
if (!State.IsGameOver)
65+
{
66+
State.ChangePlayer(StateHasChanged);
67+
}
6568
}
69+
6670
}
6771
}

Home/Pages/Games/Nim/Models/GameState.cs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,14 @@ public void CreateGameBoard(int numberOfRows, ColumnConfiguration columnConfigur
4848
CurrentBoard = [.. StartingBoard];
4949
}
5050

51-
public void TakeCoins(int row, int col)
51+
public bool TakeCoins(int row, int col)
5252
{
53+
if (!IsMoveValid(row, col))
54+
{
55+
logger.LogWarning("Invalid move attempted: row {Row}, col {Col}", row, col);
56+
return false;
57+
}
58+
5359
CurrentBoard[row] = col;
5460

5561
if (CurrentBoard.All(x => x == 0))
@@ -59,6 +65,22 @@ public void TakeCoins(int row, int col)
5965

6066
logger.LogInformation("Set {Row} to {Col} coins.", row, col);
6167
logger.LogInformation("Current board: {CurrentBoard}", CurrentBoard.Select(x => x.ToString()).Aggregate((a, b) => a + ", " + b));
68+
return true;
69+
}
70+
71+
private bool IsMoveValid(int row, int col)
72+
{
73+
if (row < 0 || row >= CurrentBoard.Count)
74+
{
75+
return false;
76+
}
77+
78+
if (col < 0 || col >= CurrentBoard[row])
79+
{
80+
return false;
81+
}
82+
83+
return true;
6284
}
6385

6486
public void ChangePlayer(Action stateHasChanged)
@@ -74,7 +96,13 @@ public void ChangePlayer(Action stateHasChanged)
7496
Task.Run(() =>
7597
{
7698
Thread.Sleep(TimeSpan.FromSeconds(1)); // Pause for dramatic effect
77-
TakeCoins(ComputerMove.Value.row, ComputerMove.Value.col);
99+
bool successfulMove = TakeCoins(ComputerMove.Value.row, ComputerMove.Value.col);
100+
101+
if (!successfulMove)
102+
{
103+
logger.LogError("Computer attempted an invalid move: row {Row}, col {Col}\nWith board state: {CurrentBoard}", ComputerMove.Value.row, ComputerMove.Value.col, CurrentBoard.Select(x => x.ToString()).Aggregate((a, b) => a + ", " + b));
104+
}
105+
78106
if (!IsGameOver)
79107
{
80108
IsPlayer1Move = !IsPlayer1Move;

0 commit comments

Comments
 (0)