用了几个小时,逐步写完,还有很多不完善的地方。
本来是要做个类的练习,写着写着就多了,有100行了,学习了一个多月的python。
有文件存储和读取,设置参数等。后续再完善,基本框架有了。
import time
import os
#定义一个猫的动物的类,接着继承定义一个猫的类
class Animal():
def __init__(self,name='小花',age=1,color='白色',weight=0):
self.name=name
self.age=age
self.color=color
self.weight=weight
def animal_info(self):
print(f"动物名称是:{self.name}\n它的年龄是:{self.age}\n它的毛色是{self.color},\n它的体重是{self.weight}KG")
def set_info(self,name='小花',color='白色',age=1):
self.name=name
self.age=age
self.color=color
save_animal(self)
def eat(self,food):
self.weight+=0.1
print(f'{self.name}吃了食物{food},它的体重增加0.1KG,现在它的体重是{self.weight}')
save_animal(self)
def play(self):
print(f"{self.name}正在和主人玩耍,健康提升1点!")
class Cat(Animal):
def __init__(self,name='小花',age=1,color='白色',weight=0):
super().__init__(name,age,color,weight)
def play(self):#重写玩耍函数,提供猫类独特的玩耍
print(f'{self.name}正在玩猫抓老鼠的游戏!')
def save_animal(animal):#保存游戏的动物数据
save_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
with open('data.txt','w',encoding='utf-8') as f:
# animal_str=animal.name+str(animal.age)+animal.color+str(animal.weight)
# print(animal_str)
f.write(animal.name+'\n')
f.write(str(animal.age)+'\n')
f.write(animal.color+'\n')
f.write(str(animal.weight)+'\n')
f.write('保存时间:\n'+save_time)
print(animal.name,'数据已经保存')
def read_animal(cat):#读取保存的动物数据,赋值给Cat类对象
with open('data.txt','r',encoding='utf-8') as f:
cat.name=f.readline().strip()
cat.age=f.readline().strip()
cat.color=f.readline().strip()
cat.weight=float(f.readline().strip())
cat.time=f.readline()#跳过这行读取下行的保存时间
cat.time=f.readline()#读取保存时间
print(f"动物名称是:{cat.name}\n它的年龄是:{cat.age}\n它的毛色是{cat.color},\n它的体重是{cat.weight}KG")
#通过用户输入数据属性初始化小猫的参数
def init_cat(cat):
save_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
file_exists=os.path.exists('data.txt')
if(file_exists==False):
print('文件不存在,新建数据文件')
with open('data.txt','w') as f:
name=input('请输入你专属小猫的昵称:')
color=input('请输入你专属小猫的颜色(白色、灰色、黄色、黑色)')
f.write(name+'\n')
f.write('1\n')
f.write(color+'\n')
f.write('0\n')
f.write('保存时间:\n'+save_time)
cat.name=name
cat.color=color
else:
print('宠物已经存在,请不要新建宠物,请继续游戏!')
#主程序开始
cat1=Cat()
file_exists=os.path.exists('data.txt')
if(file_exists==False):
print('你是首次进入游戏,请先输入 1 新建宠物!')
while True:
print('请输入对应数字选择游戏选项:\n\
1.新建宠物:\n\
2.读取存档:\n\
3.显示宠物档案\n\
4.喂养宠物\n\
5.陪宠物玩耍\n\
6.修改宠物信息\n\
7.保存并退出游戏')
input_num=input()
if(input_num=='1'):
init_cat(cat1)
if(input_num=='2'):
read_animal(cat1)
if(input_num=='3'):
cat1.animal_info()
if(input_num=='4'):
cat1.eat('小鱼')
if(input_num=='5'):
cat1.play()
if(input_num=='6'):
cat1.name=input('请输入你专属小猫的昵称:')
cat1.color=input('请输入你专属小猫的颜色(白色、灰色、黄色、黑色)')
save_animal(cat1)
if(input_num=='7'):
save_animal(cat1)
break