大家好,我是尘风,本期给大家用Python实现背包系统。
👩💻博客主页:孤雪落尘风的博客主页
✨欢迎关注🖱点赞🎀收藏⭐留言✒
🔮本文由孤雪落尘风原创,csdn首发!
😘系列专栏:pygame zero特训
🎨你的收入跟你的不可替代成正比
🀄如果觉得博主的文章还不错的话,请三连支持一下博主哦
废话不多说,直接上代码。
代码部分
首先,先定义一个类,命名为bag_tools
clsss bag_tools():
pass
然后,构建初始化魔法函数__init__()初始化类变量
class bag_tools():
def __init__(self,tools_name,tools_nums):
pass
我们目前初始化的变量有:
tools_name: 物品名称
tools_list: 物品列表
tools_nums: 物品数量
throw_things: 丢弃物品数量
del_things: 删除物品数量
self.exchange_person_name: 交换物品主人名字
self.choose_exchange_person_name: 交换物品主人是否同意
然后将其初始化
class bag_tools():
def __init__(self,tools_name,tools_nums):
self.tools_name = tools_name
self.tools_list = {}
self.tools_nums = tools_nums
self.throw_nums = 0
self.del_nums = 0
self.exchange_person_name = ''
self.choose_exchange_person_name = None
然后构建add_things方法
def add_things(self):
try:
self.tools_list[self.tools_name] = int(self.tools_nums)
except Exception as e:
print("You input isn't a number")
finally:
return self.tools_list
# 更改物品在列表中的数量,如果没有,则按数量添加此物品
使用try... except...的原因是防止出现Error
然后构建throw_things方法
def throw_things(self):
try:
self.throw_nums = int(input())
try:
if self.throw_nums > self.tools_list[self.tools_name]:
pass
else:
del self.tools_list[self.tools_name]
except Exception as e:
print("You input isn't a number")
except Exception as e:
pass
然后构建del_things方法
def del_things(self):
try:
self.del_nums = int(input())
try:
if self.del_nums > self.tools_list[self.tools_name]:
pass
else:
del self.tools_list[self.tools_name]
except Exception as e:
print("You input isn't a number")
except Exception as e:
pass
然后构建exchange_things方法
def exchange_things(self,name,choose):
self.exchange_person_name = name
if isinstance(choose,bool):
self.choose_exchange_person_name = choose
else:
print("Please choose again.")
完整代码
class bag_tools():
def __init__(self,tools_name,tools_nums):
self.tools_name = tools_name
self.tools_list = {}
self.tools_nums = tools_nums
self.throw_nums = 0
self.del_nums = 0
self.exchange_person_name = ''
self.choose_exchange_person_name = None
def add_things(self):
try:
self.tools_list[self.tools_name] = int(self.tools_nums)
except Exception as e:
print("You input isn't a number")
finally:
return self.tools_list
def get_things(self):
pass
def exchange_things(self,name,choose):
self.exchange_person_name = name
if isinstance(choose,bool):
self.choose_exchange_person_name = choose
else:
print("Please choose again.")
def throw_things(self,nums):
try:
self.throw_nums = int(nums)
try:
if self.throw_nums > self.tools_list[self.tools_name]:
pass
else:
del self.tools_list[self.tools_name]
except Exception as e:
print("You input isn't a number")
except Exception as e:
pass
def del_things(self,nums):
try:
self.del_nums = int(nums)
try:
if self.del_nums > self.tools_list[self.tools_name]:
pass
else:
del self.tools_list[self.tools_name]
except Exception as e:
print("You input isn't a number")
except Exception as e:
pass