|
# iex -r host.lan.ex |
|
|
|
defmodule Host do |
|
@host :host |
|
@client :client |
|
|
|
@questions [ |
|
["Who created Elixir? José ...?", "Valim"], |
|
["In which year did Elixir first appear?", "2011"], |
|
["What lies underneath Elixir?", "Erlang"], |
|
["Did you enjoy the presentation?", "Yes"] |
|
] |
|
|
|
def run() do |
|
Process.register(self(), @host) |
|
|
|
[@host, ip()] |
|
|> Enum.join("@") |
|
|> String.to_atom() |
|
|> Node.start(:longnames) |
|
Node.set_cookie(:cookie) |
|
IO.inspect(Node.self()) |
|
|
|
loop() |
|
end |
|
|
|
defp ip() do |
|
{:ok, [{ip, _, _}, _]} = :inet.getif() |
|
|
|
ip |
|
|> Tuple.to_list() |
|
|> Enum.join(".") |
|
end |
|
|
|
defp loop() do |
|
index = 0 |
|
ask(index) |
|
loop(index) |
|
end |
|
|
|
defp loop(index) do |
|
receive do |
|
{client, {name, :hello}} -> |
|
greet(index, client, name) |
|
{client, {name, answered}} -> |
|
check(index, client, name, answered) |
|
end |
|
|> case do |
|
:next -> |
|
index = index + 1 |
|
ask(index) |
|
index |
|
_ -> index |
|
end |
|
|> loop() |
|
end |
|
|
|
defp greet(index, client, name) do |
|
IO.puts("Hello, #{name}!") |
|
ask(index, client) |
|
end |
|
|
|
defp ask(index) do |
|
IO.puts(question(index)) |
|
Enum.each(Node.list(), fn(client) -> |
|
ask(index, client) |
|
end) |
|
end |
|
|
|
defp ask(index, client) do |
|
send_message(client, {question(index), :ask}) |
|
end |
|
|
|
defp check(index, client, name, answered) do |
|
answer = answer(index) |
|
|
|
{status, {reply, _} = message} = |
|
case answered do |
|
^answer -> |
|
{:next, {"Correct, #{name}!", :listen}} |
|
_ -> |
|
{:idle, {"Ah, #{name}. Try again!", :ask}} |
|
end |
|
|
|
IO.puts("#{reply} #{inspect answered}") |
|
send_message(client, message) |
|
status |
|
end |
|
|
|
defp question(index) do |
|
@questions |
|
|> Enum.at(index) |
|
|> Enum.at(0) |
|
end |
|
|
|
defp answer(index) do |
|
@questions |
|
|> Enum.at(index) |
|
|> Enum.at(1) |
|
end |
|
|
|
defp send_message(client, message) do |
|
destination = {@client, client} |
|
send(destination, message) |
|
end |
|
|
|
end |
|
|
|
Host.run() |