Python-购物车系统

# coding=utf-8
import os, pickle


class color:
    def echo_error(self, red):
        print(f"\033[31;1m {red}\033[0m".strip())

    def echo_ok(self, green):
        print(f"\033[32;1m {green}\033[0m".strip())

    def echo_warn(self, warning):
        print(f"\033[33;1m {warning}\033[0m".strip())


color = color()


def file_open(file, mode, *args):
    if mode == "wb":
        data = args[0]
        with open(file, mode) as f:
            pickle.dump(data, f)
    elif mode == "rb":
        with open(file, mode) as f:
            user_dict = pickle.load(f)
            return user_dict
    elif mode == "clear":
        with open(file, mode) as f:
            data = args[0]
            pickle.dump(data, f)


def user(user, pwd, mode):
    file = user + ".db"
    if mode == "regist":
        if not os.path.isfile(file):
            user_dict = {"name": user, "pwd": pwd, "stat": 0}
            file_open(file, "wb", user_dict)
            color.echo_ok("注册成功!")
        else:
            color.echo_error("用户已注册")

    elif mode == "login":
        if os.path.isfile(file):
            user_dict = file_open(file, "rb")
            if user_dict["name"] == user and user_dict["pwd"] == pwd:
                color.echo_ok("登录成功")
                return user_dict
            else:
                color.echo_error("登录失败,用户名或密码错误")
        else:
            color.echo_error("不存在此用户,请先注册")
            return None
    else:
        color.echo_error("错误")


def shopping(user_dict, list_goods):
    if user_dict["shopping_car"]:
        list_shopping = user_dict["shopping_car"]
    else:
        list_shopping = []

    while True:
        color.echo_ok("商品列表如下:\n"
                      "##########################\n"
                      "序号 商品名称 商品价格")
        for i, k in enumerate(list_goods):
            print(i, k["name"], k["price"])
        chooice = input("请输入购买商品序号 [t 查看购物车 q 退出]")
        if not chooice: continue

        if chooice.isdigit() and 0 <= int(chooice) < len(list_goods):
            num = input("请输入要购买的数量")
            if num.isdigit():
                num = int(num)
            else:
                color.echo_error("数量必须是正整数")
            goods = {"name": list_goods[int(chooice)]["name"], "num": num,
                     "total_price": list_goods[int(chooice)]["price"] * num}

            list_shopping.append(goods)
            color.echo_ok("购物成功!")
        elif chooice == "t":
            color.echo_ok("#########购物清单##########")
            print("商品名   数量    价格")
            if len(list_shopping) == 0:
                color.echo_warn("您没有购买任何东西..")
                any = input("输入任意字符继续..")
                if any: continue
                continue
            price = 0
            for i in list_shopping:
                print(i["name"], i["num"], i["total_price"])
                price += i["total_price"]
            chooice = input("总价格:%s,是否购买(yes/no),[e 查看余额 c 清空购物车]:" % price)
            if chooice == "c":
                list_shopping = []
                user_dict["shopping_car"] = list_shopping
                color.echo_ok("购物车清空成功")
                file_open(user_dict["name"] + ".db", "wb", user_dict, "clear")
            elif chooice == "e":
                color.echo_ok("您的余额为 %s" % user_dict["money"])
            elif chooice == "yes":
                if user_dict["money"] > price:
                    res_money = user_dict["money"] - price
                    color.echo_ok(f"购买成功,您的余额为 {res_money}")
                    list_shopping = []
                    user_dict["shopping_car"] = list_shopping
                    user_dict["money"] = res_money
                    file_open(user_dict["name"] + ".db", "wb", user_dict, "clear")
                    any = input("输入任意字符继续..")
                    if any: continue
                else:
                    color.echo_error("您的余额不够买这些东西,挣点钱再来吧。")
            elif chooice == "no":
                color.echo_warn("您取消购买")
                any = input("输入任意字符继续..")
                if any: continue

        elif chooice == "q":
            color.echo_warn("退出程序")
            break


def start(list_goods):
    while True:
        print('''
        1. 注册
        2. 登录并购物
        3. 登出
        ''')
        chooce = input(">>>").strip()
        if chooce == "1":
            username = input("请输入你的用户名:").strip()
            pwd = input("请输入你的密码:").strip()
            user(username, pwd, "regist")
        elif chooce == "2":
            username = input("请输入你的用户名:").strip()
            pwd = input("请输入你的密码:").strip()
            user_dict = user(username, pwd, "login")
            if user_dict == None: continue
            if user_dict["stat"] == 0:
                money = int(input("请输入你的首冲金额:"))
                user_dict["stat"] += 1
                user_dict["money"] = money
                user_dict["shopping_car"] = []
                color.echo_ok("恭喜,充值成功!,可以尽情购物了~")
                file_open(user_dict["name"] + ".db", "wb", user_dict)
                shopping(user_dict, list_goods)
            else:
                shopping(user_dict, list_goods)

        elif chooce == "3":
            break
        else:
            color.echo_error("非法操作,请重输入")


if __name__ == "__main__":
    list_goods = [
        {"name": "苹果", "price": 10},
        {"name": "芒果", "price": 20},
        {"name": "提子", "price": 30},
        {"name": "香蕉", "price": 40},
    ]

start(list_goods)

posted @ 2019-09-10 18:53  GeminiMp  阅读(545)  评论(0编辑  收藏  举报