Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- defmodule Cards do
- @moduledoc """
- Provides methods for creating and handling a deck of cards.
- """
- @doc """
- Function uses a set list of values and suits, and pairs them off.
- """
- def create_deck do
- values = ["Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
- suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
- for suit <- suits, value <- values do
- "#{value} of #{suit}"
- end
- end
- @doc """
- Function takes a `deck`, created with `create_deck` and shuffles it using `Enum.shuffle()`
- """
- def shuffle(deck) do
- Enum.shuffle(deck)
- end
- @doc """
- Function takes a `deck` argument against a `card` argument to see if it contains a given card using `Enum.member?()`
- """
- def contains?(deck, card) do
- Enum.member?(deck, card)
- end
- @doc """
- Function deals a hand of cards using Enum.split()
- ## Examples
- iex> deck = Cards.create_deck
- iex> {hand, deck} = Cards.deal(deck, 1)
- iex> hand
- ["Ace of Spades"]
- """
- def deal(deck, hand_size) do
- Enum.split(deck, hand_size)
- end
- def save(deck, filename) do
- binary = :erlang.term_to_binary(deck)
- File.write(filename, binary)
- end
- def load(filename) do
- case File.read(filename) do
- {:ok, binary} -> :erlang.binary_to_term(binary)
- {:error, _reason} -> "File does not exist"
- end
- end
- @doc """
- Function takes a `hand_size` argument, and pipes `create_deck` to `shuffle` with a final pipe to `deal` which uses the provided `hand_size` argument.
- """
- def create_hand(hand_size) do
- Cards.create_deck |> Cards.shuffle |> Cards.deal(hand_size)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement