아주 기본적인 코드로 Python Hangman 앱을 완성했습니다.

import random import sys # lets set some variables wordList = [ "lion", "umbrella", "window", "computer", "glass", "juice", "chair", "desktop", "laptop", "dog", "cat", "lemon", "cabel", "mirror", "hat" ] guess_word = [] secretWord = random.choice(wordList) # lets randomize single word from the list length_word = len(secretWord) alphabet = "abcdefghijklmnopqrstuvwxyz" letter_storage = [] def beginning(): print("Hello Mate!\n") while True: name = input("Please enter Your name\n").strip() if name == "": print("You can"t do that! No blank lines") else: break beginning() def newFunc(): print("Well, that"s perfect moment to play some Hangman!\n") while True: gameChoice = input("Would You?\n").upper() if gameChoice == "YES" or gameChoice == "Y": break elif gameChoice == "NO" or gameChoice == "N": sys.exit("That"s a shame! Have a nice day") else: print("Please Answer only Yes or No") continue newFunc() def change(): for character in secretWord: # printing blanks for each letter in secret word guess_word.append("-") print("Ok, so the word You need to guess has", length_word, "characters") print("Be aware that You can enter only 1 letter from a-z\n\n") print(guess_word) def guessing(): guess_taken = 1 while guess_taken < 10: guess = input("Pick a letter\n").lower() if not guess in alphabet: #checking input print("Enter a letter from a-z alphabet") elif guess in letter_storage: #checking if letter has been already used print("You have already guessed that letter!") else: letter_storage.append(guess) if guess in secretWord: print("You guessed correctly!") for x in range(0, length_word): #This Part I just don"t get it if secretWord[x] == guess: guess_word[x] = guess print(guess_word) if not "-" in guess_word: print("You won!") break else: print("The letter is not in the word. Try Again!") guess_taken += 1 if guess_taken == 10: print(" Sorry Mate, You lost :<! The secret word was", secretWord) change() guessing() print("Game Over!") 

그래서 내 코드에 대해 몇 가지 질문이 있습니다.

  1. 파이썬의 클래스에 대해 약간의 정보를 얻기 시작했고 “이 행맨을 클래스로 작성해 보겠습니다”라고 생각했습니다. ) “하지만 약간의 코딩 후에 저는 방금 1 func로 클래스를 만들었고 func() 대신 class.func()라고 불렀습니다.” 모두들. 행맨 게임에서 클래스를 사용하는 이유와 방법에 대한 합당한 이유가 있습니까?

  2. 코드가 매우 기본적이며 제 수준에서는 효율성을 정확히 신경 쓰지 말아야한다는 것을 알고 있습니다. 코드 자체가 아니라 내 로직이 개선되어야하는 부분은 무엇입니까? “적절한”방식으로 작성하고 싶지만 내 코드는 여전히 매우 기본적으로 보입니다.

답변

플레이 어빌리티

먼저 테스트하기 위해 게임을 실행했는데, 글자가 나오면 이상한 점을 발견했습니다. " 유리 "와 같이 같은 단어에서 두 번 발견 :

Pick a letter A You guessed correctly! ["-", "-", "a", "-", "-"] Pick a letter s You guessed correctly! ["-", "-", "a", "s", "-"] ["-", "-", "a", "s", "s"] 

저는 그것이 의도적으로 설계된 것인지 확실하지 않지만 플레이어로서 저는 그것이 이상하다고 생각합니다. “가 두 번 표시되었습니다. 코드에서 출처를 찾았습니다.

for x in range(0, length_word): #This Part I just don"t get it if secretWord[x] == guess: guess_word[x] = guess print(guess_word) 

print(guess_word) 두 단계, 루프에서 실행되지 않으므로 이러한 동작을 피할 수 있습니다.

for i in range(0, length_word): if secretWord[i] == guess: guess_word[i] = guess print(guess_word) 

["-", "-", "a", "s", "s"]와 같은 원시 배열을 인쇄하는 것은 약간 혼란 스럽습니다. 처음에는 그것이 무엇인지 몰랐습니다. 내가 하나를 맞히고 결과를 볼 때까지. 이제 좀 더 친근하게 인쇄 해 보겠습니다.

print("Word to guess: {0}".format(" ".join(guess_word))) 
Pick a letter o You guessed correctly! Word to guess: - o - 

훨씬 나아졌습니다! 그러나 매번 모든 것을 입력하는 것은 약간 어색해집니다. 유틸리티 함수를 만들어서 사용할 수 있습니다. print(guess_word) 게임을 시작할 때도 있습니다.

def print_word_to_guess(letters): """Utility function to print the current word to guess""" print("Word to guess: {0}".format(" ".join(guess_word))) 

그런 다음 print_word_to_guess(guess_word) 필요할 때마다. 선택 사항 인 다른 메시지를 만들 수도 있지만 기본값은 Word to guess:이지만,이 메시지는 도전으로 남겨 두겠습니다.


이 게임은 또한 내가 얼마나 많은 기회를 남겼는지에 대해 전혀 알려주지 않으므로 내가 알아낼 때까지 (문자 그대로) 추측을 남깁니다. 작은 유틸리티 함수를 만드는 것은 매우 쉽습니다.

def print_guesses_taken(current, total): """Prints how many chances the player has used""" print("You are on guess {0}/{1}.".format(current, total)) 

그런 다음 몇 가지 코드 추가 :

def guessing(): guess_taken = 1 MAX_GUESS = 10 print_guesses_taken(guess_taken, MAX_GUESS) while guess_taken < MAX_GUESS: 

그리고 :

for i in range(0, length_word): if secretWord[i] == guess: guess_word[i] = guess print_word_to_guess(guess_word) print_guesses_taken(guess_taken, MAX_GUESS) 

귀하의 단어 목록은 매우 제한적입니다. 나중에 온라인에서 여러 단어가 포함 된 텍스트 파일을 찾고 그 중에서 임의의 것을 읽는 것을 고려하십시오. 더 다양해질 것입니다!


코드 개선

main 기능

모든 게임을 실행합니다. 당신이 그들을 만드는 즉시 작동합니다. __main__ 함수에 넣는 것이 더 합리적입니다.

if __name__ == "__main__": beginning() newFunc() change() guessing() 

그런데 newFunc()는 이름만큼 잘 작동하지 않습니다. 그 기능에 대해 아무 말도하지 않기 때문입니다. 가 훨씬 낫습니다.


상수 이름 지정

Python에는 실제 상수가 없지만 그럼에도 불구하고 이름을 지정하는 것이 좋습니다. ALL_CAPS_WITH_UNDERSCORES에서 변경해서는 안되는 변수 (변경에 의해 다른 값으로 다시 할당됨을 의미 함). IDE 또는 텍스트 편집기에서 간단히 찾기 & 바꾸기는 전체 스크립트를 수정하는 트릭입니다.

GUESS_WORD = [] SECRET_WORD = random.choice(wordList) # lets randomize single word from the list LENGTH_WORD = len(SECRET_WORD) ALPHABET = "abcdefghijklmnopqrstuvwxyz" letter_storage = [] 

독 스트링

모든 함수, 클래스 및 모듈에 독 스트링 을 추가하여 다른 항목을 설명하는 것이 좋습니다. 프로그래머에게 문제의 코드가 무엇인지. 위의 2 가지 유틸리티 함수에 대해 그렇게했습니다.


유형 힌트

Python 3부터 이제 유형 힌트 를 사용하고 정적 코드 분석 도구를 사용합니다. 이것은 또한 인간이 코드를 읽기 쉽게 만듭니다.


개선 된 코드

여기에 제가 생각 해낸 것, 위의 모든 것을 적용하고 간격을 개선했습니다 ( 당신의 것에는 너무 많은 빈 줄이 있습니다). 개선 할 수있는 다른 사항이있을 수 있지만 좋은 시작이 될 것입니다.

import random, sys from typing import List # TODO try to load these from a text file WORD_LIST = [ "lion", "umbrella", "window", "computer", "glass", "juice", "chair", "desktop", "laptop", "dog", "cat", "lemon", "cabel", "mirror", "hat" ] GUESS_WORD = [] SECRET_WORD = random.choice(WORD_LIST) # lets randomize single word from the list LENGTH_WORD = len(SECRET_WORD) ALPHABET = "abcdefghijklmnopqrstuvwxyz" letter_storage = [] # Utility functions def print_word_to_guess(letters: List) -> None: """Utility function to print the current word to guess""" print("Word to guess: {0}".format(" ".join(letters))) def print_guesses_taken(current: int, total: int) -> None: """Prints how many chances the player has used""" print("You are on guess {0}/{1}.".format(current, total)) # Game functions def beginning() -> None: """Starts the game""" print("Hello Mate!\n") while True: name = input("Please enter Your name\n").strip() if name == "": print("You can"t do that! No blank lines") else: break def ask_user_to_play() -> None: """Ask user if they want to play""" print("Well, that"s perfect moment to play some Hangman!\n") while True: gameChoice = input("Would You?\n").upper() if gameChoice == "YES" or gameChoice == "Y": break elif gameChoice == "NO" or gameChoice == "N": sys.exit("That"s a shame! Have a nice day") else: print("Please Answer only Yes or No") continue def prepare_secret_word() -> None: """Prepare secret word and inform user of it""" for character in SECRET_WORD: # printing blanks for each letter in secret word GUESS_WORD.append("-") print("Ok, so the word You need to guess has", LENGTH_WORD, "characters") print("Be aware that You can enter only 1 letter from a-z\n\n") print_word_to_guess(GUESS_WORD) def guessing() -> None: """ Main game loop to have user guess letters and inform them of the results """ guess_taken = 1 MAX_GUESS = 10 print_guesses_taken(guess_taken, MAX_GUESS) while guess_taken < MAX_GUESS: guess = input("Pick a letter\n").lower() if not guess in ALPHABET: #checking input print("Enter a letter from a-z ALPHABET") elif guess in letter_storage: #checking if letter has been already used print("You have already guessed that letter!") else: letter_storage.append(guess) if guess in SECRET_WORD: print("You guessed correctly!") for i in range(0, LENGTH_WORD): if SECRET_WORD[i] == guess: GUESS_WORD[i] = guess print_word_to_guess(GUESS_WORD) print_guesses_taken(guess_taken, MAX_GUESS) if not "-" in GUESS_WORD: print("You won!") print("Game Over!") break else: print("The letter is not in the word. Try Again!") guess_taken += 1 print_guesses_taken(guess_taken, MAX_GUESS) if guess_taken == 10: print(" Sorry Mate, You lost :<! The secret word was {0}".format(SECRET_WORD)) if __name__ == "__main__": beginning() ask_user_to_play() prepare_secret_word() guessing() 

댓글

  • ' 당신의 답변에 감사드립니다. 여러분의 모든 팁을 살펴보고 그들에게 도전하겠습니다. 다시 한 번 감사드립니다. 🙂
  • 문제 없습니다. 리뷰도 재미있게 보았습니다! 앞으로 더 많은 게시물을 올리시기 바랍니다 =)

답글 남기기

이메일 주소를 발행하지 않을 것입니다. 필수 항목은 *(으)로 표시합니다