Skip to content

Instantly share code, notes, and snippets.

@Automatic365
Last active February 23, 2018 20:44
Show Gist options
  • Save Automatic365/73d6aa723a4e998912dad2172ec7eeb1 to your computer and use it in GitHub Desktop.
Save Automatic365/73d6aa723a4e998912dad2172ec7eeb1 to your computer and use it in GitHub Desktop.
Elixir - Cards app

First, we will need to generate a new project. To do this in Elixir, we will run the command

mix new Cards

Now navigate to the lib directory and let's look at the Cards.ex file.

defmodule Cards do
  @moduledoc """
  Provides methods for creating and handling a deck of cards
  """

@doc """
Returns a list of strings representing a deck of playing cards
"""
  def create_deck do
    values = ["Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
              "Eight","Nine", "Ten", "Jack", "Queen", "King"]
    suits = ["Clubs", "Spades", "Hearts", "Diamonds"]

    for suit <- suits, value <- values do
        "#{value} of #{suit}"
      end
  end

  def shuffle(deck) do
    Enum.shuffle(deck)
  end

@doc """
Determines whether a deck contains a specific card
## Example
    iex> deck = Cards.create_deck
    iex> Cards.contains?(deck, "Two of Clubs")
    true
"""
  def contains?(deck, card) do
    Enum.member?(deck, card)
  end

@doc """
Divides a deck into a hand and the remainder of the deck.
The `hand_size` argument indicates how many cards should be
in the hand.
## Examples
    iex> deck = Cards.create_deck
    iex> {hand, deck} = Cards.deal(deck, 1)
    iex> hand
    ["Ace of Clubs"]
"""
  def deal(deck, hand_size) do
    Enum.split(deck, hand_size)
  end

  def create_hand(hand_size) do
    Cards.create_deck
    |> Cards.shuffle
    |> Cards.deal(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} -> "This file does not exist"
    end
  end

end 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment