我正在创建一个Python3 hangman游戏,当游戏结束时,我想提示用户输入两个结果,要么是他想再次玩,要么是完成。 如何在代码中实现该功能,以便再次启动循环?在整个游戏中创建循环会更好还是还是应该创建一个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
答案 0 :(得分:0)
将与一个游戏对应的代码放入一个函数中,例如称为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!")