ITU coursework, 2019. Restored in 2026: input checks, stdin support, tests, CI. Original code: tag original-2019.
Run it online (Compiler Explorer, runs examples/example.game as stdin)
A simulation of a two-player card game. It uses hand-written linked-list stacks, so it is an exercise in dynamic memory. It is not a playable game. It prints how many cards end in the bin.
The cards carry a positive or negative whole number, not the usual suits and ranks. There are three decks: one for each player and one on the table. Each deck is a stack: cards are taken from the top and put on the top.
- The players take turns, player 1 first. A turn starts with the top card of the table deck. That card leaves the game.
- A positive card
nmeans the player takesncards, one by one, from the other player's deck. - A negative card
-nmeans the player givesncards, one by one, to the other player's deck. - A card that moves lands on the receiving deck only if its value is greater than the value of the card on top of that deck, or if that deck is empty. Otherwise it goes into the bin.
- The moving stops early when a deck has no card left to give.
- The game ends when the table deck or one of the player decks is empty.
The winner is the player who gives away all their cards. The program does not compute the winner. It only counts the cards in the bin.
- Line 1: two whole numbers
T P.Tis the number of cards in the table deck.Pis the number of cards in each player's deck. Both are from 0 to 100000. - Then
Ttable cards,Pcards for player 1 andPcards for player 2. One whole number per line, in the range of a 32-bitint. - Nothing but whitespace after the last card.
- Cards are pushed in file order, so the last number read for a deck ends up on top.
The reader accepts any whitespace between numbers. Lines only matter for error messages.
If the input is wrong, the program prints one line on stderr, such as error: line 3: card must be a whole number, got 'x', and exits with status 1. Wrong arguments print a usage line and exit with status 2. The result goes to stdout: the number of cards in the bin.
The files in examples/:
| File | T P |
Output |
|---|---|---|
examples/example.game |
2 3 | 2 |
examples/example2.game |
2 2 | 0 |
examples/example3.game |
6 5 | 0 |
examples/example4.game |
10 19 | 10 |
make # builds ./card_game
./card_game examples/example.game # read the game from a file
./card_game < examples/example.game # read the game from stdin
make test # runs the tests in tests/Both run commands print 2.
MIT. See LICENSE.