Using state_machine, how can I access the argument arguments from the inside: if lambda

I use state_machine gem to simulate a card game, and I have a transition condition that requires knowledge of the event arguments when drawing a map. Here is a sample code.

class CardGame state_machine do before_transition :drawing_card => any, :do => :drawn_card event :draw_card transition :drawing_card => :end_of_round, :if => lambda {|game| # Check goes here, I require knowing which card was taken # which is passed as arguments to the event (:ace, :spaces) } end end def drawn_card(value, suit) # I can access the event arguments in the transition callbacks end end game = CardGame.new game.draw_card(:ace, :spades) 

I think the alternative is to set the suit and value of the card to the object as variables, but it is much messier than using arguments for an event.

Thanks in advance:)

+4
source share
1 answer

The main problem here is that the state machine probably does not belong to your CardGame class. The state of the game lies elsewhere. There are four main domain models that I can see:

  • Card
  • Deck
  • Hand
  • Game

A Game will have one or more Decks (each of 52 Cards ) and one or more Hands . (You might even want to have a Player class where the player has-a Hand , your call).

As an example, Deck will probably have a shuffle! method shuffle! and deal . A Hand will have a play method. This may be the rule logic.

The Game class will consist mainly of a loop, such as:

 def run deal do play_hands check_for_winner while(playing) end 

More devil in the details, of course, but you may find this approach more refreshing and easier to test.

+2
source

Source: https://habr.com/ru/post/1400410/


All Articles