我想要打一场纸牌游戏,而目前我正在开始制作纸牌游戏。令我感到困惑的是按照他们的排名对牌进行排序然后适合如何减少重复。目前我可能会为组织卡片制作一个for循环,然后对于每种可能性有52种不同,但我想知道他们是否更容易做到这一点以及很多其他重复性任务。谢谢:D我会把代码放在下面:
from random import shuffle
class deckOfCards:
def __init__(self):
self.rank = ['2','3','4','5','6','7','8','9','T','J','Q','K','A']
self.suit = ['C', 'S', 'H', 'D']
self.deck = [r+s for r in self.rank for s in self.suit]
shuffle(self.deck)
def setValue(self, deck):
cnt = 1
self.value = {}
for i in self.deck:
self.value[i] = cnt
cnt += 1
class Deal:
def __init__(self, deck, position):
self.hand = deck[position::4] #divides the deck into 4 hands
hand = self.hand
def value(self, key): # Gives each card that the player has a value
newHand = {}
for i in self.hand:
if i in key:
newHand[i] = key[i]
return newHand
deck = deckOfCards()
player1 = Deal(deck.deck, 0) #######################################
player2 = Deal(deck.deck, 1) # Example of repetition that I wanted #
player3 = Deal(deck.deck, 2) # to get rid of if possible #
player4 = Deal(deck.deck, 3) #######################################
编辑:我认为这对于排序卡非常有效,但我仍然对如何消除一些重复感到困惑。感谢所有帮助:D
def sortHand(player):
hand = player.hand
for i in hand:
for i in hand:
index = player1.hand.index(i)
if index != 12:
if deck.value[i] > deck.value[hand[index+1]]:
hand.insert(index+1, hand.pop(index))
答案 0 :(得分:5)
我可能会稍微简化一下:
from random import shuffle
class Hand(list):
pass
class Deck(object):
rank = '23456789TJQKA'
suit = 'CSHD'
def deal(self, n):
deck = [r+s for r in Deck.rank for s in Deck.suit]
shuffle(deck)
return [Hand(sorted(deck[i::n], key=Deck.cmpkey)) for i in xrange(n)]
@staticmethod
def cmpkey(card):
return Deck.rank.index(card[0]), Deck.suit.index(card[1])
print Deck().deal(4)
通过这种安排,deal()
的结果是四手牌的列表。每只手按等级排序然后适合。
(我没有完全理解“价值”逻辑,所以我把它从我的例子中删除了。)