Python - 猜一个文字游戏

时间:2017-06-28 23:23:47

标签: python

这是我的代码:

import random

guesses = 0    #Number of tries to guess.
print ("Welcome to Guess Me!")
print ("\nYou have five guesses, choose letter and guess a word.")
print("\nAll of luck!")

def rand_word():
    f = open('sowpods.txt', 'r').readlines()  #Sowpods is library with some random words 
    return random.choice(f).strip()                                    

word = rand_word()
print word                 #I printed a word just so i can test if is working.

correct = word
lenght = len(word)       #I want to tell them how many letters a word contain
new_length = str(lenght) 

guess = raw_input("The word is " + new_length + " letters long. Guess a letter: ")

while guesses < 5:
    if guess not in word:
        print("Sorry, this letter is not in word.")
    else:
        print("Correct, word contain this letter!")

guesses =+ 1

if guesses > 5:
    final_answer = raw_input("You ran out of guesses, what is your answer?")
    if final_answer == correct:
        print("That's correct, congratulations you won!")
    else:
        print("Sorry, correct word is" + " " + word + " ,you can try again!")

问题是当我运行我的代码时,让我说我输入字母“s”,我的崇高冻结并且我收到消息“Sublime 3没有响应......”我必须将其关闭。也许这是循环?无限?

2 个答案:

答案 0 :(得分:0)

你有一个无限循环,因为你的猜测&#39;变量没有在while循环中被复制;移动猜测+ = 1&#39;进入循环本身,例如

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type='text' id='myinput'/>

答案 1 :(得分:0)

有一些事情。

guesses = + 1应该是猜测+ = 1并且在任何if语句之前的while循环的顶部 我认为你的guess = raw_input应该在任何if语句之前的while循环中。所以它将继续询问和计算每个猜测,直到它达到5.循环中的最后一个if语句应该是如果猜测== 5或猜测&gt; = 5而不是猜测&gt; 5。

主要只是在while循环中重新排序所有内容。每个猜测都会运行while循环中代码下的所有内容。

我按照上面的说法进行了改动,对我来说很有用:

while guesses < 5:
    guesses += 1
    guess = raw_input("The word is " + new_length + " letters long. Guess a letter: ")
    if guess not in word:
        print("Sorry, this letter is not in word.")
    else:
        print("Correct, word contain this letter!")
    if guesses == 5:
        final_answer = raw_input("You ran out of guesses, what is your answer?")
        if final_answer == correct:
            print("That's correct, congratulations you won!")
        else:
            print("Sorry, correct word is" + " " + word + " ,you can try again!")

    Welcome to Guess Me!

You have five guesses, choose letter and guess a word.

All of luck!
word
The word is 4 letters long. Guess a letter: 1
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 2
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 3
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 4
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 5
Sorry, this letter is not in word.
You ran out of guesses, what is your answer?numbers
Sorry, correct word is word ,you can try again!