1. 程式人生 > >Python:“NPC”小練習

Python:“NPC”小練習

class NPC:
    npc_list = []
    def __init__(self,id,name,jianjie):
        self.id = id
        self.name = name
        self.jianjie = jianjie
        NPC.npc_list.append(self)
    def __str__(self):
        return '{}  {}  {}'.format(self.id,self.name,self.jianjie)

n1 = NPC(1,'阿爾薩斯','使用霜之哀傷的怒火攻擊敵人')
n2 = NPC(2,'吉安娜','使用奧術法術遠端攻擊敵人')
n3 = NPC(3,'烏瑟爾','使用聖光力量治癒友軍')

# NPC.npc_list.extend([n1,n2,n3,n4])

class Player:
    def __init__(self):
        self.team_list = []

    def add_npc(self):
        choice = int(input('選擇NPC的ID:'))
        for i in NPC.npc_list:
            if choice == i.id:
                self.team_list.append(i)
                NPC.npc_list.remove(i)
                print('{}已加入隊伍!'.format(i.name))

    def sub_npc(self):
        choice = int(input('選擇ID:'))
        for i in self.team_list:
            if choice == i.id:
                self.team_list.remove(i)
                NPC.npc_list.append(i)
                print('{}已被踢出隊伍!'.format(i.name))

    def show_npc(self):
        if len(self.team_list)==0:
            print('沒有成員!')
            return
        for i in self.team_list:
            print(i)

if __name__ == '__main__':

    p = Player()
    while True:
        print("-"*30)
        print('可選NPC:')
        for i in NPC.npc_list:
            print(i)
        print('-'*30)
        print('當前隊伍NPC:')
        p.show_npc()
        print('*'*30)
        print('1.邀請組隊\n2.踢出隊伍\n3.完成')
        print('*' * 30)
        caozuo = int(input('請選擇要進行的操作:'))

        if caozuo == 1:
            p.add_npc()
            continue
        elif caozuo == 2:
            p.sub_npc()
            continue
        elif caozuo == 3:
            break
        else:
            print('操作無效!')

在這裡插入圖片描述在這裡插入圖片描述