Created
October 27, 2011 18:37
-
-
Save ainame/1320410 to your computer and use it in GitHub Desktop.
以前書いたジャンケンするプログラムをリファクタリングしてモジュール化してみた。あとTest::Moreの勉強がてらに超簡単なテスト。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env perl | |
| package Jyanken; | |
| use warnings; | |
| use strict; | |
| use 5.010; | |
| my @num_to_str = qw(g c p); | |
| my @num_to_handname = ("グー", "チョキ", "パー"); | |
| my %str_to_num = ( | |
| "g" => 0, | |
| "c" => 1, | |
| "p" => 2, | |
| ); | |
| my %str_to_handname = ( | |
| "g" => $num_to_handname[0], | |
| "c" => $num_to_handname[1], | |
| "p" => $num_to_handname[2] | |
| ); | |
| # 勝ち負けルール -1=負け, 1=勝ち, 0=引き分け | |
| my %rule = ( | |
| "g" => [0,1,-1], | |
| "c" => [-1,0,1], | |
| "p" => [1,-1,0] | |
| ); | |
| sub prompt{ | |
| my ($self, $human_hand, $com_hand) = @_; | |
| say "「じゃんけん・・・」"; | |
| my $hand; | |
| while (1) { | |
| say "グー[g], チョキ[c], パー[p]"; | |
| print "入力してください:"; | |
| chomp( $hand = <STDIN> ); | |
| say ""; | |
| if ( $hand eq "g" || $hand eq "c" || $hand eq "p" ) { | |
| last; | |
| } else { | |
| say "もう一度入力してください"; | |
| } | |
| } | |
| $$human_hand = $hand; | |
| $$com_hand = $num_to_str[int rand 3]; | |
| print "「・・・ポンッ!!」\n=> あなた:$str_to_handname{$$human_hand} , com:$str_to_handname{$$com_hand} \n"; | |
| } | |
| sub judge{ | |
| my ($self, $a, $b) = @_; | |
| return $rule{$a}[$str_to_num{$b}]; | |
| } | |
| # 一試合 | |
| sub game{ | |
| my ($self) = @_; | |
| my $human_hand; | |
| my $com_hand; | |
| prompt( \$human_hand, \$com_hand ); | |
| given ( $self->judge($human_hand, $com_hand) ){ | |
| when(-1){ say "あなたの負けorz"; return 0;} | |
| when(1){ say "あなたの勝ち!!"; return 0;} | |
| when(0){ say "引き分け\n\n「あいこでっ・・・」"; return 1; } | |
| default{ say "Error!!"; exit(1);} | |
| } | |
| } | |
| # ひたすらジャンケンを遊べる | |
| sub start{ | |
| my ($self) = @_; | |
| while ( $self->game() ) { | |
| } | |
| } | |
| 1; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env perl | |
| use warnings; | |
| use strict; | |
| use Test::More; | |
| use Data::Dumper; | |
| use FindBin; | |
| use FindBin::libs; | |
| use Jyanken; | |
| use_ok("Jyanken"); | |
| is( | |
| Jyanken->judge("g","g"), | |
| 0, | |
| "グーとグーであいこ", | |
| ); | |
| is( | |
| Jyanken->judge("g","c"), | |
| 1, | |
| "グーとチョキはグーが勝ち", | |
| ); | |
| is( | |
| Jyanken->judge("g","p"), | |
| -1, | |
| "グーとパーはグーが負け", | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment