LoginSignup
0
0

More than 3 years have passed since last update.

rubyでジャンケンできるようにしてみた。

Posted at

今日は皆さんご存知のじゃんけんをrubyで作ってみました。
コードはこちらです!

#じゃんけんをプログラミングでできるようにしてみました。

JANKEN = ['rock', 'scissors', 'paper']
$opponent = ''

def play_janken
  # 相手の手はランダムで、自分の手を入力で決めます
  $opponent = JANKEN.sample
  puts 'あなたは何を出す?'
  own = gets.chomp

  return 'あいこ' if index(own) == index($opponent)

  if index(own) == 0
    compare(1)
  elsif index(own) == 1
    compare(2)
  elsif index(own) == 2
    compare(0)
  end
end
# 出した手のインデックスを返します。
def index(a)
  JANKEN.index(a)
end
# じゃんけんの勝敗を返します。
def compare(i)
  return '勝ち' if index($opponent) == i
  '負け'
end

今後の改善点
opponent変数はplay_jankenとcompareで使う為グローバル変数にしたが、グローバル変数はあまり使わない方がいいと聞いたので使わないコードを模索中。
インデックスでなく、要素を直接比較できればその分コードが減るのでその実装を構想中。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0