Created
September 5, 2017 02:58
-
-
Save jacobhenke/a52b4e602d5c8d79e7b5482b722af68e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] | |
suits = ["Spades", "Clubs", "Hearts", "Diamonds"] | |
# cards = for suit <- suits do | |
# for value <- values do | |
# "#{value} of #{suit}" | |
# end | |
# end | |
# List.flatten(cards) | |
# does the same: | |
for suit <- suits, value <- values do | |
"#{value} of #{suit}" | |
end | |
end | |
def shuffle(deck) do | |
Enum.shuffle(deck) | |
end | |
@doc """ | |
Determines wheather a deck contains a given card | |
## Examples | |
iex> deck = Cards.create_deck | |
iex> Cards.contains?(deck, "Ace of Spades") | |
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 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 | |
# {status, binary} = File.read(filename) | |
# case status do | |
# :ok -> :erlang.binary_to_term binary | |
# :error -> "That file does not exist" | |
# end | |
# does the same | |
case File.read(filename) do | |
{:ok, binary} -> :erlang.binary_to_term binary | |
{:error, _} -> "That file does not exist" | |
end | |
end | |
def create_hand(hand_size) do | |
Cards.create_deck | |
|> Cards.shuffle | |
|> Cards.deal(hand_size) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment