美文网首页python自学
MVC控制台实现购物车小程序

MVC控制台实现购物车小程序

作者: 杨育银 | 来源:发表于2019-05-18 09:14 被阅读11次
"""
    购物车
    注意:
        1.商品添加到购物车后,商店对应商品数量应该相应减少
        2.当购物车清空后,已加入购物车的商品应该回到商店
        3.支付后,购物车清空,商店对应商品减少相应数量
"""


class DictCommodityInfo:
    """
        商品类
    """
    def __init__(self, key, name, price, count):
        self.__key = key
        self.__name = name
        self.__price = price
        self.__count = count

    def get_key(self):
        return self.__name

    def get_name(self):
        return self.__name

    def get_price(self):
        return self.__price

    def get_count(self):
        return self.__count


class Account:
    def __init__(self, money=0):
        self.__money = money

    def get_money(self):
        return self.__money

    def charge(self, money):
        self.__money += money

    def pay_money(self, money):
        self.__money -= money


class DictCommodityInfoManagerController:
    def __init__(self, dict, dict_shopping_cart={}):
        self.__dict = dict
        self.__account = Account()
        self.__dict_shopping_cart = dict_shopping_cart

    def get_dict(self):
        """
            获取商品列表
        :return:
        """
        return self.__dict

    def get_dict_shopping_cart(self):
        """
            获取购物车列表
        :return:
        """
        return self.__dict_shopping_cart

    def __add(self, key, name, price, count):
        """
            添加商品
        :param key:
        :param name:
        :param price:
        :param count:
        :return:
        """
        count_dict = self.__dict[key]["count"]
        self.__dict[key] = {"name": name, "price": price, "count": count_dict + count}

    def remove(self, cid, count):
        """
            删除商品
        :param cid:
        :param count:
        :return:
        """
        self.__dict[cid]["count"] -= count

    def __print_commodity(self):
        """
            打印商品信息
        :return:
        """
        for key, value in self.__dict.items():
            print("编号:%d 名称:%s 单价:%d 数量:%d" % (key, value["name"], value["price"], value["count"]))

    def print_dict_shopping_cart(self):
        """
            打印购物车信息
        :return:
        """
        if not self.__dict_shopping_cart.__len__():
            print("购物车什么也没有")
        else:
            for key, value in self.__dict_shopping_cart.items():
                print("编号:%d 名称:%s  数量:%d" % (key, value["name"], value["count"]))

    def print_account_money(self):
        """
            显示账户余额
        :return:
        """
        money = self.__account.get_money()
        print("账户余额: %d元" % (money))
        if money < 1000:
            print("你个穷逼")
        elif money >= 50000:
            print("土豪我们做朋友吧")
        else:
            print("钱不多啦,充钱使人快乐")

    def clear_shopping_cart(self):
        """
            清空购物车
        :return:
        """
        if not self.__dict_shopping_cart.__len__():
            return False
        for key, value in self.__dict_shopping_cart.items():
            self.__add(key, value["name"], value["price"], value["count"])
        self.__dict_shopping_cart.clear()
        return True

    def __create_order(self):
        """
            生成订单
        :return:
        """
        while True:
            cid = int(input("请输入商品编号:"))
            if cid in self.__dict:
                break
            else:
                print("该商品不存在")
                return False
        count = int(input("请输入购买数量:"))
        if count > self.__dict[cid]["count"]:
            print("商品数量不足,请重新购买")
            return False
        if count <= 0:
            print("请输入合法数量")
            return False
        self.remove(cid, count)
        return {"cid": cid, "name": self.__dict[cid]["name"], "price": self.__dict[cid]["price"], "count": count}

    def __calculate_paid_money(self):
        money = 0
        for key, value in self.__dict_shopping_cart.items():
            money += value["price"] * value["count"]
        return money

    # def __update_commodity_info(self):

    def buy(self):
        """
            购买
        :return:
        """
        self.__print_commodity()
        dict_order = self.__create_order()
        if not dict_order:
            return False
        # 添加商品到购物车时,商品数量及购物车数量会发生变化
        count = 0
        if self.__dict_shopping_cart.__len__():
            count = self.__dict_shopping_cart[dict_order["cid"]]["count"]
        self.__dict_shopping_cart[dict_order["cid"]] = {"name": dict_order["name"], "price": dict_order["price"],
                                                        "count": count + dict_order["count"]}
        return True

    def pay(self):
        """
            结算
        :return:
        """
        money = self.__calculate_paid_money()
        if self.__account.get_money() < self.__calculate_paid_money():
            print("您的余额不足,请充值")
            return False

        else:
            self.__account.pay_money(money)
            # self.__dict[]
            self.__dict_shopping_cart.clear()

            return True

    def charge(self):
        """
            充值
        :return:
        """
        while True:
            money = int(input("请输入你要充值的金额:"))
            self.__account.charge(money)
            print("充值成功\n1: 是否继续充值 0:退出")
            is_pay = input("")
            if is_pay == '1':
                money = int(input("请输入你要充值的金额:"))
                self.__account.charge(money)
            elif is_pay == '0':
                break
            else:
                print("您的选择有误")


class CommodityInManagerView:
    def __init__(self, commodity_control):
        self.__commodity_control = commodity_control

    def __display_menu(self):
        print("(1) 购买")
        print("(2) 结算")
        print("(3) 查看购物车")
        print("(4) 清空购物车")
        print("(5) 查看账户余额")
        print("(6) 充值")

    def __select_menu_item(self):
        number = input("请输入选项:")
        if number == '1':
            if self.__commodity_control.buy():
                print("商品已成功添加到购物车")
            else:
                print("添加购物车失败")
        elif number == '2':
            if self.__commodity_control.pay():
                print("支付成功")
            else:
                print("支付失败")
        elif number == '3':
            self.__commodity_control.print_dict_shopping_cart()

        elif number == '4':
            if self.__commodity_control.clear_shopping_cart():
                print("购物车清空啦")
            else:
                print("您的购物车什么都没有哦")
        elif number == "5":
            self.__commodity_control.print_account_money()
        elif number == "6":
            self.__commodity_control.charge()
        else:
            print("输入数字有误,请重新输入:")

    def main(self):
        """
            入口逻辑
        :return:
        """
        while True:
            self.__display_menu()
            if not self.__select_menu_item():
                continue


dict_commodity_info = {
    101: {"name": "屠龙刀", "price": 10000, "count": 100},
    102: {"name": "倚天剑", "price": 10000, "count": 1},
    103: {"name": "九阴白骨爪", "price": 8000, "count": 0},
    104: {"name": "九阳神功", "price": 9000, "count": 9},
    105: {"name": "降龙十八掌", "price": 8000, "count": 3},
    106: {"name": "乾坤大挪移", "price": 10000, "count": 1}
}

dict_manager_controller = DictCommodityInfoManagerController(dict_commodity_info)
view = CommodityInManagerView(dict_manager_controller)
view.main()

相关文章

网友评论

    本文标题:MVC控制台实现购物车小程序

    本文链接:https://www.haomeiwen.com/subject/lcqzaqtx.html