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

Jeongchul Kim

BaseBallGame.py 본문

Computer Language

BaseBallGame.py

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



'Computer Language' 카테고리의 다른 글

SonarGame.py  (0) 2015.01.14
CartesianCorrdinateSystems.py  (0) 2015.01.14
BaglesGame.py  (0) 2015.01.13
TicTacToeGame.py  (0) 2015.01.12
HangmanGame_edit.py  (0) 2015.01.12
Comments