Jeongchul Kim
BaglesGame.py 본문
- # Bagles
- # 'bagels' 숫자 3개 하나도 맞는 게 없음
- # 'pico' 맞는 숫자는 있지만 자리가 틀리다.
- # 'fermi' 맞는 숫자도 있고, 자리도 맞음
- # Baseball 게임과 유사하다.
- import random
- def getSecretNum(numDigits):
- # Returns a string that is numDigits long, made up of unique random digits.
- numbers = list(range(10)) # 0~9 까지의 값을 리스트로 저장
- # random 모듈의 shuffle()함수 : 리스트의 레퍼런스를 파라미터로 줘야하며, 아이템의 순서를 무작위로 바꾼다.
- # - 값을 따로 반환하지 않으며, 리스트 자체를 변경한다.
- random.shuffle(numbers)
- secretNum = ''
- # 게임의 정답을 만드는 과정
- for i in range(numDigits): # numDigits(3)만큼 암호를 만든다.-> 4로 변경하면 Baseball Game이다.
- secretNum += str(numbers[i]) # 대입 연산자 : +=,-=,*=,/=
- return secretNum
- def getClues(guess, secretNum):
- # Returns a string with the pico, fermi, bagels clues to the user.
- if guess == secretNum:
- return 'You got it!'
- clue = []
- for i in range(len(guess)):
- if guess[i] == secretNum[i]:
- clue.append('Fermi')
- elif guess[i] in secretNum:
- clue.append('Pico')
- if len(clue) == 0:
- return 'Bagels'
- # 리스트의 sort()메소드 : 리스트를 알파벳과 숫자 순서로 정렬해준다.
- # 반환형은 None반환이다.
- # join() 문자열 메소드 : 리스트 인자를 합친 문자열을 반환한다.
- # '@'.join(['x','y'] => 'x@y' 중간 중간 별로 @가 삽입된다.
- def isOnlyDigits(num):
- # Returns True if num is a string made up only of digits. Otherwise returns False.
- if num == '':
- return False
- for i in num:
- return False
- return True
- def playAgain():
- # This function returns True if the player wants to play again, otherwise it returns False.
- NUMDIGITS = 3
- MAXGUESS = 10
- while True:
- secretNum = getSecretNum(NUMDIGITS)
- numGuesses = 1
- while numGuesses <= MAXGUESS:
- guess = ''
- while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
- # 문자열 삽입 기법(String interpolation)
- # - 문자열 삽입을 쓰면 표시자(placeholder,마커) %s(변환 지시자(conversion specifier))를
- # - 쓰고, 끝에 변수 이름을 쓴다. print('%s %s %s',%( , , ))
- guess = input()
- clue = getClues(guess, secretNum)
- numGuesses += 1
- if guess == secretNum:
- break
- if numGuesses > MAXGUESS:
- if not playAgain():
- break
'Computer Language' 카테고리의 다른 글
CartesianCorrdinateSystems.py (0) | 2015.01.14 |
---|---|
BaseBallGame.py (0) | 2015.01.13 |
TicTacToeGame.py (0) | 2015.01.12 |
HangmanGame_edit.py (0) | 2015.01.12 |
HangmanGame.py (0) | 2015.01.10 |
Comments