一个很简单的猜单词游戏。


你的机会是有限的,你每猜错一次,你要拯救的小人就出现一部分。




当整个小人出现的时候,游戏结束,你便看到了惨象:一个吊死的屌丝!大笑


可以把单词换成你每天背的单词,便于复习。。。偷笑


直接放代码。


#!usr/bin/env python3
#-*- coding:utf-8 -*-

import random
try:
    import cPickle as pickle
except Exception:
    import pickle

# global viriable strokes

with open("strokes.txt",'r') as f:
    strokes = pickle.loads(f.read().encode('utf-8'))
filename = "2of12inf.txt"

def askForInput(word, guessed, pic):
    """
    pic: a string that displays the hangman.
    word: string, the mystery word.
    guessed: set, the characters in uper case which user have guessed.
    this function ask the user guess word until the word is valid.
    """
    print(pic)
    print("Letters already guessed: {}".format(" ".join(list(guessed))))
    print("The current state of your guess: {}".format(showWord(word, guessed)))
    characters = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    while True:
        ans = input("What is your next letter? (or type your guess) :")
        ans = ans.strip()
        ans = ans.upper()
        if len(ans) > 1:
            if len(ans) == len(word):
                if all([ele in characters for ele in ans]):
                    return ans
                else:
                    print("Invalid entry: enter a word that is a alphabeta string.")
            else:
                print("Invalid entry: enter a word that exists {} characters.".format(len(word)))

        elif len(ans) == 1:
            if ans in characters:
                if ans not in guessed:
                    return ans
                else:
                    print("Invalid entry: enter a single letter you have not already guessed.")
            else:
                print("Invalid entry: enter a single letter that is a alphabeta character.")
        else:
            print("Invalid entry: enter a single alphabeta letter or guess a  alphabeta word.")


def getWordList(minLength, maxLength):
    """
    minLength:int, the min length of the word.
    maxLength:int, the max length of the word.
    return: the wordList, a list of strings.
    this function read the words from text file: 2of12inf.txt.
    """
    wordList = []
    with open(filename, 'r') as f: # iterate the file from top to bottom
        for line in f:
            line = line.strip()
            line = line.strip("%") # remove plurals
            if len(line) >= minLength and len(line) <= maxLength:
                wordList.append(line)

    return wordList


def selectWord(minLength, maxLength):
    """
    minLength: int, the min length of the word
    maxLength: int, the max length of the word
    return: a word in upper case
    """
    wordList = getWordList(minLength, maxLength)
    word = random.choice(wordList)
    return word.upper()

def showWord(word, guessed):
    """
    word:the upper case of  the mystery word 
    guessed: the set of all guessed characters
    return : a sstring like "_ _ E E _ E"
    """
    word = word.upper()
    word_hint = ["_" if ele not in guessed else ele for ele in word]
    return " ".join(word_hint)


def printBanner(word):
    """
    word: string, the mystery word.
    this function print out the number of the target word.
    """
    print("YOU WILL GUESS A WORD WITH {} LETTERS!".format(len(word)))


def theEnd(word, wrong_times):
    if wrong_times < len(strokes):
        print("Congratulations! You win!!")
        print("The word was {}".format(" ".join(list(word))))
    else:
        print("Sorry, you lose!")
        print("The word was {}".format(" ".join(list(word))))
    print("Welcome to my blog:")
    print("---------------------")
    print("http://blog.csdn.net/myjiayan")
    print("---------------------")


def main():
    print("WELCOME TO HANGMAN!")
    print("Welcome to my blog:")
    print("---------------------")
    print("http://blog.csdn.net/myjiayan")
    print("---------------------")
    minLength = 6
    maxLength = 8
    word = selectWord(minLength, maxLength)
    word = word.upper()
    printBanner(word)
    guessed = set()
    wrong_times = 0
    # tha main loop
    while wrong_times < len(strokes):
        # upper case ans
        ans = askForInput(word, guessed, strokes[wrong_times])
        # ans is an character
        if len(ans) == 1:
            numAns = word.count(ans)
            print("There is {} {}!".format(numAns, ans))
            guessed.add(ans)
            if all([ele in guessed for ele in word]):
                break
            if numAns == 0:
                wrong_times += 1
        elif len(ans) == len(word):
            if ans == word:
                break
            else:
                wrong_times += 1
                print("the word you guessed is wrong!")

    theEnd(word, wrong_times)


if __name__ == "__main__":
    main()

strokes.txt 和 单词文件 2of12inf.txt 在 http://download.csdn.net/detail/u013805817/9468750 上有下载。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐