gpt4 book ai didi

python - 根据python中的等级和花色对一手牌进行排序

转载 作者:太空狗 更新时间:2023-10-30 02:49:22 25 4
gpt4 key购买 nike

我正打算制作一款纸牌游戏,目前我正在制作它的开头部分。我感到困惑的是,按等级排序手中的牌,然后按花色排序,以及如何减少重复。目前,我可能可以制作一个 for 循环来组织卡片,然后为每种可能性设置 52 个不同的 if,但我想知道它们是否是一种更简单的方法来执行此操作以及许多其他重复性任务。谢谢 :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))

最佳答案

我可能会稍微简化一下:

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() 的结果是四手牌的列表。每手牌按等级排序,然后按花色排序。

(我没有完全理解“值(value)”逻辑,所以我把它从我的例子中去掉了。)

关于python - 根据python中的等级和花色对一手牌进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8511745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com