2014年7月12日 星期六

[Python] 幫我家電子寵物做了一個草皮!


        看著自己的單細胞只能孤獨的為生命倒數計時讓我不僅感到悲傷,為了給他們更好的生存環境,今天早上特別幫他們打造5星級的生存環境!


## create the map
land=[]
class Myland:
##建立一個場景物件
def creatLand(self,size,symbol):
#這邊有兩個參數,size決定邊長,symbol可讓使用者自行輸入想要的圖示
self.symbol = str(symbol) ##不管使用者輸入什麼都轉成str
for i in range(size):##用for迴圈做出i個row
land.append([self.symbol for x in range(size)]) #用內建迴圈做出一個row
def printLand(self,land): ##列印方法
for i in range(len(land)):
print " ".join(land[i])
def setLocate(self,land,name,locate): ##讓寵物出現在地圖上的方法
land[locate[1]][locate[0]] = name[0].upper() ##取名字的第一個字並轉大寫
def cleanLand(self,land,locate): ##當寵物掛點後要清除地圖
land[locate[1]][locate[0]] = self.symbol
myLand = Myland()
myLand.creatLand(10,"艸")
myLand.printLand(land)
"""
馬上就出現草皮了!!
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
"""
view raw gistfile1.py hosted with ❤ by GitHub
看起來很高級吧 XD,為了配合地圖物件,所以原有的細胞生物的程式碼也有些微更動

class monocell(threading.Thread):
lifeCost = 1
def __init__(self,name,life):
threading.Thread.__init__(self)
self.birthTime = datetime.datetime.now()
self.name = name
self.life = life
def run(self):
#print self.name, "is borned, and birth on", self.birthTime
self.locate = setbirthLocate(land) ##多了取得出生地點的方法
myLand.setLocate(land,self.name, self.locate) ##呼叫地圖物件,在地點上顯示位置
heart(self.name, self.life, self.lifeCost)
myLand.cleanLand(land,self.locate)##死亡後更新地圖物件
thread.exit()
def heart(name,life,lifecost):
while True:
if life <= 0:
print name,"is died"
break
#print name, "remain", life,"HP"
time.sleep(1)
life -= lifecost
def setbirthLocate(land): ##新增的方法,用隨機方式產生地點
locate =[0,0]
locate[0] = randint(0,len(land[0])-1)
locate[1] = randint(0, len(land)-1)
return locate
view raw gistfile1.py hosted with ❤ by GitHub
這是出生的結果:

cellMicky = monocell("micky",5)
cellMini = monocell("Kini",7)
#cellLucky = monocell("Lucky",15)
cellMicky.start()
cellMini.start()
myLand.printLand(land)
'''
艸 艸 艸 艸 艸 艸 K 艸 艸 艸 ##全形半形造成位移
艸 艸 艸 艸 M 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
micky is died
Kini is died
'''
myLand.printLand(land)
##死亡後草地又恢復了整潔(誤)
'''
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
艸 艸 艸 艸 艸 艸 艸 艸 艸 艸
'''
view raw gistfile1.py hosted with ❤ by GitHub
目前有幾個缺點:
1. 地圖物件可以接受全形和半形中英數文字(暫時不考慮丟入超過1個字的字串)
    但是細胞生物的命名都是英文半形,在顯示上會造成位移

2. 沒有排除兩個細胞生物假使出生地點剛好在同一個地方的狀況

圖片來源:http://travel.ettoday.net/article/372615.htm


沒有留言:

張貼留言