Testing out JmonkeyEngine to make a game in Scala with Akka Actors within a pure FP layer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.7 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package wow.doge.mygame.utils
  2. import scala.concurrent.duration.FiniteDuration
  3. import scala.util.Random
  4. import akka.actor.typed.ActorRef
  5. import akka.actor.typed.Behavior
  6. import akka.actor.typed.scaladsl.ActorContext
  7. import akka.actor.typed.scaladsl.Behaviors
  8. import akka.actor.typed.scaladsl.TimerScheduler
  9. import wow.doge.mygame.implicits._
  10. object GenericTimerActor {
  11. sealed trait Command
  12. final case object Start extends Command
  13. final case object Stop extends Command
  14. private case object Tick extends Command
  15. case class TimerKey(seed: Long)
  16. case class Props[T](
  17. target: ActorRef[T],
  18. messageToSend: T,
  19. timeInterval: FiniteDuration
  20. ) {
  21. def behavior =
  22. Behaviors.withTimers[Command] { timers =>
  23. Behaviors.setup { ctx =>
  24. new GenericTimerActor(
  25. ctx,
  26. timers,
  27. TimerKey(Random.nextLong()),
  28. this
  29. ).idle
  30. }
  31. }
  32. }
  33. }
  34. class GenericTimerActor[T](
  35. ctx: ActorContext[GenericTimerActor.Command],
  36. timers: TimerScheduler[GenericTimerActor.Command],
  37. timerKey: GenericTimerActor.TimerKey,
  38. props: GenericTimerActor.Props[T]
  39. ) {
  40. import GenericTimerActor._
  41. val idle: Behavior[Command] =
  42. Behaviors.receiveMessage {
  43. case Start =>
  44. timers.startTimerWithFixedDelay(timerKey, Tick, props.timeInterval)
  45. active
  46. case _ => Behaviors.unhandled
  47. }
  48. val active: Behavior[Command] =
  49. Behaviors.receiveMessage {
  50. case Start =>
  51. ctx.log.warnP(s"Timer-${timerKey.seed}: Timer already started")
  52. Behaviors.same
  53. case Tick =>
  54. props.target ! props.messageToSend
  55. Behaviors.same
  56. case Stop =>
  57. timers.cancel(timerKey)
  58. idle
  59. }
  60. }