Ho terminato la mia app Python Hangman con un codice molto semplice.

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!") 

Quindi, ho un paio di domande sul mio codice:

  1. Ho iniziato a imparare qualcosa sulle classi in Python e ho pensato “Hey, scriviamo questo Hangman con le classi ) “Ma dopo un po di programmazione ho capito, ho appena creato classi con 1 func e invece di func() le ho chiamate class.func() e così” è tutto. Cè qualche buona ragione per cui e come dovrei usare le classi in un gioco dellimpiccato?

  2. So che il codice è molto semplice e al mio livello non dovrei preoccuparmi esattamente dellefficacia di il codice ma ancora – Quale parte dovrebbe essere migliorata (non il codice stesso ma la mia logica lì)? Voglio scrivere in un modo “corretto” ma il mio codice sembra ancora super semplice.

Risposta

Giocabilità

Ho eseguito il tuo gioco per provarlo prima e ho notato qualcosa di strano quando una lettera è trovati due volte nella stessa parola, ad esempio ” glass ” qui:

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

Non sono sicuro che sia di design, ma come giocatore trovo strano che “viene visualizzato due volte. Ho trovato la sua origine nel codice:

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) 

Se annulli il rientro di print(guess_word) di due livelli, eviterai questo comportamento poiché non verrà eseguito in un ciclo:

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

Stampare un array grezzo come ["-", "-", "a", "s", "s"] è un po confuso, allinizio non sapevo cosa fosse finché non ne ho indovinato uno giusto e ho visto i risultati. Quindi facciamogli stampare qualcosa di più amichevole:

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

Molto meglio! Ma diventerà un po goffo digitare tutto ciò ogni volta, quindi creiamo una funzione di utilità per esso e possiamo usarlo per il print(guess_word) anche allinizio di una partita.

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

Quindi print_word_to_guess(guess_word) ogni volta che ne abbiamo bisogno. Sarebbe anche possibile creare un messaggio diverso facoltativo, ma il valore predefinito è Word to guess:, ma lo lascio per te come una sfida.


Il gioco inoltre non mi dice mai nulla su quante possibilità mi restano, quindi rimango a indovinare (letteralmente) finché non lo capisco. È molto facile creare una piccola funzione di utilità da fare:

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

Quindi alcune aggiunte di codice:

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

E:

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) 

Il tuo elenco di parole è piuttosto limitato, per il futuro potresti prendere in considerazione la possibilità di cercare un file di testo online con un intero gruppo di parole e leggerne uno a caso, che porterebbe più varietà!


Miglioramenti al codice

main funzione

Esegui tutto il tuo gioco funzioni non appena le crei. Avrebbe più senso inserirli nella funzione __main__ :

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

A proposito, newFunc() non funziona bene come nome, in quanto non dice nulla su ciò che fa. Qualcosa come ask_user_to_play() sarebbe molto meglio.


Denominazione di costanti

Python non ha costanti reali, ma ciononostante è buona norma nominare variabili che non dovrebbero cambiare (per modifica intendo riassegnate a valori diversi) in ALL_CAPS_WITH_UNDERSCORES. Una semplice & sostituzione di ricerca in un IDE o in un editor di testo aiuta a correggere lintero script.

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

Docstring

È “una buona abitudine aggiungere una docstring a tutte le funzioni, classi e moduli, per descrivere per altri programmatori a cosa serve il codice in questione. Lho fatto per la funzione di utilità 2 sopra.


Suggerimenti sul tipo

Dato che Python 3, ora puoi usare suggerimenti di tipo per le firme di funzioni e metodi e utilizza strumenti di analisi statica del codice. Questo rende anche il codice più facile da leggere per gli esseri umani.


Codice migliorato

Ecco cosa mi è venuto in mente, applicando tutto quanto sopra e migliorando la spaziatura ( il tuo aveva troppe righe vuote ovunque). Probabilmente ci sono altre cose che potrebbero essere migliorate, ma questo dovrebbe essere un buon inizio.

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() 

Commenti

  • Non posso ‘ dire quanto apprezzo la tua risposta! Esaminerò tutti i tuoi suggerimenti e metterò alla prova me stesso con loro, grazie ancora 🙂
  • Nessun problema, mi sono divertito anchio a rivederlo! Spero che ne pubblicherai altri in futuro =)

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *