Hangman Game

花了一整个下午用python写了个叫"hang man"的文字小游戏.虽然自己还是弱鸡,而且感觉代码不够简洁,不过弄出来以后成就感还是杠杠的.就是有一个函数调用的时候写成了另一个,然后检查了1个小时才找到原因...仔细啊仔细(敲黑板).

# -*- coding: utf-8 -*-
"""
Created on Wed Feb  8 18:24:35 2017

@author: Tom
"""

# Hangman game
#

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE...
    allIn = True
    
    while allIn:
        
       for i in range(len(secretWord)):
           
           if secretWord[i] not in lettersGuessed:
               
              allIn = False 
              
       break
           
    return allIn



def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    testWord = ''
    
    for i in range(len(secretWord)):
        
      word = secretWord[i]

      if secretWord[i] in lettersGuessed:
          
        testWord = testWord + word + ' '
        
      else:
          
        testWord += "_ "
        
    testWord = testWord[0:-1]

    return testWord
 


def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    alphaList = "abcdefghijklmnopqrstuvwxyz"
    
    finalList = ""
    
    for i in range(len(alphaList)):
    
      if alphaList[i] not in  lettersGuessed:
      
        finalList += alphaList[i]
        
    return finalList
    

secretWord = chooseWord(wordlist)    
    
def hangman(secretWord):
   print("Welcome to the game Hangman!")
   print("I am thinking of a word that is " + str(len(secretWord)) + " letters long")
   print('-----------')
   timesLeft = 8      
   lettersGuessed = ""
   letterAvailable = ""
   guessingWord = ""
   
   while timesLeft > 0:
       
       print("You have " + str(timesLeft) + " guesses left.")        
                
       letterAvailable = getAvailableLetters(lettersGuessed)
        
       print("Available Letters: " +  letterAvailable)
        
       letterGuess = input("Please guess a letter: ")                      
           
       if letterGuess in lettersGuessed:
            
          print("Oops! You've already guessed that letter: " + guessingWord)
          
            
       else:
            
           lettersGuessed += letterGuess
                        
           guessingWord =  getGuessedWord(secretWord, lettersGuessed)
           
                       
                       
           if letterGuess in secretWord:
            
               print("Good guess: " + guessingWord)
              
               
               if isWordGuessed(secretWord, lettersGuessed) == True:
                 
                 timesLeft = 0
                                 
           else:
                
                timesLeft -= 1
                
                print("Oops! That letter is not in my word: " + guessingWord)
       print('-----------')           
                
   
   if isWordGuessed(secretWord, lettersGuessed) == False:
     print("Sorry, you ran out of guesses. The word was " + secretWord)
     
   else:
     print("Congratulations, you won!")
                
                
                

hangman(secretWord)




# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)

# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)
# -*- coding: utf-8 -*-
"""
Created on Wed Feb  8 18:24:35 2017

@author: Tom
"""

# Hangman game
#

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE...
    allIn = True
    
    while allIn:
        
       for i in range(len(secretWord)):
           
           if secretWord[i] not in lettersGuessed:
               
              allIn = False 
              
       break
           
    return allIn



def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    testWord = ''
    
    for i in range(len(secretWord)):
        
      word = secretWord[i]

      if secretWord[i] in lettersGuessed:
          
        testWord = testWord + word + ' '
        
      else:
          
        testWord += "_ "
        
    testWord = testWord[0:-1]

    return testWord
 


def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    alphaList = "abcdefghijklmnopqrstuvwxyz"
    
    finalList = ""
    
    for i in range(len(alphaList)):
    
      if alphaList[i] not in  lettersGuessed:
      
        finalList += alphaList[i]
        
    return finalList
    

secretWord = chooseWord(wordlist)    
    
def hangman(secretWord):
   print("Welcome to the game Hangman!")
   print("I am thinking of a word that is " + str(len(secretWord)) + " letters long")
   print('-----------')
   timesLeft = 8      
   lettersGuessed = ""
   letterAvailable = ""
   guessingWord = ""
   
   while timesLeft > 0:
       
       print("You have " + str(timesLeft) + " guesses left.")        
                
       letterAvailable = getAvailableLetters(lettersGuessed)
        
       print("Available Letters: " +  letterAvailable)
        
       letterGuess = input("Please guess a letter: ")                      
           
       if letterGuess in lettersGuessed:
            
          print("Oops! You've already guessed that letter: " + guessingWord)
          
            
       else:
            
           lettersGuessed += letterGuess
                        
           guessingWord =  getGuessedWord(secretWord, lettersGuessed)
           
                       
                       
           if letterGuess in secretWord:
            
               print("Good guess: " + guessingWord)
              
               
               if isWordGuessed(secretWord, lettersGuessed) == True:
                 
                 timesLeft = 0
                                 
           else:
                
                timesLeft -= 1
                
                print("Oops! That letter is not in my word: " + guessingWord)
       print('-----------')           
                
   
   if isWordGuessed(secretWord, lettersGuessed) == False:
     print("Sorry, you ran out of guesses. The word was " + secretWord)
     
   else:
     print("Congratulations, you won!")
                
                
                

hangman(secretWord)




# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)

# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)
# -*- coding: utf-8 -*-
"""
Created on Wed Feb  8 18:24:35 2017

@author: Tom
"""

# Hangman game
#

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE...
    allIn = True
    
    while allIn:
        
       for i in range(len(secretWord)):
           
           if secretWord[i] not in lettersGuessed:
               
              allIn = False 
              
       break
           
    return allIn



def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    testWord = ''
    
    for i in range(len(secretWord)):
        
      word = secretWord[i]

      if secretWord[i] in lettersGuessed:
          
        testWord = testWord + word + ' '
        
      else:
          
        testWord += "_ "
        
    testWord = testWord[0:-1]

    return testWord
 


def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    alphaList = "abcdefghijklmnopqrstuvwxyz"
    
    finalList = ""
    
    for i in range(len(alphaList)):
    
      if alphaList[i] not in  lettersGuessed:
      
        finalList += alphaList[i]
        
    return finalList
    

secretWord = chooseWord(wordlist)    
    
def hangman(secretWord):
   print("Welcome to the game Hangman!")
   print("I am thinking of a word that is " + str(len(secretWord)) + " letters long")
   print('-----------')
   timesLeft = 8      
   lettersGuessed = ""
   letterAvailable = ""
   guessingWord = ""
   
   while timesLeft > 0:
       
       print("You have " + str(timesLeft) + " guesses left.")        
                
       letterAvailable = getAvailableLetters(lettersGuessed)
        
       print("Available Letters: " +  letterAvailable)
        
       letterGuess = input("Please guess a letter: ")                      
           
       if letterGuess in lettersGuessed:
            
          print("Oops! You've already guessed that letter: " + guessingWord)
          
            
       else:
            
           lettersGuessed += letterGuess
                        
           guessingWord =  getGuessedWord(secretWord, lettersGuessed)
           
                       
                       
           if letterGuess in secretWord:
            
               print("Good guess: " + guessingWord)
              
               
               if isWordGuessed(secretWord, lettersGuessed) == True:
                 
                 timesLeft = 0
                                 
           else:
                
                timesLeft -= 1
                
                print("Oops! That letter is not in my word: " + guessingWord)
       print('-----------')           
                
   
   if isWordGuessed(secretWord, lettersGuessed) == False:
     print("Sorry, you ran out of guesses. The word was " + secretWord)
     
   else:
     print("Congratulations, you won!")
                
                
                

hangman(secretWord)




# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)

# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)
# -*- coding: utf-8 -*-
"""
Created on Wed Feb  8 18:24:35 2017

@author: Tom
"""

# Hangman game
#

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE...
    allIn = True
    
    while allIn:
        
       for i in range(len(secretWord)):
           
           if secretWord[i] not in lettersGuessed:
               
              allIn = False 
              
       break
           
    return allIn



def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    testWord = ''
    
    for i in range(len(secretWord)):
        
      word = secretWord[i]

      if secretWord[i] in lettersGuessed:
          
        testWord = testWord + word + ' '
        
      else:
          
        testWord += "_ "
        
    testWord = testWord[0:-1]

    return testWord
 


def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    alphaList = "abcdefghijklmnopqrstuvwxyz"
    
    finalList = ""
    
    for i in range(len(alphaList)):
    
      if alphaList[i] not in  lettersGuessed:
      
        finalList += alphaList[i]
        
    return finalList
    

secretWord = chooseWord(wordlist)    
    
def hangman(secretWord):
   print("Welcome to the game Hangman!")
   print("I am thinking of a word that is " + str(len(secretWord)) + " letters long")
   print('-----------')
   timesLeft = 8      
   lettersGuessed = ""
   letterAvailable = ""
   guessingWord = ""
   
   while timesLeft > 0:
       
       print("You have " + str(timesLeft) + " guesses left.")        
                
       letterAvailable = getAvailableLetters(lettersGuessed)
        
       print("Available Letters: " +  letterAvailable)
        
       letterGuess = input("Please guess a letter: ")                      
           
       if letterGuess in lettersGuessed:
            
          print("Oops! You've already guessed that letter: " + guessingWord)
          
            
       else:
            
           lettersGuessed += letterGuess
                        
           guessingWord =  getGuessedWord(secretWord, lettersGuessed)
           
                       
                       
           if letterGuess in secretWord:
            
               print("Good guess: " + guessingWord)
              
               
               if isWordGuessed(secretWord, lettersGuessed) == True:
                 
                 timesLeft = 0
                                 
           else:
                
                timesLeft -= 1
                
                print("Oops! That letter is not in my word: " + guessingWord)
       print('-----------')           
                
   
   if isWordGuessed(secretWord, lettersGuessed) == False:
     print("Sorry, you ran out of guesses. The word was " + secretWord)
     
   else:
     print("Congratulations, you won!")
                
                
                

hangman(secretWord)




# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)

# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容