Advertisement
Tyrsdei

Cards 99%

Jan 21st, 2022
3,581
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.70 KB | None | 0 0
  1. defmodule Cards do
  2.   @moduledoc """
  3.  Provides methods for creating and handling a deck of cards.
  4.  """
  5.  
  6.   @doc """
  7.  Function uses a set list of values and suits, and pairs them off.
  8.  """
  9.   def create_deck do
  10.     values = ["Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
  11.     suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
  12.  
  13.     for suit <- suits, value <- values do
  14.       "#{value} of #{suit}"
  15.     end
  16.   end
  17.  
  18.   @doc """
  19.  Function takes a `deck`, created with `create_deck` and shuffles it using `Enum.shuffle()`
  20.  """
  21.   def shuffle(deck) do
  22.     Enum.shuffle(deck)
  23.   end
  24.  
  25.   @doc """
  26.  Function takes a `deck` argument against a `card` argument to see if it contains a given card using `Enum.member?()`
  27.  """
  28.   def contains?(deck, card) do
  29.     Enum.member?(deck, card)
  30.   end
  31.  
  32.   @doc """
  33.  Function deals a hand of cards using Enum.split()
  34.  
  35.  ## Examples
  36.  
  37.      iex> deck = Cards.create_deck
  38.      iex> {hand, deck} = Cards.deal(deck, 1)
  39.      iex> hand
  40.      ["Ace of Spades"]
  41.  
  42.  """
  43.   def deal(deck, hand_size) do
  44.     Enum.split(deck, hand_size)
  45.   end
  46.  
  47.   def save(deck, filename) do
  48.     binary = :erlang.term_to_binary(deck)
  49.     File.write(filename, binary)
  50.   end
  51.  
  52.   def load(filename) do
  53.  
  54.     case File.read(filename) do
  55.       {:ok, binary} -> :erlang.binary_to_term(binary)
  56.       {:error, _reason} -> "File does not exist"
  57.     end
  58.   end
  59.  
  60.   @doc """
  61.  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.
  62.  """
  63.   def create_hand(hand_size) do
  64.     Cards.create_deck |> Cards.shuffle |> Cards.deal(hand_size)
  65.   end
  66. end
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement