Notice
Recent Posts
Recent Comments
Today
Total
05-21 05:41
Archives
관리 메뉴

Jeongchul Kim

BaglesGame.py 본문

Computer Language

BaglesGame.py

김 정출 2015. 1. 13. 15:22
  1. # Bagles
  2. # 'bagels' 숫자 3개 하나도 맞는 게 없음
  3. # 'pico' 맞는 숫자는 있지만 자리가 틀리다.
  4. # 'fermi' 맞는 숫자도 있고, 자리도 맞음
  5. # Baseball 게임과 유사하다.
  6.  
  7. import random
  8.  
  9. def getSecretNum(numDigits):
  10.     # Returns a string that is numDigits long, made up of unique random digits.
  11.     numbers = list(range(10)) # 0~9 까지의 값을 리스트로 저장
  12.     # random 모듈의 shuffle()함수 : 리스트의 레퍼런스를 파라미터로 줘야하며, 아이템의 순서를 무작위로 바꾼다.
  13.     #   - 값을 따로 반환하지 않으며, 리스트 자체를 변경한다.
  14.     random.shuffle(numbers)
  15.     secretNum = ''
  16.  
  17.     # 게임의 정답을 만드는 과정
  18.     for i in range(numDigits)# numDigits(3)만큼 암호를 만든다.-> 4로 변경하면 Baseball Game이다.
  19.          secretNum += str(numbers[i]) # 대입 연산자 : +=,-=,*=,/=
  20.        
  21.     return secretNum
  22.  
  23.  
  24. def getClues(guess, secretNum):
  25.     # Returns a string with the pico, fermi, bagels clues to the user.
  26.     if guess == secretNum:
  27.         return 'You got it!'
  28.  
  29.     clue = []
  30.  
  31.     for i in range(len(guess)):
  32.         if guess[i] == secretNum[i]:
  33.             clue.append('Fermi')
  34.         elif guess[i] in secretNum:
  35.             clue.append('Pico')
  36.     if len(clue) == 0:
  37.         return 'Bagels'
  38.  
  39. # 리스트의 sort()메소드 : 리스트를 알파벳과 숫자 순서로 정렬해준다.
  40. # 반환형은 None반환이다.
  41.     clue.sort()
  42. # join() 문자열 메소드 : 리스트 인자를 합친 문자열을 반환한다.
  43. # '@'.join(['x','y'] => 'x@y' 중간 중간 별로 @가 삽입된다.
  44.     return ' '.join(clue)
  45.  
  46.  
  47. def isOnlyDigits(num):
  48.     # Returns True if num is a string made up only of digits. Otherwise returns False.
  49.     if num == '':
  50.         return False
  51.  
  52.     for i in num:
  53.         if i not in '0 1 2 3 4 5 6 7 8 9'.split():
  54.             return False
  55.  
  56.     return True
  57.  
  58. def playAgain():
  59.     # This function returns True if the player wants to play again, otherwise it returns False.
  60.     print('Do you want to play again? (yes or no)')
  61.     return input().lower().startswith('y')
  62.  
  63. NUMDIGITS = 3
  64. MAXGUESS = 10
  65.  
  66. print('I am thinking of a %s-digit number. Try to guess what it is.' % (NUMDIGITS))
  67. print('Here are some clues:')
  68. print('When I say:    That means:')
  69. print('  Pico         One digit is correct but in the wrong position.')
  70. print('  Fermi        One digit is correct and in the right position.')
  71. print('  Bagels       No digit is correct.')
  72.  
  73. while True:
  74.     secretNum = getSecretNum(NUMDIGITS)
  75.     print('I have thought up a number. You have %s guesses to get it.' % (MAXGUESS))
  76.  
  77.     numGuesses = 1
  78.     while numGuesses <= MAXGUESS:
  79.         guess = ''
  80.         while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
  81.             print('Guess #%s: ' % (numGuesses))
  82.     # 문자열 삽입 기법(String interpolation)
  83.     #   - 문자열 삽입을 쓰면 표시자(placeholder,마커) %s(변환 지시자(conversion specifier))를
  84.     #   - 쓰고, 끝에 변수 이름을 쓴다. print('%s %s %s',%( , , ))
  85.             guess = input()
  86.  
  87.         clue = getClues(guess, secretNum)
  88.         print(clue)
  89.         numGuesses += 1
  90.  
  91.         if guess == secretNum:
  92.             break
  93.         if numGuesses > MAXGUESS:
  94.             print('You ran out of guesses. The answer was %s.' % (secretNum))
  95.  
  96.     if not playAgain():
  97.         break
  98.  


'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