python-撰寫石頭剪刀布小游戲
1.基本功能能實作版本
#撰寫石頭、剪刀、布的小游戲
import random
pc = random.choice(['石頭', '剪刀', '布'])
player = input('請出拳(石頭/剪刀/布):')
print("你出的拳是:%s,計算機出的拳是: %s" % (player, pc))
if player == '石頭':
if pc == '石頭':
print('平局')
elif pc == '剪刀':
print('你贏了!')
else:
print('你輸了!')
elif player == '剪刀':
if pc == '石頭':
print('你輸了')
elif pc == '剪刀':
print('平局')
else:
print('你贏了')
else:
if pc == '石頭':
print('你贏了')
elif pc == '剪刀':
print('你輸了')
else:
print('平局')
2.精簡版本
#撰寫石頭、剪刀、布的小游戲
import random
pc = random.choice(['石頭', '剪刀', '布'])
player = input('請出拳(石頭/剪刀/布):')
#人能贏的三種情況,寫成串列的形式
win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']]
print("你出的拳是:%s,計算機出的拳是: %s" % (player, pc))
if player == pc:
print('平局')
elif [player, pc] in win_list: #成員關系判斷
print('你贏了')
else:
print('你輸了')
3.升級版本-三局兩勝
#撰寫石頭、剪刀、布的小游戲
import random
all_choice = ['石頭', '剪刀', '布'] #只有三種選擇,定義成串列
win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']] #人能贏的三種情況,寫成串列的形式
prompt = """*********************
(0) 石頭
(1) 剪刀
(2) 布
********************
請出拳(0/1/2):
"""
player_win = 0 #人贏的次數
pc_win = 0 #計算機贏的次數
while player_win < 2 and pc_win < 2:
#注意這里:為什么不是player_win < 2 or pc_win < 2呢?
#or的兩邊有一邊是True,其結果就是True,就往下執行,
#也就是說得等到player_win < 2為True時,且pc_win < 2為True時,回圈才會結束
#and的兩邊有一邊是False,回圈就會結束
pc = random.choice(all_choice)
ind = int(input(prompt)) #把人輸入的數字序號轉換成字符型別
player = all_choice[ind]
print("你出的拳是:%s,計算機出的拳是: %s" % (player, pc))
if player == pc:
print('\033[32m平局\033[0m')
elif [player, pc] in win_list: #成員關系判斷
print('\033[32m你贏了\033[0m')
player_win += 1
else:
print('\033[31m你輸了\033[0m')
pc_win += 1
4.游戲效果


轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/397491.html
標籤:其他
上一篇:Unity 裁剪
下一篇:用C++寫的猜數字游戲
