随机文字游戏python 3.5

时间:2017-03-01 19:50:50

标签: python-3.x

嗨,我完全是编程的新手,并且一直在尝试自学python,我一直在尝试创建一个程序,选择一个单词,然后随机播放字母并提示用户在3次尝试中输入他们的猜测。我遇到的问题是当输入错误的答案时,它会重新调整所选单词的字母或返回一个完全不同的单词,这是我的代码:

import random
import sys

##Welcome message
print ("""\tWelcome to the scrambler,
  select [E]asy, [M]edium or [H]ard
  and you have to guess the word""")

##Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()

##For counting number of guesses it takes
tries = 0

while tries < 3:
    tries += 1

##Starting the game on easy
if difficulty == 'E':
    words = ['teeth', 'heart', 'police', 'select', 'monkey']
    chosen = random.choice(words)
    letters = list(chosen)
    random.shuffle(letters)
    scrambled = ''.join(letters)
    print (scrambled)

    guess = input("> ")

    if guess == chosen:
        print ("Congratulations!")
        break
    else:
        print ("you suck")

else:
    print("no good")
    sys.exit(0)

正如你所看到的那样,我只是变得容易,我试图一点一点地去做,并设法克服其他问题,但我似乎无法修复我所拥有的那个。如果我遇到问题或者您可能在我的代码中发现任何其他问题,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

为您的游戏做了一些改进和修复。

import random
import sys

# Game configuration
max_tries = 3

# Global vars
tries_left = max_tries

# Welcome message
print("""\tWelcome to the scrambler,
select [E]asy, [M]edium or [H]ard
and you have to guess the word""")


# Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()

if difficulty == 'E':
    words = ['teeth', 'heart', 'police', 'select', 'monkey']
    chosen = random.choice(words)
    letters = list(chosen)
    random.shuffle(letters)
    scrambled = ''.join(letters)
else:
    print("no good")
    sys.exit(0)

# Now the scrambled word fixed until the end of the game

# Game loop
print("Try to guess the word: ", scrambled, " (", tries_left, " tries left)")

while tries_left > 0:
    print(scrambled)
    guess = input("> ")

    if guess == chosen:
        print("Congratulations!")
        break
    else:
        print("You suck, try again?")
        tries_left -= 1

告诉我,如果你不理解某些事情,我很乐意帮助你。