Solution: Lets Play Cards
The solution to the cards coding challenge is provided in this lesson.
Problem 1: Solution
Press + to interact
struct Card {dchar suit;dchar value;}void main () {}
Solution explanation
- Lines 2 and 3:
Since we have to store the value
and suit
of the card, one of the simplest designs is to use two dchar
members.
Problem 2: Solution
Press + to interact
import std.stdio;struct Card {dchar suit;dchar value;this(dchar s, dchar v) { // constructorsuit = s;value = v;}}void printCard(Card card) {write(card.suit, card.value);}void main() {auto card = Card('♠','4');printCard(card);}
Solution explanation
- Line 14:
Our goal is to print the suit shape and value together, so we are using the write
function here, which has two parameters: card.suit
and card.value
.
Problem 3: Solution
Press + to interact
import std.stdio;struct Card {dchar suit;dchar value;}void printCard(Card card) {write(card.suit, card.value);}Card[] newDeck()out (result) {assert(result.length == 52);} do {Card[] deck;deck ~= newSuit('♠');deck ~= newSuit('♡');deck ~= newSuit('♢');deck ~= newSuit('♣');return deck;}Card[] newSuit(dchar suit)in {assert((suit == '♠') ||(suit == '♡') ||(suit == '♢') ||(suit == '♣'));} out (result) {assert(result.length == 13);} do {Card[] suitCards;foreach (value; "234567890JQKA") {suitCards ~= Card(suit, value);}return suitCards;}void main() {Card[] deck = newDeck();int count;foreach (card; deck) {printCard(card);write(' ');count++;if(count%13 == 0){writeln();}}writeln();}
Solution explanation
- Lines 17 - 20