在完成一項家庭作業時,我必須撰寫三個函式來創建一個簡單的 21 點游戲。
- 第一個函式
card_to_value接受一個代表卡片的 str ,該函式回傳每張卡片的 int 值,其中 'A' 僅回傳 11。 - 第二個函式計算給定手牌的硬分,其中 'A' 為 11,而不管手牌中有多少 A。
- 第三個函式計算軟得分,其中手牌中的第一個“A”為 11,但所有后續 A 的值為 1,因此例如手牌“AAA”在軟得分函式中應回傳 13,而在硬得分函式中回傳 33 .
我的代碼目前適用于前兩個函式,但不會為軟評分函式回傳正確的值。
def card_to_value(card=''):
card_list=['2','3','4','5','6','7','8','9','T','J','Q','K','A']
while card in list(card_list):
if card in card_list[8:12]:
card=10
return card
if card in card_list[12:]:
card=1
return card
if card == '2':
card=2
return card
if card == '3':
card=3
return card
if card == '4':
card=4
return card
if card == '5':
card=5
return card
if card == '6':
card=6
return card
if card == '7':
card=7
return card
if card == '8':
card=8
return card
if card == '9':
card=9
return card
def hard_score(hand):
h = list(hand)
total=0
for each in h:
total=total card_to_value(each)
return total
def soft_score(hand):
ace_found=False
h = list(hand)
total = 0
for each in h:
total = total card_to_value(each)
if each == 'A':
ace_found=True
elif ace_found == True:
total = 1
else: total = 11
return total
uj5u.com熱心網友回復:
你要加到total兩次。你需要檢查它是否是一個王牌打電話之前card_to_value。
def soft_score(hand):
ace_found=False
h = list(hand)
total = 0
for each in h:
total = total card_to_value(each)
# handle the aces first
if each == 'A':
if not ace_found :
ace_found=True
total = 11
else :
total = 1
# handle all other cards
else:
total = card_to_value(each)
uj5u.com熱心網友回復:
也許這樣的事情對你有用......
import itertools
# Dictionary of possible card values
card_values = {
'2':[2],
'3':[3],
'4':[4],
'5':[5],
'6':[6],
'7':[7],
'8':[8],
'9':[9],
'T':[10],
'J':[10],
'Q':[10],
'K':[10],
'A':[11,1],
}
# Function that takes a list of cards considered a "hand"
# and returns all possible hand totals
def get_possible_totals(hand):
values=[card_values.get(card) for card in hand]
return [sum(tup) for tup in itertools.product(*values)]
用法示例:
hand = ['5','A','A']
get_possible_totals(hand)
returns:
[27, 17, 17, 7]
uj5u.com熱心網友回復:
我更改了所有函式以顯示如何撰寫它。這對初學者來說可能是太多的投入,但是如果您嘗試并設法理解它(幾天、幾周或幾個月內),您就會學到很多東西。
該card_to_value函式使用字典來獲取卡片的正確值。print(card_values)在此函式中使用以查看構造的字典的外觀。
hard_score顯示了使用sum值生成器的用法。
soft_score使用原始方法。但是由于card_to_value現在回傳11ace,我們從第一個 ace 之后的每個 ace 的總數中減去 10。
def card_to_value(card=''):
card_values = dict(zip('23456789TJQKA', [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]))
return card_values.get(card, 0)
def hard_score(hand):
return sum(card_to_value(card) for card in hand)
def soft_score(hand):
ace_found = False
total = 0
for card in hand:
total = card_to_value(card)
if card == 'A':
if not ace_found:
ace_found = True
else:
total -= 10 # subtract 10 if it is not the first ace
return total
hand = ['3', 'A', '5', 'A']
print(hard_score(hand))
print(soft_score(hand))
這將列印出30和20。
獎勵版本soft_score:
def soft_score(hand):
return hard_score(hand) - max(hand.count('A') - 1, 0) * 10
思路:數一數手中的 A 數,減去 1,留下最小值0,乘以 10,然后從硬分中減去。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348106.html
上一篇:在for回圈中向資料框添加新列
