用Python核心編程破解游戲練習(xí)題中的難題
如果你在游戲練習(xí)題中遇到一些令你痛疼的問題時,以下的文章就是對Python核心編程中關(guān)于游戲練習(xí)題的實際操作中遇到相關(guān)問題的解決,以及相關(guān)代碼的詳細分析,以下是文章的具體介紹。
Python核心編程中的一個游戲練習(xí)題
根據(jù)書上的題目,偶擴展了一下,寫成了一個游戲機器人自動游戲比賽策劃說明:先定義一個基類:AutoPeople,類中存在一個全局類成員,所有隊員有效GameDic = {'石頭':'剪刀','剪刀':'布','布':'石頭'}含義為 石頭>剪刀>布>石頭 等然后需要定義一個分數(shù)值 Score
代碼如下:
- PythonCode: # -*- coding: gbk -*-
- import time,random
- class BaseAuto:
- GameDic = {'石頭':'剪刀','剪刀':'布','布':'石頭'}
- def __init__(self):
- self.score = 0
- def OutHandle(self):
- return None
- class AutoPeopl1(BaseAuto):
- def OutHandle(self):
- return self.GameDic.keys()[0]
- class AutoPeople2(BaseAuto):
- def OutHandle(self):
- return self.GameDic.keys()[random.randint(0,2)]
- class DoStart:
- def __init__(self,Pa,Pb):
- self.pa = Pa
- self.pb = Pb
- def Play(self,PlayCount):
- self.pa.score = 0
- self.pb.score = 0
- PjCount = 0
- for i in range(0,PlayCount):
- paT = time.clock()
- paValue = self.pa.OutHandle()
- paT = time.clock() - paT
- pbT = time.clock()
- pbValue = self.pb.OutHandle()
- pbT = time.clock() - pbT
- if (paT > 100) or (pbT > 100):
- if paT > 100:
- self.pa.score -= 5
- if pbT > 100:
- self.pb.score -= 5
- continue
- if (paT > 10) or (pbT >10):
- if paT > 10:
- self.pa.score -= 1
- if pbT > 10:
- self.pb.score -= 1
- print '-*-*-*-*-*-*-*-*-*第%d局-*-*-*-*-*-*-*-*-*\n
機器人1出:%s\n機器人2出:%s'%(i+1,paValue,pbValue)- if self.pa.GameDic[paValue] == pbValue:
- self.pa.score += 5
- print '機器人1勝利'
- elif self.pb.GameDic[pbValue] == paValue:
- self.pb.score += 5
- print '機器人2勝利'
- else:
- PjCount += 1
- print '最后得分:\n機器人1得分:%d\n機器人2得分:%d\n
平局%d'%(self.pa.score,self.pb.score,PjCount)- def GameTest():
- p1 = AutoPeopl1()
- p2 = AutoPeople2()
- playgame = DoStart(p1,p2)
- inputI = 'sdf'
- count = 0
- while not inputI.isdigit():
- inputI = raw_input('請輸入一個數(shù)字')
- print 'test'
- if inputI.isdigit():
- count = int(inputI)
- break
- else: print ('請輸入一個數(shù)字')
- playgame.Play(count)
- if __name__ == "__main__":
- GameTest()
以上的文章就是對Python核心編程中的一個游戲練習(xí)題的實際操作方案與其相關(guān)代碼的介紹。
【編輯推薦】