python常用模块(random)学习之实现人和电脑猜拳

import random

all = ['石头','剪刀','布']
computer = random.choice(['石头','剪刀','布'])

#所有赢了的情况
win = [['石头','剪刀'],['布','石头'],['剪刀','布']]

class Text():

    def func_play(self):
        ind = input('请输入【0】石头【1】剪刀【2】布')
        if ind.isalpha():
            try:
                raise ValueError('请输入数字')
            except ValueError as v:
                print(v)
        elif ind.isdigit():
            ind = int(ind)
            if 0<=ind<=2:
                play = all[ind]
                print('你输入的是%s,电脑输入的是%s'%(play,computer))
                if play == computer:
                    self.a = '平局'
                elif [play, computer] in win:
                    self.a = '你赢了'
                else:
                    self.a = '你输了'
            else:
                print('请输入0到2之间的数')
            print(self.a)
    def write_file(self):
        with open('wuhan.txt','a',encoding='utf-8') as f:
            f.write(self.a+'\n')
while True:
    t = Text()
    t.func_play()
    t.write_file()




发布了65 篇原创文章 · 获赞 50 · 访问量 3598

猜你喜欢

转载自blog.csdn.net/qq_44907926/article/details/104582664