Game Programming Python (d) Hangman

Hangman is a double game, usually paper and pencil to play. A player wants a good word, and then on paper to draw each letter in a word space. Then the second player to guess the word in this letter may contain.
If the second player guesses right, the first player to fill in the correct letters in the space provided. If you did not guess right, the first player to draw a portion matches the person's body. The second player must draw a good person before the match, I guessed all the letters in the word, the only way he can win.

main content:

  • List;
  • in operator;
  • method;
  • Method string lower (), upper (), split (), startswith () and endsWith ();
  • elif statement;

Source:

import random
HANGMAN_PICS = ['''
  +---+
       |
       |
       |
      ===''','''
  +---+
  0    |
       |
       |
      ===''','''      
  +---+
  0    |
  |    |
       |
      ===''','''      
  +---+
  0    |
  /|   |
       |
      ===''','''      
  +---+
  0    |
 /|\   |
       |
      ===''','''      
  +---+
  0    |
 /|\   |
 /     |
      ===''','''      
  +---+
  0    |
 /|\   |
 / \   |
      ===''']
words = '''ant baboon badger bat beer beaver 
         camle cat clam cobra cougar
         coyote crow deer dog donkey duck eagle
         ferret fox frog goat goose hawk'''.split()
 
def getRandomWord(wordList):
    #This function returns a random string from the passed list of string.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

def displayBoard(missedLetters, correctLetters, secretWord):
    print(HANGMAN_PICS[len(missedLetters)])
    print()
    
    print('Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()
    
    blanks = '_'*len(secretWord)
    
    
    for i in range(len(secretWord)):
        #Replace blanks with correctly guessed letters.
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i + 1:]
    
    #Show the secret word with spaces in betweeen each letter.    
    for letter in blanks:
        print(letter, end=' ')
    print()
    
    
def getGuess(alreadyGuessed):
    #Return the letter the player entered. This function makes sure the 
    #player entered asingle letter and not something else.
    while True:
        print('Guess a letter.')
        guess = input()
        guess = guess.lower()
        if len(guess) != 1:
            print('Please enter a single letter.')
        elif guess in alreadyGuessed:
            print('you have already guessed that letter. Choose again.')
        elif guess not in 'abcdefghizklmnopqrstuvwxyz':
            print('Please enter a LETTER.')
        else:
            return guess
    
def playAgain():
    #This function returns True if the player wants to play agains;
    #otherwise, it returns False.
    print('Do you want to play again ? (yes or no)')
    return input().lower().startswith('y')

print('H A N G M A N')
missedLetters = ' '
correctLetters = ' '
secretWord = getRandomWord(words)
gameIsDone = False

while True:
    displayBoard(missedLetters, correctLetters, secretWord)
    
    guess = getGuess(missedLetters + correctLetters)
    
    if guess in secretWord:
        correctLetters = correctLetters + guess
        
        foundAllLetters = True
        for i in range(len(secretWord)):
            if secretWord[i] not in correctLetters:
                foundAllLetters = False
                break
        
        if foundAllLetters == True:
            print('Yes! The secret word is "' + secretWord + '"! You have won!')
                
            gameIsDone = True
    else:
            missedLetters = missedLetters + guess
            
            #Check if player has guessed too many times and lost.
            if len(missedLetters) == len(HANGMAN_PICS) - 1:
                displayBoard(missedLetters, correctLetters, secretWord)
                print('You have run out of guesses!\nAfter ' + 
                      str(len(missedLetters)) + ' missed guesses and '+
                      str(len(correctLetters)) + ' correct guesses, the word was "'
                      + secretWord +' " ')
                gameIsDone = True
                
    #Ask the player if they want to play again(but only if the game is done.)
    if gameIsDone:
        if playAgain():
            missedLetters = ''
            correctLetters = ''
            gameIsDone = False
            secretWord = getRandomWord(words)
        else:
            break

constant:

HANGMAN_PICS variable name is all uppercase, it is a constant practice. Constants (constsnt) is the amount after the first assignment of its value is not changing.

List of data types

HANGMAN_PICS contains several multi-line strings. Each comma-separated values ​​in the list, these values ​​are also called element (item). HANGMAN_PICS Each element is a multi-line string list enables you to store a plurality of values, without the need to use a value for each variable.

The list can be accessed through an index, remember the list index value is zero, that 0 is the first element in the list.

List Connection

Connecting the list using the + sign in the following example:

>>> [1,2,3] + [4,5,6] + [7,8,9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

in operator

in operator can tell us whether a value is in the list, use the expression in operator returns a Boolean value. If the value in the list, the return value is True; if the value is not in the list, the return value is False.

[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 1 in [1,2,3]
True
>>> 4 in [1,2,3]
False

Calling the method:
Method (method) is attached to a function of the value above. To call a method, you must use a sentence that point attached to a specific value.

reverse () method will reverse the order of the elements in the list.

>>> x = [1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]

append () method will add it as an argument to the value of the end of the list.

>>> x = [1,2,3]
>>> x.append(4)
>>> x
[1, 2, 3, 4]

split () method returns a list of the plurality of strings

>>> y ='Hello Pyhton'
>>> y.split()
['Hello', 'Pyhton']

lower () method returns a string lowercase letter is
upper () method returns a string that letter is capitalized

>>> y ='Hello Pyhton'
>>> y.split()
['Hello', 'Pyhton']
>>> y = 'Hello World'
>>> y.lower()
'hello world'
>>> y.upper()
'HELLO WORLD'

startswith () method begins with the brackets return True, otherwise it is False
endsWith () method is to return Flase beginning in parentheses, breeding is True

>>> 'hello'.startswith('h')
True
>>> 'python'.endswith('p')
False

reference:

  1. "Python Game Programming Quick Start" fourth edition, AI Sweigart with, Li Qiang translation
Released nine original articles · won praise 1 · views 416

Guess you like

Origin blog.csdn.net/weixin_45755966/article/details/104023289