けんぴーgadget

ガジェット等紹介ぶろぐです。

Pythonのじゃんけんゲームのサンプルコードを書きました

Pythonでじゃんけんゲームを作りたい人向けにサンプルコードを書きました。

今回書いたコードはコピペOKです。また、自分好みに書き換えてもらっても大丈夫です。お好きにお使いください!!

それではサンプルコードです。

 

# Rock-Paper-Scissors Game
import random

print("Rock, Paper, Scissors Game")

while True:
    print("Enter choice \n1. Rock \n2. Paper \n3. Scissors")
    try:
        choice = int(input("User turn: "))
    except EOFError:
        print("Invalid input. Please try again.")
        continue

    while choice > 3 or choice < 1:
        choice = int(input("Enter valid input: "))
        
    if choice == 1:
        choice_name = 'rock'
    elif choice == 2:
        choice_name = 'paper'
    else:
        choice_name = 'scissors'
        
    print(f"Your choice is: {choice_name}")
    print("Now its computer turn.......")

    comp_choice = random.randint(1, 3)
    
    if comp_choice == 1:
        comp_choice_name = 'rock'
    elif comp_choice == 2:
        comp_choice_name = 'paper'
    else:
        comp_choice_name = 'scissors'
        
    print(f"Computer's choice is: {comp_choice_name}")

    print(f"{choice_name} V/s {comp_choice_name}")
    
    result = None
    if *1:
        result = "paper"
    elif *2:
        result = "rock"
    else:
        result = "scissors"

    if result == "paper":
        if choice == 1:
            print("Computer wins!", comp_choice_name, "covers", choice_name)
        else:
            print("You win!", choice_name, "covers", comp_choice_name)
    elif result == "rock":
        if choice == 1:
            print("You win!", choice_name, "smashes", comp_choice_name)
        else:
            print("Computer wins!", comp_choice_name, "smashes", choice_name)
    else:
        if choice == 3:
            print("Computer wins!", comp_choice_name, "cut", choice_name)
        else:
            print("You win!", choice_name, "cut", comp_choice_name)
    
    play_again = input("Do you want to play again? (Y/N)")
    if play_again == 'n' or play_again == 'N':
        break

print("Thanks for playing")

 

 

こんな感じです。英語で表示されるようになっています。

いつでも使えますので是非!!楽しいPythonライフを:)

*1:choice == 1 and comp_choice == 2) or
        (choice == 2 and comp_choice == 1

*2:choice == 1 and comp_choice == 3) or
          (choice == 3 and comp_choice == 1