Python

가위 바위 보 게임 코드 만들기

monster route 2024. 7. 4. 03:22

 

 

컴퓨터유저가 대결을 하는 가위바위보 게임이다.

 

가장 먼저 컴퓨터가 가위 바위 보 중 하나를 랜덤으로 뽑아야 해서 random 모듈을 import 했다.

import random

print("게임을 시작합니다.")

 


오늘 세션 이후 추가해준 코드

win = 0
lose = 0
draw = 0
option: ["가위", "바위", "보"]

 

["가위", "바위", "보"]가  반복적으로 여러번 나오니까 option list로 묶어줬고 

마지막에 승, 패, 무승부 결과를 알려주기 위해 win, lose, draw 변수를 추가했다. 


 

 

get_computer_choice() : 컴퓨터가 선택한 가위 바위 보 함수로, 가위 바위 보 중 하나를 랜덤으로 뽑아야하므로 option을 인수로 받는 random.choice를 썼다.

 

get_player_choice(): 유저가 선택한 가위 바위 보 함수로,  while True 반복문으로 option 중 하나를 제대로 입력할 때까지 무한 반복하고, 제대로 입력된 값은 player_choice 라는 이름의 변수로 반환하도록 했다.

def get_computer_choice():
    return random.choice(option)


def get_player_choice():
    while True:
        player_choice = input("가위, 바위, 보 중 하나를 입력하세요: ").strip()
        if player_choice in option:
            return player_choice
        else:
            print("입력이 올바르지 않습니다.")

 

 

이제 누가 이겼는지를 결정하는 함수를 만들어준다. 코드컨벤션 강의 때문인지 변수와 함수, 클래스 등을 네이밍하는게 생각보다 고민이 됐다.

 

경우의 수를 따져보면 총 9가지인데,

1. if player_choice == computer_choice 가 무승부 (둘다 같은 걸 낸 경우의 수 3가지)

2. elif 어떤 걸 내도 유저가 이기는 경우의 수 3가지 

그럼 3. else 에는 남은 경우의 수인 유저가 무조건 지는 경우 3가지, 즉 컴퓨터가 이기는 경우의 수가 나온다.

def determine_winner(player_choice, computer_choice):
    if player_choice == computer_choice:
        draw += 1
        return "무승부!"
    elif (
        (player_choice == "바위" and computer_choice == "가위")
        or (player_choice == "가위" and computer_choice == "보")
        or (player_choice == "보" and computer_choice == "바위")
    ):
        win += 1
        return "이겼습니다"
    else:
        lose += 1
        return "졌습니다"

 

 

이제 게임 함수를 만든다. 각각 뭐를 냈는지, 결과가 뭔지를 보여주도록 했다.

def play_game():
    player_choice = get_player_choice()
    computer_choice = get_computer_choice()
    play_result = determine_winner(player_choice, computer_choice)
    print(f"나: {player_choice}, 컴퓨터: {computer_choice} \n{play_result}")
    return play_result

 

여기서 get_player_choice()와 get_computer_choice()함수를 호출하도록 player_choicecomputer_choice로 변수를 지정해주고, 승패 결과인 play_result를 determine_winner(player_choice, computer_choice)함수의 리턴값으로 반환하도록 했다. 

유저와 컴퓨터가 각각 뭘 냈는지도 출력해주면 직관적으로 알 수 있다.

 

이제 마지막.

while True 반복문으로 게임을 더 할지 말지를 결정하면 되는데, 난 무승부일 경우 선택권 없이 자동으로 한 판이 더 진행되도록 만들었다.

그래서 앞 반복문에 play_game함수의 결과가 "무승부!"일 경우 continue를 줘서 아래는 다 건너뛰고 반복문 맨 처음으로 가도록 했다. 

 

이기거나 지면, 정상적으로 게임을 한 판 더 할건지 물어보고 대답 옵션으로 ["예", "ㅇ", "아니오", "ㄴ", "노"]를 넣어줬다.

왜냐하면 코드를 실행해서 게임을 해보니까 이 질문이 나왔을때 귀찮아서 예 대신 ㅇ을 치게 되고 아니오 대신 ㄴ 이나 노를 치게 됐기 때문이다. if문에서 리스트 옵션 안에 있는 것만 입력하면 일단 break로 다 빠져나오게 하고 예, ㅇ는 다시 반복문으로 돌아가서 게임을 진행하게 하고 아니오, ㄴ, 노 는 아래의 if문으로 빠져서 break로 끝이 난다.

 

그리고 그 외에 다른 문자를 입력하면 예외없이 다시 입력하도록 했다.. 잘못된 값을 계속 입력하면 영원히 게임 안에서 살아야함...

while True:
    result = play_game()
    if result == "무승부!":
        print("한 판 더 진행합니다.")
        continue

    while True:
        play_again = input("한 판 더? (예/아니오): ").strip()
        if play_again in ["예", "ㅇ", "아니오", "ㄴ", "노"]:
            break
        else:
            print("잘못된 입력입니다. 다시 입력해주세요.")

    if play_again in ["아니오", "ㄴ", "노"]:
        break

print("게임을 종료합니다!")
print(f"결과: 승:{win}, 패:{lose}, 무승부:{draw}")

 

그리고 앞에서 추가해줬던 통계자료를 마지막에 출력해서 보여준다. 

 

코드를 실행시키고 게임을 진행해보면?

 

UnboundLocalError 라는 에러가 뜬다. 전역변수 지역변수 오류였다. 

 

위에서 이렇게 전역변수를 지정해줬는데

win = 0
lose = 0
draw = 0
option: ["가위", "바위", "보"]

 

determine_winner()함수 안에서 얘네를 쓰려고 해서 발생한 문제였다.

 

그래서 global을 써서 함수 안에서 win, lose, draw를 쓸 수 있게 만들어줬다.

def determine_winner(player_choice, computer_choice):
    global win, lose, draw
    if player_choice == computer_choice:
        draw += 1
        return "무승부!"
    elif (
        (player_choice == "바위" and computer_choice == "가위")
        or (player_choice == "가위" and computer_choice == "보")
        or (player_choice == "보" and computer_choice == "바위")
    ):
        win += 1
        return "이겼습니다!"
    else:
        lose += 1
        return "졌습니다.."

 

이러면 문제없이 돌아간다.

 

 

전체코드

import random

print("게임을 시작합니다.")

option = ["가위", "바위", "보"]


def get_computer_choice():
    return random.choice(option)


def get_player_choice():
    while True:
        player_choice = input("가위, 바위, 보 중 하나를 입력하세요: ").strip()
        if player_choice in option:
            return player_choice
        else:
            print("입력이 올바르지 않습니다.")


win = 0
lose = 0
draw = 0


def determine_winner(player_choice, computer_choice):
    global win, lose, draw
    if player_choice == computer_choice:
        draw += 1
        return "무승부!"
    elif (
        (player_choice == "바위" and computer_choice == "가위")
        or (player_choice == "가위" and computer_choice == "보")
        or (player_choice == "보" and computer_choice == "바위")
    ):
        win += 1
        return "이겼습니다!"
    else:
        lose += 1
        return "졌습니다.."


def play_game():
    player_choice = get_player_choice()
    computer_choice = get_computer_choice()
    play_result = determine_winner(player_choice, computer_choice)
    print(f"나: {player_choice}, 컴퓨터: {computer_choice} \n{play_result}")
    return play_result


while True:
    result = play_game()
    if result == "무승부!":
        print("한 판 더 진행합니다.")
        continue

    while True:
        play_again = input("한 판 더? (예/아니오): ").strip()
        if play_again in ["예", "ㅇ", "아니오", "ㄴ", "노"]:
            break
        else:
            print("잘못된 입력입니다. 다시 입력해주세요.")

    if play_again in ["아니오", "ㄴ", "노"]:
        break

print("게임을 종료합니다!")
print(f"결과: 승:{win}, 패:{lose}, 무승부:{draw}")

 

 

실행시켜서 게임을 진행해보면 잘된다.