相信很多的小伙伴小時候都有玩過剪刀石頭布的游戲吧那么你和電腦玩過嗎?以下是小編用Python腳本寫的剪刀石頭布的小游戲。
1、電腦贏的情況
電腦(computer) | 玩家(player) |
---|---|
石頭 (stone) | 剪刀(scissors) |
剪刀 (scissor) | 布(cloth) |
布 (cloth) | 石頭(stone) |
2、玩家贏的情況
玩家 (player) | 電腦(computer) |
---|---|
石頭 (stone) | 剪刀(scissors) |
剪刀 (scissor) | 布(cloth) |
布 (cloth) | 石頭(stone) |
根據(jù)以上規(guī)則我們可以用 if 的形式來做到,代碼如下:
import random
C_G = ['stone','scissor','cloth']
computer = random.choice(C_G)
player = input('please enter your choice(stone,scissor,cloth):')
if computer == 'stone':
if player == 'stone':
print('\033[33mdraw\033[0m')
elif player == 'scissor':
print('\033[32myou lose!!!\033[0m')
else:
print('\033[31myou win!!!\033[0m')
if computer == 'scissor':
if player == 'scissor':
print('\033[33mdraw\033[0m')
elif player == 'stone':
print('\033[31myou win!!!\033[0m')
else:
print('\033[32myou lose!!!\033[0m')
if computer == 'cloth':
if player == 'cloth':
print('\033[33mdraw\033[0m')
elif player == 'scissor':
print('\033[31myou win!!!\033[0m')
else:
print('\033[32myou lose!!!\033[0m')
print('your choice:%s' % player,'computer choice:%s' % computer )
進階一
可以把贏的情況寫在一個列表中這樣可以讓上面的腳本更精簡些
import random
C_G = ['stone','scissor','cloth']
computer = random.choice(C_G)
WinList = [['stone','scissor'],['scissor','cloth'],['cloth','stone']]
player = input('please enter your choice(stone,scissor,cloth):')
if computer == player:
print('\033[33mdraw\033[0m')
elif [player,computer] in WinList:
print('\033[33myou win!!\033[0m')
else:
print('\033[32myou lose!!!\033[0m')
print('your choice:%s' % player,'computer choice:%s' % computer )
進階二
為了更加方便玩我們分別用數(shù)字 0, 1, 2 代替:石頭(stone)、剪刀(scissor)、布(cloth)
import random
C_G = ['stone','scissor','cloth']
computer = random.choice(C_G)
WinList = [['stone','scissor'],['scissor','cloth'],['cloth','stone']]
choice_memu = '''
(0)stone
(1)scissor
(2)cloth
please choice(0/1/2):'''
number = int(input(choice_memu))
player = C_G[number]
if computer == player:
print('\033[33mdraw\033[0m')
elif [player,computer] in WinList:
print('\033[33myou win!!\033[0m')
else:
print('\033[32myou lose!!!\033[0m')
print('your choice:%s' % player,'computer choice:%s' % computer )
進階三
我們用三局兩勝的手段來決出最后的冠軍如果是平局就繼續(xù)猜直至電腦贏了兩局或者玩家贏了兩局才得出最后的冠軍。
import random
C_G = ['stone','scissor','cloth']
computer = random.choice(C_G)
WinList = [['stone','scissor'],['scissor','cloth'],['cloth','stone']]
choice_memu = '''
(0)stone
(1)scissor
(2)cloth
please choice(0/1/2):'''
c_win = 0
p_win = 0
d_win = 1
while c_win < 2 and p_win < 2:
number = int(input(choice_memu))
player = C_G[number]
if computer == player:
d_win+=1
elif [player,computer] in WinList:
p_win+=1
if p_win == 2:
print('\033[31myou win!!!\033[0m')
break
else:
c_win+=1
if c_win == 2:
print('\033[32myou lose!!!\033[0m')
break
total_time = p_win + c_win + d_win
print('you guesse: %s times' % total_time,'you lost: %s times' % c_win,'you win: %s times' % p_win,'draw: %s times' % d_win)
以上就是小編對剪刀石頭布小游戲的編寫思路了,希望小伙伴們能夠有所收獲。
推薦好課:Python Flask建站框架、Python Django框架。