完成人机猜拳互动游戏的开发,用户通过控制台输入实现出拳,电脑通过程序中的随机数实现出拳,每一局结束后都要输出结果。当用户输入n时停止游戏,并输出总结果。
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()