1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 23:07:35 +00:00

LibCards/CardStack: Helper to update the cards' disabled flags

This adds a little helper in Cards::CardStack that updates the disabled
flags for its cards depending on a movement rule. It does this by
searching from the bottom up for the last card that is valid. It then
sets the disabled flag for all cards above that card, if it isn't upside
down.
This commit is contained in:
david072 2023-11-12 11:37:52 +01:00 committed by Sam Atkins
parent 55168b50dc
commit 0a806837b5
2 changed files with 55 additions and 0 deletions

View file

@ -1,5 +1,6 @@
/*
* Copyright (c) 2020, Till Mayer <till.mayer@web.de>
* Copyright (c) 2023, David Ganz <david.g.ganz@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@ -205,6 +206,57 @@ ErrorOr<void> CardStack::add_all_grabbed_cards(Gfx::IntPoint click_location, Vec
return {};
}
void CardStack::update_disabled_cards(MovementRule movement_rule)
{
if (m_stack.is_empty())
return;
for (auto& card : m_stack)
card->set_disabled(false);
Optional<size_t> last_valid_card = {};
uint8_t last_rank;
Color last_color;
for (size_t idx = m_stack.size(); idx > 0; idx--) {
auto i = idx - 1;
auto card = m_stack[i];
if (card->is_upside_down()) {
if (!last_valid_card.has_value())
last_valid_card = i + 1;
break;
}
if (i != m_stack.size() - 1) {
bool color_valid;
switch (movement_rule) {
case MovementRule::Alternating:
color_valid = card->color() != last_color;
break;
case MovementRule::Same:
color_valid = card->color() == last_color;
break;
case MovementRule::Any:
color_valid = true;
break;
}
if (!color_valid || to_underlying(card->rank()) != last_rank + 1) {
last_valid_card = i + 1;
break;
}
}
last_rank = to_underlying(card->rank());
last_color = card->color();
}
if (!last_valid_card.has_value())
return;
for (size_t i = 0; i < last_valid_card.value(); i++)
m_stack[i]->set_disabled(true);
}
bool CardStack::is_allowed_to_push(Card const& card, size_t stack_size, MovementRule movement_rule) const
{
if (m_type == Type::Stock || m_type == Type::Waste || m_type == Type::Play)