python 實現人和電腦猜拳的示例程式碼
阿新 • • 發佈:2020-03-03
完成人機猜拳互動遊戲的開發,使用者通過控制檯輸入實現出拳,電腦通過程式中的隨機數實現出拳,每一局結束後都要輸出結果。當用戶輸入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()
到此這篇關於python 實現人和電腦猜拳的示例程式碼的文章就介紹到這了,更多相關python 人和電腦猜拳內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!