第一次寫這東西,主要是為了記錄自己的學習歷程,或者說是為了忘記的時候找回來看看,
今天是參加風變編程培訓第10天,昨天晚上完成了第10關關底的猜拳小游戲,
要求:人和電腦輪流出拳,判斷輸贏,
給出串列:punches=['石頭','剪刀','布']
正常代碼如下:(風變給出的標準答案)
n = 0
while n < 10000:
import random
punches = ['石頭','剪刀','布']
computer_choice = random.choice(punches)
user_choice = random.choice(punches)
if user_choice == computer_choice:
print('平局!')
elif (user_choice == '石頭' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '布') or (user_choice == '布' and computer_choice == '石頭'):
print('你贏了!')
else:
print('你輸了!')
import random
n = n+1
拿到題目的第一個印象是,這個串列里,左側贏右側,或者說按照鍵值,小的為贏,讓后想到‘布’的鍵值為2,怎么讓2小于0是一個問題,為了解決這個問題,列出了一個Excel,來解釋這個問題:

根據組合和查看,當電腦選擇布的時候,將其結果強制表達為-1(這個在串列里是允許的)這樣就滿足了左側贏右側的要求,于是我的代碼寫成了下面的樣子:
import random
# 出拳
punches = ['石頭','剪刀','布']
computer_choice = random.choice(punches)
user_choice = ''
user_choice = input('請出拳:(石頭、剪刀、布)') # 請用戶輸入選擇
while user_choice not in punches: # 當用戶輸入錯誤,提示錯誤,重新輸入
print('輸入有誤,請重新出拳')
user_choice = input()
# 亮拳
print('————戰斗程序————')
print('電腦出了:%s' % computer_choice)
print('你出了:%s' % user_choice)
# 勝負
print('—————結果—————')
a=punches.index(computer_choice)
b=punches.index(user_choice)
if a==b:
print('本次和局')
elif a==2:
a=-1
if punches(a,b)in punches:
print('你輸了,')
else:
print('你贏了,')
與標準答案的不同尋常之處用紅色標志了,是不是對程式簡略了?哈哈哈,雖然只是一個小游戲,對于剛剛開始學習編程的我來說還是比較有成就感的,畢竟是一個更加簡略的思路,
有沒有哪位朋友幫忙捧場呢?第一次用這個東西,也不知道有沒有點贊之類,哈哈哈,比較得意了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/240347.html
標籤:Python
上一篇:PHP設計模式之組合模式
