Skip to content

Instantly share code, notes, and snippets.

@Taishikun0721
Last active November 12, 2020 10:06
Show Gist options
  • Save Taishikun0721/263c916710593bbee8927c757772bc9c to your computer and use it in GitHub Desktop.
Save Taishikun0721/263c916710593bbee8927c757772bc9c to your computer and use it in GitHub Desktop.

じゃんけんプログラムを作成した

要件

  1. 1、3、5回勝負の中から選択できる。
  2. 1勝負終わると、そこまでの通算戦績ができる(1勝1負の様に出力)
  3. 最後に結果発表がある

追加した機能

  1. 指定した文字以外を入れるともう一度入力させるバリデーション

感想

if文が多くなってしまったので、もっと簡単な書き方があるんじゃないかと思う。と言うかプログラムを書くと毎回その様に思う。

class Janken
attr_reader :game_count, :change
attr_accessor :player_hand, :cpu_hand, :win_count, :lose_count
def initialize(game_count)
@player_hand = nil
@cpu_hand = nil
@game_count = game_count
@change = { 'g' => 'グー', 'c' => 'チョキ', 'p' => 'パー' }
@win_count = 0
@lose_count = 0
end
def self.set_game_count(count)
if 1 == count
puts '1本勝負を選びました。'
count
elsif count == 3
puts '3本勝負を選びました。'
count
elsif count == 5
puts '5本勝負を選びました。'
count
else
puts 'もう一度入力してください。'
inputs = gets.to_i
set_game_count(inputs)
end
end
def pon
1.upto(game_count) do |i|
puts "#{i}本目"
puts 'じゃんけん…(press g or c or p)'
self.player_hand = gets.chomp
validation
judge
end
show_result
end
private
def validation
return if player_hand == 'g' || player_hand == 'c' || player_hand == 'p'
puts 'もう一度入力してください (press g or c or p)'
self.player_hand = gets.chomp
validation
end
def judge
validation
self.cpu_hand = ['グー', 'チョキ', 'パー'].sample(1)[0]
puts "CPU...#{cpu_hand}"
puts "あなた...#{change[player_hand]}"
goo if player_hand == 'g'
choki if player_hand == 'c'
pa if player_hand == 'p'
puts "#{win_count}勝#{lose_count}敗" + "\n" * 2
end
def show_result
if game_count == win_count + lose_count && win_count > lose_count
puts "\n" * 4 + "#{win_count}勝#{lose_count}敗であなたの勝ちです。"
else
puts "\n" * 4 + "#{win_count}勝#{lose_count}敗であなたの負けです。"
end
end
def goo
if cpu_hand == 'グー'
puts 'あいこで...(press g or c or p)'
self.player_hand = gets.chomp
judge
elsif cpu_hand == 'チョキ'
puts '勝ち!'
self.win_count += 1
else
puts '負け!'
self.lose_count += 1
end
end
def choki
if cpu_hand == 'グー'
puts '負け!'
self.lose_count += 1
elsif cpu_hand == 'チョキ'
puts 'あいこで...(press g or c or p)'
self.player_hand = gets.chomp
judge
else
puts '勝ち!'
self.win_count += 1
end
end
def pa
if cpu_hand == 'グー'
puts '勝ち!'
self.win_count += 1
elsif cpu_hand == 'チョキ'
puts '負け!'
self.lose_count += 1
else
puts 'あいこで...(press g or c or p)'
self.player_hand = gets.chomp
judge
end
end
end
puts '何本勝負?(press 1 or 3 or 5)'
game_count = Janken.set_game_count(gets.to_i)
janken = Janken.new(game_count)
janken.pon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment