예제 #1
0
class PizzaSlicer:
    def __init__(self, dataset):
        input_file = InputFile(DATASETS_PATH + dataset + INPUT_FORMAT)
        output_file = OutputFile(DATASETS_PATH + dataset + OUTPUT_FORMAT)
        self.pizza = Pizza(input_file, output_file)

    def get_valid_slices(self):
        log(f"Finding all valid slices...")

        p = Problem()
        p.addVariable("r1", range(0, self.pizza.num_rows))
        p.addVariable("c1", range(0, self.pizza.num_cols))
        p.addVariable("r2", range(0, self.pizza.num_rows))
        p.addVariable("c2", range(0, self.pizza.num_cols))

        p.addConstraint(self.pizza.is_valid_slice, ["r1", "c1", "r2", "c2"])
        valid_slices = p.getSolutions()
        log(f"Found {len(valid_slices)} total valid slices")

        return [Slice(self.pizza, s['r1'], s['c1'], s['r2'], s['c2']) for s in valid_slices]

    def get_valid_cuts(self, valid_slices, num_slices):
        log(f"Finding valid cuts with {num_slices} slices...")

        p = Problem()
        slice_vars = [f"slice_{i}" for i in range(num_slices)]

        for var in slice_vars:
            p.addVariable(var, valid_slices)

        for i in range(num_slices):
            for j in range(num_slices):
                if i != j:
                    p.addConstraint(FunctionConstraint(self.pizza.is_valid_cut), [slice_vars[i], slice_vars[j]])

        valid_cuts_iter = p.getSolutionIter()
        valid_cuts = list(next(valid_cuts_iter) for _ in range(N))
        valid_cuts = [tuple(c.values()) for c in valid_cuts]

        log(f"Took first {N} valid cuts with {num_slices} slices")
        # log(f"Found {len(valid_cuts)} valid cuts with {num_slices} slices")

        return {cut: self.pizza.cut(cut) for cut in valid_cuts}

    def slice_pizza(self):
        valid_slices = self.get_valid_slices()

        num_slices_min = self.pizza.num_slices_min
        num_slices_max = 10  # self.pizza.num_slices_max

        valid_cuts_all = {}
        for i in range(num_slices_min, num_slices_max + 1):
            valid_cuts = self.get_valid_cuts(valid_slices, i)
            if len(valid_cuts) == 0:
                break
            valid_cuts_all = {**valid_cuts, **valid_cuts_all}

        best_cut = max(valid_cuts_all.items(), key=operator.itemgetter(1))[0]
        log("Best cut with total number of cells: " + str(self.pizza.cut(best_cut)))
        self.pizza.write_output()
예제 #2
0
 def __init__(self, pizza_config):
     self.pizza = Pizza(pizza_config['pizza_lines'])
     self.min_each_ingredient_per_slice = pizza_config['l']
     self.max_ingredients_per_slice = pizza_config['h']
     self.cursor_position = (0, 0)
     self.slice_mode = False
     self.valid_slices = []
     self.score = 0
예제 #3
0
 def setUp(self):
     self.pizza = Pizza()
     self.pizza._grid = [
         ['T', 'T', 'T', 'T', 'T'],
         ['T', 'M', 'M', 'M', 'T'],
         ['T', 'T', 'T', 'T', 'T'],
     ]
     self._min_ingredient = 1
     self._max_part_size = 0
예제 #4
0
def main():
    """ Execute the program """

    args = parse_args()

    size = int(args.length)
    if args.shape == 'round':
        dough = Round(size)

    pizza = Pizza(dough)
    output(args, pizza.get_dough_amount())
예제 #5
0
def rungame():
    pygame.init()
    ai_setting = Settings()
    screen_game = pygame.display.set_mode(
        (ai_setting.game_width, ai_setting.game_height))
    pygame.display.set_caption("Panic at the pizzeria")
    # Создание кнопки Play.
    play_button = Button(ai_setting, screen_game, "Play")

    # Создание сковороды.
    pan = Pan(screen_game, ai_setting)
    # Создание пиццы.
    pizza = Pizza(screen_game, ai_setting)
    # Создание группы спрайтов.
    pizzas = Group()
    pans = Group()
    # Объявление переменной stats.
    stats = GameStats(ai_setting)
    # Вывод очков на экран.
    sb = ScoreBoard(ai_setting, screen_game, stats)
    chef = Chef(screen_game, ai_setting, pizza)
    # Вывод колличества пиццы на экран.
    numberspizza = NumbersPizza(ai_setting, screen_game, stats)
    """Основной цикл игры."""
    while True:
        # Обновление экрана.
        screen_game.blit(ai_setting.bg_fon, ai_setting.bg_rect)
        gf.update_screen(screen_game, ai_setting, pizzas, pan, pans, pizza,
                         stats, sb, chef, numberspizza, play_button)
예제 #6
0
def fileToObject(route):
    try:
        lista = open(route).readlines()
    except UnicodeDecodeError:
        return None
    pedidos = [x.replace('\n', '') for x in lista]
    print(pedidos)
    i = 0
    listaOrdenes = []
    while(i < len(pedidos)):
        if pedidos[i] == 'COMIENZO_PEDIDO':
            
            j = i+2
            # A dos líneas del comienzo se encuentran las pizzas
            listaPizzas = []
            while(pedidos[j] != 'FIN_PEDIDO'):
                orden = pedidos[j].split(";")
                # Separa la pizza y extras en una lista
                pizza = Pizza([10, 15, 20], orden[0])
                orden.remove(orden[0])
                for extra in orden:
                    # Agrega cada ingrediente a la pizza
                    ingrediente = Ingredient([1.5, 1.75, 2], extra)
                    pizza = Decorator(pizza, ingrediente)
                listaPizzas.append(pizza)
                j = j+1
            order = Order(pedidos[i+1].split(";")[1], listaPizzas)
            listaOrdenes.append(order)
            i = j+1
        else:
            return None
    return listaOrdenes
예제 #7
0
def no_extras_order():
    pizza = Pizza(id=5,
                  name="Cheese & Tomato",
                  price=11.90,
                  ingredients=["tomato", "cheese"],
                  img="cheesetomato.jpg")

    order = Order(pizza=pizza)
    return order
예제 #8
0
def parse(file_name):
    with open(file_name) as f:
        R, C, L, H = map(int, f.readline().strip().split())
        pizza = Pizza(R, C, L, H)

        for line in f:
            row = []
            for char in line.strip():
                row.append(_topping[char])
            pizza.grid.append(row)

    return pizza
예제 #9
0
파일: db.py 프로젝트: RNogales94/usersnack
    def get_pizza(self, id):
        try:
            id = int(id)
        except ValueError:
            return None

        raw = self.db.pizzas.find_one({'id': int(id)}, {'_id': 0})
        if raw is None:
            return None
        pizza = Pizza.load(raw)

        return pizza
예제 #10
0
파일: utils.py 프로젝트: dcurto95/Pizza-CBR
def load_case_base(filename='../data/pizzas.json'):
    # Open the filename in read mode
    with open(filename, 'r', encoding='utf-8') as f:
        # Load the content
        pizzas = json.load(f)

    # Convert the JSON into list of Pizza objects
    case_base = [
        Pizza(pizza['dough'], pizza['sauce'], pizza['toppings'],
              pizza['recipe'], pizza['name']) for pizza in pizzas
    ]
    return case_base
예제 #11
0
def complete_order():
    pizza = Pizza(id=5,
                  name="Cheese & Tomato",
                  price=11.90,
                  ingredients=["tomato", "cheese"],
                  img="cheesetomato.jpg")
    peppers = Extra(name="green peppers", price=1.2)
    mushrooms = Extra(name="mushrooms", price=1.2)
    onion = Extra(name="onion", price=1)

    order = Order(pizza=pizza, extras=[peppers, mushrooms, onion])
    return order
예제 #12
0
def read_data(filename):
    """Read data from the specified file"""
    with open(filename, 'r') as f:
        content = f.read().splitlines()
    n_pizzas, teams_of2, teams_of3, teams_of4 = map(int, content[0].split(' '))

    menu = []

    for i in range(n_pizzas):
        menu.append(Pizza(i, content[i + 1].split(' ')[1:]))

    return menu, teams_of2, teams_of3, teams_of4
예제 #13
0
파일: api.py 프로젝트: RNogales94/usersnack
def order_price():
    raw_pizza = request.json.get('pizza')
    raw_extras = request.json.get('extras')

    pizza = Pizza.load(raw_pizza)
    extras = [Extra.load(e) for e in raw_extras]

    order = Order(pizza=pizza, extras=extras)
    price = order.get_total_price()

    return Response(json.dumps({"price": price}),
                    status=200,
                    mimetype='application/json')
예제 #14
0
파일: api.py 프로젝트: RNogales94/usersnack
def register_order():
    raw_pizza = request.json.get('pizza')
    raw_extras = request.json.get('extras')
    name = request.json.get('name')
    address = request.json.get('address')

    if raw_pizza is None:
        return Response(json.dumps({'error': '"pizza" field missing'}),
                        status=400,
                        mimetype='application/json')
    if raw_extras is None:
        return Response(json.dumps({'error': '"extras" field missing'}),
                        status=400,
                        mimetype='application/json')
    if name is None:
        return Response(json.dumps({'error': '"name" field missing'}),
                        status=400,
                        mimetype='application/json')
    if address is None:
        return Response(json.dumps({'error': '"address" field missing'}),
                        status=400,
                        mimetype='application/json')

    try:
        pizza = Pizza.load(raw_pizza)
    except KeyError:
        return Response(json.dumps(
            {'error': 'Keyerror: Check "pizza" attributes'}),
                        status=400,
                        mimetype='application/json')

    try:
        extras = [Extra.load(e) for e in raw_extras]
    except KeyError:
        return Response(json.dumps(
            {'error': 'Keyerror: Check "extras" attributes'}),
                        status=400,
                        mimetype='application/json')

    order = Order(pizza=pizza, extras=extras, name=name, address=address)

    db.insert_order(order)

    return Response(json.dumps(order.serialize()),
                    status=200,
                    mimetype='application/json')
예제 #15
0
def test_insert_orders():
    pizza = Pizza({
        "id": 5,
        "name": "Cheese & Tomato",
        "price": 11.90,
        "ingredients": ["tomato", "cheese"],
        "images": "cheesetomato.jpg"
    })
    peppers = Extra({"name": "green peppers", "price": 1.2})
    mushrooms = Extra({"name": "mushrooms", "price": 1.2})
    onion = Extra({"name": "onion", "price": 1})

    order = Order(pizza=pizza,
                  extras=[peppers, mushrooms, onion],
                  name="Fake Name",
                  address="Fake Street 123")

    assert DB().insert_order(order)
예제 #16
0
	def agregar_detalle_pedido(self, lista_pizzas=[]):
		"""metodo para agragar una linea del pedido
		1 - crear instancia de Detalle Pedido, preguntando cual es la pizza, que desea(listar las pizas que hay)
		2- llamar al metodo calcular precio de la piza
		2 - agregarlo a self.detalle_pedido
		"""
		print('antes de listadoMenu')
		listadoMenu = VariedadPizza(listadoPizzas)
		print(listadoMenu.imprimirLista())
		variedad = int(input("Elija la variedad según código: "))
		elegida = listadoMenu.getVariedadById(variedad)

		print("Tipo de cocción: [1]piedra->+5% -- [2]molde->+3% -- [3]parrilla->+1%")
		tipo = input("Elija el tipo de cocción: ")
		if(tipo == '1'):
			tipo = 'piedra'
		elif(tipo == '2'):
			tipo = 'molde'
		elif(tipo == '3'):
			tipo = 'parrilla'
		else:
			print('Codigo incorrecto')
		print("Tamaño: [1]8 porciones->+0% -- [2]10 porciones->+10% -- [3]12 porciones->+15%")
		tamanio = input("Elija el tamaño: ")
		if(tamanio == '1'):
			tamanio = 'chica'
		elif(tamanio == '2'):
			tamanio = 'mediana'
		elif(tamanio == '3'):
			tamanio = 'grande'
		else:
			print('Codigo incorrecto')
		miPizza = Pizza("Muza", 250, tipo, elegida, tamanio)
		lista_pizzas.append(miPizza)

		eldetalle= DetallePedido(len(lista_pizzas), lista_pizzas)
		print("Subtotal: ", eldetalle.calcularSubtotal())
		seguir = input('Desea seguir pidiendo pizzas??: ')
		if(seguir=='1'):
			return False
		return True
		#eldetalle = DetallePedido(10, lista_pizzas, calcular)
예제 #17
0
파일: CBR.py 프로젝트: dcurto95/Pizza-CBR
def adapt(constraints, closest_pizza):
    new_recipe = np.array(closest_pizza.recipe, copy=True)
    actions = new_recipe[:, 0]

    closest_pizza.set_recipe()  # To create new references
    new_ingredients = closest_pizza.toppings.copy()

    # Obtain the topping differences separated by task
    topping_deletions, topping_insertions, topping_substitutions = get_delete_insert_substitute_toppings(
        closest_pizza, constraints)
    # Update the ingredients list of the adapted pizza
    new_ingredients.extend(topping_insertions)
    new_ingredients = np.asarray(new_ingredients)

    # Obtain the steps for each list of toppings
    insert_tasks = np.asarray(
        get_recipe_from_toppings('', [], topping_insertions))
    insert_tasks = insert_tasks[(insert_tasks[:, 0] != 'bake')
                                & (insert_tasks[:, 0] != 'extend')]
    substitute_tasks = np.asarray(
        get_recipe_from_toppings('', [], topping_substitutions))
    substitute_tasks = substitute_tasks[(substitute_tasks[:, 0] != 'bake')
                                        & (substitute_tasks[:, 0] != 'extend')]

    # Split the topping insertions by new steps in the recipes and appending toppings in existing steps
    add_tasks_index = [
        task_tuple[0] not in actions for task_tuple in insert_tasks
    ]
    add_tasks = insert_tasks[add_tasks_index] if add_tasks_index else np.array(
        [])
    insert_tasks = insert_tasks[
        ~np.asarray(add_tasks_index)] if add_tasks_index else np.array([])

    # Create the recipe
    new_recipe, new_ingredients = update_recipe_from_baseline(
        actions, add_tasks, constraints, insert_tasks, new_ingredients,
        new_recipe, substitute_tasks, topping_deletions)
    if not isinstance(new_ingredients, list):
        new_ingredients = new_ingredients.tolist()
    new_ingredients = list(set(new_ingredients))
    return Pizza(constraints['dough'], constraints['sauce'], new_ingredients,
                 new_recipe)
예제 #18
0
 def main(self):
     pizza=Pizza()
     pizza.setTipo()
     tipo1=Tipo()
     tipo1.setIngredientes(pizza.getTipo())
     
     print("Pizza elegida: " ,pizza.getTipo())
     print("Ingredientes: ",end="")
     lista=tipo1.getIngredientes()
     for i in range(len(lista)):
         if i==0:
             print(lista[i],end="")
         else:
             print(",",lista[i],end="")
     print()
예제 #19
0
    def ejecutar(self):
        pizza = Pizza()
        pizza.setTipo()
        tipo1 = Tipo()
        tipo1.setIngredientes(pizza.getTipo())
        os.system("clear")

        print("\nTipo de pizza:", pizza.getTipo())
        print("Ingredientes: ", end="")
        lista = tipo1.getIngredientes()
        for i in range(len(lista)):
            if i == 0:
                print(lista[i], end="")
            else:
                print(",", lista[i], end="")
        print()
    def setUp(self):
        self.pizza1 = Pizza()
        self.pizza1.adicionaIngrediente("Mussarela")
        self.pizza1.adicionaIngrediente("Molho")
        self.pizza1.adicionaIngrediente("Tomate")
        self.pizza1.adicionaIngrediente("Manjericão")

        self.pizza2 = Pizza()
        self.pizza2.adicionaIngrediente("Mussarela")
        self.pizza2.adicionaIngrediente("Provolone")
        self.pizza2.adicionaIngrediente("Parmesão")
        self.pizza2.adicionaIngrediente("Cheddar")
        self.pizza2.adicionaIngrediente("Molho")
        self.pizza2.adicionaIngrediente("Roquefort")

        self.pizza3 = Pizza()
        self.pizza3.adicionaIngrediente("Mussarela")
예제 #21
0
 def test_wrong_pizza_size(self):
     with self.assertRaises(TypeError):
         Pizza(4)
예제 #22
0
 def test_big_pizza(self):
     pizza = Pizza(PIZZA_BIG_SIZE)
     self.assertEqual(pizza.size, 1)
예제 #23
0
 def test_small_pizza(self):
     pizza = Pizza(PIZZA_SMALL_SIZE)
     self.assertEqual(pizza.size, 0)
예제 #24
0
파일: 01.py 프로젝트: reisnobre/CET078
from pizza import Pizza

lPizza = Pizza()
lPizza.addIngredient('mussarela')
lPizza.addIngredient('mussarela')
print(Pizza.__dict__)
print(lPizza.__dict__)
예제 #25
0
class PizzaTests(unittest.TestCase):

    def setUp(self):
        self.pizza = Pizza()

    def test_take_order(self):
        self.pizza.take("take rado 5.0")
        self.assertEqual(self.pizza.order, {"rado": 5.0})
        self.pizza.take("take toni 6")
        self.assertEqual(self.pizza.order, {"rado": 5.0, "toni": 6.0})

    def test_save_order(self):
        self.pizza.take("take rado 5")
        self.pizza.save()
        self.assertEqual(self.pizza.loadOrder(self.pizza.orderNames[-1]),
                         {"rado": 5.0})
        remove(self.pizza.orderNames[-1])

    def test_load_order(self):
        self.pizza.take("take rado 5")
        self.pizza.save()
        self.pizza.take("take toni 60")
        self.pizza.isListCalled = True      # in order to bypass user input
        self.pizza.isLastOrderSaved = True  # in order to bypass user input
        self.pizza.load("load 1")
        self.assertEqual(self.pizza.order, {"rado": 5.0})
        remove(self.pizza.orderNames[-1])
예제 #26
0
 def setUp(self):
     self.pizza = Pizza()
예제 #27
0
from pizza import Pizza

meat_lovers = Pizza()
meat_lovers.size = "16"
meat_lovers.style = "Deep dish"
meat_lovers.add_topping("Pepperoni")
meat_lovers.add_topping("Olives")
meat_lovers.print_order()

meatball_parm = Pizza()
meatball_parm.size = "20"
meatball_parm.style = "Hand-tossed"
meatball_parm.add_topping("Meatballs")
meatball_parm.add_topping("Parmesan")
meatball_parm.print_order()
예제 #28
0
from pizza import Pizza
from cutter import Cutter

pizza = Pizza()
pizza.read('small')
pizza.slice((0, 0), (0, 2))
pizza.slice((0, 0), (3, 6))

for i in range(1, 7):
    pizza.slice((1, 5), (i, i))

pizza.parse_to_file()

pizza = Pizza()
pizza.read('medium')
Cutter(pizza).solve(4, 3)

pizza = Pizza()
pizza.read('big')
Cutter(pizza).solve(2, 6)
        if (choice2 == 1):
            menu = [
                "chicken bali", "pepperoni", "sweet corn", "onion mushroom"
            ]
            quantity = 0
            list_of_size = ["mini", "small", "medium", "large"]
            sizes_and_price = {
                "mini": 500,
                "small": 1000,
                "medium": 3000,
                "large": 5000
            }
            toppings = ["cheese", "meat", "sauce", "vegetable"]

            # creates an instance of the Pizza class
            main_menu = Pizza(menu, quantity, sizes_and_price, toppings)
            print("\n<<< Our Menu >>>")

            # call get_menu() function from the Pizza class
            main_menu.get_menu()

            choice3 = str(input("\nProceed to order? (y/n): "))

            # Check if user input is valid
            while (choice3 != "y") and (choice3 != "n"):
                print("\nPlease enter a valid answer")
                choice3 = str(input("\nProceed to order? (y/n): "))

            if choice3 == "y":

                # receive customers prefered menu
예제 #30
0
                        #STEP = 3 -->  Realizar o pedido
                        elif STEP == 3:
                            if mensagemrecebida == "1":
                                send_message(
                                    client_socket, user,
                                    menuUtilsChatBot.opcaoPizza(message))
                                STEP = 4
                            elif mensagemrecebida == "2":
                                send_message(
                                    client_socket, user,
                                    menuUtilsChatBot.opcaoBebida(message))
                                STEP = 5

                        #STEP = 4 --> Confimar o pedido de pizza
                        elif STEP == 4:
                            pizza = Pizza()
                            opcao = int(mensagemrecebida) - 1

                            if opcao >= 0 and opcao <= 2:
                                pizza.opcao = PIZZAS_DISPONIVEIS[opcao]
                                send_message(
                                    client_socket, user,
                                    menuUtilsChatBot.confirmaPedido(
                                        message, pizza.prefixo, pizza.opcao))
                                STEP = 6
                            else:
                                send_message(
                                    client_socket, user,
                                    menuUtilsChatBot.opcaoInvalida(message))
                                STEP = 1
예제 #31
0
def opcionPizzas():
    tamaño = input('Ingresa el tamaño de la pizza\n')
    precio = int(input('Ingresa el precio\n'))

    return Pizza(tamaño, precio)
예제 #32
0
def read_input(file_name: str = '') -> Pizza:
    """Read input from file and compile a pizza.

    :param file_name: optional file name
    :type file_name: str
    :return: compiled pizza
    :rtype: Pizza
    :raises FileNotFoundError: if file missing or is not valid
    :raises ValueError: if file input is wrong or malformed
    """

    pizza = None

    try:
        file_name = file_name if file_name else argv[1]
    except IndexError:
        raise FileNotFoundError
    else:
        if not isfile(file_name):
            raise FileNotFoundError

    with open(file_name) as file_descriptor:
        headers_line = file_descriptor.readline()
        if not headers_line:
            raise ValueError

        headers = headers_line.split(HEADERS_SEPARATOR, HEADERS_NUMBER - 1)
        headers = map(int, headers)
        headers = map(lambda value: min(value, HEADERS_MAX), headers)
        headers = map(lambda value: max(value, HEADERS_MIN), headers)
        headers = list(headers)

        try:
            rows = headers[0]
            columns = headers[1]
            minimum_ingredient_number = headers[2]
            maximum_cells_number = headers[3]
        except IndexError:
            raise ValueError

        cells = [[None for _ in range(columns)] for _ in range(rows)]

        number_of_mushrooms = 0
        number_of_tomatoes = 0

        for row in range(rows):
            for column in range(columns):
                cell = Cell(column, row)
                pizza_cell = PizzaCell(str(file_descriptor.read(1)))
                pizza_cell.cell = cell

                cells[row][column] = pizza_cell
                number_of_mushrooms += 1 if pizza_cell.mushroom else 0
                number_of_tomatoes += 1 if pizza_cell.tomato else 0
            file_descriptor.read(1)

        if cells[0][0] is None:
            raise ValueError

        pizza = Pizza(cells)
        pizza.rows = rows
        pizza.columns = columns
        pizza.minimum_ingredient_number = minimum_ingredient_number
        pizza.maximum_cells_number = maximum_cells_number
        pizza.number_of_mushrooms = number_of_mushrooms
        pizza.number_of_tomatoes = number_of_tomatoes

    return pizza