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

Jeongchul Kim

HangmanGame_edit.py 본문

Computer Language

HangmanGame_edit.py

김 정출 2015. 1. 12. 16:11
  1. #Hangman Game
  2.  
  3.  
  4. import random
  5.  
  6. # 딕셔너리(dictionary) : Data type
  7. #  - 리스트와 같은 많은 값의 집합이지만 이 값을 얻어낼 때는 정수 인덱스(딕셔너리에서 인덱스는 키(key)라고 한다.)가 아니라,
  8. #    특정 데이터 타입의 인덱스를 쓸 수 있다.(하지만 대부분의 경우 문자열을 사용한다.)
  9. #  - 딕셔너리에서는 {}(대괄호)를 사용한다. key : value
  10. #       Dictionary = {'hello':'Hello there, how are you?','chat':'How is the weather?'}
  11. #  - 딕셔너리에서 값을 얻어올 때는 리스트와 같이 Dictionary[key] 즉[key] 값으로 얻어온다.
  12. #  - 딕셔너리 크기 알아보기 len(Dictionary)
  13. #  - 딕셔너리와 리스트의 큰 차이점은 딕셔너리는 첫 번째 아이템이라는 것이 없다. 반면, 리스트는 인덱스가 0으로 시작한다.
  14. #  - 딕셔너리의 for문
  15. #       for i in Dictionary : i는 키 값을 받게된다. value로 접근은 Dictionary[i]로 값을 알아낼 수 있다.
  16. #  - 딕셔너리 keys() 메소드 : key 값을 리스트로 출력
  17. #  - 딕셔너리 values() 메소드 : value 값을 리스트로 출력
  18.  
  19. HANGMANPICS = ['''  
  20.  
  21.  +---+
  22.  |   |
  23.      |
  24.      |
  25.      |
  26.      |
  27. =========''''''
  28.  
  29.  +---+
  30.  |   |
  31.  O   |
  32.      |
  33.      |
  34.      |
  35. =========''''''
  36.  
  37.  +---+
  38.  |   |
  39.  O   |
  40.  |   |
  41.      |
  42.      |
  43. =========''''''
  44.  
  45.  +---+
  46.  |   |
  47.  O   |
  48. /|   |
  49.      |
  50.      |
  51. =========''''''
  52.  
  53.  +---+
  54.  |   |
  55.  O   |
  56. /|\  |
  57.      |
  58.      |
  59. =========''''''
  60.  
  61.  +---+
  62.  |   |
  63.  O   |
  64. /|\  |
  65. /    |
  66.      |
  67. =========''''''
  68.  
  69.  +---+
  70.  |   |
  71.  O   |
  72. /|\  |
  73. / \  |
  74.      |
  75. =========''''''
  76.  
  77.  +---+
  78.  |   |
  79. [O   |
  80. /|\  |
  81. / \  |
  82.      |
  83. =========''''''
  84.  
  85.  +---+
  86.  |   |
  87. [O]  |
  88. /|\  |
  89. / \  |
  90.      |
  91. =========''''''
  92.  
  93.  +---+
  94.  |   |
  95. [x]  |
  96. /|\  |
  97. / \  |
  98.      |
  99. =========''']
  100.  
  101. # split() 리스트 메소드 : 문자열 데어터 타입에서 사용하는 메소드
  102. # 단어들은 빈칸으로 구분되어 있다. split()메소드는 이 문자열을 시트로 바꾸며, 단어 하나하나 모두 리스트의 아이템으로 삽입된다.
  103. # 문자열에서 빈칸은 문자열들을 각각 나누고 있는 것이다.
  104. words = {'Colors':'red orange yellow gree blue indigo violet white black brown'.split(),
  105.          'Shapes':'square triangle rectangle circle ellipse rhombus pentagon hexagon septagon octagon'.split(),
  106.          'Fruits':'apple orange lemon lime pear watermelon grape cherry banana mango strawberry tomato'.split(),
  107.          'Animals':'bat bear cat crab deer dog donkey duck eagle fish frog goat lion lizard monkey moose mouse owl panda python rat shark sheep tiger turkey whale wolf zebra'.split()
  108.          }
  109.  
  110. def getRandomWord(wordDict):
  111.     # This function returns a random string from the passed list of strings.
  112.     # random.randint()메소드 : 랜덤의 정수를 뽑아낸다.
  113.     # random.choice()메소드 : 문자열과 키로 된 딕셔너리를 넘겨주면 임의의 문자열을 반환한다.
  114.     wordKey = random.choice(list(wordDict.keys()))
  115.     wordIndex = random.randint(0, len(wordDict[wordKey]) - 1) # 랜덤 수를 뽑아 그 수를 인덱스로 지정한다.
  116.     # len()메소드는 리스트의 길이를 정수로 반환한다.
  117.     return [wordKey,wordDict[wordKey][wordIndex]] # 리스트를 반환한다.
  118.     # wordDict[][] ->2차원 배열로 생각하면 쉽다. key의 index번째 문자열
  119.  
  120. def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
  121.     print(HANGMANPICS[len(missedLetters)]) # 틀린 횟수 만큼 행맨의 그림을 출력한다.
  122.     print()
  123.     print('Miss Count: '+str(len(missedLetters))+'/'+str(len(HANGMANPICS)-1))
  124.     print()
  125.     print('Missed letters:', end=' ') # 줄 바 꿈을 자동으로 붙이지 않고, end을 붙인다.
  126.  
  127. # for문 : 리스트에 대해 반복 수행 시 편한다.
  128. # while문은 조건이 true인 동안에 반복문을 수행하지만,
  129. # for문은 리스트와 문자열 처리시 간단한다. 각 반복(iteration)에 대해 순서대로 가져온다.
  130. # for 변수이름 in 리스트,문자열,range()
  131.  
  132.     for letter in missedLetters: # 유저가 지금까지 틀린 글자를 출력한다.
  133.         print(letter, end=' ')
  134.     print()
  135.  
  136.    
  137.  
  138. # range() 메소드
  139. #   - range(int @) : 0부터 @미만의 객체를 반환하는데 주로 list(range(@))로 사용해 리스트에 저장한다.
  140. #   - range(int @,int #) : @부터 #미만의 객체를 반환한다.
  141. # list() 메소드
  142. #   - 전달 받은 객체를 리스트로 반환한다.
  143.  
  144.     blanks = '_' * len(secretWord) # 정답 길이 만큼 _ _ _ 채우기
  145.    
  146.     for i in range(len(secretWord))# replace blanks with correctly guessed letters
  147.         if secretWord[i] in correctLetters: # correctLetters 안에 secretWord[i]가 있는 지 검사 true이면 들어간다.
  148.             blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
  149.             # i미만까지 blanks / i번째 secretWord / i+1부터 끝까지 blanks
  150.            
  151.  
  152.     for letter in blanks: # show the secret word with spaces in between each letter
  153.         print(letter, end=' ')
  154.     print()
  155.  
  156.  
  157. def getGuess(alreadyGuessed):
  158.     # 플레이어가 글자를 입력했는지, 유효할 글자 인지 검사 후 반환한다.
  159.     # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
  160.  
  161.     while True: # 무한 루프(infinte loop) 돌기 때문에 break문, return문을 만나야 빠져나올수 있다.
  162.         print('Guess a letter.')
  163.         guess = input()
  164.  
  165.         guess = guess.lower() # lower()메소드는 문자열을 소문자로 만들어서 반환한다. <-> upper()
  166.  
  167.         # 다중 if문 : if문, elif(=else if)문, else문 구성
  168.         if len(guess) != 1# 입력길이가 1이상일 경우
  169.             print('Please enter a single letter.')
  170.         elif guess in alreadyGuessed: # 이미 입력한 글자일 경우
  171.             print('You have already guessed that letter. Choose again.')
  172.         elif guess not in 'abcdefghijklmnopqrstuvwxyz'# 문자열 a~z까지에 포함이 안되는 경우
  173.             print('Please enter a LETTER.')
  174.         else# 위에 포함되지 않는다면 글자를 출력한다.
  175.             return guess
  176.  
  177. def playAgain():
  178.     # This function returns True if the player wants to play again, otherwise it returns False.
  179.     print('Do you want to play again? (yes or no)')
  180.     return input().lower().startswith('y')  # startwith('@')메소드 : @로 시작하는 문자열인지 검사하여 boolean으로 반환한다. 맞으면 True
  181.  
  182.  
  183. print('H A N G M A N')
  184. missedLetters = ''
  185. correctLetters = ''
  186. # 다중 대입문
  187. secretKey, secretWord = getRandomWord(words)
  188. #secretWord = getRandomWord(words)
  189. #secretKey = secretWord[0]
  190. #secretWord = secretWord[1]
  191. gameIsDone = False
  192.  
  193. while True:
  194.     print('The secret word is in the set: '+secretKey)
  195.     displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
  196.  
  197.     # Let the player type in a letter.
  198.     guess = getGuess(missedLetters + correctLetters)
  199.  
  200.     if guess in secretWord: # 추측한 글자가 정답과 일치한가?
  201.         # 일치하다면
  202.         correctLetters = correctLetters + guess
  203.  
  204.         # Check if the player has won , 정답과 모든 글자가 다 맞는지 확인한다.
  205.         foundAllLetters = True
  206.         for i in range(len(secretWord)):
  207.             if secretWord[i] not in correctLetters: # 맞는 글자가 정답에 없다면
  208.                 foundAllLetters = False
  209.                 break
  210.         if foundAllLetters: # 정답과 일치한다.
  211.             print('Yes! The secret word is "' + secretWord + '"! You have won!')
  212.             gameIsDone = True # 게임 종료
  213.     else# 틀리다면
  214.         missedLetters = missedLetters + guess
  215.  
  216.         # Check if player has guessed too many times and lost
  217.         if len(missedLetters) == len(HANGMANPICS) - 1# 플레이어가 제한 횟수를 넘겨서 졌는지 확인한다.
  218.             displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
  219.             print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord +'"')
  220.             gameIsDone = True
  221.  
  222.     # Ask the player if they want to play again (but only if the game is done).
  223.     if gameIsDone:
  224.         if playAgain()# Play Again == Ture  게임 재시작
  225.             missedLetters = ''
  226.             correctLetters = ''
  227.             gameIsDone = False
  228.             secretKey, secretWord = getRandomWord(words)
  229.             #secretWord = getRandomWord(words)
  230.             #secretKey = secretWord[0]
  231.             #secretWord = secretWord[1]
  232.         else# while문 탈출 및 종료
  233.             break
  234.  



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

BaglesGame.py  (0) 2015.01.13
TicTacToeGame.py  (0) 2015.01.12
HangmanGame.py  (0) 2015.01.10
bug & debugger  (0) 2015.01.09
DragonGame.py  (0) 2015.01.09
Comments