Я создал игру в угадайку, и я не могу понять, почему не работает моя команда - = - PullRequest
0 голосов
/ 29 октября 2019

Я очень новый программист (начал меньше месяца назад). Мне действительно нужна помощь с этим. Извините, если это немного долго ... Как это работает, мои догадки теряются каждый раз, когда я что-то не так (довольно очевидно). Или все-таки предполагается.

Это программа, которую я создал в качестве прототипа для проекта Hangman. Как только я пойму это правильно, я смогу попробовать более крупный проект. Скажите мне, если приведенная выше полная команда работает по-другому для вас, или если у вас есть какие-либо предложения относительно того, как сделать ее короче или лучше, или мне пока слишком рано пытаться выполнить такой большой проект. Спасибо!

import random

player_name = input("What is your name? ")
print("Good luck, " + player_name + "!")

words = ["program", "giraffe", "python", "lesson", "rainbows", "unicorns", "keys", "exercise"]
guess = " "
repeat = True

word = random.choice(words)
guesses = int(len(word))

while repeat is True:
    print("The word is " + str(len(word)) + " characters long.")
    guess = input("Enter your guess: ")
    if guess != word:
        guesses -= 1
        print("Incorrect")
        print("Try again")
    elif guess == word:
        print("Good job!")
        print(str.capitalize(word) + " is the right answer!")
        repeat = input("Do you want to play again? (input Yes/No)")
        if repeat == "Yes" or "yes":
            word = random.choice(words)
            repeat = True
        elif repeat == "No" or "no":
            print("Better luck next time!")
            repeat = False
        if guesses == 1:
            print("You only have one chance left.")
        if guesses <= 0:
            print("You lose...")
            repeat = input("Do you want to play again? (input Yes/No)")
            if repeat == "Yes" or "yes":
                repeat = True
            elif repeat == "No" or "no":
                print("Better luck next time!")
                repeat = False

1 Ответ

0 голосов
/ 29 октября 2019

проблема связана с областью действия ваших условий

while repeat is True:
    print("The word is " + str(len(word)) + " characters long.")
    guess = input("Enter your guess: ")
    if guess != word:
        guesses -= 1
        print("Incorrect")
        print("Try again")
    elif guess == word:
        print("Good job!")
        print(str.capitalize(word) + " is the right answer!")
        repeat = input("Do you want to play again? (input Yes/No)")
        if repeat == "Yes" or "yes":
            word = random.choice(words)
            repeat = True
        elif repeat == "No" or "no":
            print("Better luck next time!")
            repeat = False
    if guesses == 1:
        print("You only have one chance left.")
    if guesses <= 0:
        print("You lose...")
        repeat = input("Do you want to play again? (input Yes/No)")
        if repeat == "Yes" or "yes":
            repeat = True
        elif repeat == "No" or "no":
            print("Better luck next time!")
            repeat = False

, это решит проблему с угадыванием, но вам нужно будет реорганизовать логику повторного воспроизведения. Как то так

repeat = True
gameOver = False

while repeat is True:
    print("The word is " + str(len(word)) + " characters long.")
    guess = input("Enter your guess: ")
    if guess != word:
        guesses -= 1
        print("Incorrect")
        print("Try again")
    elif guess == word:
        print("Good job!")
        print(str.capitalize(word) + " is the right answer!")
        gameOver = True
    if guesses == 1:
        print("You only have one chance left.")
    if guesses <= 0:
        print("You lose...")
        gameOver = True

    if gameOver:
        playAgain = input("Do you want to play again? (input Yes/No)")
        if playAgain == "Yes" or "yes":
            word = random.choice(words)
            repeat = True
            gameOver = False
        elif repeat == "No" or "no":
            print("Better luck next time!")
            repeat = False
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...