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 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 |
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
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