まずはランニング効果を見てみましょう
面倒な作業はせずに、コードに直接進みます
import random
class Role:
def __init__(self, name=None, score=0):
self.name = name
self.score = score
def chooseRole(self):
roleOptions = ('张三', '李四', '王二麻子')
while True:
choice = input('请选择角色:1. 张三 2. 李四 3. 王二麻子').strip()
if choice in '123' and len(choice) == 1:
self.name = roleOptions[int(choice) - 1]
print('您选择的角色是{0}。'.format(self.name))
return
else:
print('输入错误,请重新选择。')
def showFist(self):
fistOptions = ('剪刀', '石头', '布')
while True:
yourstake = input('请出拳:1. 剪刀 2. 石头 3. 布').strip()
if yourstake in '123' and len(yourstake) == 1:
print('{0}出“{1}”'.format(self.name, fistOptions[int(yourstake) - 1]))
return fistOptions[int(yourstake) - 1]
else:
print('输入错误,请重新输入。')
def __str__(self):
return '角色名称:{}'.format(self.name)
class Computer:
def __init__(self, name='电脑', score=0):
self.name = name
self.score = score
def showFist(self):
rdom = random.choice(['剪刀', '石头', '布'])
print('{0}出“{1}”'.format(self.name, rdom))
return rdom
class Game:
noWin = 0
role = Role()
computer = Computer()
def startGame(self):
print(' 人机猜拳 '.center(100, '-'))
self.role.chooseRole()
while True:
roleFist = self.role.showFist()
computerFist = self.computer.showFist()
self.judgeWinner(roleFist, computerFist)
gameOver = input('是否结束游戏?任意键继续,按“y”退出。').strip()
if gameOver.lower() == 'y':
break
self.showResult()
print('对战结束')
def judgeWinner(self, rFist, cFist):
fistComp = ('剪刀', '石头', '布')
if rFist == cFist:
print('平局')
self.noWin += 1
elif fistComp.index(rFist) + 1 == fistComp.index(cFist) or fistComp.index(rFist) - 2 == fistComp.index(cFist):
print('{0}赢'.format(self.computer.name))
self.computer.score += 1
else:
print('{0}赢'.format(self.role.name))
self.role.score += 1
def showResult(self):
print(' {0} VS {1} '.center(100, '-').format(self.role.name, self.computer.name))
print('{0}赢 {1} 局。'.format(self.role.name, self.role.score))
print('{0}赢 {1} 局。'.format(self.computer.name, self.computer.score))
print('平局 {0} 次。'.format(self.noWin))
if self.role.score > self.computer.score:
print('{0}赢了!'.format(self.role.name))
elif self.role.score == self.computer.score:
print('双方打平!')
else:
print('{0}赢了!'.format(self.computer.name))
game = Game()
game.startGame()