[新星计划] Python面向对象练习 | 回合制对战游戏模拟ATMLinux用户管理类

Posted cPen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[新星计划] Python面向对象练习 | 回合制对战游戏模拟ATMLinux用户管理类相关的知识,希望对你有一定的参考价值。


系列文章
https://blog.csdn.net/cpen_web/category_11089219.html


菜鸟教程:面向对象
https://www.runoob.com/python3/python3-class.html


● ①、回合制对战游戏

回合制对战游戏
 
●创建角色:名字、性别、血量、装备   ●战斗
●创建房间:                                              ●装备-防弹衣
●角色可加入房间                                       ●血量默认100
●房间内的人可互打                                   ●正常被攻击-10滴血
●房间上限2人                                            ●有防弹衣-5滴血

class Role():
    def __init__(self,name,sex,blood=100,body_armor=None):
        self.name = name
        self.sex = sex
        self.blood = blood
        self.body_armor = body_armor
        self.room = None
    def attack(self,other):
        if self.room == other.room:	# 注:同一房间
            if self != other:		# 注:不同的人
                if self.blood > 0 and other.blood > 0:
                    reduce_blood = 5 if other.body_armor else 10
				# 注:body_armor为假 返回10(没有设置防弹衣)
                    other.blood -= reduce_blood
                    print(f"{self.name}攻击{other.name} {reduce_blood}点血量\\t{self.name}当前血量:{self.blood}\\t{other.name}当前血量:{other.blood}")
                else:
                    print("其中一方已死亡,不能攻击")
                    exit()
            else:
                print("你不能攻击自己")
        else:
            print("攻击对象,不在同一个房间")
class Room():
    def __init__(self,name):
        self.member = []
        self.name = name
    def join(self,role):
        if role.room == None:
	# 注:在角色的类里定义的属性room
            if len(self.member) < 2:
                self.member.append(role)
		# 注:member房间的属性,房间只能加2个人 所以<2
                role.room = self.name
		# 注:达到条件,定义角色加入到 某个房间
            else:
                print("此房间已满")
        else:
            print("此角色已经加入房间了")

role_dict = {}  # 存放初始化实例	# 注:存放名字和对象的关系
room_dict = {}  # 存放初始化实例
while True:
    print("请选择:1.创建角色\\t2.创建房间\\t3.加入房间\\t4.开始战斗\\t5.退出")
    enter_number = input("请输入你的选择\\t")
    if enter_number.isdigit():
        enter_number = int(enter_number)
        if 1 <= enter_number <=5:
            if enter_number == 1:
                name, sex = input("请输入角色的姓名与性别,空格隔开\\n").split()
		#注:split()是为了 分割 将字符 赋给2个变量
                role_dict[name] = Role(name, sex)
                def_blood = input("输入自定义血量\\n")
                if def_blood.isdigit():
                    role_dict[name].blood = int(def_blood)
                    print(f"自定义成功,用户{name}当前血量{role_dict[name].blood}")
                else:
                    print(f"自定义失败,用户{name}当前血量{role_dict[name].blood}")
                wear_body_armor = input("输入y装备防弹衣\\n")
                if wear_body_armor == "y":
                    role_dict[name].body_armor = 1
            elif enter_number == 2:
                name = input("请输入房间的名字\\n")
                room_dict[name] = Room(name)
		# 注:创建好的对象(实例化对象) 保存在字典里
            elif enter_number == 3:
                print(f"当前角色有{role_dict.keys()},当前房间有{room_dict.keys()}")
                role_name, room_name = input("请输入要加入的角色和房间名,空格隔开\\n").split()
		# 注:这里可以做1个判断 (考虑到各种情况)
                room_dict[room_name].join(role_dict[role_name])
		# 注:从字典 取出房间对象,调用房间对象的join()方法
            elif enter_number == 4:
                print(f"当前房间有{room_dict.keys()}")
                room_name = input("请输入房间的名字\\n")	# 注:选择房间
                if len(room_dict[room_name].member) == 2:
		# 注:len()==2 这是保证房间里有2个人  才能对打
                    while True:
                        room_dict[room_name].member[0].attack(room_dict[room_name].member[1])
                        room_dict[room_name].member[1].attack(room_dict[room_name].member[0])
			# 注:通过字典获取房间实例对象,member是房间的属性
			# 注:为什么房间实例能获取到创建角色类的对象?因为选项3 是角色类属性 加入 房间member属性,保证了这一步能调用成功实例化对象
                else:
                    print(f"房间{room_name}人数不足2人,对战失败!")
                    continue
            elif enter_number == 5:
                print("退出对战")
                break
        else:
            print("输入错误,请输入1-5选择操作!")
    else:
        print("输入错误,请输入1-5选择操作!")

pic1


● ②、模拟ATM

模拟ATM
 
●1、创建ATM
      ○ATM里的总金额
      ○ATM可向里面加钱
      ○ATM里的钱取出来
 
●2、创建账户去取钱
      ○账户属性 名称、余额、密码
      ○账户要选择1台ATM进行操作
      ○可以取钱、存钱、查询余额

class Atm():
    def __init__(self,name,atm_total):
        self.name = name
        self.atm_total = atm_total
    def add(self,money):
        self.atm_total += money
        print(f"机器{self.name}增加金额{money}元,{self.name}当前总金额为{self.atm_total}元")
    def decrease(self,money):
        if self.atm_total < money:
            print(f"{self.name}余额不足,取钱失败")
        else:
            self.atm_total -= money
            print(f"机器{self.name}取出金额{money}元,{self.name}当前总金额为{self.atm_total}元")
class Account():
    def __init__(self,name,balance,passwd):
        self.name = name
        self.balance = balance
        self.passwd = passwd
    def draw(self,atm,money):
        if money <= self.balance:
            if money <= atm.atm_total:
                self.balance -= money
                atm.atm_total -= money
                print(f"成功取款{money}元,{self.name}当前余额为{self.balance}元")
            else:
                print(f"ATM机 {atm.name}余额不足,取款失败!")
        else:
            print("您输入的金额大于您的账户余额,取款失败!")
    def save(self,atm,money):
        self.balance += money
        atm.atm_total += money
        print(f"成功存款{money}元,{self.name}当前余额为{self.balance}元")
    def look(self):
        print(f"{self.name}当前余额为{self.balance}元")

# 管理员操作
def atm_os():
    # 管理员登录验证
    name, paaswd = input("请输入管理员账号和密码,空格隔开\\n").split()
    if (name, paaswd) in admin_dict.items():
        pass
    else:
        print("管理员账号出错")
        return
    while True:
        print("请选择:1.创建ATM\\t2.ATM加钱\\t3.ATM取钱\\t4.返回上一级")
        enter_number = input("请输入你的选择\\t")
        if enter_number.isdigit():
            enter_number = int(enter_number)
            if 1 <= enter_number <= 4:
                # 1、创建ATM
                if enter_number == 1:
                    name, atm_total = input("请输入ATM名称,总金额,空格隔开\\n").split()
                    atm_total = int(atm_total)
                    atm_dict[name] = Atm(name,atm_total)
                    print(f"创建ATM机 {name}成功,{name}当前总金额{atm_total}元")
                # 2、ATM加钱
                elif enter_number == 2:
                    print(f"当前存在的ATM机器:{atm_dict.keys()}")
                    atm_name = input("请输入ATM名称\\n")
                    if atm_name in atm_dict.keys():
                        money = int(input("请输入金额\\n"))
                        atm_dict[atm_name].add(money)
                    else:
                        print(f"{atm_name}不存在")
                # 3、ATM取钱
                elif enter_number == 3:
                    print(f"当前存在的ATM机器:{atm_dict.keys()}")
                    atm_name = input("请输入ATM名称\\n")
                    if atm_name in atm_dict.keys():
                        money = int(input("请输入金额\\n"))
                        if money > 0:
                            atm_dict[atm_name].decrease(money)
                        else:
                            print("取出的金额不能为负")
                    else:
                        print(f"{atm_name}不存在")
                elif enter_number == 4:
                    print("退出ATM操作")
                    break
            else:
                print("输入错误,请输入1-4选择操作")
# 账户操作
def account_os():
    while True:
        print("请选择:1.创建账户\\t2.取钱\\t3.存钱\\t4.查询余额\\t5.返回上一级")
        enter_number = input("请输入你的选择\\t")
        if enter_number.isdigit():
            enter_number = int(enter_number)
            if 1 <= enter_number <= 5:
                # 1、创建账户
                if enter_number == 1:
                    name, balance, passwd = input("请输入账户名称、余额和密码进行创建,空格分割\\n").split()
                    balance = int(balance)
                    account_dict[name] = Account(name,balance,passwd)
                    account_passwd[name] = passwd
                    print(f"创建用户 {name}成功,余额为{balance}")
                elif enter_number == 2 or enter_number == 3 or enter_number == 4:
                    print(f"当前的ATM机有{atm_dict.keys()}")
                    atm, name, passwd = input("请输入您选择的ATM机、您的账户名称和密码进行登陆,空格分割\\n").split()
                    # 验证ATM是否存在
                    if atm in atm_dict.keys():
                        # 验证账户
                        if (name, passwd) in account_passwd.items():
                            atm = atm_dict[atm]
                            # 2、取钱
                            if enter_number == 2:
                                money = int(input("请输入取款金额\\n"))
                                account_dict[name].draw(atm, money)
                            # 3、存钱
                            elif enter_number == 3:
                                money = int(input("请输入存款金额\\n"))
                                account_dict[name].save(atm, money)
                            # 4、查询余额
                            elif enter_number == 4:
                                account_dict[name].look()
                        else:
                            print("账户错误")
                    else:
                        print(f"{atm}不存在")
                elif enter_number == 5:
                    print("退出账户操作")
                    break
            else:
                print("输入错误,请输入1-5选择操作")

admin_dict = {"admin":"123456"} # 管理员信息
account_passwd = {} # 账户信息
atm_dict = {}       # 存放初始化实例
account_dict = {}   # 存放初始化实例
while True:
    print("请选择:1.ATM操作\\t2.账户操作\\t3.退出")
    enter_number = input("请输入你的选择\\t")
    if enter_number.isdigit():
        enter_number = int(enter_number)
        if 1 <= enter_number <= 3:
            # 1、ATM操作
            if enter_number == 1:
                atm_os()
            # 2、账户操作
            elif enter_number == 2:
                account_os()
            else:
                print("退出操作!")
                exit()
        else:
            print("输入错误,请输入1-3选择操作")
    else:
        print("输入错误,请输入1-3选择操作")

pic2


● ③、Linux用户管理类

Linux用户管理类
 
●基类:实现往linux系统里添加用户
●子类A:
  ○能够查看、修改uid和gid、shell等信息    ●子类C(A,B):
●子类B:                                                        ○1.可以单独新建组
  ○1.能删除用户                                              ○2.可以将某个用户的gid修改为新建的组的gid
  ○2.能删除组                                                  ○3.加入异常机制,异常的名字需要自己定义

import subprocess
class Base():
    def add(self,name,passwd):
        subprocess.Popen(f'useradd {name} -p {passwd}&>/dev/null && echo "{name}创建成功" ||echo "创建失败"', shell=True)

class A(Base):
    def look(self,name):
        p = subprocess.Popen(f'cut -d ":" -f 1,3,4,7 /etc/passwd|grep -E ^{name}:', shell=True)
    def modify(self,name,uid,gid,shell):
        p = subprocess.Popen(f'usermod -u {uid} -g {gid} -s {shell} {name}&>/dev/null && echo "修改成功" ||echo "修改失败"', shell=True)

class B(Base):
    def del_user(self,name):
        p = subprocess.Popen(f'userdel -r {name}&>/dev/null && echo "删除成功" ||echo "创建失败"', shell=True)
    def del_group(self,name):
        p = subprocess.Popen(f'groupdel {name}&>/dev/null && echo "删除成功" ||echo "删除失败"', shell=True)

class C(A,B):
    group_member = []
    def group_add(self,gid,name):
        p = subprocess.Popen(f'groupadd -g {gid} {name}&>/dev/null && echo "创建成功" ||echo "创建失败"', shell=True)
        C.group_member.append(gid)
    def gid_modify(self,gid,name):
        if gid in C.group_member:
            p = subprocess.Popen(f'usermod -g {gid} {name}&>/dev/null && echo "修改成功" ||echo "修改失败"', shell=True)
        else:
            print(f"修改失败,{gid}不是新建的组id")

class DefinedError(Exception):
    def __str__(self):
        return "这是自定义异常"

while True:
    print('''请选择:
1.添加用户\\t2.查看uid、gid和shell信息\\t3.修改uid、gid和shell信息
4.删除用户\\t5.删除组\\t6.新建组\\t7.修改用户gid\\t8.触发异常\\t9.退出''')
    enter_number = input("请输入你的选择\\t")
    if enter_number.isdigit():
        enter_number = int(enter_number)
        if 1 <= enter_number <= 9:
            if enter_number == 1:
                sample = Base()
                name, passwd = input("请输入用户名和密码,空格分割\\n(2个参数)\\t").split()
                sample.add(name, passwd)
            elif enter_number == 2:
                sample = A()
                name = input("请输入用户名\\n")
                sample.look(name)
            elif enter_number == 3:
                sample = A()
                name,uid,gid,shell = input("请输入用户名,修改后的uid、gid和shell,空格分割\\n(4个参数)\\t").split()
                sample.modify(name,uid,gid,shell)
            elif enter_number == 4:
                sample = B()
                name = input("请输入用户名\\n")
                sample.del_user(name)
            elif enter_number == 5:
                sample = B()
                name = input("请输入组名\\n")
                sample.del_group(name)
            elif enter_number == 6:
                sample = C()
                name, gid [新星计划] Python面向对象练习 | 回合制对战游戏模拟ATMLinux用户管理类

面向对象编程-回合制游戏

回合对战制游戏第一篇

0.计划用libgdx写一个六边形回合制slg兵棋游戏

iOS-Google Play 游戏服务的可用性回合制多人游戏

Python制作回合制手游外挂简单教程(上)