Skip to content

Instantly share code, notes, and snippets.

@hirozhu
Created March 15, 2019 08:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hirozhu/f0f09e32635e90d95dd8b2e88b987485 to your computer and use it in GitHub Desktop.
Save hirozhu/f0f09e32635e90d95dd8b2e88b987485 to your computer and use it in GitHub Desktop.
Python Restaurant Simulator Project
from MenuItem import MenuItem
class Diner(object):
STATUSES = ["seated", "ordering", "eating", "paying", "leaving"]
# Set the diner’s name attribute to the input value.
# Set the diner’s order attribute to an empty list.
# Set the status attribute to 0.
def __init__(self, name):
self.__name = name
self.__order = []
self.__status = 0
# Define getters and setters for all the instance attributes.
def getName(self):
return self.__name
def setName(self, n):
self.__name = n
def getOrder(self):
return self.__order
def setOrder(self, n):
self.__order = n
def getStatus(self):
return self.__status
def setStatus(self, n):
self.__status = n
# Add the new MenuItem object to the diner’s order list.
def addToOrder(self, n):
self.__order.append(n)
# Increase the diner’s status by 1.
def updateStatus(self):
self.__status += 1
# Print a message containing all the menu items the diner ordered.
def printOrder(self):
print(self.__name, "ordered: ")
for i in self.__order:
print("-", i)
# Total up the cost of each of the menu items the diner ordered.
def calculateMealCost(self):
cost = 0
for i in self.__order:
cost += i.getPrice()
cost = float(cost)
return cost
# Construct a message containing the diner’s name and status.
def __str__(self):
msg = "Diner " + self.__name + " is currently " + Diner.STATUSES[self.__status]
return msg
Ice Cream Dessert 3.50 3 scoops of chocolate or vanilla or strawberry
Soda Drink 1.50 Choose from sprite coke or pepsi
Shrimp Lo Mein Entree 8.50 Noodles with shrimp and veggies
Chocolate cake Dessert 4.50 Slice of dark chocolate cake
Fresh Spring Rolls Appetizer 3.99 4 vegetarian rolls wrapped in rice paper either fresh or fried
Cream Cheese Wantons Appetizer 5.99 Vegetarian friendly fried wantons stuffed with creamcheese
Tofu Vegetable Soup Entree 5.99 Bowl of vegetarian soup with tofu in chicken broth
Thai Iced Tea Drink 3.00 Glass of thai iced tea
Beef fried rice Entree 7.50 Rice fried with egg vegetables and beef
Vegetable Lo Mein Entree 8.50 Vegetarian friendly noodles
Apple Pie Dessert 4.50 American classic served with vanilla ice cream
Coffee Drink 1.50 Black coffee either hot or cold
Dumplings Appetizer 5.99 8 pieces of meat dumplings either fried or steamed
Chicken Mushroom Soup Entree 5.99 Bowl of soup with chicken and mushrooms in chicken broth
from MenuItem import MenuItem
class Menu(object):
MENU_ITEM_TYPES = ["Drink", "Appetizer", "Entree", "Dessert"]
def __init__(self, dict):
self.__dict = dict
self.__menuItemDictionary = {}
self.__menuItemDictionary["Drink"] = []
self.__menuItemDictionary["Appetizer"] = []
self.__menuItemDictionary["Entree"] = []
self.__menuItemDictionary["Dessert"] = []
# Open and read the csv file and create a MenuItem object from each line in the file.
fin = open(dict, "r")
for line in fin:
line = line.strip()
dataList = line.split(",")
name = dataList[0]
t = dataList[1]
price = dataList[2]
description = dataList[3]
item = MenuItem(name, t, price, description)
# Add the new object to the dictionary by using its type as the key.
if t == "Drink":
self.__menuItemDictionary["Drink"].append(item)
elif t == "Appetizer":
self.__menuItemDictionary["Appetizer"].append(item)
elif t =="Entree":
self.__menuItemDictionary["Entree"].append(item)
elif t == "Dessert":
self.__menuItemDictionary["Dessert"].append(item)
fin.close()
# Get the MenuItem object from the dictionary using its type and index position in the list of items.
def getMenuItem(self, types, index):
item = self.__menuItemDictionary[types][index]
return item
# Print a header with the type of menu items, followed by a numbered list of all the menu items of that type
def printMenuItemsByType(self, types):
counter = 0
print("--------", types, "----------")
for menuItem in self.__menuItemDictionary[types]:
print(counter, ")",
"\n", menuItem)
counter += 1
# get the number of MenuItems of the input type of the food.
def getNumMenuItemsByType(self, types):
x = 0
for i in self.__menuItemDictionary[types]:
x += 1
return x
class MenuItem(object):
def __init__(self, name, t, price, description):
self.__name = name
self.__type = t
self.__price = float(price)
self.__description = description
# Define getters and setters for each of the 4 attributes
def getName(self):
return self.__name
def setName(self, n):
self.__name = n
def getType(self):
return self.__type
def setType(self, n):
self.__type = n
def getPrice(self):
return self.__price
def setPrice(self, n):
self.__price = n
def getDescription(self):
return self.__description
def setDescription(self, n):
self.__description = n
# Construct a message to describe the food using all four attributes.
def __str__(self):
msg = self.__name + "(" + self.__type + "): " + str(self.__price) + "\n" + self.__description
return msg
"""
This helper class is intended to be used to randomly generate new diners for a restaurant Simulation
- randomDinerGenerator() will randomly generate either a diner or return None
- generateRandomName() will randomly generate a name (str) that is used for the random diner
* Note: if you have not installed the BeautifulSoup4 module in Pycharm, these methods cannot be used
To install beautifulsoup4: go to Preferences (Mac) or Settings (PC), and under Project Interpreter,
add and install beautifulsoup4
"""
import random
from Diner import Diner
from bs4 import BeautifulSoup
import urllib.request
class RestaurantHelper(object):
URL = "http://random-name-generator.info/"
# Input: -
# Return value: a new Diner object with a random name
# OR
# None (aka no new diner has arrived)
@staticmethod
def randomDinerGenerator():
if random.randint(1, 10) % 3 == 0:
return Diner(RestaurantHelper.generateRandName())
else:
return None
# UNCOMMENT THIS IF DOING EC OPTION 2
# also comment out the above definition of the method
# @staticmethod
# def randomDinerGenerator():
# if random.randint(1, 10) % 3 == 0:
# return Diner(RestaurantHelper.generateRandName(), random.randrange(3))
# else:
# return None
# Input: -
# Return: random name
# DO NOT make any method calls to generateRandName
@staticmethod
def generateRandName():
page = urllib.request.urlopen(RestaurantHelper.URL)
soup = BeautifulSoup(page.read(), "html.parser")
orderedListName = soup.find(class_="nameList")
return orderedListName.find("li").text.split()[0]
"""
Xubo Zhu
ITP 115
Final Project
5/9/2017
"""
"""
ITP 115, SP17 Final project
Run this file in order to start the restaurant simulation program
"""
import datetime
import time
# TODO 0: uncomment the following 3 import statements when you create these files
from Menu import Menu
from Waiter import Waiter
from RestaurantHelper import RestaurantHelper
def main():
RESTAURANT_NAME = "TODO's" # TODO 1: add your own restaurant name in the quotes
restaurantTime = datetime.datetime(2017, 5, 1, 5, 0)
# Create the menu object
menu = Menu("menu.csv") # TODO 2: uncomment this once the Menu class is implemented
# create the waiter object using the created Menu we just created
waiter = Waiter(menu) # TODO 4: uncomment this one the Waiter class is implemented
print("Welcome to " + RESTAURANT_NAME + "!")
print(RESTAURANT_NAME + " is now open for dinner.\n")
#
for i in range(21):
print("\n~~~ It is currently", restaurantTime.strftime("%H:%M PM"), "~~~")
restaurantTime += datetime.timedelta(minutes=15)
# TODO 3: uncomment the following 3 lines once the Diner class is implemented
potentialDiner = RestaurantHelper.randomDinerGenerator()
if potentialDiner is not None:
print("\n" + potentialDiner.getName() + " welcome, please be seated!") # we have a diner to add to the waiter's list of diners
# TODO 4: uncomment the following 2 lines once the Waiter class is implemented
waiter.addDiner(potentialDiner)
waiter.advanceDiners()
time.sleep(2)
print("\n~~~ ", RESTAURANT_NAME, "is now closed. ~~~")
# After the restaurant is closed, progress any diners until everyone has left
# TODO 5: uncomment the following 5 lines once the Waiter class is implemented
while waiter.getNumDiners():
print("\n~~~ It is currently", restaurantTime.strftime("%H:%M PM"), "~~~")
restaurantTime += datetime.timedelta(minutes=15)
waiter.advanceDiners()
time.sleep(2)
print("Goodbye!")
main()
from Menu import Menu
from Diner import Diner
class Waiter(object):
# Input: a Menu object.
def __init__(self, menu):
self.__menu = menu
self.__diners = []
# Input: a Diner object
# Add the new Diner object to the waiter’s list of diners.
def addDiner(self, diner):
self.__diners.append(diner)
# get the number of diners the waiter is currently keeping track of
def getNumDiners(self):
x = 0
for i in self.__diners:
x += 1
return x
# Print all the diners the waiter is keeping track of, grouped by their statuses.
def printDinerStatuses(self):
for i in Diner.STATUSES:
print("Diners who are", i, end=": ")
for k in self.__diners:
if k.getStatus() > 4:
pass
elif Diner.STATUSES[k.getStatus()] == i:
print(k, end=",")
print()
def takeOrders(self):
for i in self.__diners:
if i.getStatus() == 2:
for types in Menu.MENU_ITEM_TYPES:
self.__menu.printMenuItemsByType(types)
print(i.getName(), ", please select a ", types,"menu item number.")
choice = int(input(">"))
n = self.__menu.getNumMenuItemsByType(types) # This is Error Checking.
while choice < 0 or choice >= n:
choice = int(input(">"))
i.addToOrder(self.__menu.getMenuItem(types, choice)) # This is adding the item to the diner.
i.printOrder() # This is printing the diner’s order.
# For each diner that is paying, calculate the diner’s meal cost and print it out in a message to the diner.
def ringUpDiners(self):
for i in self.__diners:
if i.getStatus() == 4:
mealCost = i.calculateMealCost()
print("\n", i.getName(), ", your meal cost", mealCost)
# For each diner that is leaving, print a message thanking the diner.
# And then remove the “leaving” diners from the list of diners.
def removeDoneDiners(self):
for i in self.__diners:
if i.getStatus() == 5:
print("\n", i.getName(), ", thank you for dining with us! Come again soon!")
self.__diners.remove(i)
# To move each diner on to the next stage.
def advanceDiners(self):
self.printDinerStatuses()
for diner in self.__diners:
diner.updateStatus()
self.takeOrders()
self.ringUpDiners()
self.removeDoneDiners()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment