1
2

More than 3 years have passed since last update.

【Ruby,Python】初心者がじゃんけんゲーム作ってみた

Posted at

前提

某プログラミングスクールでRubyを学習しました。
Rubyの復習、Pythonの学習を兼ねてじゃんけんゲームを作って見ました。

Ruby.ver

# <じゃんけんゲーム>
# 間違った番号を入れた場合のループ
def validate(player_hand, hands)
  if player_hand < 0 || player_hand > 2
    loop{
      puts "0~2の番号を選択してください"
      puts "0.#{hands[0]} 1.#{hands[1]} 2.#{hands[2]}"
      player_hand = gets.chomp.to_i
      if player_hand >= 0 && player_hand <= 2
        break
      end
    }
  end
end

# 入力フォーム
hands = ["グー","チョキ","パー"]
puts "__________________________"
puts "名前を入力してください"
player_name = gets.chomp
puts "0.#{hands[0]} 1.#{hands[1]} 2.#{hands[2]}"
puts "0~2の番号を選択してください"
player_hand = gets.chomp.to_i
validate(player_hand, hands)
puts "#{player_name}さんの選択された手は#{hands[player_hand]}です。"

# コンピュータとの勝敗判定
program_hand = rand(3)
if player_hand == program_hand
  puts "コンピュータの手は#{hands[program_hand]}あいこです"
elsif (player_hand == 0 && program_hand == 1) || (player_hand == 1 && program_hand == 2) || (player_hand == 2 && program_hand == 0)
  puts "コンピュータの手は#{hands[program_hand]}で#{player_name}さんの勝ちです"
else 
  puts "コンピュータの手は#{hands[program_hand]}で#{player_name}さんの負けです"
end

Python.ver

# <じゃんけんゲーム>
import random
# 間違った番号を入れた場合のループ
def validate(player_hand, hands):
  if player_hand < 0 and player_hand > 2:
    while player_hand != 0 or player_hand != 1 or player_hand != 2:
      print ('0~2の番号を選択してください')
      player_hand = int(input(f'0.{hands[0]} 1.{hands[1]} 2.{hands[2]}'))
      if player_hand >= 0 and player_hand <= 2:
        break

# 入力フォーム
hands = ['グー','チョキ','パー']
print ('__________________________')
print ('名前を入力してください')
player_name = input('')
print (f"0.{hands[0]} 1.{hands[1]} 2.{hands[2]}")
print ('0~2の番号を選択してください')
player_hand = int(input(''))
validate(player_hand, hands)
print (f'{player_name}さんの選択された手は{hands[player_hand]}です。')

# コンピュータとの勝敗判定
program_hand = random.randint(0,2)
if player_hand == program_hand:
  print (f'コンピュータの手は{hands[program_hand]}あいこです')
elif (player_hand == 0 and program_hand == 1) or (player_hand == 1 and program_hand == 2) or (player_hand == 2 and program_hand == 0):
  print (f'コンピュータの手は{hands[program_hand]}で{player_name}さんの勝ちです')
else :
  print (f'コンピュータの手は{hands[program_hand]}で{player_name}さんの負けです')

じゃんけんゲームで学んだRubyとPythonの違い

  • Rubyと違いPythonはインデントに注意する必要がある。(インデントを間違えると正しい挙動を示さない)
  • メソッド(関数)やif文などpythonではendをつけず、:(コロン)をつける。
  • 式展開を行う際、Rubyは#{}で記述を行うがPythonは(f'{}')で記述(一例)

まとめ

同じオブジェクト指向の言語であったが、色々と記述方法が違うのでこれから引き続き学習を行って行きたいと思います。
また、Pythonの式展開は一例なので今後、まとめて行きたいと思います。

1
2
2

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
1
2