导入'游戏'和窗口关闭

时间:2016-05-27 12:34:33

标签: python import

我正在尝试制作一个程序,打开其他程序(我之前制作的游戏),窗口立即关闭。

#Program that runs game i have made
import subprocess

choice = input("What would you like to do? \nGuess my number game (1) \nCalorie counter (2) \nWord jumble game (3) \nInsert your decision here - ")

while choice == "1":
    print("Let us begin")
    def start_guess_my_number():   
        subprocess.call(['python', 'Guess my number game2.py'])
    start_guess_my_number() 
    choice = input("What would you like to do now? 1 2 or 3 ? - ")
while choice == "2":
    print("Let us begin")
    def start_calorie_counter():
        subprocess.call(['python', 'Calorie counter.py'])
    start_calorie_counter()
    choice = input("What would you like to do now? 1 2 or 3 ? - ")
while choice == "3":
    print("Let us begin")
    def start_guess_my_number():
        subprocess.call(['python', 'Word jumble game.py'])
    start_guess_my_number()
    choice = input("What would you like to do now? 1 2 or 3 ? - ")
input("Press enter to exit")

注意:我确保我正在调用的程序正在运行,并且在黑色命令窗口中打开时,它们保持打开状态,这与我通过此程序打开它们不同。

1 个答案:

答案 0 :(得分:4)

您遇到以下问题:

  • 您需要将输入与int进行比较,而不是字符串
  • 您需要在正确的文件夹中打开游戏,默认情况下,新进程在包含python可执行文件的文件夹中运行。
  • 您使用的是while循环而不是if语句,您的代码将被无限循环捕获。
  • 没有办法退出主循环,你需要一个break语句来实现它。

我还将代码分成了函数。

#Program that runs a game I have made
import os
import subprocess


def play_game(name):
    print("Let us begin")
    subprocess.call(['python', os.path.dirname(os.path.realpath(__file__))+os.path.sep+name])


choice = input("What would you like to do? \nGuess my number game (1) \nCalorie counter (2) \nWord jumble game (3) \nInsert your decision here - ")

while True:
    if choice == 1:
        play_game('Guess my number game2.py')
    elif choice == 2:
        play_game('Calorie counter.py')
    elif choice == 3:
        play_game('Word jumble game.py')
    else:
        break
    choice = input("What would you like to do now? 1 2 or 3 ? - ")
print("Goodbye")