原型模式

只有在调用时才会占用资源

骑士类

class Knight(object):
    def __init__(self, level):
        self.unit_type = 'Knight'
        if level == 1:
            self.life = 400
            self.speed = 5
            self.attack_power = 3
            self.attack_range = 1
            self.weapon = 'short sword'

        elif level == 2:
            self.life = 400
            self.speed = 5
            self.attack_power = 6
            self.attack_range = 1
            self.weapon = 'short sword'

    def __str__(self):
        return f'Type: {self.unit_type} \n' \
               f'Life: {self.life} \n' \
               f'Speed: {self.speed} \n' \
               f'Attack Power: {self.attack_power} \n' \
               f'Attack Range: {self.attack_range} \n' \
               f'Weapon: {self.weapon} \n'

射手类

class Archer(object):
    def __init__(self, level):
        self.unit_type = 'Archer'
        if level == 1:
            self.life = 200
            self.speed = 7
            self.attack_power = 1
            self.attack_range = 5
            self.weapon = 'short bow'
        elif level == 2:
            self.life = 200
            self.speed = 7
            self.attack_power = 3
            self.attack_range = 10
            self.weapon = 'long bow'

    def __str__(self):
        return f'Type: {self.unit_type} \n' \
               f'Life: {self.life} \n' \
               f'Speed: {self.speed} \n' \
               f'Attack Power: {self.attack_power} \n' \
               f'Attack Range: {self.attack_range} \n' \
               f'Weapon: {self.weapon} \n'

建筑类

class Barracks(object):
    def build_unit(self, unit_type, level):
        if unit_type == 'knight':
            return Knight(level)
        elif unit_type == 'archer':
            return Archer(level)

调用

barracks = Barracks()
knight1 = barracks.build_unit('knight', 1)
archer1 = barracks.build_unit('archer', 2)
print(f'[knight1] {knight1}')
print(f'[archer1] {archer1}')

输出

[knight1] Type: Knight 
Life: 400 
Speed: 5 
Attack Power: 3 
Attack Range: 1 
Weapon: short sword 

[archer1] Type: Archer 
Life: 200 
Speed: 7 
Attack Power: 3 
Attack Range: 10 
Weapon: long bow 

文件 Knight_1.dat

400
5
3
1
short sword

文件 Archer_1.dat

200
7
3
10
Logn Bow
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇