Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬으로 구현하는 가위바위보 게임 프로그램


파이썬을 활용하면 재미있는 게임도 손쉽게 개발할 수 있습니다. 그중 대표적인 예가 바로 가위바위보(Rock Paper Scissors) 게임입니다. 이 프로그램에서는 random 모듈의 randint() 함수를 사용해 무작위 숫자를 생성하며, 컴퓨터가 랜덤하게 선택을 하도록 만듭니다.

가위바위보는 원래 두 명의 플레이어가 "하나, 둘, 셋"을 외치면서 주먹을 쥔 손을 아래로 흔들다가 마지막에 가위·바위·보 중 하나를 내는 방식으로 진행되는 게임입니다. 파이썬으로는 이 과정을 간단한 입력과 조건문, 반복문만으로 충분히 구현할 수 있습니다.

게임 규칙

  • 바위(Rock) vs 보(Paper) → 가 이깁니다
  • 바위(Rock) vs 가위(Scissors) → 바위가 이깁니다
  • 보(Paper) vs 가위(Scissors) → 가위가 이깁니다

예제 코드

# 필요한 random 모듈 임포트
import random

print("The Rules of Rock paper scissor game will be follows: \n"
      +"Rock vs paper --> paper wins \n"
      +"Rock vs scissor --> Rock wins \n"
      +"paper vs scissor --> scissor wins \n")

while True:
    print("Now please enter your choice no. \n 1. Rock \n 2. paper \n 3. scissor \n")

    # 사용자로부터 입력 받기
    ch = int(input("Now Your turn: "))
    while ch > 3 or ch < 1:
        ch = int(input("Enter your valid input here: "))

    # 입력값에 따라 선택 이름 지정
    if ch == 1:
        choice_name = 'Rock'
    elif ch == 2:
        choice_name = 'paper'
    else:
        choice_name = 'scissor'

    # 사용자가 선택한 값 출력
    print("Your choice is: " + choice_name)
    print("\nNow its computer turn to initiate.......")

    # 컴퓨터는 randint() 메서드를 사용해
    # 1, 2, 3 중에서 무작위로 하나를 선택합니다.
    comp_choice = random.randint(1, 3)

    # 컴퓨터의 선택이 사용자의 선택과 같아지지 않도록 반복
    while comp_choice == ch:
        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 = 'scissor'

    print("So computer choice is: " + comp_choice_name)
    print(choice_name + " V/s " + comp_choice_name)

    # 게임 승리 조건 판별
    if ((ch == 1 and comp_choice == 2) or
            (ch == 2 and comp_choice == 1)):
        print("paper wins => ", end="")
        final_result = "paper"
    elif ((ch == 1 and comp_choice == 3) or
          (ch == 3 and comp_choice == 1)):
        print("Rock wins =>", end="")
        final_result = "Rock"
    else:
        print("scissor wins =>", end="")
        final_result = "scissor"

    # 사용자 또는 컴퓨터의 승리 여부 출력
    if final_result == choice_name:
        print("<== You are the winner ==>")
    else:
        print("<== Computer wins ==>")

    # 재시작 여부 확인
    print("Do you want to play again? (Y/N)")
    ans = input()

    # 사용자가 n 또는 N을 입력하면 종료
    if ans == 'n' or ans == 'N':
        break

# while 루프 종료 후
print("\nThanks for sharing time with us...")

코드 설명

이 프로그램의 핵심 동작 흐름은 다음과 같습니다.

  1. 규칙 안내: 게임 시작 시 가위바위보의 승부 규칙을 화면에 출력합니다.
  2. 사용자 입력: 플레이어에게 1(바위), 2(보), 3(가위) 중 하나를 입력받고, 잘못된 값이 들어오면 유효한 값을 입력할 때까지 다시 요청합니다.
  3. 컴퓨터 선택: randint(1, 3)으로 1~3 사이의 무작위 숫자를 생성해 컴퓨터의 선택을 결정합니다.
  4. 승부 판정: 조건문을 통해 어느 쪽이 이겼는지 판별하고 결과를 출력합니다.
  5. 반복 여부: 사용자가 'N' 또는 'n'을 입력하면 프로그램이 종료되고, 그렇지 않으면 게임이 다시 시작됩니다.

실행 결과

The Rules of Rock paper scissor game will be follows:
Rock vs paper --> paper wins
Rock vs scissor --> Rock wins
paper vs scissor --> scissor wins

Now please enter your choice no.
1. Rock
2. paper
3. scissor

Now Your turn: 1
Your choice is: Rock

Now its computer turn to initiate.......
So computer choice is: paper
Rock V/s paper
paper wins =><== Computer wins ==>
Do you want to play again? (Y/N)
y
Now please enter your choice no.
1. Rock
2. paper
3. scissor

Now Your turn: 2
Your choice is: paper

Now its computer turn to initiate.......
So computer choice is: Rock
paper V/s Rock
paper wins =><== You are the winner ==>
Do you want to play again? (Y/N)
n
Thanks for sharing time with us...

이처럼 파이썬의 기본 문법인 while 반복문, if-elif-else 조건문, 그리고 random 모듈만 활용하면 누구나 간단한 대화형 게임을 만들 수 있습니다. 초보자 학습용 프로젝트로도 매우 적합한 예제이니, 직접 코드를 입력하고 실행해 보며 동작 원리를 익혀보시기 바랍니다.