We did the card dealing program as our complex program. This program takes in a number
of players and a number of cards per hand, then returns what cards each player has
along with what cards remain in the deck. It can be compiled with the following command:
$ cargo build
This is required as the program uses the rand library which cargo is able to import.
Once that is done, the program can be run with command line arguments and the next command:
$ cargo run <num-players> <cards-per-hand>
The program will output something similar to the following:
The main.rs file runs most of the program.
It first parses the command line arguments as integers, then initializes the deck.
//parse the args
let arg1 = args[1].clone();
let arg2 = args[2].clone();
//parse the args as ints
let num_players = arg1.parse::().unwrap();
let cards_per_hand = arg2.parse::().unwrap();
//create the deck and the suits
let suits = ["Hearts", "Diamonds", "Clubs", "Spades"];
let binding = String::new();
let mut cardDeck = Deck {cards: [Card { suit: &binding, value: 0}; 52]};
We then populate the deck with cards and use a double for loop to deal a random card from the deck
to each player.
for current_hand in &mut player_hands{
for j in 0..cards_per_hand{
//choose a random card and add it
let random_card = rng.gen_range(0..current_deck_size);
current_hand.cards.push(cardDeck.cards[random_card]);
//remove the card from the deck
let mut temp_card = cardDeck.cards[current_deck_size-1]; //temp storage of last card
cardDeck.cards[current_deck_size-1] = cardDeck.cards[random_card]; //set last card to random card
cardDeck.cards[random_card] = temp_card; //random card index = the former last card
current_deck_size = current_deck_size-1;
}
}
Finally the cards for each hand is printed along with what remains of the deck.