If you encounter problems that cause you pain in game exercises, the following articles will solve the problems encountered in the actual operations on game exercises in Python core programming, and detailed analysis of the relevant code, the following is a detailed introduction of the article.
A game exercise in Python core programming
According to the questions in the book, I expanded it and wrote a game robot automatic game competition plan description: first define a base class: AutoPeople, which contains a global member, valid GameDic = {'stone ': 'scissors', 'scissors ': 'bus', 'bus ': 'stone '} refers to stone> scissors> Cloth> stone, and a Score value must be defined.
The Code is as follows:
- PythonCode: #-*-coding: gbk -*-
- Import time, random
- Class BaseAuto:
- GameDic = {'stone ': 'scissors', 'scissors ': 'cloth', 'cloth ': 'stone '}
- 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 '-* bureau % d -*-*-*-*-*-*-*-* -* \ n
Robot 1 Output: % s \ n robot 2 output: % s' % (I + 1, paValue, pbValue)
- If self. pa. GameDic [paValue] = pbValue:
- Self. pa. score + = 5
- Print 'Robot 1 Shengli'
- Elif self. pb. GameDic [pbValue] = paValue:
- Self. pb. score + = 5
- Print 'Robot 2 Shengli'
- Else:
- PjCount + = 1
- Print 'final score: \ n robot 1 score: % d \ n robot 2 score: % d \ n
Draw % 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 ('enter a number ')
- Print 'test'
- If inputI. isdigit ():
- Count = int (inputI)
- Break
- Else: print ('enter a number ')
- Playgame. Play (count)
- If _ name _ = "_ main __":
- GameTest ()
The above article introduces the actual operation scheme and related code of a game exercise in Python core programming.