Skip to content

Instantly share code, notes, and snippets.

@pedrosnk

pedrosnk/guessing_game.ex

Last active Jan 3, 2016
Embed
What would you like to do?
Guessing Game on Elixir based on blog post http://www.elixirdose.com/elixir-guessing-game/
defmodule GuessingGameUI do
IO.puts "Elixir Guessing Game\n\n\n"
IO.puts "========================\n"
random_number = :random.uniform(10)
user_input = GuessingGame.convert_user_input(IO.gets('Enter your guess: '))
{status, message} = GuessingGame.check_user_input(user_input)
if status == :ok do
{compare_status, compare_message} = GuessingGame.compare_numbers(random_number, user_input)
if compare_status == :ok do
IO.inspect "Conglatulations, You're the winner!"
else
IO.inspect compare_message
end
else
IO.inspect message
end
end
defmodule GuessingGame do
def check_user_input(number) when number <= 10 do
{:ok, number}
end
def check_user_input(number) do
{:error, "#{number} is not a valid number. Please input number between 1-10"}
end
def convert_user_input(input) do
input |> String.strip |> binary_to_integer
end
def compare_numbers(input_number, guess_number) when input_number == guess_number do
{:ok, "You Have guessed the number and it is #{input_number}"}
end
def compare_numbers(input_number, guess_number) when input_number != guess_number do
{:error, "you have entered #{input_number}, but the correct random number is #{guess_number}"}
end
end
defmodule GuessingGameTest do
use ExUnit.Case
test 'Checking valid user input' do
assert GuessingGame.check_user_input(5) == {:ok, 5}
assert GuessingGame.check_user_input(9) == {:ok, 9}
assert GuessingGame.check_user_input(10) == {:ok, 10}
end
test 'Invalid user input' do
# user input bigger than 10
assert GuessingGame.check_user_input(11) == {:error,
"11 is not a valid number. Please input number between 1-10"}
assert GuessingGame.check_user_input(22) == {:error,
"22 is not a valid number. Please input number between 1-10"}
end
test 'Convert user input' do
assert GuessingGame.convert_user_input("1") == 1
assert GuessingGame.convert_user_input("4\n") == 4
end
test 'Compare equality of random numbers' do
assert GuessingGame.compare_numbers(5, 5) == {:ok,
"You Have guessed the number and it is 5"}
assert GuessingGame.compare_numbers(8, 8) == {:ok,
"You Have guessed the number and it is 8"}
end
test 'Compare when the guess of random number is wrong' do
assert GuessingGame.compare_numbers(5, 6) == {:error,
"you have entered 5, but the correct random number is 6"}
assert GuessingGame.compare_numbers(8, 1) == {:error,
"you have entered 8, but the correct random number is 1"}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment