Python 之 老王開槍 練習

2021-09-23 15:37:50 字數 2803 閱讀 5386

知識點:

這篇部落格是對前面python基礎的乙個複習,更應該學到的是如何設計一系列的動作,或者說是設計程式

1.分析有哪些類,並且建立:人 槍 彈夾 子彈 

2.物件的建立

3.各個類的屬性設定

4.類的方法設計,由里向外 ,1》人拿槍 eg :1彈夾裝子彈  2 .槍裝彈夾 3.人拿槍

2》人開槍 eg. 1.槍發射 2 彈夾彈出子彈 再將子彈返回給槍 子彈傷害人

5.物件的建立可以放在迴圈中。

class person(object):

"""人類"""

def __init__(self,name):

super(person, self).__init__()

self.name = name

self.qiang = none

self.ph = 100

def an_zhuangzidan(self,danjia,zidan):

danjia.baocun(zidan)

def an_zhuangdanjia(self,qiang,danjia):

qiang.baocun(danjia)

def naqiang(self,qiang):

self.qiang = qiang

def __str__(self):

if self.qiang == none:

if self.ph>0:

return "%s 沒槍,血量為 %s ph"%(self.name,self.ph)

else:

return "%s 已經掛了.."%self.name

else:

return "%s 有槍,血量為 %s ph %s"%(self.name,self.ph,self.qiang)

def kaiqiang(self,diren):

zidan =self.qiang.sheji()

if zidan:

diren.diaoxue(zidan.weili)

else:

pass

def diaoxue(self,weili):

self.ph -= weili

class qiang(object):

def __init__(self,name):

super(qiang, self).__init__()

self.name = name

self.danjia = none

def baocun(self,danjia):

self.danjia = danjia

def sheji(self):

return self.danjia.tanchuzidan()

def __str__(self):

if self.danjia == none:

return "槍是:%s"%(self.name)

else:

return "槍是:%s,%s"%(self.name,self.danjia)

class zidan(object):

def __init__(self,weili):

super(zidan, self).__init__()

self.weili = weili

class danjia():

def __init__(self,max_size):

super(danjia, self).__init__()

self.max_size = max_size

self.zidan_list =

def baocun(self,zidan):

def __str__(self):

return "彈夾%d/%d"%(len(self.zidan_list),self.max_size)

def tanchuzidan(self):

if self.zidan_list:

return self.zidan_list.pop()

else:

return none

def main():

#1建立老王

laowang = person("laowang")

#2建立敵人

diren = person("diren")

#3建立槍

ak47 = qiang("ak47")

danjia = danjia(100)

#4建立一些子彈

for i in range(15):

zidan = zidan(10)

danjia.baocun(zidan)

#5建立彈夾

#6老王裝子彈2彈夾

laowang.an_zhuangzidan(danjia,zidan)

#7老王裝彈夾2槍

laowang.an_zhuangdanjia(ak47,danjia)

#8老王拿開槍

laowang.naqiang(ak47)

#9敵人建立

diren = person("laosong")

print(diren)

#9老王打敵

print(danjia)

print(ak47)

print(laowang)

for i in range(15):

laowang.kaiqiang(diren)

print(diren)

if __name__ == "__main__":

main()

python基礎練習之老王開槍

class people object def init self,name self.name name self.gun none self.hp 100 def load zidan self,dianjia temp,zidan temp 把子彈裝進彈夾 dianjia temp.anzhu...

Python案例練習 老王開槍

import time class person object 人的類 def init self,name super person,self init self.name name 記錄人的名字 self.gun none 預設人是沒有槍的 self.hp 100 預設人的血量100 defan...

Python案例練習 老王開槍

import time class person object 人的類 def init self,name super person,self init self.name name 記錄人的名字 self.gun none 預設人是沒有槍的 self.hp 100 預設人的血量100 defan...