claudia doppioslash - time travel for game development with elm
TRANSCRIPT
Time TravelTime Travelfor Game Developmentfor Game Development
with Elmwith Elmby by @doppioslash@doppioslash
20th of November 2015 - Codemotion - Milan
+ClaudiaDoppioslash+ClaudiaDoppioslash
@doppioslash@doppioslash
blog.doppioslash.comblog.doppioslash.com
About meAbout me
Game Developer &Game Developer &
Functional ProgrammerFunctional Programmer
Table of ContentsTable of ContentsGameDev workflow = hellTime Travelling Debugger?Meet ElmStructuring programs in ElmTime Travelling DemoGotchas
What is the single mostWhat is the single mostsoul destroying thing insoul destroying thing in
game development?game development?
What is the single most soulWhat is the single most souldestroying thing in gamedestroying thing in game
development?development?
C++?C++?
What is the single most soulWhat is the single most souldestroying thing in gamedestroying thing in game
development?development?
Having to redo a 10Having to redo a 10moves combo everymoves combo every
time you check iftime you check ifthe bug is gone?the bug is gone?
What is the single most soulWhat is the single most souldestroying thing in gamedestroying thing in game
development?development?
Projects gettingProjects gettingcanned?canned?
Slow Iteration timesSlow Iteration times
What is the single most soulWhat is the single most souldestroying thing in gamedestroying thing in game
development?development?
Example CommonExample CommonGame DevelopmentGame Development
WorkflowWorkflow(starring Unity)(starring Unity)
1. Write some code1. Write some code
Example CommonExample Common
Game Development WorkflowGame Development Workflow
2. Playtest it2. Playtest it(in the Unity Editor)(in the Unity Editor)
Example CommonExample Common
Game Development WorkflowGame Development Workflow
Now to test thatNow to test thatsame change onsame change onmobile devices:mobile devices:
Example Common Game DevelopmentExample Common Game DevelopmentWorkflow (starring Unity)Workflow (starring Unity)
Make a change and test onMake a change and test onDeviceDevice
1. Start build1. Start build
Make a change and test onMake a change and test onDeviceDevice
3. load the ipa/apk3. load the ipa/apkon deviceon device
Make a change and test onMake a change and test onDeviceDevice
4. playtest until your4. playtest until yourcode runscode runs
Make a change and test onMake a change and test onDeviceDevice
5. Find new and5. Find new andexciting bugsexciting bugs(only on device)(only on device)
Slow Iteration timesSlow Iteration times
Say bye to FlowSay bye to Flow
Slow Iteration timesSlow Iteration times
Error prone forest ofError prone forest ofbuild settingsbuild settings
Slow Iteration timesSlow Iteration times
Deadline panic 10xDeadline panic 10xincreaseincrease
(suffering together at late hours might be team-buildingbut surely we don't need this :P)
What can fix this?What can fix this?
What can help?What can help?
Jenkins churning buildsJenkins churning buildsout in backgroundout in background
What can help?What can help?
Type system to catchType system to catchbugs before runningbugs before running
What can help?What can help?
Unit testingUnit testing
What is the idealWhat is the idealworkflow?workflow?
InventingInventingonon
PrinciplePrinciple
As seen on :LambdaCat
Inventing on PrincipleInventing on Principle
Hot reloadHot reload::reload changes to thereload changes to thecode without stoppingcode without stopping
the gamethe game
Inventing on PrincipleInventing on Principle
Time TravelTime Travel::being able to scrubbeing able to scrubto any point in theto any point in the
sessionsession
Inventing on PrincipleInventing on Principle
OmniscienceOmniscience::see all the statesee all the statein the sessionin the session
Is that even possible?Is that even possible?
Racket,VR andRacket,VR andJohn CarmackJohn Carmack
(watch it)(watch it)
John CarmackJohn Carmack
John CarmackJohn Carmack LISP (Racket)LISP (Racket)
Which language makes itWhich language makes itall possible RIGHT NOW?all possible RIGHT NOW?
ElmElm
(I'm sure no one saw this coming)(I'm sure no one saw this coming)
((
Mario demo)Mario demo)
debug.elm-lang.orgdebug.elm-lang.org
What sort ofWhat sort oflanguage is Elm?language is Elm?
What sort of language is Elm?What sort of language is Elm?
PurelyPurelyFunctionalFunctional
FunctionalFunctionalReactiveReactive
(FRP)(FRP)
What sort of language is Elm?What sort of language is Elm?
EagerEager
What sort of language is Elm?What sort of language is Elm?
Static TypeStatic TypeSystemSystem
What sort of language is Elm?What sort of language is Elm?
Compiles toCompiles toJavascript,Javascript,HTML, CSSHTML, CSS
What sort of language is Elm?What sort of language is Elm?
Interoperates withInteroperates withJavascript while stillJavascript while still
being type safebeing type safe
What sort of language is Elm?What sort of language is Elm?
SmallSmall
What sort of language is Elm?What sort of language is Elm?
Invented byInvented byEvan CzaplickiEvan Czaplickifor his thesisfor his thesis
What sort of language is Elm?What sort of language is Elm?
Meant to beMeant to beapproachableapproachableand practicaland practical
What sort of language is Elm?What sort of language is Elm?
Meant to be approachableMeant to be approachableand practicaland practical
No 'scary' terms likeNo 'scary' terms likeMonadMonad
In Production atIn Production at
Elm ReactorElm Reactor(the Time Travelling Debugger)(the Time Travelling Debugger)
Elm ReactorElm Reactor
Inspired byInspired byInventing onInventing on
PrinciplePrinciple
Elm ReactorElm Reactor
FundamentalsFundamentalsmade in a fewmade in a fewdays by Laszlodays by Laszlo
Elm ReactorElm Reactor
Elm's languageElm's languagedesign isdesign is
accidentallyaccidentally'compatible''compatible'
Elm ReactorElm Reactor
You can "stepYou can "stepthrough" whilethrough" while
moving the mousemoving the mouse
How do youHow do youstructurestructure
programs inprograms inElm?Elm?
The Functional TriforceThe Functional Triforce
MaybeMaybe
UnionUnionTypesTypes
PatternPatternMatchingMatching
The Functional TriforceThe Functional Triforce
Union TypesUnion Types
define the Model:define the Model:
type Tile = Door Size | Column | BackGround BackGroundTile | Shadow ShadowTile
The Functional TriforceThe Functional Triforce
MaybeMaybe
gets rid of NULL errorsgets rid of NULL errors
type Maybe a = Just a | Nothing
The Functional TriforceThe Functional Triforce
Pattern MatchingPattern MatchingString.toInt : String -> Maybe Int
toMonth : String -> Maybe Int toMonth rawString = case String.toInt rawString of Nothing -> Nothing Just n -> if n > 0 && n <= 12 then Just n else Nothing
Elm ArchitectureElm Architecture
Elm isElm isopinionatedopinionated
Elm ArchitectureElm Architecture
Use theUse the"" ""Elm ArchitectureElm Architecture
Elm ArchitectureElm Architecture
ModelModel
ViewView
UpdateUpdate
OverviewOverview
Elm ArchitectureElm Architecture
ModelModel = =the Data Structurethe Data Structurewe pass aroundwe pass around
ModelModel
type alias UserInput = {}userInput : Signal UserInputuserInput = Signal.constant {}type alias Input = { timeDelta : Float , userInput : UserInput }
ModelModel
type alias UserInput = {}userInput : Signal UserInputuserInput = Signal.constant {}type alias Input = { timeDelta : Float , userInput : UserInput }
TypeTypesignaturesignature
ModelModel
type alias UserInput = {}userInput : Signal UserInputuserInput = Signal.constant {}type alias Input = { timeDelta : Float , userInput : UserInput }
A recordA record
Type aliasType alias
SignalSignal
ModelModel
Record =Record =
set of key value pairsset of key value pairs
ModelModel
Type alias =Type alias =
give name to a set of fieldsgive name to a set of fieldsin a recordin a record
ModelModel
Signal =Signal =
updates every time variableupdates every time variablechangeschanges
ModelModel
type alias GameState = {}defaultGame : GameStatedefaultGame = {}
Elm ArchitectureElm Architecture
ViewView = =the code thatthe code thatrenders from therenders from theModelModel
DisplayDisplay
display : (Int,Int) -> GameState ->Element
display (w,h) gameState = showgameState
DisplayDisplay
display : (Int,Int) -> GameState ->Element
display (w,h) gameState = showgameState
TypeTypesignaturesignature
Elm ArchitectureElm Architecture
UpdateUpdate = =the function thatthe function thatdoes the change ofdoes the change ofstate state
UpdateUpdate
stepGame : Input -> GameState ->GameStatestepGame {timeDelta,userInput}gameState = gameState
UpdateUpdate
stepGamestepGame uses theuses thecurrentcurrent InputInput
(which is (which is UserInputUserInput and a and atimeDeltatimeDelta))
to make a newto make a new GameStateGameState
Elm ArchitectureElm Architecture
SignalsSignals
SignalsSignals
delta : Signal Floatdelta = Time.fps 30input : Signal Inputinput = Signal.sampleOn delta (Signal.map2 Input delta userInput)
sampleOnsampleOn
SignalsSignals
delta : Signal Floatdelta = Time.fps 30input : Signal Inputinput = Signal.sampleOn delta (Signal.map2 Input delta userInput)
map2map2
SignalsSignals
gameState : Signal GameStategameState = Signal.foldp stepGame defaultGame input
SignalsSignals
gameState : Signal GameStategameState = Signal.foldp stepGame defaultGame input foldpfoldp
SignalsSignals
Signal.map2 = Signal.map2 =
applies a function thatapplies a function thattakes 2 arguments takes 2 arguments
to a signalto a signal
SignalsSignals
Signal.sampleOn =Signal.sampleOn =samples from 2ndsamples from 2ndinput anytime aninput anytime an
event occurs in the 1stevent occurs in the 1st
SignalsSignals
Signal.foldp =Signal.foldp =
a signal dependent ona signal dependent onthe past the past
MainMain(where you wire(where you wireeverything up)everything up)
Elm ArchitectureElm Architecture
MainMain
main : Signal Elementmain = Signal.map2 display Window.dimensions gameState
MainMain
main : Signal Elementmain = Signal.map2 display Window.dimensions gameState
Signal ofSignal ofElementElementvaluesvalues
Overview (again)Overview (again)
What are Signals?What are Signals?
Stream of valuesStream of values
What are Signals?What are Signals?
What are Signals?What are Signals?
What are Signals?What are Signals?
a different way ofa different way ofthinking aboutthinking about
variablesvariables
What are Signals?What are Signals?
an explicit model ofan explicit model ofvariable mutation invariable mutation in
timetime
What are Signals?What are Signals?
non-awkward way ofnon-awkward way ofstructuring callbacksstructuring callbacks
What are Signals?What are Signals?
they are wired inthey are wired insignal graphssignal graphs
(directed acyclic(directed acyclicgraphs)graphs)
What are Signals?What are Signals?
What kind ofWhat kind offunctions can wefunctions can weapply on signals?apply on signals?
What kind of functions canWhat kind of functions canwe apply on signals?we apply on signals?
: Signal a ->
Signal a -Signal a ->> Signal a Signal a
merge
What kind of functions canWhat kind of functions canwe apply on signals?we apply on signals?
:: (a (a ->-> Bool) Bool) ->-> a a ->->
Signal a Signal a ->-> Signal a Signal a
filterfilter
What kind of functions canWhat kind of functions canwe apply on signals?we apply on signals?
:: (a (a ->-> result) result) ->-> Signal a Signal a --
>> Signal result Signal result
mapmap
applies a function on a signalapplies a function on a signal
returns another, transformed, signalreturns another, transformed, signal
What kind of functions canWhat kind of functions canwe apply on signals?we apply on signals?
:: (a (a ->-> b b ->-> result) result) ->->
Signal a Signal a ->-> Signal b Signal b ->->
Signal resultSignal result
map2map2
applies a function on two signalsapplies a function on two signals
What kind of functions canWhat kind of functions canwe apply on signals?we apply on signals?
makes a signal that depends on themakes a signal that depends on thepast values of a signalpast values of a signal
: (a -> state -> state) -> state -> Signal a ->
Signal state
foldp
What is a What is a foldpfoldp??
Fold from the pastFold from the pastFold from the pastFold from the pastFoldFold from the from the pastpast
What is a foldp?What is a foldp?
takes (a -> state -> state) foldp
a function
What is a foldp?What is a foldp?
... -> state -> ...
a default state
What is a foldp?What is a foldp?
... -> Signal a -> ...
an input signal
What is this foldp thing?What is this foldp thing?
... -> Signal state
returns a signal(= next state of the program,
after applying update)
How Elm ReactorHow Elm Reactorworksworks
Record InputsRecord Inputs
How Elm Reactor worksHow Elm Reactor works
ReappliesReappliesfunctions tofunctions to
inputsinputs
How Elm Reactor worksHow Elm Reactor works
previous stateprevious state++
previous inputsprevious inputs==
next statenext state
How Elm Reactor worksHow Elm Reactor works
snapshottingsnapshottingforfor
performanceperformance
How Elm Reactor worksHow Elm Reactor works
How Elm Reactor worksHow Elm Reactor works
changes to typeschanges to typeswill break hotwill break hot
swappingswapping
also if a changealso if a changedoesn't compiledoesn't compile
How Elm Reactor worksHow Elm Reactor works
Why is Elm goodWhy is Elm goodfor Time Travelling?for Time Travelling?
Why Elm Reactor worksWhy Elm Reactor works
Applying the sameApplying the sameinputs will return theinputs will return the
same outputsame output(referential transparency)(referential transparency)
Why Elm Reactor worksWhy Elm Reactor works
No side effects No side effects ==can replay codecan replay code
Why Elm Reactor worksWhy Elm Reactor works
All mutable state isAll mutable state isstored in the foldpstored in the foldp
Static signalStatic signalgraphgraph
Why Elm Reactor worksWhy Elm Reactor works
But, can itBut, can itscale?scale?
Castle of ElmCastle of Elm
But, can it scale?But, can it scale?
Game Jam gameGame Jam game
Castle of ElmCastle of Elm
Somewhat RoguelikeSomewhat Roguelike
In 2 daysIn 2 days
From scratchFrom scratch
Flexible tile systemFlexible tile system
Castle of ElmCastle of Elm
CollisionsCollisions
(let's break the(let's break thecollisions system)collisions system)
Castle of ElmCastle of Elm
GotchasGotchas
Out of memoryOut of memory
GotchasGotchas
SchroedingerSchroedingerHot SwappingHot Swapping
GotchasGotchas
But you can help!But you can help!It's OSSIt's OSS
<- CODE HERE<- CODE HERE
Why use staticallyWhy use staticallytyped pure Functionaltyped pure Functional
languages in Gamelanguages in GameDevelopment?Development?
Why it's worth to use new language researchWhy it's worth to use new language researchin Game Developmentin Game Development
No runtimeNo runtimeexceptionsexceptions
Why it's worth to use new language researchWhy it's worth to use new language researchin Game Developmentin Game Development
No raceNo raceconditionsconditions
Why it's worth to use new language researchWhy it's worth to use new language researchin Game Developmentin Game Development
Better toolsBetter tools
Why it's worth to use new language researchWhy it's worth to use new language researchin Game Developmentin Game Development
Less codeLess code
Why it's worth to use new language researchWhy it's worth to use new language researchin Game Developmentin Game Development
Ease ofEase ofparallelisationparallelisation
elm-lang.org/docselm-lang.org/docs
@elmlang@elmlang
#elmlang#elmlang
Where to learn Elm?Where to learn Elm?
#haskell.it @ freenode#haskell.it @ freenode
haskell-ita.ithaskell-ita.it
@Haskell_ITA@Haskell_ITA
Maybe join Haskell ITAMaybe join Haskell ITA
@lambda_cat@lambda_cat
lambdacat.comlambdacat.com
Read Read LambdaCatLambdaCat!!