私は、2枚のカードを扱う簡単なカードゲームを作っています。カードが同じスーツ、同じランク(値)、またはプレイで勝った場合は勝ちます。プレイヤーの手にこれらの特性がない場合、プレイヤーは負けます。次のように私が使用していたコードは次のとおりです。単純なカードゲーム(パイソン)
from itertools import product
import random
class Card(object):
FACES = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}
def __init__(self, rank, suit):
self.suit = suit
self.rank = rank
def __str__(self):
value = self.FACES.get(self.rank, self.rank)
return "{0} of {1}".format(value, self.suit)
def __lt__(self, other):
return self.rank < other.rank
class Deck(object):
def __init__(self, ranks=None, suits=None):
if ranks is None:
ranks = xrange(2, 15)
if suits is None:
suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
self.deck = []
for r in ranks:
for s in suits:
self.deck.append(Card(r, s))
def deal(self, n):
return random.sample(self.deck, n)
ranks = xrange(2, 15)
suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
deck = Deck()
hand = deck.deal(2)
print "Your hand is"
print " - ".join(map(str, hand))
suits_in_hand = []
for card in hand:
suits_in_hand.append(card.suit)
if all(suits_in_hand == suit for suit in suits):
print "\nAll cards are of the same suit"
print "You Win!"
elif all(suits_in_hand == rank for rank in ranks):
print "\nAll cards are of the same rank"
print "You Win!"
# I don't know how to test if the cards in the player's hand are a run
else:
print "\nYou Lose."
しかし、カードが同じスーツ(例えば「2スペードの」と「スペードの3」)または同じランクの両方であっても(例えば「2の「ハーツ」と「クラブの2つ」)は、You Lose
を出力します。この問題を解決するにはどうすればいいですか?また、プレーヤーの手札にあるカードが実行されているかどうかをテストするために、elif
ステートメントを追加するにはどうすればよいですか。
はない 'すべて(suits_in_hand ==スーツスーツスーツ)'スーツのリストかどうかを確認していすべての可能なスーツに等しいですか? –