Skip to content

Instantly share code, notes, and snippets.

@akisaarinen
Created September 22, 2012 14:29
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save akisaarinen/3766325 to your computer and use it in GitHub Desktop.
Functional Pong
package pong.functional
sealed trait Event
sealed trait Action
object Action {
case object MoveUp extends Action
case object MoveDown extends Action
case object ShootMissile extends Action
}
object Actions {
val none: Seq[Action] = Seq()
def up: Seq[Action] = Seq(Action.MoveUp)
def shoot: Seq[Action] = Seq(Action.ShootMissile)
}
case class State(
myDirection: Int = 0,
missileInventory: Int = 0,
enemyPosition: Int = 0
)
case object State {
def up(state: State): State = {
state.copy(myDirection = 1)
}
def shoot(state: State): State = {
state.copy(missileInventory = state.missileInventory - 1)
}
}
object Bot {
def actions(state: State, event: Event): (State, Seq[Action]) = (state, event) match {
case (s,e) if conditionA(s,e) => State.up(state) -> Actions.up
case (s,e) if conditionB(s,e) => State.shoot(state) -> Actions.shoot
case _ => state -> Actions.none
}
private def conditionA(state: State, event: Event): Boolean = sys.error("not implemented")
private def conditionB(state: State, event: Event): Boolean = sys.error("not implemented")
}
object Pong extends App {
val events = createSource()
val initialState = State()
events.foldLeft(initialState) { case (state, msg) =>
val (newState, actions) = Bot.actions(state, msg)
actions.foreach(execute)
newState
}
private def createSource(): Iterator[Event] = sys.error("not implemented")
private def execute(action: Action) = sys.error("not implemented")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment