list_example_i
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
list_example_i [2023/10/27 10:31] – created appledog | list_example_i [2023/11/06 01:06] (current) – appledog | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | = List Example I | + | [[pyhang game]] |
- | * Hangman | + | |
- | + | ||
- | == Hangman Game | + | |
- | The following game illustrates the use of lists. | + | |
- | + | ||
- | < | + | |
- | def hangman(): | + | |
- | # List of words to choose from | + | |
- | words = [" | + | |
- | + | ||
- | # Choose a random word from the list | + | |
- | word = random.choice(words) | + | |
- | + | ||
- | # Create a list to store the guessed letters | + | |
- | guessed_letters = [] | + | |
- | + | ||
- | # Maximum number of incorrect guesses allowed | + | |
- | max_attempts = 6 | + | |
- | attempts = 0 | + | |
- | + | ||
- | # Create a string to store the partially revealed word | + | |
- | current_word = [" | + | |
- | + | ||
- | while attempts < max_attempts: | + | |
- | # Display the current state of the word | + | |
- | print(" | + | |
- | + | ||
- | # Ask the player for a letter guess | + | |
- | guess = input(" | + | |
- | + | ||
- | # Check if the guess is a single letter | + | |
- | if len(guess) != 1 or not guess.isalpha(): | + | |
- | print(" | + | |
- | continue | + | |
- | + | ||
- | # Check if the letter has already been guessed | + | |
- | if guess in guessed_letters: | + | |
- | print(" | + | |
- | continue | + | |
- | + | ||
- | # Add the guess to the list of guessed letters | + | |
- | guessed_letters.append(guess) | + | |
- | + | ||
- | # Check if the guess is in the word | + | |
- | if guess in word: | + | |
- | for i in range(len(word)): | + | |
- | if word[i] == guess: | + | |
- | current_word[i] = guess | + | |
- | else: | + | |
- | attempts += 1 | + | |
- | print(f" | + | |
- | + | ||
- | # Check if the word has been completely guessed | + | |
- | if "" | + | |
- | print(" | + | |
- | break | + | |
- | + | ||
- | if attempts >= max_attempts: | + | |
- | print(" | + | |
- | + | ||
- | </ | + |
list_example_i.1698402676.txt.gz · Last modified: 2023/10/27 10:31 by appledog