A Hangman game for Mike
Sunday, May 18th, 2008My buddy Mike Pence motivated me to write a Hangman game. It shows some Apotomo concepts in a playful (painful?) way.
The complete game is encapsulated in a widget.
app/cells/hangman_cell.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | class HangmanCell < Apotomo::StatefulWidget def transition_map { :hangman => [:_guess], :_guess => [:_guess, :hangman] } end def hangman @word = random_word @guessed = [] @hits = [] @try = 0 @total_tries = 6 @tries_left = @total_tries - @try nil end def _guess @try+=1 @tries_left = @total_tries - @try guess = param(:guess) @guessed << guess @hits << guess if @word.include?(guess) if @hits.uniq.size == @word.split("").uniq.size jump_to_state :_you_won end if @tries_left == 0 jump_to_state :_game_over end state_view :hangman end def _you_won end def _game_over end def random_word "Apotomo" # this game IS hard. end end |
To actually play, we should plug the game widget into our application widget tree.
app/apotomo/application_widget_tree.rb
some_pg << cell(:hangman, :hangman, 'hangman_game')
I set :hangman as the start state. The respective method initializes the game variables (line 9-18) and shows the according view.
app/cells/hangman/hangman.haml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | %h1
Hangman goes Apotomo
(Tries left:
= @tries_left
)
%h2
- @guess_str = ""
- @word.split("").each { |c| @guess_str+= (@guessed.include?(c) ? c : "-") }
= @guess_str
= form_to_event(:state => :_guess)
%input{:type=>:text, :id=>"guess", :name=>"guess", :size => 3, :value => ""}
</form>
%p
You already tried
= @guessed.split("").join(", ") |
Whenever the form is submitted, the widgets’ state machine is set to the state :_guess (line 13), which is a valid state method in our hangman cell (line 20-37).
The _guess method just processes the guess from the player, decreases the number of tries and decides what to do next. Normally, this means it stays in the state :_guess and reuses the state view hangman (line 36).
However, if the player guessed the complete word the widget goes into the state :_you_won (line 29). Awesome.
BTW, if someone knows a good state chart drawing app, please contact me right away.
Cheers, Mike!




