55 lines
1.4 KiB
C#
55 lines
1.4 KiB
C#
using MessagePack;
|
|
using OECS;
|
|
|
|
namespace Game.Blackjack;
|
|
|
|
/// <summary>
|
|
/// Player hits: draws one card from the deck to the player's hand.
|
|
/// </summary>
|
|
[MessagePackObject]
|
|
public struct HitCommand : ICommand
|
|
{
|
|
public void Execute(World world)
|
|
{
|
|
var state = world.ReadSingleton<GameState>();
|
|
|
|
if (state.Phase != GamePhase.PlayerTurn)
|
|
return;
|
|
|
|
DrawCard<PlayerHand>(world);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Draws the top card from the deck and adds it to the given hand.
|
|
/// </summary>
|
|
internal static void DrawCard<THand>(World world)
|
|
where THand : struct
|
|
{
|
|
var deckEntity = world.FindEntity<Deck>();
|
|
var handEntity = world.FindEntity<THand>();
|
|
|
|
if (deckEntity == Entity.Null || handEntity == Entity.Null)
|
|
return;
|
|
|
|
// Find a card still in the deck.
|
|
var cardsInDeck = world.GetSources<InDeck>(deckEntity);
|
|
if (cardsInDeck.Count == 0)
|
|
return;
|
|
|
|
var cardEntity = cardsInDeck.First();
|
|
|
|
// Remove from deck, add to hand.
|
|
world.RemoveComponent<InDeck>(cardEntity);
|
|
world.AddComponent(cardEntity, new Holds { Target = handEntity });
|
|
|
|
// Flush so subsequent DrawCard calls see the updated state.
|
|
world.FlushPendingMutations();
|
|
}
|
|
|
|
internal static Entity FindEntity<T>(World world)
|
|
where T : struct
|
|
{
|
|
return world.FindEntity<T>();
|
|
}
|
|
}
|