You can use a dict
here:
Example:
>>> card_vals = {"Jack" : 5, "Queen": 15, "King": 20, "Ace":10}
>>> card_vals.update({ x:x for x in range(2,11)})
>>> card_vals["Jack"]
5
>>> card_vals["Jack"]
5
>>> card_vals[2]
2
>>> card_vals[5]
5
質問
I just started learning to program last week and I'm having trouble writing a blackjack program. I can generate a deck list but I can't seem to think of a way to assign the cards values according to the rules of blackjack. Like face cards are equal to 10, ace can be 1 or 1,1 and the rest are equal to their face value. I know my code is probably a mess to you guys, but I would rather continue with it and make mistakes and learn, rather than copy and pastes a pros work. So could you give me some tips to assign the cards values, thanks.
Here is what I have so far
import random
import time
deck = []
hand = []
dealer_hand = []
def deck_shuffle():
for suit in ["Clubs", "Dimonds", "Hearts", "Spades"]:
for face in ["Jack", "Queen", "King", "Ace"]:
deck.append([face, suit])
for num in range(2, 11):
deck.append([num, suit])
random.shuffle(deck)
return deck
def deal_cards():
for x in range(0,2):
deal_card = deck.pop(0)
hand.append(deal_card)
deal_card = deck.pop(0)
dealer_hand.append(deal_card)
deck_shuffle()
deal_cards()
print (deck)
print("Dealers hand is", dealer_hand)
print("Your hand is", hand)
解決
You can use a dict
here:
Example:
>>> card_vals = {"Jack" : 5, "Queen": 15, "King": 20, "Ace":10}
>>> card_vals.update({ x:x for x in range(2,11)})
>>> card_vals["Jack"]
5
>>> card_vals["Jack"]
5
>>> card_vals[2]
2
>>> card_vals[5]
5
他のヒント
I would do something like this
class Card:
def __init__(self,suit,value):
self.suit = suit
self.value = value
def __str__(self):
return "A,2,3,4,5,6,7,8,9,10,J,Q,K".split(",")[self.value]+" of "+["Clubs", "Dimonds", "Hearts", "Spades"][self.suit]
def getValue(self):
if 0 <self.value < 10: return self.value + 1
if self.value == 0: return 11
return 10
class Deck:
def __init__(self):
self.cards = [Card(i,j) for i in range(4) for j in range(13)]
self.cards.shuffle()
d = Deck()
print d.cards[0]
print d.cards[0].getValue()