回答編集履歴
4
デクリメント演算子の廃止
test
CHANGED
@@ -56,7 +56,7 @@
|
|
56
56
|
|
57
57
|
end
|
58
58
|
|
59
|
-
player_hand-
|
59
|
+
player_hand -= 1
|
60
60
|
|
61
61
|
program_hand = rand(3)
|
62
62
|
|
3
改良
test
CHANGED
@@ -19,3 +19,95 @@
|
|
19
19
|
...
|
20
20
|
|
21
21
|
```
|
22
|
+
|
23
|
+
|
24
|
+
|
25
|
+
gets.to_iは,無効な入力(何も入力せずにエンターした場合など)には0を返します.
|
26
|
+
|
27
|
+
そのため,0を正しい入力とすると,変な入力があった場合にグーを選択することになります.
|
28
|
+
|
29
|
+
プログラムの内部では0をグーとしてもよいのですが,入力を受け取る段階では,
|
30
|
+
|
31
|
+
1:グー,2:チョキ,3:パーとしておき,正しいと判定した後にデクリメントすることをおすすめします.
|
32
|
+
|
33
|
+
|
34
|
+
|
35
|
+
また勝敗を判定する条件分岐が長くなっていますが,ビット演算を使うと楽に表現できます.
|
36
|
+
|
37
|
+
なぜこれで動くのかは,考えてみてください.
|
38
|
+
|
39
|
+
```ruby
|
40
|
+
|
41
|
+
#!/usr/bin/ruby
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
def janken
|
46
|
+
|
47
|
+
puts "[1]:グー\n[2]:チョキ\n[3]:パー"
|
48
|
+
|
49
|
+
player_hand = gets.to_i
|
50
|
+
|
51
|
+
if player_hand < 1 || 3 < player_hand then
|
52
|
+
|
53
|
+
puts "無効な値です"
|
54
|
+
|
55
|
+
return true
|
56
|
+
|
57
|
+
end
|
58
|
+
|
59
|
+
player_hand--
|
60
|
+
|
61
|
+
program_hand = rand(3)
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
janken = ["グー", "チョキ", "パー"]
|
66
|
+
|
67
|
+
jbit = [9, 18, 4]
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
puts "あなたの:#{janken[player_hand]}, 私の手:#{janken[program_hand]}"
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
if (jbit[player_hand] & (jbit[program_hand] << 2)) > 0 then
|
76
|
+
|
77
|
+
puts "あなたの勝ちです"
|
78
|
+
|
79
|
+
return false
|
80
|
+
|
81
|
+
elsif (jbit[player_hand] & (jbit[program_hand] << 1)) > 0 then
|
82
|
+
|
83
|
+
puts "あなたの負けです"
|
84
|
+
|
85
|
+
return false
|
86
|
+
|
87
|
+
else
|
88
|
+
|
89
|
+
puts "あいこで..."
|
90
|
+
|
91
|
+
return true
|
92
|
+
|
93
|
+
end
|
94
|
+
|
95
|
+
end
|
96
|
+
|
97
|
+
|
98
|
+
|
99
|
+
next_game = true
|
100
|
+
|
101
|
+
|
102
|
+
|
103
|
+
puts "最初はグー、じゃんけん..."
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
while next_game
|
108
|
+
|
109
|
+
next_game = janken
|
110
|
+
|
111
|
+
end
|
112
|
+
|
113
|
+
```
|
2
訂正
test
CHANGED
@@ -4,7 +4,7 @@
|
|
4
4
|
|
5
5
|
player_hand = gets.to_i
|
6
6
|
|
7
|
-
if player_hand <
|
7
|
+
if player_hand < 0 || 2 < player_hand then
|
8
8
|
|
9
9
|
puts "無効な値です"
|
10
10
|
|
1
誤字の修正
test
CHANGED
@@ -6,7 +6,7 @@
|
|
6
6
|
|
7
7
|
if player_hand < -1 || 2 < player_hand then
|
8
8
|
|
9
|
-
puts "
|
9
|
+
puts "無効な値です"
|
10
10
|
|
11
11
|
return true
|
12
12
|
|