Implement a card simulation system similar to the board game Splendor. A player holds gems in five colors: Blue (B), White (W), Green (G), Red (R), Yellow (Y). Each card has a gem cost to purchase it, and the card itself has a color. The data model and code structure are up to you.
There are three tasks to implement:
- Implement a
can_purchase(card, player_gems)function. Given a card and the player's gem inventory, decide whether the player can afford the card, and return true or false. - Implement a
purchase(card, player_gems)function. First check whether the player can afford the card. If so, add the card to the player's hand, deduct the gem cost from the player's gem inventory, and return true. Otherwise return false. - Introduce a discount mechanism. The colors of the cards already in the player's hand act as gem discounts on the same color when buying new cards later (for example, 1 card of a color covers 1 gem of that color). For example: if the player's hand has 2 White cards and 1 Red card, and they want to buy a card that costs 4 White and 1 Red gems, after the discount they only need to pay 2 White gems.
Follow-up
If the system needs to run in a multi-threaded / parallel environment, where the same player might send multiple card purchase requests at the same time, how would you change the current design to guarantee concurrency safety and data consistency?
Discussion
Loading comments…