« blib/lib/OpenFrame/AppKit/Segment/SessionLoader.pm
↑ Summary
blib/lib/OpenFrame/AppKit/Segment/TT2.pm »
| 1 | package OpenFrame::AppKit::Examples::Hangman; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use Games::GuessWord; | ||
| 5 | use OpenFrame::AppKit::App; | ||
| 6 | use base qw(OpenFrame::AppKit::App); | ||
| 7 | |||
| 8 | sub entry_points { | ||
| 9 | return { | ||
| 10 | guess => ['guess'], | ||
| 11 | }; | ||
| 12 | } | ||
| 13 | |||
| 14 | sub wordlist { | ||
| 15 | my $self = shift; | ||
| 16 | my $words = shift; | ||
| 17 | if (defined($words)) { | ||
| 18 | $self->{words} = $words; | ||
| 19 | return $self; | ||
| 20 | } else { | ||
| 21 | return $self->{words}; | ||
| 22 | } | ||
| 23 | } | ||
| 24 | |||
| 25 | sub default { | ||
| 26 | my $self = shift; | ||
| 27 | my $store = shift; | ||
| 28 | delete $self->{message}; | ||
| 29 | |||
| 30 | # Start a new game if there isn't one already | ||
| 31 | if (not $self->{game}) { | ||
| 32 | my $words = $self->wordlist || die "No wordlist given!"; | ||
| 33 | my $game = Games::GuessWord->new(file => $words); | ||
| 34 | $self->{game} = $game; # save the game in our session | ||
| 35 | $self->{guessed} = {}; | ||
| 36 | } | ||
| 37 | return 1; | ||
| 38 | } | ||
| 39 | |||
| 40 | sub guess { | ||
| 41 | my $self = shift; | ||
| 42 | my $store = shift; | ||
| 43 | |||
| 44 | my $request = $store->get('OpenFrame::Request'); | ||
| 45 | |||
| 46 | delete $self->{message}; | ||
| 47 | |||
| 48 | # Retrieve the game and the guess | ||
| 49 | my $game = $self->{game}; | ||
| 50 | my $guess = $request->arguments->{guess}; | ||
| 51 | |||
| 52 | if (not defined $game) { | ||
| 53 | # We don't have a game, so set one up | ||
| 54 | $self->default($store); | ||
| 55 | return 1; | ||
| 56 | } | ||
| 57 | |||
| 58 | $game->guess(lc $guess); | ||
| 59 | $self->{guessed}->{$guess} = 1; | ||
| 60 | |||
| 61 | if ($game->won) { | ||
| 62 | # They got the whole word | ||
| 63 | $self->{message} = "You guessed the correct word: ". | ||
| 64 | $game->answer; | ||
| 65 | $game->new_word(); | ||
| 66 | $self->{guessed} = {}; | ||
| 67 | } elsif ($game->lost) { | ||
| 68 | # They ran out of chances | ||
| 69 | $self->{message} = "You didn't guess the word. It was: " . | ||
| 70 | $game->secret; | ||
| 71 | $self->{finalscore} = $game->score(); | ||
| 72 | # Remove the game from our session | ||
| 73 | delete $self->{game}; | ||
| 74 | } else { | ||
| 75 | # Show the results of the guess | ||
| 76 | } | ||
| 77 | return 1; | ||
| 78 | } | ||
| 79 | |||
| 80 | 1; | ||
| 81 | |||
| 82 | __END__ |