Спросите пользователя, хочет ли он перезапустить игру? - PullRequest
0 голосов
/ 24 мая 2019

Я создаю игру на Python3 в виде палача, и когда игра закончится, я хотел бы попросить пользователя ввести данные, которые имеют два результата: либо он захочет снова играть, либо закончить. Как я могу реализовать эту функцию в коде, чтобы он снова начал цикл? Лучше ли создать цикл по всей игре, или я должен создать оператор if?

Это мой текущий код (не завершен и не завершен):

import random
# from collections import Counter

unknown_words_list = [" "]
known_words_list = [" "]
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z"]
name = input("What is your name? ")
print("Hello, " + name, "lets play hangman. I'll be guessing your word. Don't cheat ;)")

time.sleep(0.5)
print("Think about a word with at least 2 Characters.")
"""
time.sleep(0.5)
user_word = input("Type your word here: ")
x = len(user_word)
"""
user_word = input("Type your word here: ")
x = len(user_word)
turns = x * 2 # amount of guesses for the bot multiply the letters of the users word
guesses = ""
time.sleep(0.5)
bot_guess = "" # letters the bot has guessed correctly
failed = 0 # fail counter

# while loop to avoid a one character game.
while x < 2:
    print("Haven't we agreed on a word that has at least 2 characters?"
          "Please try again: ")
    user_word = input()
    x = len(user_word)
    if x > 2:
        print("Great, managed to find a word with at least 2 characters.")
        break


print("No worries, I won't know your word by the way, but at the end of our game I will add it to my Library, "
      "if it isn't there yet.")
time.sleep(0.5)
print("Has your word " + str(x), "characters?")
print("For your word I will have " + str(turns), "turns to guess"
                                                 "and can fail maximum 10 times.")

while turns > 0 and failed < 10:
    random_guess = random.choice(alphabet)
    print("My guess is the letter " + random_guess, ".")
    alphabet.remove(random_guess)
    turns -= 1
    time.sleep(0.5)
    if random_guess in user_word:
        bot_guess += random_guess
        print(bot_guess)
    else:
        failed += 1
    if failed == 9:
        print("I guessed to often wrong, you win.")
    elif turns <= 0:
        print("I reached the maximum amount of turns and could not figure out the word, you win.")


# adding not guessed words to unknown list
def unidentified_word():
    time.sleep(0.5)
    print("Hmm, I was not able to guess your word in time, this should teach me a lesson!")
    if user_word not in unknown_words_list:
        print("I'll add this word to my collection of unknown words which I also did not guess.")
        unknown_words_list.append(user_word)
    return


# adding not guessed words to known list
def identified_word():
    time.sleep(0.5)
    print("Yeey, I was able to guess your word after " + str(guesses), " guesses. ")
    if user_word not in known_words_list:
        time.sleep(0.5)
        print("I'll add this word to my collection of correctly guessed words.")
        known_words_list.append(user_word)
    return

1 Ответ

0 голосов
/ 24 мая 2019

Поместите код, соответствующий одной игре, в функцию, например, с названием start (), и вызовите ее внутри цикла while.После вызова вашей функции просто запросите ввод, и если ответ «нет», прервите цикл.

while True:
  start()  # Call one game
  again = input("Do you want to play again? ").lower()
  if again.startswith("n"):
    break
  print("Yaay again!")
print("Thanks for playing!")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...