def __init__(self): super().__init__() self.setupUi(self) self.screen.setText("Welcome to the Vending Machine!") self.products = {"Coke": 25, "Pepsi": 35, "Soda": 45} self.coins = {"P": 1, "N": 5, "D": 10, "Q": 25} self.coins_received = {"Q": 0, "D": 0, "N": 0, "P": 0} self.coins_names = { "Q": "Quarter(s)", "D": "Dime(s)", "N": "Nickel(s)", "P": "Penny(ies)" } self.amount = 0 self.coins_str = "" self.coins_short_str = "" self.ven_ma = VendingMachine(self.products, self.coins) self.qCoin.pressed.connect(self.add_q) self.dCoin.pressed.connect(self.add_d) self.nCoin.pressed.connect(self.add_n) self.pCoin.pressed.connect(self.add_p) self.coke.pressed.connect(self.order_coke) self.pepsi.pressed.connect(self.order_pepsi) self.soda.pressed.connect(self.order_soda) self.refund.pressed.connect(self.order_refund)
def test_reload(self): '''Check if the machine contains the loaded products''' machine=VendingMachine(self.products,self.coins) self.assertEqual(10,machine.products[1].quantity) self.assertEqual(10, machine.coins['5p'].quantity) machine.reload(self.products,self.coins) self.assertEqual(20,machine.products[1].quantity) self.assertEqual(20,machine.coins['5p'].quantity)
def test_buy_product_not_enough_change(self): '''Now try to buy a product but the machine has not enough change''' machine=VendingMachine(self.products,[Coin('1p',0.01,10)]) result=machine.give_product(1, 2) self.assertEqual('P1', result['product']) self.assertEqual(0.1, result['change']) #check the credit on the machine self.assertEqual(0.4, machine.credit)
def test_buy_all_products(self): '''Now try to buy all the 10 products of type P1. Then try to buy another one''' machine=VendingMachine(self.products,self.coins) for i in range(10): machine.give_product(1, 1.5) result=machine.give_product(1, 1.5) self.assertEqual(None, result['product']) self.assertEqual('Product not present', result['message'])
def event_handler(self, event): # change selected color if rectange clicked if event.type == pygame.MOUSEBUTTONDOWN: # is some button clicked if event.button == 1: # is left button clicked if self._rect.collidepoint(event.pos): # is mouse over button if VendingMachine.getInstance().products[self.name] >= 1: VendingMachine.insertProduct(self) VendingMachine.getInstance().products[self.name] -= 1 print(self.name)
def test_buy_with_a_tons_of_money(self): '''Try to buy a product inserting more money than the possible change..than free products for all :)''' machine=VendingMachine(self.products,self.coins) result=machine.give_product(1, 50) self.assertEqual('P1', result['product']) self.assertEqual(38.8, result['change']) #a product given without putting money result=machine.give_product(1, 0) self.assertEqual('P1', result['product']) #but no change! self.assertEqual(0, result['change'])
def event_handler(self, event): # change selected color if rectange clicked if event.type == pygame.MOUSEBUTTONDOWN: # is some button clicked if event.button == 1: # is left button clicked if self.button_rect.collidepoint( event.pos): # is mouse over button VendingMachine.inpPin(self.value) if len(VendingMachine.pin) == 4: InpText.requested_change = True elif len(VendingMachine.pin) > 4: VendingMachine.pin = VendingMachine.pin[0:4]
def testWhenPenniesArePassedToVendingMachineTheyArePlacedInCoinReturn( self): vendingMachine = VendingMachine() successful = vendingMachine.insert(2.5, 0.75) self.assertEqual(successful, False) coinReturn = vendingMachine.getCoinReturn() self.assertEqual(len(coinReturn), 1) self.assertEqual(len(vendingMachine.getCoinReturn()), 0) self.assertEqual(coinReturn[0].getWeight(), 2.5) self.assertEqual(coinReturn[0].getDiameter(), 0.75)
def test_make_sale_post_conditions(self): """ Tests that make_sale sets the object variables correctly """ vending_machine = VendingMachine() vending_machine.amount_left = 100 product_info = vending_machine.product_dict[1] product_price = product_info[0].price vending_machine.make_sale(1) self.assertEqual(vending_machine.amount_left, 100 - product_price) self.assertTrue(vending_machine.sale_success) self.assertEqual(vending_machine.current_state, PRODUCT_BUYING_INFO) self.assertTrue(1 in vending_machine.sale_item_ids)
class TestVendingMachine(unittest.TestCase): """ Tests for VendingMachine """ def setUp(self): """Test setup""" self.vending_machine = VendingMachine() @mock.patch('VendingMachine.VendingMachine.are_input_coins_acceptable', mock.MagicMock(return_value=True)) def test_set_amount_inserted_sets_amount_correctly(self): """ Tests that set_amount_inserted() sets the inserted amount correctly """ return_value = self.vending_machine.set_amount_inserted( [10, 50, 10, 100]) self.assertEqual(self.vending_machine.amount_inserted_list, [10, 50, 10, 100]) self.assertEqual(self.vending_machine.current_state, INPUT_ACCEPTANCE) self.assertTrue(return_value) @mock.patch('VendingMachine.VendingMachine.is_sale_possible', mock.MagicMock(return_value=False)) def test_check_make_sale_returns_false_if_sale_not_possible(self): """ Tests that make_sale returns False if sale is not possible """ self.assertFalse(self.vending_machine.make_sale(1)) @mock.patch('VendingMachine.VendingMachine.is_sale_possible', mock.MagicMock(return_value=True)) def test_make_sale_post_conditions(self): """ Tests that make_sale sets the object variables correctly """ vending_machine = VendingMachine() vending_machine.amount_left = 100 product_info = vending_machine.product_dict[1] product_price = product_info[0].price vending_machine.make_sale(1) self.assertEqual(vending_machine.amount_left, 100 - product_price) self.assertTrue(vending_machine.sale_success) self.assertEqual(vending_machine.current_state, PRODUCT_BUYING_INFO) self.assertTrue(1 in vending_machine.sale_item_ids)
def testWhenThereIsNotEnoughMoneyInTheVendingMachineExactChangeOnlyShouldBeDisplayed( self): vendingMachine = VendingMachine(quarters=0, nickels=0, dimes=0) self.assertEqual(vendingMachine.getDisplay(), "EXACT CHANGE ONLY") vendingMachine = VendingMachine(quarters=0, nickels=1, dimes=1) self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN")
def loop(): print('press CTRL+C or CTLR+D to exit') vm = VendingMachine('hospital', initialCash = 130) vm.fill(32) while True: try: data = input('MACHINE> ') if (data == 'PRODUCTS'): vm.productsList() except (KeyboardInterrupt, EOFError): print('goodbye!') break
def main(): '''Function instantiate a vending machine and passes user inputs''' purchase = "" VendingMachine1 = VendingMachine(1, 2) quarters = input("How many quarters are you inserting: ") dimes = input("How many dimes are you inserting: ") nickels = input("How many nickels are you inserting: ") VendingMachine1.insert(quarters, dimes, nickels) while(True): ifPurchase = input("Purchase?\n1: yes and 2: No\n") if ifPurchase == "1": purchase = "yes" break if ifPurchase == "2": purchase = "no" break print("Please enter 1 or 2.\n") if purchase == "yes": VendingMachine1.select() else: VendingMachine1.refund()
class VendingMachineUI(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.screen.setText("Welcome to the Vending Machine!") self.products = {"Coke": 25, "Pepsi": 35, "Soda": 45} self.coins = {"P": 1, "N": 5, "D": 10, "Q": 25} self.coins_received = {"Q": 0, "D": 0, "N": 0, "P": 0} self.coins_names = { "Q": "Quarter(s)", "D": "Dime(s)", "N": "Nickel(s)", "P": "Penny(ies)" } self.amount = 0 self.coins_str = "" self.coins_short_str = "" self.ven_ma = VendingMachine(self.products, self.coins) self.qCoin.pressed.connect(self.add_q) self.dCoin.pressed.connect(self.add_d) self.nCoin.pressed.connect(self.add_n) self.pCoin.pressed.connect(self.add_p) self.coke.pressed.connect(self.order_coke) self.pepsi.pressed.connect(self.order_pepsi) self.soda.pressed.connect(self.order_soda) self.refund.pressed.connect(self.order_refund) def add_q(self): self.add_coin("Q") def add_d(self): self.add_coin("D") def add_n(self): self.add_coin("N") def add_p(self): self.add_coin("P") def add_coin(self, coin): self.coins_received[coin] += 1 self.coins_str = "You've inserted: " self.coins_short_str = "" self.amount += self.coins[coin] self.coins_str = f"You've inserted {self.amount} cents" for coin in self.coins_received: self.coins_short_str += f"{self.coins_received[coin]}{coin[0]}" return self.screen.setText(self.coins_str) def order_coke(self): order_str = f"Coke,{self.coins_short_str}" self.order_drink(order_str) def order_pepsi(self): order_str = f"Pepsi,{self.coins_short_str}" self.order_drink(order_str) def order_soda(self): order_str = f"Soda,{self.coins_short_str}" self.order_drink(order_str) def order_drink(self, order_str): drink, money = self.ven_ma.input_converter(order_str) response = self.ven_ma.execute_order(drink, money) self.order_response(response) def order_response(self, response): if "Sorry" in response: self.screen.setText(response) elif "Here you go" in response: for coin in self.coins_names: response = response.replace(coin, f" {self.coins_names[coin]} ") self.screen.setText(response) for coin in self.coins_received: self.coins_received[coin] = 0 self.amount = 0 self.coins_str = "" self.coins_short_str = "" else: self.screen.setText("Sorry, something went wrong") def order_refund(self): if not self.coins_short_str: response = f"Sorry, you've inserted no coins to refund" else: response = f"Your refund is {self.ven_ma.amount_to_coins_converter(self.amount)}" for coin in self.coins_names: response = response.replace(coin, f" {self.coins_names[coin]} ") self.screen.setText(response) for coin in self.coins_received: self.coins_received[coin] = 0 self.amount = 0 self.coins_str = "" self.coins_short_str = ""
def test_buy_with_a_lot_of_money(self): '''Try to buy a product inserting a lot of money''' machine=VendingMachine(self.products,self.coins) result=machine.give_product(1, 37.5) self.assertEqual('P1', result['product']) self.assertEqual(36, result['change'])
def testWhenCoinsAreAndAreNotInsertedAndSoldOutProductIsSelectedSoldOutIsDisplayed( self): vendingMachine = VendingMachine() vendingMachine.select(0) self.assertEqual(vendingMachine.getDisplay(), "SOLD OUT") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") vendingMachine.select(1) self.assertEqual(vendingMachine.getDisplay(), "SOLD OUT") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") vendingMachine.select(2) self.assertEqual(vendingMachine.getDisplay(), "SOLD OUT") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.select(0) self.assertEqual(vendingMachine.getDisplay(), "SOLD OUT") self.assertEqual(vendingMachine.getDisplay(), "0.25")
def testWhenAnyProductIsSelectedAndInsufficientFundsAreAvailableDisplayReturnsValueOfItemOnceThenAvailableFunds( self): vendingMachine = VendingMachine(cola=1, chips=1, candy=1) vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) vendingMachine.select(0) # Selecting cola self.assertEqual(vendingMachine.getDisplay(), "PRICE 1.00") self.assertEqual(vendingMachine.getDisplay(), "0.05") vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) vendingMachine.select(1) # Selecting chips self.assertEqual(vendingMachine.getDisplay(), "PRICE 0.50") self.assertEqual(vendingMachine.getDisplay(), "0.15") vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.select(2) # Selecting candy self.assertEqual(vendingMachine.getDisplay(), "PRICE 0.65") self.assertEqual(vendingMachine.getDisplay(), "0.40")
def testWhenAProductIsPurchasedWithExcessFundsCorrectChangeIsReturned( self): vendingMachine = VendingMachine(cola=3) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.select(0) coinReturn = vendingMachine.getCoinReturn() self.assertEqual( round(sum([aCoin.getValue() for aCoin in coinReturn]), 2), Coins.QUARTER_VALUE) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) vendingMachine.select(0) coinReturn = vendingMachine.getCoinReturn() self.assertEqual( round(sum([aCoin.getValue() for aCoin in coinReturn]), 2), 0.35) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) vendingMachine.select(0) coinReturn = vendingMachine.getCoinReturn() self.assertEqual( round(sum([aCoin.getValue() for aCoin in coinReturn]), 2), 0.4)
def testWhenValidWeightAndDiametersArePassedToVendingMachineTheyAreStoredAndAddedToTotalCorrectly( self): vendingMachine = VendingMachine() successful = vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) self.assertTrue(successful) inserted = vendingMachine.getInserted() self.assertEqual(len(inserted), 1) self.assertEqual(inserted[0].getWeight(), Coins.NICKEL_WEIGHT) self.assertEqual(inserted[0].getDiameter(), Coins.NICKEL_DIAMETER) self.assertEqual(inserted[0].getValue(), Coins.NICKEL_VALUE) self.assertEqual(vendingMachine.getTotal(), Coins.NICKEL_VALUE) vendingMachine = VendingMachine() successful = vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) self.assertTrue(successful) inserted = vendingMachine.getInserted() self.assertEqual(len(inserted), 1) self.assertEqual(inserted[0].getWeight(), Coins.DIME_WEIGHT) self.assertEqual(inserted[0].getDiameter(), Coins.DIME_DIAMETER) self.assertEqual(inserted[0].getValue(), 0.1) self.assertEqual(vendingMachine.getTotal(), 0.1) vendingMachine = VendingMachine() successful = vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) self.assertTrue(successful) inserted = vendingMachine.getInserted() self.assertEqual(len(inserted), 1) self.assertEqual(inserted[0].getWeight(), Coins.QUARTER_WEIGHT) self.assertEqual(inserted[0].getDiameter(), Coins.QUARTER_DIAMETER) self.assertEqual(inserted[0].getValue(), Coins.QUARTER_VALUE) self.assertEqual(vendingMachine.getTotal(), Coins.QUARTER_VALUE) successful = vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) self.assertTrue(successful) self.assertEqual(len(inserted), 2) self.assertEqual(inserted[1].getWeight(), Coins.NICKEL_WEIGHT) self.assertEqual(inserted[1].getDiameter(), Coins.NICKEL_DIAMETER) self.assertEqual(inserted[1].getValue(), Coins.NICKEL_VALUE) self.assertEqual(vendingMachine.getTotal(), 0.30)
from VendingMachine import VendingMachine from Payment import Cash, Card from Button import Button, CashButton, CardButton from Button import Text, PriceText, CoinsText, TextButton, TakeMoney, PlotText, PinText, InpText, ErrText, InsText import pygame import os Machine = VendingMachine(10,10,10,10,10,10,Cash(),Card()) print(Machine.totalCash.getMoney()) Machine.totalCash.initTotalMoney() print(Machine.totalCash.getMoney()) print(Machine.balance.getFunds()) selectedPaymentOption = "" pygame.init() win = pygame.display.set_mode((1000,436)) pygame.display.set_caption("Vending Machine") x = 50 y = 50 width = 40 height = 60 vel = 5 Products = [] Change = [] total = PriceText("Total: "+str(VendingMachine.getBasketPrice())+"$", (315, height+20), 17, True) aviraPrimePath = os.path.join('images', 'aviraPrime.jpg') #93x133 antivirusProPath = os.path.join('images', 'antivirusPro.jpg') #93x132 phantomVPNPath = os.path.join('images', 'phantomVPN.jpg') #93x132
def redrawGameWindow(): NoAviraPrimeText = Text('x' + str(Machine.getNoAviraPrime()), (113, 72)) NoAntivirusProText = Text('x' + str(Machine.getNoAntiVirusPRO()), (113, 214)) NoPhantomVPNText = Text('x' + str(Machine.getNoPhantomVPN()), (113, 357)) NoSystemSpeedupText = Text('x' + str(Machine.getNoSystemSpeedup()), (256, 72)) NoPasswordManagerText = Text('x' + str(Machine.getNoPaswordManager()), (256, 214)) NoOptimizerText = Text('x' + str(Machine.getNoOptimizer()), (256, 357)) aviraPrimeBtn.draw(win) antivirusProBtn.draw(win) phantomVPNBtn.draw(win) systemSpeedupBtn.draw(win) passwordManagerBtn.draw(win) optimizerBtn.draw(win) cashBtn.draw(win) cardBtn.draw(win) NoAviraPrimeText.draw(win) NoAntivirusProText.draw(win) NoPhantomVPNText.draw(win) NoSystemSpeedupText.draw(win) NoPasswordManagerText.draw(win) NoOptimizerText.draw(win) PriceAviraPrimeText.draw(win) PriceAntivirusProText.draw(win) PricePhantomVPNText.draw(win) PriceSystemSpeedupText.draw(win) PricePasswordManagerText.draw(win) PriceOptimizerText.draw(win) plotText.draw(win) paymentMethodText.draw(win) if CashButton.payment_method == "Cash": CreditText.draw(win) BillsText.draw(win) oneCentBtn.draw(win) fiveCentBtn.draw(win) tenCentBtn.draw(win) twentyFiveCentBtn.draw(win) fiftyCentBtn.draw(win) oneDollarBtn.draw(win) twoDollarBtn.draw(win) fiveDollarBtn.draw(win) tenDollarBtn.draw(win) twentyDollarBtn.draw(win) fiftyDollarBtn.draw(win) oneHundredDollarBtn.draw(win) requestChangeBtn.draw(win) ProductsText.draw(win) for product in Products: product.draw(win) if TextButton.requested_change == True: if VendingMachine.credit.getMoney() != 0: for rest in Change: rest.draw(win) RestText.draw(win) takeChange.draw(win) else: VendingMachine.credit.clearMoney() TextButton.requested_change = False if VendingMachine.getBasketPrice()>0: total.draw(win) if InsText.requested_change == True: insfunds.draw(win) elif CardButton.payment_method == "Card": FundsText.draw(win) pinzero.draw(win) pinone.draw(win) pintwo.draw(win) pinthree.draw(win) pinfour.draw(win) pinfive.draw(win) pinsix.draw(win) pinseven.draw(win) pineight.draw(win) pinnine.draw(win) for product in Products: product.draw(win) if InpText.requested_change == True: inppin.draw(win) if VendingMachine.getBasketPrice()>0: total.draw(win) elif CardButton.payment_method == "Err": if ErrText.requested_change1 == True: err1.draw(win) if ErrText.requested_change2 == True: err2.draw(win) paymentMethodText.draw(win) pygame.display.update()
def testAfterAProductIsPurchasedCorrectCoinsAreInTheMachine(self): vendingMachine = VendingMachine(candy=2, quarters=0, nickels=0, dimes=0) self.assertEqual(vendingMachine.quarters, 0) self.assertEqual(vendingMachine.dimes, 0) self.assertEqual(vendingMachine.nickels, 0) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) vendingMachine.select(2) self.assertEqual(vendingMachine.quarters, 2) self.assertEqual(vendingMachine.dimes, 1) self.assertEqual(vendingMachine.nickels, 1) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.select(2) self.assertEqual(vendingMachine.quarters, 5) self.assertEqual(vendingMachine.dimes, 0) self.assertEqual(vendingMachine.nickels, 1)
__author__ = "Arun Sondhi" from VendingMachine import VendingMachine from Coin import Coins if __name__ == '__main__': vendingMachine = VendingMachine(cola=5, chips=5, candy=5) while True: print "\nProducts:" print "\tCola: 0\n\tChips: 1\n\tCandy: 2" print "\nCoins:" print "\tQuarter: q\n\tDime: d\n\tNickel: n\n\tPenny: p\n\tReturn Coins: r" print "\nDisplay:", vendingMachine.getDisplay() userInput = raw_input("Insert Coin or Select Product: ") if userInput == "0" or userInput == "1" or userInput == "2": vendingMachine.select(int(userInput)) elif userInput == "q": vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) elif userInput == "d": vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) elif userInput == "n": vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.DIME_DIAMETER) elif userInput == "p": vendingMachine.insert(2.5, 0.75) elif userInput == "r": vendingMachine.returnCoins()
import barchart, stats from VendingMachine import VendingMachine import tkinter as tk from tkinter import messagebox from tkinter.ttk import * #Window initialization window = tk.Tk() window.title("Avira Vending Machine") window.geometry('720x480') #Global variables vender = VendingMachine() payment_method = tk.StringVar() payment_method.set("Cash") money_str = tk.StringVar() money_str.set("0") input_money = 0 input_bills = {"1": 0, "5": 0, "10": 0, "50": 0, "100": 0} product_names = [ "Avira Prime", "Antivirus PRO", "Phantom VPN", "Password Manager", "Optimizer", "System Speedup" ] selected_product = tk.StringVar() selected_product.set(product_names[0])
def event_handler(self, event): # change selected color if rectange clicked if event.type == pygame.MOUSEBUTTONDOWN: # is some button clicked if event.button == 1: # is left button clicked if self.button_rect.collidepoint( event.pos): # is mouse over button print(VendingMachine.card.checkPin(VendingMachine.pin)) if VendingMachine.card.checkPin(VendingMachine.pin) == 1: VendingMachine.pin = [] InpText.requested_change = False if VendingMachine.card.getFunds( ) < VendingMachine.getBasketPrice(): VendingMachine.pin = [] InpText.requested_change = False ErrText.requested_change2 = True CardButton.payment_method = "Err" for item in VendingMachine.getInstance().products: if item in VendingMachine.Basket: VendingMachine.getInstance().products[ item] += VendingMachine.Basket[item] VendingMachine.clearBasket() else: VendingMachine.card.updateFunds( VendingMachine.getBasketPrice()) items = [0] * 6 for item in VendingMachine.Basket: if item == "Avira Prime": items[0] += VendingMachine.Basket[item] if item == "System Speedup": items[1] += VendingMachine.Basket[item] if item == "Antivirus PRO": items[2] += VendingMachine.Basket[item] if item == "Password Manager": items[3] += VendingMachine.Basket[item] if item == "Phantom VPN": items[4] += VendingMachine.Basket[item] if item == "Optimizer": items[5] += VendingMachine.Basket[item] pricelist = VendingMachine.getPrices() VendingMachine.readItems() i = 0 for value in items: if value != 0: if i == 0: VendingMachine.itemHistory[i].append( int(VendingMachine.itemHistory[i] [-1]) + value * pricelist["Avira Prime"]) if i == 1: VendingMachine.itemHistory[i].append( int(VendingMachine.itemHistory[i] [-1]) + value * pricelist["System Speedup"]) if i == 2: VendingMachine.itemHistory[i].append( int(VendingMachine.itemHistory[i] [-1]) + value * pricelist["Antivirus PRO"]) if i == 3: VendingMachine.itemHistory[i].append( int(VendingMachine.itemHistory[i] [-1]) + value * pricelist["Password Manager"]) if i == 4: VendingMachine.itemHistory[i].append( int(VendingMachine.itemHistory[i] [-1]) + value * pricelist["Phantom VPN"]) if i == 5: VendingMachine.itemHistory[i].append( int(VendingMachine.itemHistory[i] [-1]) + value * pricelist["Optimizer"]) i += 1 with open("plot_input.txt", "w") as f: for i in range(6): for value in VendingMachine.itemHistory[i]: if int(value) != 0: f.write("%d " % int(value)) f.write('\n') VendingMachine.itemHistory = [[], [], [], [], [], []] VendingMachine.vendorBalance.append( float(VendingMachine.vendorBalance[-1]) + VendingMachine.getBasketPrice()) VendingMachine.credit.setMoney( VendingMachine.getInstance().totalCash.getRest( VendingMachine.credit.getMoney(), VendingMachine.getBasketPrice())) VendingMachine.clearBasket() CardButton.payment_method = "" else: VendingMachine.pin = [] InpText.requested_change = False ErrText.requested_change1 = True CardButton.payment_method = "Err"
def testWhenValidCoinsArePassedVendingMachineDisplaysCorrectAmount(self): vendingMachine = VendingMachine() vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) self.assertEqual(vendingMachine.getDisplay(), "0.05") vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) self.assertEqual(vendingMachine.getDisplay(), "0.15") vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) self.assertEqual(vendingMachine.getDisplay(), "0.40")
def test_buy_product_not_enough_money(self): '''Now try to buy a product giving less money than needed''' machine=VendingMachine(self.products,self.coins) result=machine.give_product(1, 0.5) self.assertEqual(None, result['product']) self.assertEqual('Not enough money', result['message'])
def testWhenAnyProductIsSelectedAndNoCoinsAreInsertedDisplayReturnsValueOfItemOnce( self): vendingMachine = VendingMachine(cola=1, chips=1, candy=1) vendingMachine.select(0) # Selecting cola self.assertEqual(vendingMachine.getDisplay(), "PRICE 1.00") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") vendingMachine.select(1) # Selecting chips self.assertEqual(vendingMachine.getDisplay(), "PRICE 0.50") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") vendingMachine.select(2) # Selecting candy self.assertEqual(vendingMachine.getDisplay(), "PRICE 0.65") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN")
class TerminalAdapter(): """ Acts as a terminal interface for the VendingMachine """ def __init__(self): self.vending_machine = VendingMachine() self.product_to_be_sold = None self.error_msg = None def __call__(self, *args, **kwargs): while True: self.produce_display() self.handle_input() def handle_input(self, input_value=None): """ Handles user input and then takes relevant actions """ if not input_value: input_value = input().strip() if not input_value: self.handle_input() input_value_list = list(map(int, input_value.split())) input_command = input_value_list[0] input_args = [] if len(input_value_list) > 1: input_args = input_value_list[1:] valid_command, valid_states = self.vending_machine.command_allowed( input_command) if not valid_command: self.error_msg = f'Wrong command selected. Allowed command ' \ f'at this stage {str(valid_states)}' return if input_command == INPUT_ACCEPTANCE and input_args: coins_acceptable = self.vending_machine.set_amount_inserted( input_args) if not coins_acceptable: self.error_msg = 'Invalid amount inserted. Please try again' if input_command == PRODUCT_BUYING_INFO and input_args: # import ipdb; ipdb.set_trace() sale_success = self.vending_machine.make_sale(input_args[0]) if not sale_success: self.error_msg = 'Unable to make sale. Please try again' if input_command == ITEM_AT_OUTLET: self.vending_machine.set_item_at_outlet() if input_command == CHANGE_AMOUNT_PRODUCTION: self.vending_machine.get_change_amount() if input_command == CHANGE_AT_RETURN_GATE: self.vending_machine.get_coins_from_return_gate() if input_command == MACHINE_SHUT_DOWN: self.vending_machine.shut_down() def produce_display(self): """ Produces terminal output on the basis of Vending Machine state """ call('clear' if os.name == 'posix' else 'cls') curreny = self.vending_machine.get_currency() input_amount = self.vending_machine.get_input_amount() change_coins_state = self.vending_machine.get_current_change_status() print('---------------------------------------------') print(f'[Input amount]\t\t{input_amount} {curreny}') change_coin_text = '[Change]\t' not_first = False for change_coins in change_coins_state.items(): if not_first: change_coin_text += '\t' not_first = True change_coin_text += f'\t{str(change_coins[0])} {curreny} \t {change_coins[1]}\n' print(change_coin_text) return_gate_text = '[Return gate]\t' # import ipdb; ipdb.set_trace() return_coins = self.vending_machine.get_change_coins_dict() if return_coins: return_coins_list = list(return_coins.keys()) return_coins_list.sort() for return_coin in return_coins_list: for _ in range(0, return_coins[return_coin]): return_gate_text += f'\t\t{return_coin} {curreny}\n' else: return_gate_text += 'Empty\n' print(return_gate_text) items_for_sale_text = '[Items for sale]' product_details_list = self.vending_machine.get_product_details_list() not_first = False for product in product_details_list: if not_first: items_for_sale_text += '\t\t' not_first = True items_for_sale_text += f'\t {product["id"]}. {product["name"]} \t ' \ f'{product["price"]} {curreny} \t {product["status"]} \n' print(items_for_sale_text) outlet_text = f'[Outlet]' items_in_outlet = self.vending_machine.get_items_in_outlet_list() not_first = False for product_id in items_in_outlet: if not_first: outlet_text += '\t' not_first = True outlet_text += f'\t {self.vending_machine.get_product_details(product_id)["name"]} \n' print(outlet_text) if self.error_msg: print(f'Error : {self.error_msg}') self.error_msg = None print('---------------------------------------------')
def testWhenAProductIsSelectedAndSufficientFundsAreAvailableDisplayReturnsThankYou( self): vendingMachine = VendingMachine(cola=5, chips=4, candy=3) self.assertEqual(vendingMachine.getQuantity(0), 5) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.select(0) self.assertEqual(vendingMachine.getDisplay(), "THANK YOU") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") self.assertEqual(vendingMachine.getQuantity(0), 4) self.assertEqual(vendingMachine.getQuantity(1), 4) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.select(1) self.assertEqual(vendingMachine.getDisplay(), "THANK YOU") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") self.assertEqual(vendingMachine.getQuantity(1), 3) self.assertEqual(vendingMachine.getQuantity(2), 3) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) vendingMachine.select(2) self.assertEqual(vendingMachine.getDisplay(), "THANK YOU") self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN") self.assertEqual(vendingMachine.getQuantity(2), 2)
def test_buy_two_products_check_balance(self): '''Now try to buy two products cheking at the end if the balance is correct''' machine=VendingMachine(self.products,self.coins) machine.give_product(1, 3) machine.give_product(2, 0.5) self.assertEqual(2,machine.balance)
def testWhenCoinsAreInsertedAndCoinsAreReturnedCorrectCoinsAreReturned( self): vendingMachine = VendingMachine() vendingMachine.insert(2.5, 0.75) vendingMachine.insert(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER) vendingMachine.insert(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER) vendingMachine.insert(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER) vendingMachine.returnCoins() coinReturn = vendingMachine.getCoinReturn() self.assertEqual( round(sum([aCoin.getValue() for aCoin in coinReturn]), 2), 0.4) self.assertEqual(len(coinReturn), 4)
def __init__(self): self.vending_machine = VendingMachine() self.product_to_be_sold = None self.error_msg = None
def test_buy_product_invalid_code(self): '''Test if the machine gives no product with appropriate error if a wrong code is typed''' machine=VendingMachine(self.products, self.coins) result=machine.give_product(10, 100) self.assertEqual(None, result['product']) self.assertEqual('Invalid code', result['message'])
def main(): # Connect to the vending machine rfh, wfh = connect_to_vendingmachine() vm = VendingMachine(rfh, wfh) # Anything you want to do prior to starting your program should happen here while True: # Everything you want to run continuously should go here for i in ["/LOADING\\", "-LOADING-", "\\LOADING/", "|LOADING|"]: vm.display(i) sleep(0.5) vm.vend("99") vm.display("BEEP") vm.beep() in1 = vm.get_key() vm.display("SELECT:" + str(in1)) in2 = vm.get_key() vm.display("SELECT:" + str(in1) + str(in2))
def test_buy_product_no_product(self): '''Test if the machine gives no product if they are finished''' machine=VendingMachine([Product('P1',1,1.5,0)],[]) result=machine.give_product(1, 100) self.assertEqual(None, result['product']) self.assertEqual('Product not present', result['message'])
def test_buy_product_change_present(self): '''Now try to buy a product that is present in the machine, and check that the change is correct''' machine=VendingMachine(self.products,self.coins) result=machine.give_product(1, 3) self.assertEqual('P1', result['product']) self.assertEqual(1.5, result['change'])
def testWhenInvalidCoinsArePassedToVendingMachineDisplaysInsertCoin(self): vendingMachine = VendingMachine() vendingMachine.insert(2.5, 0.75) self.assertEqual(vendingMachine.getDisplay(), "INSERT COIN")
def setUp(self): """Test setup""" self.vending_machine = VendingMachine()