컴퓨터가 생성한 랜덤 숫자를 사용자가 맞추는 게임을 만들어보자.
1) 1~100의 숫자 중 하나를 랜덤하게 생성하고
2) 사용자가 예상하는 숫자를 입력하면
3) 사용자가 입력한 숫자가 컴퓨터가 생성한 숫자보다 큰지, 작은지, 같은지를 알려준다.
4) 사용자가 랜덤하게 생성된 숫자와 같은 숫자를 입력하면 프로그램이 종료된다.
이를 위해서, random 모듈을 import하고 random.randrange() 메소드를 사용했다.
import random
intRandom = random.randrange(0,101)
while True:
userInput = int(input('👇 Guess the number! \nEnter a number from 0 to 100:'))
if(userInput < intRandom):
print('HIGHER. Try again!')
elif(userInput > intRandom):
print('LOWER. Try again!')
else:
print('YOU WIN.')
break
처음에는 사용자가 입력한 숫자가 컴퓨터 숫자보다 작으면, LOWER가 뜨고, 반대의 경우에는 HIGHER가 출력되도록 코드를 짰다.
그런데, 전자의 경우, 사실 사용자가 입력한 것이 작으면 더 큰 숫자를 다시 입력해야 하니깐, HIGHER를 출력해서, 사용자가 더 큰 숫자를 입력하기 쉽도록 유도하는 방향으로 코드를 수정했다.
이게 맞는 것인지는 모르겠지만, 직관적으로 볼 때, 출력된 문장에 따라서 바로 다시 숫자를 입력하기 용이한 것 같아서 이 코드가 실제로 코드를 실행하고 게임할 때 더 편한 것 같다.
게임[a]와 정반대로 이번 게임은 사용자가 생각한 숫자를 컴퓨터가 맞히는 게임이다.
1) 컴퓨터는 랜덤한 숫자를 출력하고
2) 사용자는 그 숫자가 큰지, 작은지, 똑같은지에 대해서 입력한다.
3) 컴퓨터가 사용자의 숫자를 맞히면 게임은 종료된다.
import random
intRandom = random.randrange(0,100)
print('Choose one number from 0 to 100 and make the computer guess. \nIf computer\'s number is corret: type 1. \nif computer\'s number is lower: type 0 \nif computer\'s number is higher: type 2\n')
while True:
print('Am I right?:',intRandom)
userInput = int(input('Is the number correct?:'))
if (userInput == 0 or userInput == 2):
print(random.randrange(0,100))
elif(userInput == 1):
print('I am a genius!')
break
이 코드에서는 랜덤하게 숫자가 나오지 않고 한 번 생성된 숫자만 계속해서 출력되었다. 이 점을 수정하고자 두 번째 코드를 만들었다.
import random
print('Choose one number from 0 to 100 and make the computer guess. \nIf computer\'s number is corret: type 1. \nif computer\'s number is lower: type 0 \nif computer\'s number is higher: type 2\n')
while True:
intRandom = random.randrange(0,100)
print('Am I right?:',intRandom)
userInput = int(input('Is the number correct?:'))
if (userInput == 0 or userInput == 2):
continue
elif(userInput == 1):
print('I am a genius!')
break
이 코드에서는 다행히 숫자가 계속해서 랜덤하게 생성되는 것을 확인할 수 있다. 그러나, 사용자가 입력한 값에 따라 추측하는 숫자를 up and down 해서 출력하는 역할을 하지 못한다.