Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 巨蟒:刽子手游戏,未在正确位置显示字母_Python_String_Replace - Fatal编程技术网

Python 巨蟒:刽子手游戏,未在正确位置显示字母

Python 巨蟒:刽子手游戏,未在正确位置显示字母,python,string,replace,Python,String,Replace,我正在用Python为GCSE计算任务制作一个刽子手游戏,我所要做的就是确保当有人键入正确的字母时,它会将其放置在单词的正确位置。 代码如下: def guess_part(word): lives = 6 LetterCount = 0 LetterMask = "" for x in range(len(word)): #run for loop for the amount of the length of word LetterMask =

我正在用Python为GCSE计算任务制作一个刽子手游戏,我所要做的就是确保当有人键入正确的字母时,它会将其放置在单词的正确位置。 代码如下:

def guess_part(word):
    lives = 6
    LetterCount = 0
    LetterMask = ""
    for x in range(len(word)): #run for loop for the amount of the length of word
        LetterMask = LetterMask + "*"
    print LetterMask
    while lives != 0 and LetterMask.find("*")!=-1: #while lives are not 0 and the amount of asterisks are not -1
        LetterGuess = raw_input("Enter a letter to guess?")
        LetterCount = 0
        for char in word:
            LetterCount = LetterCount + 1
        if LetterGuess not in word:
            lives = lives - 1
        else:
            if LetterGuess in word and lives != 0:
                print "Good Guess."
                LetterMask = list(LetterMask)
                LetterMask[LetterCount-1] = LetterGuess
                LetterMask = "".join(LetterMask)
                print LetterMask
            else:
                print "Incorrect."
    if lives == 0:
        print "You have ran out of lives, your word was: ", word
    else:
        print "You have correctly guess the word! Score: ", lives
        print "Play again?"
        again = raw_input("")
        again.lower()
        if again == "y":
            menu()
        elif again == "n":
            exit()
        else:
            exit()


def rand_word():
    from random import randrange
    random_words = ['extraordinary','happy','computer','python','screen','cheese','cabaret','caravan','bee','wasp','insect','mitosis','electronegativity','jumper','trousers']
    word = random_words[randrange(0, 15)] #pick a random number, and use this number as an index for the list, "random_words".
    guess_part(word) #call the function, "guess_part" with the parameter "word"

def user_word():
    print "All words will be changed to lowercase."
    print "Enter the word you would like to guess."
    print ""
    validation_input = False
    while validation_input == False: #while the validation input is not False, do below.
        word = raw_input("")
        if word.isalpha(): #If word contains only strings, no numbers or symbols, do below.
            word = word.lower() #set the string of variable, "word", to all lowercase letters.
            guess_part(word) #call the function, "guess_part" with the parameter, "word".
            validation_input = True #Break the while loop
        else:
            print "Word either contained numbers or symbols."

def menu():
    print "Hangman Game"
    print ""
    print "Ashley Collinge"
    print ""
    print "You will have 6 lives. Everytime you incorrectly guess a word, you will lose a life."
    print "The score at the end of the game, is used to determine the winner."
    print ""
    print "Would you like to use a randomly generated word, or input your own?"
    print "Enter 'R' for randomly generated word, or 'I' for your own input."
    decision_bool = False
    decision_length = False
    while decision_bool == False: #While decision_bool equals "False", do below.
        while decision_length == False: #While decision_length equals "False", do below.
            decision = raw_input("")
            if len(decision) == 1: #If the length of decision eqausl 1, do below.
                decision_length = True
                decision = decision.capitalize() #Capitalize the string value of decision.
                if decision == "R": #if the value of decision, eqauls "R".
                    print "You chose randomly generated word."
                    print ""
                    print "Forwarding..."
                    decision_bool = True
                    print ""
                    rand_word() #Call the function, rand_word()
                elif decision =="I": #If decision equals "I", do below.
                    print "You chose to input your own word."
                    print ""
                    print "Forwarding..."
                    decision_bool = True
                    print ""
                    user_word() #Call the function, user_word()
                else:
                    print "You entered an incorrect value for the question. Try again."
            else:
                print "You entered an incorrect value for the question. Try again."

menu()

下面的代码可能会回答您的问题:
“我所要做的就是确保当有人输入
正确的字母会将其放置在单词的正确位置。“
它不验证输入。
提示:如果您进行验证,我建议您查看
re
模块
由于
print
语句,如果您使用的是python 3+,则此代码将不起作用:

from random import choice

def found(s , v):  
    # returns a list of indexes if v is in s
    # else it returns None
    return [i for i in range(len(s))if s[i] == v]

def guess_word(word, mask, lives):  

    # returns a 2 tuple : lettermask and the lives left
    # just like  'guess_part' but with 2 more para's  
    # to increase flexibility.
    # Beware !!! this function does not check the para's

    lettermask=list(len(word)* mask)
    livesleft ='You have {} lives left .\n'
    guess='Plz type a char a-z.\n>:'
    print word # just for checking
    while mask in lettermask:   
        if lives < 1: break
        print 'lettermask= '+ ''.join(lettermask)
        p = livesleft.format(lives)
        letterguess= raw_input(p + guess)
        print 'letterguess= '+ letterguess
        result = found( word, letterguess)
        if result:  
            print 'Good guess :) '
            for i in result :
                lettermask[i]=word[i]
        else:   
            print 'Wrong guess :( '
            lives-=1
    return lettermask,lives

random_words = ['extraordinary','happy','computer',
'python','screen','cheese','cabaret',
'caravan','bee','wasp','insect','mitosis',
'electronegativity','jumper','trousers']


word=choice (random_words)
# or word= raw_intput('pls type a word')
mask='*'
lives= 6
resultS,lives = guess_word(word, mask, lives)
if mask in resultS:  
   print 'Your result: {}'.format("".join(resultS))
   print 'You have failed,the word was: {}'.format(word)
else:
   print 'Congrats !!! Your score is: {}'.format(lives)
来自随机导入选择
发现def(s、v):
#如果v在s中,则返回索引列表
#否则它将不返回任何值
如果s[i]==v,则返回范围(len(s))中的i的[i]
def guess_单词(单词、面具、生命):
#返回一个2元组:lettermask和剩余生命
#就像“猜”一样,但还有两个段落
#增加灵活性。
#当心!!!此函数不检查段落的
字母掩码=列表(长(字)*掩码)
livesleft='您还有{}条生命。\n'
guess='Plz键入字符a-z.\n>:'
打印word#仅供检查
在lettermask中使用掩码时:
如果生命<1:中断
打印'lettermask='+''。连接(lettermask)
p=livesleft.format(lives)
letterguess=原始输入(p+猜测)
打印“letterguess=”+letterguess
结果=找到(单词、字母猜测)
如果结果为:
打印“猜得好:)”
就我而言,结果是:
字母掩码[i]=单词[i]
其他:
打印“猜错了:(”
寿命-=1
回信面具,生命
random_words=[‘非凡’、‘快乐’、‘电脑’,
‘python’、‘screen’、‘cheese’、‘cabaret’,
“商队”,“蜜蜂”,“黄蜂”,“昆虫”,“有丝分裂”,
“电负性”、“套头衫”、“裤子”]
单词=选择(随机单词)
#或word=原始输入('请键入一个单词')
掩码='*'
生命=6
结果,生命=猜测(单词,面具,生命)
如果蒙版结果为:
打印“您的结果:{}”。格式(“.”连接(结果))
打印“您已失败,单词为:{}”。格式(word)
其他:
打印“恭喜!!!你的分数是:{}”。格式(lives)

对于堆栈溢出问题,代码相当长。您应该尝试找到行为不正常的部分,并关注它。另一个问题是您的注释。我知道这可能是您编写的第一个程序之一,但了解它永远都不为时尚早……您的注释大部分都是琐碎的,从某种意义上说,它们不会给程序添加任何内容代码。将注释“使用参数词调用函数guess\u part”放在guess\u part(word)行上不会帮助任何人阅读您的代码。在编写代码时,您应该假设阅读代码的人会了解语言。嗨,Ashley,欢迎来到StackOverflow。您有什么问题?您能否将代码缩短到重现问题所需的最小行数?请简短地说一句:您应该考虑使用什么以及如何使用注释.
while decision==False:#decision=False时,请执行以下操作。
不是很有用。请说明您为什么要做这些事情,不要完全重复代码本身已经说过的内容。@zmbq唯一重要的部分是
guess\u部分()
func,因为它是“猜测”发生的地方。此外,
如果字母guess不在word中
forwardsashley,请查看代码中迭代单词的部分……您真的找到了被猜测字符在单词中的哪个索引了吗?您可能需要查看
查找
索引x
内置字符串的方法。