1

I am trying to make it so that when I press escape, it will exit the loop at anytime. I was hoping that it would work with importing keyboard but I think the issue is because it was opening in a command prompt window instead of working in the IDE.

import subprocess
import sys
import time
import random
import msvcrt

def print_with_typing(text):
    for char in text:
        print(char, end='', flush=True)
        time.sleep(0.01)  # Adjust the delay (in seconds) to control the typing speed

def start_new_window():
    subprocess.Popen(['start', 'cmd', '/k', 'python', 'CoffeeShop.py', 'new_window'], shell=True)
    sys.exit()

if len(sys.argv) > 1 and sys.argv[1] == "new_window":
    print("running in new window\n\n")
else:
    print("Opening a new window...")
    start_new_window()

running = True

while running:
    daily_income = 0
    wallet_amount = random.randint(5, 100)
    print_with_typing("Your wallet amount: $" + str(wallet_amount) + "\n")
    print_with_typing("Hello, \nWelcome to That Food Place!\n")
    time.sleep(1)

    name = input("What is your name?\n")

    print_with_typing("Hello, " + name + "! \nThank you so much for coming!")
    time.sleep(1)
    entree = [
        ("Dino Nuggets", "5 minutes", 5),
        ("Veggie Fries", "10 minutes!", 6),
        ("Impossible Steak", "20 minutes!", 25),
        ("Cheese Log", "15 minutes!", 10),
        ("Lobster Wings", "25 minutes!", 50),
    ]

    sides = [
        ("French onion sticks", 2),
        ("Frog legs", 4),
        ("Buttered toast", 1),
        ("Crunch rat", 2),
        ("Apple", 1),
        ("Roasted stank", 10),
    ]

    drinks = [
        ("Water", ""),
        ("Four loko", ""),
        ("Liquid grass", ""),
        ("Dirty water", ""),
        ("Coka", ""),
    ]

    print_with_typing("\nOur menu today consists of the following options:\n")
    for item in entree:
        print_with_typing("- " + item[0] + "\n")

    time.sleep(2)

    order_list = []  # Store the customer's orders

    while running:
        order = input("\nWhat would you like to order? (Enter 'done' to finish ordering)\n")
        if order.lower() == "done":
            break

        found_entree = None
        found_side = None
        found_drink = None

        for item in entree:
            if item[0].lower() in order.lower():
                found_entree = item
                break

        for item in sides:
            if item[0].lower() in order.lower():
                found_side = item
                break

        for item in drinks:
            if item[0].lower() in order.lower():
                found_drink = item
                break

        if found_entree:
            item_price = found_entree[2]
            if item_price <= wallet_amount:
                side_order = input("Would you like a side and drink with that?\n")
                if side_order.lower() == "yes":
                    # Prompt for side selection
                    print_with_typing("Please choose a side from the following options:\n")
                    for side in sides:
                        print_with_typing("- " + side[0] + "\n")
                    selected_side = input()
                    found_side = None
                    for side in sides:
                        if side[0].lower() == selected_side.lower():
                            found_side = side
                            break
                    if found_side:
                        order_list.append(found_side[0])
                        print_with_typing("Great! One " + found_side[0] + " side added to your order.\n")
                    else:
                        print_with_typing("I'm sorry, we don't carry that side. Please choose from the listed options.\n")

                    drink_order = input("Would you like a drink as well?\n")
                    if drink_order.lower() == "yes":
                        # Prompt for drink selection
                        print_with_typing("Please choose a drink from the following options:")
                        for drink in drinks:
                            print_with_typing("- " + drink[0] +"\n")
                        selected_drink = input()
                        found_drink = None
                        for drink in drinks:
                            if drink[0].lower() == selected_drink.lower():
                                found_drink = drink
                                break
                        if found_drink:
                            order_list.append(found_drink[0])
                            print_with_typing("Great! One " + found_drink[0] + " drink added to your order.\n")
                        else:
                            print_with_typing("I'm sorry, we don't carry that drink. Please choose from the listed options.\n")
                    else:
                        print_with_typing("Alrighty then!\n")

                print_with_typing("That will be $" + str(found_entree[2]) + ".\n")
                wallet_amount -= item_price
                daily_income += item_price
                order_list.append(found_entree[0])  # Add the ordered item to the order list
                time.sleep(1)
                print_with_typing("Thank you, " + name + ". Your " + found_entree[0] + " will be out in " + found_entree[1] + "\n")
                time.sleep(1)
                print_with_typing("$" + str(wallet_amount) + " remaining\n")
            else:
                time.sleep(1)
                print_with_typing("I'm sorry, you don't have enough for this item. Please choose another item!\n")
        else:
            time.sleep(1)
            print_with_typing("I'm sorry, we are not serving " + order + " today. Please choose from an item listed!\n")
            continue

        order_more = input("Would you like to order something else?\n")
        if order_more.lower() == "no":
            break

    time.sleep(3)
    print_with_typing("\nHere are your orders. Enjoy!\n")

    for item in order_list:
        print_with_typing("- " + item + "\n")

    time.sleep(1)
    opinion = input("Did you enjoy your meal, " + name + "?\n")

    if "no" in opinion.lower():
        print_with_typing("I am sorry to hear that. Please enjoy a refund on your order!\n")
        wallet_amount += item_price
        print("Refunded " + str(item_price))
        print("Current wallet amount = $" + str(wallet_amount))
    elif "yes" in opinion.lower():
        print_with_typing("I am happy to hear that! Enjoy the rest of your day!\n")

    time.sleep(2)
    print_with_typing("Next customer, please!\n\n\n")

    if msvcrt.kbhit() and msvcrt.getch() == b'\x1b':  # Check if Escape key is pressed
        running = False

print_with_typing("Thank you for visiting That Food Place. Have a great day!\n")
print_with_typing("Daily income = $" + str(daily_income))
time.sleep(5)
sys.exit()

I tried importing msvcrt after some research and I was able to get it to work once while mashing the escape key the entire time it was running but I haven't been able to exit consistently.

This is my first pet project so any help. I'm adding more from time to time to get more familiar with different concepts in python so all tips and tricks are appreciated!

  • Check out the answers here and see if that helps: [Key Listeners in python?](https://stackoverflow.com/questions/11918999/key-listeners-in-python) – JonSG Jun 29 '23 at 14:54

2 Answers2

1

The way you wrote this program does not let you interrupt with escape because it does not have an event loop.

The execution is line by line in the order of the file, so it will only be able to check for escape keypress at the very end of the loop. If you just want to stop the program without going through the entire process, press CTRL+C. This is a special key that send a signal to your program that will raise an exception in response. Signals are a special kind of interaction that is handled by the OS.

If you really want to use escape to quit, you need to change the structure of your program. In windows, the best solution is to use a GUI framework (terminal UI are not very developed in windows). For a beginner in Python tkinter is a good first choice.

WIP
  • 348
  • 2
  • 11
  • 1
    Awesome! I'll look into tkinter. Are there any others you would suggest for when I get more experienced? – FalafelWaffle Jun 29 '23 at 16:27
  • 1
    I don't know many of the new ones, and I don't often use any of them, so not the best person to ask. PySide is ok and based on Qt. Kivy is very popular nowadays, but I have never tried it. – WIP Jun 29 '23 at 16:34
0

I suggest you use the signal library and just listen for a Ctrl and X key press

# Base imports
import subprocess
import sys
import time
import random
import msvcrt

import signal # Import signal handler llibrary


running = True # define at top level

# define what to do when ctrl and x are pressed
def signal_handler(signal, frame):
    print("Ctrl + X detected. Exiting...")
    #put your closing code here.
    running = False # change to false
    exit(0)

# Register your handler here
signal.signal(signal.SIGINT, signal_handler)

# Main code logic here
def print_with_typing(text):
    for char in text:
        print(char, end='', flush=True)
        time.sleep(0.01)  # Adjust the delay (in seconds) to control the typing speed

def start_new_window():
    subprocess.Popen(['start', 'cmd', '/k', 'python', 'CoffeeShop.py', 'new_window'], shell=True)
    sys.exit()

if len(sys.argv) > 1 and sys.argv[1] == "new_window":
    print("running in new window\n\n")
else:
    print("Opening a new window...")
    start_new_window()


while running:
    daily_income = 0
    wallet_amount = random.randint(5, 100)
    print_with_typing("Your wallet amount: $" + str(wallet_amount) + "\n")
    print_with_typing("Hello, \nWelcome to That Food Place!\n")
    time.sleep(1)

    name = input("What is your name?\n")

    print_with_typing("Hello, " + name + "! \nThank you so much for coming!")
    time.sleep(1)
    entree = [
        ("Dino Nuggets", "5 minutes", 5),
        ("Veggie Fries", "10 minutes!", 6),
        ("Impossible Steak", "20 minutes!", 25),
        ("Cheese Log", "15 minutes!", 10),
        ("Lobster Wings", "25 minutes!", 50),
    ]

    sides = [
        ("French onion sticks", 2),
        ("Frog legs", 4),
        ("Buttered toast", 1),
        ("Crunch rat", 2),
        ("Apple", 1),
        ("Roasted stank", 10),
    ]

    drinks = [
        ("Water", ""),
        ("Four loko", ""),
        ("Liquid grass", ""),
        ("Dirty water", ""),
        ("Coka", ""),
    ]

    print_with_typing("\nOur menu today consists of the following options:\n")
    for item in entree:
        print_with_typing("- " + item[0] + "\n")

    time.sleep(2)

    order_list = []  # Store the customer's orders

    while running:
        order = input("\nWhat would you like to order? (Enter 'done' to finish ordering)\n")
        if order.lower() == "done":
            break

        found_entree = None
        found_side = None
        found_drink = None

        for item in entree:
            if item[0].lower() in order.lower():
                found_entree = item
                break

        for item in sides:
            if item[0].lower() in order.lower():
                found_side = item
                break

        for item in drinks:
            if item[0].lower() in order.lower():
                found_drink = item
                break

        if found_entree:
            item_price = found_entree[2]
            if item_price <= wallet_amount:
                side_order = input("Would you like a side and drink with that?\n")
                if side_order.lower() == "yes":
                    # Prompt for side selection
                    print_with_typing("Please choose a side from the following options:\n")
                    for side in sides:
                        print_with_typing("- " + side[0] + "\n")
                    selected_side = input()
                    found_side = None
                    for side in sides:
                        if side[0].lower() == selected_side.lower():
                            found_side = side
                            break
                    if found_side:
                        order_list.append(found_side[0])
                        print_with_typing("Great! One " + found_side[0] + " side added to your order.\n")
                    else:
                        print_with_typing("I'm sorry, we don't carry that side. Please choose from the listed options.\n")

                    drink_order = input("Would you like a drink as well?\n")
                    if drink_order.lower() == "yes":
                        # Prompt for drink selection
                        print_with_typing("Please choose a drink from the following options:")
                        for drink in drinks:
                            print_with_typing("- " + drink[0] +"\n")
                        selected_drink = input()
                        found_drink = None
                        for drink in drinks:
                            if drink[0].lower() == selected_drink.lower():
                                found_drink = drink
                                break
                        if found_drink:
                            order_list.append(found_drink[0])
                            print_with_typing("Great! One " + found_drink[0] + " drink added to your order.\n")
                        else:
                            print_with_typing("I'm sorry, we don't carry that drink. Please choose from the listed options.\n")
                    else:
                        print_with_typing("Alrighty then!\n")

                print_with_typing("That will be $" + str(found_entree[2]) + ".\n")
                wallet_amount -= item_price
                daily_income += item_price
                order_list.append(found_entree[0])  # Add the ordered item to the order list
                time.sleep(1)
                print_with_typing("Thank you, " + name + ". Your " + found_entree[0] + " will be out in " + found_entree[1] + "\n")
                time.sleep(1)
                print_with_typing("$" + str(wallet_amount) + " remaining\n")
            else:
                time.sleep(1)
                print_with_typing("I'm sorry, you don't have enough for this item. Please choose another item!\n")
        else:
            time.sleep(1)
            print_with_typing("I'm sorry, we are not serving " + order + " today. Please choose from an item listed!\n")
            continue

        order_more = input("Would you like to order something else?\n")
        if order_more.lower() == "no":
            break

    time.sleep(3)
    print_with_typing("\nHere are your orders. Enjoy!\n")

    for item in order_list:
        print_with_typing("- " + item + "\n")

    time.sleep(1)
    opinion = input("Did you enjoy your meal, " + name + "?\n")

    if "no" in opinion.lower():
        print_with_typing("I am sorry to hear that. Please enjoy a refund on your order!\n")
        wallet_amount += item_price
        print("Refunded " + str(item_price))
        print("Current wallet amount = $" + str(wallet_amount))
    elif "yes" in opinion.lower():
        print_with_typing("I am happy to hear that! Enjoy the rest of your day!\n")

    time.sleep(2)
    print_with_typing("Next customer, please!\n\n\n")

print_with_typing("Thank you for visiting That Food Place. Have a great day!\n")
print_with_typing("Daily income = $" + str(daily_income))
time.sleep(5)
sys.exit()

The script will keep running until the user presses "Ctrl + X" or "Ctrl + C", at which point the signal_handler function will be executed, allowing you to handle the interruption gracefully.

Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28