import random
class Person(object):
#属性:name,score分数,出拳的名字cqname
#方法:选择人物,出拳
name = None
score = 0
cqname = None
def __init__(self,name=None,score=0,cqname=None):
self.name = name
self.score = score
self.cqname = cqname
def perName(self):
while True:
option = input('请输入角色编号-1.曹操 2.张飞 3.刘备:')
if option.isdigit():
option = int(option)
if option == 1:
self.name = '曹操'
break
elif option == 2 :
self.name = '张飞'
break
elif option == 3:
self.name = '刘备'
break
else:
print('所选编号不在范围内,请选择有效编号!')
else:
print('请输入数字,编号是数字形式!')
print('您选择的角色是:{}'.format(self.name))
def chuquan(self):
cqnum = random.randint(1,3)
if cqnum == 1:
self.cqname = '剪刀'
elif cqnum == 2:
self.cqname = '石头'
else:
self.cqname = '布'
print('{0}出的是{1}'.format(self.name,self.cqname))
return self.cqname
#电脑
import random
class Computer:
name = '电脑'
score = 0
cqname = None
def chuquan(self):
cqnum = random.randint(1, 3)
if cqnum == 1:
self.cqname = '剪刀'
elif cqnum == 2:
self.cqname = '石头'
else:
self.cqname = '布'
print('电脑出的是{}'.format(self.cqname))
return self.cqname
#开始游戏
class Game:
count = 0 #平局次数
per = Person() #对象作为属性
com = Computer() #对象作为属性
def startGame(self):
print('人机游戏'.center(60,'-'))
self.per.perName()
while True:
presult = self.per.chuquan()
cresult = self.com.chuquan()
self.getResult(presult,cresult)
isgo = input('是否继续游戏?y/n').lower().strip()
if isgo != 'y':
break
self.vs()
print('游戏结束!')
def getResult(self,presult,cresult):
if presult == cresult:
self.count += 1
elif (presult == '剪刀' and cresult == '布') or (presult == '石头' and cresult =='剪刀') or (presult == '布' and cresult == '石头'):
self.per.score += 1
else:
self.com.score += 1
print('一共{0}局,平局{1}次,{2}赢了{3}次,电脑赢了{4}次'.format(self.count+self.per.score+self.com.score,self.count,self.per.name,self.per.score,self.com.score))
def vs(self):
if self.per.score == self.com.score:
print('平局')
elif self.per.score > self.com.score:
print('恭喜{0}胜出'.format(self.per.name))
else:
print('电脑胜出')
game = Game()
game.startGame()
人机猜拳
最新推荐文章于 2019-08-23 16:10:25 发布