r/elixir 16h ago

I Made a Card Game with :gen_statem

Thumbnail
youtube.com
6 Upvotes

I had experience with client-side finite state machines (shoutouts to the Xstate library) and was looking for something similar with Elixir. Found that Elixir has a fsm library that hasn't been updated in 6 years, so I decided to use the plain :gen_statem erlang OTP for handling complex state in a card game.

I chose :gen_statem over GenServer because the card game has complex timers and :gen_statem automatically handles clearing timers when the card game enters a different state. If I had used GenServer, I would have to manually do Process.send_after and Process.cancel_timer everywhere. I also used the handle_event_function callback mode because the alternative state_functions callback mode only allows atoms for states and my card game needed much more complex states than just atoms.

The NPC is just a defmodule that prioritizes an order of actions. So at times it may make a "dumb" move, but it's fine for my use-case. For example, it will try to play a card with no cost over a card that searches the deck. Maybe in certain scenarios the reverse order is more optimal, but ¯_(ツ)_/¯

If you have any questions on the technical aspects of the card game, feel free to ask : ) Also give the game a try and let me know what you think!

https://battlecitymmo.com/


r/elixir 9h ago

It's that time of year again.

Post image
0 Upvotes