项目:猜拳游戏
'''
猜拳游戏
分析类:属性、方法
自己玩家:Player 选角色[“美羊羊”,“喜羊羊”,"沸羊羊"]
出拳 石头1 剪刀2 布3
计算机玩家:Computer 选角色[“1美羊羊”,“2喜羊羊”,"3沸羊羊"] 随机选角
随机出拳
game类,包含了整个游戏流程,让玩家选角色、出拳、计算机选角色、出拳、比较出拳,显示解决
再玩一次
赢+1分
可以循环玩
当游戏结束之后,可以提示计算机和玩家的分数
'''
import random
class Player:
roles = ['美羊羊', '喜羊羊', '沸羊羊']
fists = ['石头', '剪刀', '布']
def __init__(self):
self.role = ''
self.fist = ''
self.score = 0
def choose_role(self):
print(Player.roles)
while True:
choose = input('请选择角色:(1-3)')
if choose.isdigit():
c = int(choose)
if c > 0 and c < 4:
self.role = Player.roles[c - 1]
break
else:
print('输入错误!')
continue
else:
print('输入错误')
continue
def choose_fist(self):
print(Player.fists)
while True:
choose = input('请出拳:(1-3)')
if choose.isdigit():
c = int(choose)
if c > 0 and c < 4:
self.fist = Player.fists[c - 1]
break
else:
print('输入错误!')
continue
else:
print('输入错误')
continue
class Computer:
roles = ['美羊羊', '喜羊羊', '沸羊羊']
fists = ['石头', '剪刀', '布']
def __init__(self):
self.role = ''
self.fist = ''
self.score = 0
self.__name ='abc'
def choose_role(self):
index = random.randint(0, 2)
self.role = Computer.roles[index]
def choose_fist(self):
index = random.randint(0, 2)
self.fist = Computer.fists[index]
def test_computer(self):
self.choose_role()
self.choose_fist()
print('{}:{}'.format(self.role, self.fist))
print(self.__name)
class Game:
def __init__(self):
self.p = Player()
self.c = Computer()
self.score = 0
def get_start(self):
flag = input('是否开始游戏?(y/n):')
if flag == 'y':
self.init_role()
while True:
self.init_fist()
self.compare_fist()
chose = input('是否继续游戏?(y/n):')
if chose == 'n':
break
print('玩家{}赢:{},电脑{}赢:{},平均:{}'.format(self.p.role, self.p.score, self.c.role, self.c.score, self.score))
def init_role(self):
self.p.choose_role()
self.c.choose_role()
def init_fist(self):
self.p.choose_fist()
self.c.choose_fist()
def compare_fist(self):
if self.p.fist == self.c.fist:
print('平局')
self.score += 1
elif (self.p.fist == '石头' and self.c.fist == '剪刀') or (self.p.fist == '剪刀' and self.c.fist == '布') or (
self.p.fist == '布' and self.c.fist == '石头'):
print('玩家赢')
self.p.score += 1
else:
print('电脑赢')
self.c.score += 1