Logo Minnano Code

じゃんけんゲームを作ろう

じゃんけんゲームを作ろう

Pythonを使って、コンピュータとじゃんけんをするプログラムを作ってみましょう。

最初はコンピュータの手をランダムで出すところから始め、最終的には「3回勝負して先に2勝した方が勝ち」というゲームが完成します。

複雑な機能は使わず、基本的な書き方だけでステップを踏んで学んでいきます。

以下の問題はコピペでそのまま授業に利用できます。
各問題を1つずつ取り組んでいきましょう。

①randomモジュールを使って、コンピュータの手(0〜2)をランダムに表示するプログラムを作成してください。
結果として、ランダムに0,1,2のいずれかが表示されれば良いです。
(0はグー、1はチョキ、2はパーとして扱う想定です。)

解答例:
import random
computer = random.randint(0,2)
print(computer)

 

②コンピュータの出した手(0〜2)を、「グー」「チョキ」「パー」の文字で表示するようにしてください。
(if文を使って判定しましょう)

解答例:
import random
computer = random.randint(0,2)
if computer == 0:
    print("グー")
if computer == 1:
    print("チョキ")
if computer == 2:
    print("パー")

 

③input関数を使って、人間の出す手(0〜2)を入力できるようにしてください。
その後、人間の出した数字を表示してください。

解答例:
hand = input("0=グー, 1=チョキ, 2=パー のどれかを入力してください:")
print("あなたの手は", hand)

 

④人間の出した手(0〜2)を、「グー」「チョキ」「パー」の文字で表示するようにしてください。
ここから、リスト hands = [“グー”, “チョキ”, “パー”] を使って、手を表示するようにします。

解答例:
hands = ["グー", "チョキ", "パー"]
hand = int(input("0=グー, 1=チョキ, 2=パー のどれかを入力してください:"))
print("あなたの手は", hands[hand])

 

⑤コンピュータの手と人間の手を両方表示し、もし両者の手が同じ時には、「あいこです」と表示する処理を作ってください。
(あいこの時のみの結果表示。勝ち負けについては後に処理します。)

解答例:
import random
hands = ["グー", "チョキ", "パー"]
computer = random.randint(0,2)
hand = int(input("0=グー, 1=チョキ, 2=パー のどれかを入力してください:"))
print("コンピュータの手は", hands[computer])
print("あなたの手は", hands[hand])
if computer == hand:
    print("あいこです")

 

⑥勝ちと負けを判定するプログラムを作成してください。
グーはチョキに勝ち、チョキはパーに勝ち、パーはグーに勝ちです。
0,1,2の数値を使って条件判断をします。
あいこは「あいこです」と表示してください。

解答例:
import random
hands = ["グー", "チョキ", "パー"]
computer = random.randint(0,2)
hand = int(input("0=グー, 1=チョキ, 2=パー のどれかを入力してください:"))
print("コンピュータの手は", hands[computer])
print("あなたの手は", hands[hand])
if computer == hand:
    print("あいこです")
if (hand == 0 and computer == 1) or (hand == 1 and computer == 2) or (hand == 2 and computer == 0):
    print("あなたの勝ちです")
if (computer == 0 and hand == 1) or (computer == 1 and hand == 2) or (computer == 2 and hand == 0):
    print("あなたの負けです")

 

⑦じゃんけんを繰り返して、先に2勝した方が勝ちとするゲームを作成してください。
あいこはカウントしません。

解答例:
import random
hands = ["グー", "チョキ", "パー"]
win = 0
lose = 0
while win < 2 and lose < 2:
    computer = random.randint(0,2)
    hand = int(input("0=グー, 1=チョキ, 2=パー のどれかを入力してください:"))
    print("コンピュータの手は", hands[computer])
    print("あなたの手は", hands[hand])
    if computer == hand:
        print("あいこです")
    if (hand == 0 and computer == 1) or (hand == 1 and computer == 2) or (hand == 2 and computer == 0):
        print("あなたの勝ちです")
        win = win + 1
    if (computer == 0 and hand == 1) or (computer == 1 and hand == 2) or (computer == 2 and hand == 0):
        print("あなたの負けです")
        lose = lose + 1
print("ゲーム終了")
if win == 2:
    print("あなたの勝ち!")
if lose == 2:
    print("あなたの負け…")