首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Hangman程序

Python Hangman程序
EN

Code Review用户
提问于 2014-03-03 16:45:17
回答 1查看 11.9K关注 0票数 7

为了学习Python,我一直在使用用艰苦的方法学习Python,为了练习我的Python技能,我写了一个PyHangman游戏(PyHangman --创造性的,对吗?)

代码语言:javascript
复制
#! /usr/bin/env python2.7

import sys, os, random

if sys.version_info.major != 2:
    raw_input('This program requires Python 2.x to run.')
    sys.exit(0)


class Gallows(object):
    def __init__(self):
        '''Visual of the game.'''
        self.state = [
            [
                '\t  _______ ',
                '\t  |     | ',
                '\t        | ',
                '\t        | ',
                '\t        | ',
                '\t        | ',
                '\t________|_',
            ],
            [
                '\t  _______ ',
                '\t  |     | ',
                '\t  O     | ',
                '\t        | ',
                '\t        | ',
                '\t        | ',
                '\t________|_',
            ],
            [
                '\t  _______ ',
                '\t  |     | ',
                '\t  O     | ',
                '\t  |     | ',
                '\t  |     | ',
                '\t        | ',
                '\t________|_',
            ],
            [
                '\t  _______ ',
                '\t  |     | ',
                '\t  O     | ',
                '\t \|     | ',
                '\t  |     | ',
                '\t        | ',
                '\t________|_',
            ],
            [
                '\t  _______ ',
                '\t  |     | ',
                '\t  O     | ',
                '\t \|/    | ',
                '\t  |     | ',
                '\t        | ',
                '\t________|_',
            ],
            [
                '\t  _______ ',
                '\t  |     | ',
                '\t  O     | ',
                '\t \|/    | ',
                '\t  |     | ',
                '\t /      | ',
                '\t________|_',
            ],
            [
                '\t  _______ ',
                '\t  |     | ',
                '\t  O     | ',
                '\t \|/    | ',
                '\t  |     | ',
                '\t / \\    | ',
                '\t________|_',
            ]
        ]

    def set_state(self, misses):
        '''Sets the current visual being used.'''
        image = ''

        state = self.state[misses] # set state to the list of desired gallows image
        # construct gallows image into str from list
        for piece in state:
            image += piece + '\n'
        return image


class Wordlist(object):
    def __init__(self):
        '''Set the length of the wordlist.'''
        self.numLines = sum(1 for line in open('test.txt'))

    def new_word(self):
        '''Choose a new word to be guessed.'''
        stopNum = random.randint(0, self.numLines-1) # establish random number to be picked from list
        # extract word from file
        with open('test.txt') as file:
            for x, line in enumerate(file):
                if x == stopNum:
                    word = line.lower().strip() # remove endline characters
        return word


def set_blanks(word):
    '''Create blanks for each letter in the word.'''
    blanks = []

    for letter in word:
        # Don't hide hyphens
        if letter == '-':
            blanks += '-'
        else:
            blanks += '_'
    return blanks


def check_letter(word, guess, blanks, used, missed):
    '''Check if guessed letter is in the word.'''
    newWord = word

    # If the user presses enter without entering a letter
    if guess.isalpha() == False:
        raw_input("You have to guess a letter, silly!")

    # If the user inputs multiple letters at once
    elif len(list(guess)) > 1:
        raw_input("You can't guess more than one letter at a time, silly!")

    # If the user inputs a letter they've already used
    elif guess in used:
        raw_input("You already tried that letter, silly!")

    # replace the corresponding blank for each instance of guess in the word
    elif guess in word:
        for x in range(0, word.count(guess)):
            blanks[newWord.find(guess)] = guess
            newWord = newWord.replace(guess, '-', 1) # replace already checked letters with dashes
        used += guess # add the guess to the used letter list

    #If the guess is wrong
    else:
        missed = True
        used += guess
    return blanks, used, missed


def new_page():
    '''Clears the window.'''
    os.system('cls' if os.name == 'nt' else 'clear')


def reset(image, wordlist):
    wrongGuesses = 0 # number of incorrect guesses
    currentImg = image.set_state(wrongGuesses) # current state of the gallows
    word = wordlist.new_word() # word to be guessed
    blanks = set_blanks(word) # blanks which hide each letter of the word until guessed
    used = [] # list of used letters
    return wrongGuesses, currentImg, word, blanks, used


def play(image, currentImg, wrongGuesses, word, blanks, used):
    missed = False

    new_page()
    print currentImg
    for x in blanks:
        print x,
    print '\n'
    for x in used:
        print x,
    print '\n'

    guess = raw_input("Guess a letter: ")
    blanks, used, missed = check_letter(word, guess.lower(), blanks, used, missed)

    if missed == True and wrongGuesses < 6:
        wrongGuesses += 1
        currentImg = image.set_state(wrongGuesses)
        play(image, currentImg, wrongGuesses, word, blanks, used)
    elif missed == False and blanks != list(word) and wrongGuesses != 7:
        play(image, currentImg, wrongGuesses, word, blanks, used)
    elif blanks == list(word):
        endgame('win', word)
    else:
        endgame('lose', word)


def endgame(result, word):
    new_page()
    if result != 'lose':
        print "Congratulations, you win!"
        print "You correctly guessed the word '%s'!" % word
    else:
        print "Nice try! Your word was '%s'." % word
    while True:
        play_again = raw_input("Play again? [y/n]")
        if 'y' in play_again.lower():
            return
        elif 'n' in play_again.lower():
            sys.exit(0)
        else:
            print "Huh?"


def main():
    image = Gallows()
    wordlist = Wordlist()

    new_page()
    print("\nWelcome to Hangman!")
    print("Guess the word before the man is hung and you win!")
    raw_input("\n\t---Enter to Continue---\n")
    new_page()

    while True:
        misses, currentImg, word, blanks, used = reset(image, wordlist)
        play(image, currentImg, misses, word, blanks, used)

if __name__ == '__main__':
    main()

那你们都怎么想?这是程序的第二次迭代,作为第一个一片狼藉,但是我想我现在已经做得更好了。

其中一件事,我仍然认为是混乱的是,我如何有游戏循环后,你猜到了一个字母,因为它只是简单地称为自己。有更好的方法吗?

任何技巧,使我的代码更奏鸣曲赞赏!

EN

回答 1

Code Review用户

发布于 2014-03-03 18:48:37

Python支持多行字符串文字。您可以使用这些而不是使用列表来编码您的状态映像。

代码语言:javascript
复制
a = r""" 'hello' \n
  more """
print a

您有多个名为set_XXX()的方法,它们返回值而不是存储值。这些方法的名称可以更改,以便更好地描述它们正在做的事情。

即使在找到选定的单词之后,Wordlist.new_word()仍将继续遍历整个文件。将return放在创建word变量的位置,一旦得到所需的值,就会中断循环。

Wordlist对文件名使用硬编码字符串,该字符串在两个不同的位置指定。如果您想要更改为不同的文件,您必须记住更改这两种情况。这是一个简单的例子,看起来很简单,但是当代码变得更大和更复杂时,很难跟踪这种类型的错误。

票数 4
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/43318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档