游戲規則::有21根火柴,人和計算機輪流拿,人先拿(輸入拿幾根)計算機后拿,每次至少1根最多4根,拿到最后一根火柴的算輸,要確保計算機一定可以獲勝
tips:保證計算機最后能拿到20,所以就不能取16~19之間,只能取到15,以此類推,計算機取的火柴數必須使總數到達5,10,15和20,
代碼如下:
rint("規則:一次自能取1~4根火柴,最后取到21為輸家")
#total代表取出的火柴總數
total = 0
while True:
person = int(input('人取多少根火柴: ')) #person表示人取出的火柴數
total += person
print(f'當前取出火柴總數為{total},還剩下{21 - total}')
if total < 5:
computer = 5 - total # computer表示計算機取出的火柴數
total += computer
print(f'計算機拿{computer}根')
print(f'當前取出火柴總數為{total},還剩下{21 - total}')
elif total < 10 :
computer = 10 - total
total += computer
print(f'計算機拿{computer}根')
print(f'當前取出火柴總數為{total},還剩下{21 - total}')
elif total < 15:
computer = 15 - total
total += computer
print(f'計算機拿{computer}根')
print(f'當前取出火柴總數為{total},還剩下{21 - total}')
elif total < 20 :
computer = 20 - total
total += computer
print(f'計算機拿{computer}根')
print(f'當前取出火柴總數為{total},還剩下{21 - total}')
else:
print("游戲結束")
break
結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/290090.html
標籤:python
