Skip to content

Instantly share code, notes, and snippets.

@pguillory
Last active Feb 25, 2016
Embed
What would you like to do?
defmodule Game do
# Client
def start do
spawn &Game.play/0
end
def move(pid, request) do
send(pid, {:request, self, request})
receive do
{:response, ^pid, response} -> response
end
end
# Server
def listen do
receive do
{:request, pid, request} ->
Process.put(:last_pid, pid)
request
end
end
def reply(response) do
pid = Process.get(:last_pid)
send(pid, {:response, self, response})
end
def play do
case listen do
name -> reply "Hello #{name}. You are in a maze. You can go :left or :right."
case listen do
:left -> reply "You are eaten by a grue. Game over, #{name}."
:right -> reply "You see an old man. He asks your favorite color."
case listen do
:blue -> reply "You win #{name}!"
_ -> reply "He tosses you into a pit. Game over, #{name}."
end
end
end
end
end
iex(1)> import Game
nil
iex(2)> g = start
#PID<0.69.0>
iex(3)> move g, "Mario"
"Hello Mario. You are in a maze. You can go :left or :right."
iex(4)> move g, :right
"You see an old man. He asks your favorite color."
iex(5)> move g, :blue
"You win Mario!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment