这是我的代码(适用于hang子手游戏):
import random, os
def main():
print("******THIS IS HANGMAN******")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["school", "holiday", "computer", "books"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, x in enumerate(word):
if x == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print('You won')
elif choice == "2":
os.system("cls")
main()
else:
print("that is not a valid option")
main()
我尝试过os.system("clear")
,但是它不能清除屏幕,我希望它清除整个屏幕,但是(cls)使它再次打印菜单,而(clear)除了清除2以外什么也没做。如果我缺少明显的东西,可能是因为我是python新手。
答案 0 :(得分:0)
它再次打印菜单,因为您再次调用main()
而不是仅在此停靠。 :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
现在可以进行清理了,os.system("clear")
在Windows上运行,os.system("cls")
在Linux / OS X上运行here。
此外,您的程序当前还会告诉用户是否不支持他们的选择,但不会提供第二次机会。您可能会遇到这样的事情:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()