python實現猜拳游戲項目
本文實例為大家分享了python實現猜拳游戲的具體代碼,供大家參考,具體內容如下
項目功能:
1.系統生成隨機的石頭剪刀布,玩家輸入石頭剪刀布2.因為玩家可能會輸入shitou st這樣的輸入,需要格式化成合理輸入3.進行石頭剪刀布的游戲,輸出游戲結果,假設每次可以玩5局4.將游戲結果寫入到excel中,包括系統出拳,玩家出拳,游戲結果,目前得分5.游戲有歡迎信息(歡迎來到游戲)和用戶交互(游戲剩余次數)6.如果游戲的得分達到0分,游戲也會結束7.在開始游戲的時候要求用戶輸入玩家姓名,會創建于玩家姓名同名的sheet頁8.如果玩家已經存在,則輸出歡迎回來,您目前的積分為:xx分9.如果玩家不存在,則輸出歡迎來到游戲,您目前有5個積分10.當是老玩家,游戲積分為0分,則提示用戶充值,充值1元2積分
代碼如下:
import openpyxlimport randomclass excel: def __init__(self,filename,sheetname):#讀某個單元格的值 self.file = openpyxl.load_workbook(filename) self.sheet = self.file[sheetname] self.name=filename def write(self, sheet, data,num):#將數據以列表形式寫入 sheet = self.file[sheet] for i in range(1, len(data) + 1): sheet.cell(num,i).value = data[i-1] self.file.save(self.name)def formatx(indata): if indata==’shitou’ or indata==’shi tou’ or indata==’st’: indata = ’石頭’ elif indata==’bu’ or indata==’b u’: indata = ’布’ elif indata==’jiandao’ or indata==’jd’: indata=’剪刀’ elif indata==’石頭’ or indata==’布’ or indata==’剪刀’: pass return indatadef getscore(name): wb = openpyxl.load_workbook(’first.xlsx’) sheet = wb[name] maxrow = sheet.max_row maxcol = sheet.max_column score = sheet.cell(maxrow, maxcol).value if score==’積分’: score = 5 print('歡迎來到游戲') else:print('歡迎回來游戲') return scoredef login(name): wb = openpyxl.load_workbook(’first.xlsx’) names = wb.sheetnames if name not in names: wb.create_sheet(name) sheet = wb[name] sheet.cell(1,1).value=’電腦’ sheet.cell(1, 2).value = ’玩家’ sheet.cell(1, 3).value = ’結果’ sheet.cell(1, 4).value = ’積分’ wb.save(’first.xlsx’)if __name__=='__main__': name = input(’請輸入您的名字:’) login(name) score = getscore(name) print('積分{}'.format(score)) if score<=0: print(’請充值:’) money = int(input(’請輸入充值金額’)) score += money*2 opt = excel(’first.xlsx’, name) for num in range(1,6): compute = random.choice([’石頭’,’剪刀’,’布’]) player = input(’請輸入猜拳的內容:’) player=formatx(player) if player==compute: result = [compute,player,’平局’,score] print(’電腦出拳:{},玩家出拳:{},游戲結果:{}’.format(compute,player,result[2],score)) opt.write(name, result,num+1) elif (player==’石頭’ and compute==’剪刀’) or (player==’剪刀’ and compute==’布’) or player==’布’ and compute==’石頭’: score+=1 result = [compute, player, ’玩家勝利’,score] print(’電腦出拳:{},玩家出拳:{},游戲結果:{}’.format(compute, player, result[2],score)) opt.write(name, result,num+1) else: score-=1 result = [compute, player, ’玩家失敗’,score] print(’電腦出拳:{},玩家出拳:{},游戲結果:{}’.format(compute, player, result[2],score)) opt.write(name, result,num+1) if score<=0: break print(’游戲剩余次數:{}’.format(5-num)) print('游戲結束')
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: