공부/Python(FastAPI)

[노마드코더] while 및 if문 사용한 게임 만들기

줘요 2023. 10. 3. 23:50

조건문을 사용해서 숫자를 맞추는 게임을 해보겠습니다!

 

먼저 랜덤으로 숫자를 받아야 하니 python에서 지원하는 라이브러리를 import 해줍니다.

from random import randint

 

시작하면 환영인사도 남겨줍니다.

print("Welcome casino")

 

pc는 1-100 사이에 값을 랜덤으로 선택합니다.

pc_choice = randint(1, 100)

 

이제 게임을 시작하죠!

playing = True

#playing이 True인 동안 while문이 반복됩니다.
while playing:
  #유저는 1-100 사이에 숫자를 선택합니다.
  user_choice = int(input("Choose number(1-100):"))
  
  #pc보다 숫자가 높다면 Lower 숫자가 낮다면 higher 맞추면 You won을 표시하며 게임이 끝나게 됩니다.
  if user_choice == pc_choice:
    print("You won")
    playing = False
  elif user_choice > pc_choice:
    print('Lower')
  elif user_choice < pc_choice:
    print('higher')

 

아래는 게임을 진행해 본 예시입니다.(숫자 이외의 것을 입력하면,,? 바로 에러)

 

1-100 사이에 숫자를 입력하지 않거나 숫자 이외의 문자를 입력할 경우에도 추가를 해보겠습니다.

playing = True

#playing이 True인 동안 while문이 반복됩니다.
while playing:
    try:
    	#유저는 1-100 사이에 숫자를 선택합니다.
        user_choice = int(input("Choose number (1-100): "))
        #유저가 1-100 사이 숫자를 입력하지 않으면 1-100 사이 숫자를 입력해달라고 합니다.
        if user_choice < 1 or user_choice > 100:
            print("Please enter a number between 1 and 100.")
        else:
        	 #pc보다 숫자가 높다면 Lower 숫자가 낮다면 higher 맞추면 You won을 표시하며 게임이 끝나게 됩니다.
            if user_choice == pc_choice:
                print("You won")
                playing = False
            elif user_choice > pc_choice:
                print('Lower')
            elif user_choice < pc_choice:
                print('Higher')
    except ValueError:
    	#숫자 이외의 것을 입력하게 되면 숫자를 입력해달라고 합니다.
        print("Please enter a valid number.")

예외까지 잘 표시해주는 모습입니다!