SlideShare a Scribd company logo
1 of 46
CREATING A
STEALING POINTS
GAME SERVER
WITH ELIXIR
Kleber N. Gueriero
Web Developer
Ruby Developer
There is this alchemists
language ...
Created by José Valim
(Rails Core Team)
Influenced by nice
Languages(such as
Ruby and Erlang)
Functional
Runs on Erlang VM
and has a lot of
Erlang inheritance
Which kind of
inheritances?
Ready to Fault-tolerance
Handles High
Concurrency
The Game
Structs
defmodule ExStealerGame.Player do
defstruct [:id, :name, :score, :client_pid]
end
The Structs
defmodule ExStealerGame.Match do
defstruct [:last_id, {:players, []}]
end
defmodule ExStealerGame do
use Application
def start(_type, _args) do
IO.puts "STARTING THE APPLICATION"
ExStealerGame.Supervisor.start_link
end
end
Starting Point
Supervisors
New server
process was
started by
Supervisor
defmodule ExStealerGame.Supervisor do
use Supervisor
def start_link() do
Supervisor.start_link(__MODULE__, [])
End
...
end
The Supervisor
defmodule ExStealerGame.Supervisor do
use Supervisor
…
def init(_) do
children = [
worker(Task, [Server, :start_server, []]),
worker(Match, [])]
supervise children, strategy: :one_for_one
end
end
The Supervisor
Keeping State
- Elixir is Immutable
- Processes are used to keep state
- Processes sends and receives messages to
each other to request to receive/set this state
Agents
defmodule ExStealerGame.Match do
...
def start_link do
Agent.start_link(fn -> %Match{last_id: 0} end, name: __MODULE__)
end
end
The Match’s State
defmodule ExStealerGame.Match do
...
def register_player(player_name, client_pid) do
new_player = %Player{id: next_id(), name: player_name,
score: @starting_score, client_pid: client_pid}
Agent.update(__MODULE__, fn(current) ->
%{current | players: [new_player | current.players]}
end)
new_player
end
end
The Match’s State
defmodule ExStealerGame.Match do
...
def get_players do
Agent.get(__MODULE__, fn(current_match) -> current_match.players end)
end
end
The Match’s State
defmodule ExStealerGame.Server do
def start_server() do
{:ok, socket} = :gen_tcp.listen(@port, [some_options])
accept_connection(socket)
end
end
Starting the Server
Tasks
defmodule ExStealerGame.Server do
…
defp accept_connection(socket) do
{:ok, client} = :gen_tcp.accept(socket)
handle_player_join(client) # keep player with Agent and send msg to client
{:ok, pid} = Task.start(fn -> match_loop(client) end)
:gen_tcp.controlling_process(client, pid)
accept_connection(socket) # recursively keeps open to new connections
end
end
Connecting to Clients
defmodule ExStealerGame.Server do
…
defp match_loop(client) do
client
|> read_client() #wait for client’s message and receive it
|> handle_match_message(client)
match_loop(client) #again, recursively, keeps the game’s match running
end
end
The Game Loop
Pattern Matching
defmodule ExStealerGame.Server do
defp handle_match_message("quit", client) do
quit_player(client)
end
defp handle_match_message(message, client) do
...
end
end
Quitting the Game
defmodule ExStealerGame.Server do
defp quit_player(client) do
IO.puts "PLAYER QUITTING"
Match.get_player(client)
|> Match.remove_player
send_score_to_clients() # send message to clients with players list and score
Process.exit(self(), :kill) # kills current process, along with the conection
end
end
Quitting the Game
defmodule ExStealerGame.Server do
defp handle_match_message(message, client) do
case Integer.parse(message) do
{target_id, _} ->
Match.get_player(client).id
|> Match.execute_steal(target_id)
Match.get_winners
|> handle_match_state
:error -> send_score_to_clients()
end
end
end
Stealing Points
defmodule ExStealerGame.Server do
defp handle_match_state([]) do
send_score_to_clients()
end
defp handle_match_state(winners) do
...
end
end
Checking if there is a winner
defmodule ExStealerGame.Server do
defp handle_match_state(winners) do
Match.get_players
|> Enum.each(fn(player) ->
"<End of Match Message>"
|> send_to_client(player.client_pid)
end)
:timer.sleep 2000
Match.restart_match
send_score_to_clients
end
end
Checking if there is a winner
- Structs
- Supervisors
- Agents
- Tasks
- Pattern Matching
Thank’s!

More Related Content

What's hot (6)

Enumerating behaviour: PHP needs better enum [Berlin, 4. 12. 2018]
Enumerating behaviour: PHP needs better enum [Berlin, 4. 12. 2018]Enumerating behaviour: PHP needs better enum [Berlin, 4. 12. 2018]
Enumerating behaviour: PHP needs better enum [Berlin, 4. 12. 2018]
 
Specs Presentation
Specs PresentationSpecs Presentation
Specs Presentation
 
Install notes
Install notesInstall notes
Install notes
 
How to install a personal condor
How to install a personal condorHow to install a personal condor
How to install a personal condor
 
Volt ruby framework
Volt ruby frameworkVolt ruby framework
Volt ruby framework
 
Intro to MQ
Intro to MQIntro to MQ
Intro to MQ
 

Similar to TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had a SRE team at - Creating a stealing points game server with elixir

Live Streaming & Server Sent Events
Live Streaming & Server Sent EventsLive Streaming & Server Sent Events
Live Streaming & Server Sent Events
tkramar
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
deimos
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
Luiz Messias
 

Similar to TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had a SRE team at - Creating a stealing points game server with elixir (20)

Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015
 
Scaling Ruby with Evented I/O - Ruby underground
Scaling Ruby with Evented I/O - Ruby undergroundScaling Ruby with Evented I/O - Ruby underground
Scaling Ruby with Evented I/O - Ruby underground
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
The Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation PlatformsThe Challenge of Bringing FEZ to PlayStation Platforms
The Challenge of Bringing FEZ to PlayStation Platforms
 
Live Streaming & Server Sent Events
Live Streaming & Server Sent EventsLive Streaming & Server Sent Events
Live Streaming & Server Sent Events
 
Anatomy of a Gem: Bane
Anatomy of a Gem: BaneAnatomy of a Gem: Bane
Anatomy of a Gem: Bane
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
 
Elixir and OTP
Elixir and OTPElixir and OTP
Elixir and OTP
 
Concurrency in Elixir with OTP
Concurrency in Elixir with OTPConcurrency in Elixir with OTP
Concurrency in Elixir with OTP
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Introducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASHIntroducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASH
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
 

More from tdc-globalcode

More from tdc-globalcode (20)

TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidadeTDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
 
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
 
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - ACATE - Cases de SucessoTDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
 
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPATDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
 
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVinoTDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
 
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
 
TDC2019 Intel Software Day - Inferencia de IA em edge devices
TDC2019 Intel Software Day - Inferencia de IA em edge devicesTDC2019 Intel Software Day - Inferencia de IA em edge devices
TDC2019 Intel Software Day - Inferencia de IA em edge devices
 
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca PublicaTrilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
 
Trilha .Net - Programacao funcional usando f#
Trilha .Net - Programacao funcional usando f#Trilha .Net - Programacao funcional usando f#
Trilha .Net - Programacao funcional usando f#
 
TDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Go - Case EasylocusTDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Go - Case Easylocus
 
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
 
TDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - Clean architecture em GolangTDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - Clean architecture em Golang
 
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QATDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
 
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendenciaTDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
 
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR ServiceTDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
 
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NETTDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
 
TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - .NET funcional com F#TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - .NET funcional com F#
 
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor  em .Net CoreTDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor  em .Net Core
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had a SRE team at - Creating a stealing points game server with elixir

Editor's Notes

  1. Elixir é uma linguagem que possui diversas características do paradigma funcional. IMUTABILIDADE, FIRST CLASS FUNCTIONS, PATTERN MATCHING, e etc
  2. Erlang foi construído para isso. Com um conceito chamado SUPERVISOR, que trata de reiniciar pedaços do sistema quando algo da errado, Erlang te entrega uma arquitetura para lidar com isso.
  3. Seja o Erlang em si ou Elixir, empresas como Whatsapp, Facebook e Discord utilizam em aplicações de alta demanda, milhões de conexões ao mesmo tempo e etc.
  4. Nessa aplicação, utilizei da abstração Agent para gerenciar estado. Agent é uma abstração do Elixir para simplificar esse uso de estado mantido em processos
  5. Vou iniciar pelas 2 structs que defini no projeto, por serem os pontos mais simples. Em elixir, para criarmos uma estrutura pré definida de dados, nós utilizamos essa syntax “defstruct” dentro de um módulo. O nome da Struct será o mesmo nome desse módulo
  6. Nessa aplicação, utilizei da abstração Agent para gerenciar estado. Agent é uma abstração do Elixir para simplificar esse uso de estado mantido em processos
  7. Nessa aplicação, utilizei da abstração Agent para gerenciar estado. Agent é uma abstração do Elixir para simplificar esse uso de estado mantido em processos
  8. Nessa aplicação, utilizei da abstração Agent para gerenciar estado. Agent é uma abstração do Elixir para simplificar esse uso de estado mantido em processos
  9. Nessa aplicação, utilizei da abstração Agent para gerenciar estado. Agent é uma abstração do Elixir para simplificar esse uso de estado mantido em processos
  10. Nessa aplicação, utilizei da abstração Agent para gerenciar estado. Agent é uma abstração do Elixir para simplificar esse uso de estado mantido em processos