oecs-sharp/Game.TicTacToe/Commands/PlaceMarkCommand.cs

40 lines
1.1 KiB
C#

using MessagePack;
using OECS;
namespace Game.TicTacToe;
/// <summary>
/// Places the current player's mark on the cell at (Row, Col).
/// Validates that the cell is empty and the game is still playing.
/// </summary>
[MessagePackObject]
public struct PlaceMarkCommand : ICommand
{
[Key(0)] public int Row;
[Key(1)] public int Col;
public void Execute(World world)
{
if (world.ReadSingleton<GameState>().Status != GameStatus.Playing)
return;
// Find the cell entity at (Row, Col) that has no Mark.
Entity? target = null;
ref var state = ref world.GetSingleton<GameState>();
foreach(var iter in world.Select(new Query<Cell>().Without<Mark>())){
if (iter.Val1.Row != Row || iter.Val1.Col != Col) continue;
target = iter.Entity;
break;
}
if (target == null)
return;
world.AddComponent(target.Value, new Mark { Player = state.CurrentPlayer });
state.MoveCount++;
state.CurrentPlayer = state.CurrentPlayer == Player.X ? Player.O : Player.X;
}
}