代码改变世界

python面向对象游戏练习:好人坏人手枪手榴弹

2020-11-16 14:34  清风软件测试开发  阅读(255)  评论(0编辑  收藏  举报

python面向对象游戏练习:好人坏人手枪手榴弹

主要是多态的练习,对象作为参数传给方法使用

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 class Bulletbox(object):
 5     def __init__(self,bulletcount):
 6         self.bulletcount = bulletcount
 7 
 8 
9 class Gun(object): 10 def __init__(self,bulletbox): 11 self.bulletbox = bulletbox 12 13 def shoot(self): 14 if self.bulletbox.bulletcount == 0: 15 print('没子弹了') 16 else: 17 self.bulletbox.bulletcount -= 1 18 print(str(self) + '开一枪,还剩%d颗子弹' % (self.bulletbox.bulletcount)) 19 20
21 class Grenade(object): 22 def __init__(self,grenadecount): 23 self.grenadecount = grenadecount 24 25 def damage(self): 26 if self.grenadecount == 0: 27 print('手雷没有了') 28 else: 29 self.grenadecount -= 1 30 print(str(self) + "轰他一炮,手雷还剩%d颗" % (self.grenadecount)) 31 32
33 class Person(object): 34 def __init__(self, gun, grenade, blood): 35 self.gun = gun 36 self.grenade = grenade 37 self.blood = blood 38 39 def fire(self, person): 40 person.blood -= 5 41 self.gun.shoot() 42 print(str(person) + "血量减少5,剩余" + str(person.blood) ) 43 44 def fire2(self, person): 45 person.blood -= 10 46 self.grenade.damage() 47 print(str(person) + "血量减少10,剩余" + str(person.blood) ) 48 49 def fillbullet(self): 50 self.gun.bulletbox.bulletcount += 10 51 52 def fillblood(self,num): 53 self.blood += num 54 if self.blood > 100: 55 self.blood = 100 56 print(str(self) + "补血后血量:" + str(self.blood)) 57 58
59 class Profector(Person): 60 def __init__(self, gun, grenade, blood = 100): 61 super(Profector,self).__init__(gun, grenade, blood) 62 63
64 class Gengster(Person): 65 def __init__(self, gun, grenade, blood=100): 66 super(Gengster, self).__init__(gun, grenade, blood) 67 68
69 bulletbox = Bulletbox(10) 70 gun = Gun(bulletbox) 71 grenade = Grenade(20) 72 73 good1 = Profector(gun,grenade) 74 good2 = Profector(gun,grenade) 75 bad1 = Gengster(gun,grenade) 76 bad2 = Gengster(gun,grenade) 77 78 print("好人1开枪打坏人1和2") 79 good1.fire(bad1) 80 good1.fire(bad2) 81 print("好人2开枪打坏人1和2") 82 good2.fire(bad1) 83 good2.fire(bad2) 84 print("坏人1炸好人1和2") 85 bad1.fire2(good1) 86 bad1.fire2(good2) 87 print("坏人2炸好人1和2") 88 bad2.fire2(good1) 89 bad2.fire2(good2) 90 print("坏人1补血3个") 91 bad1.fillblood(3)

运行结果如下: