生成5张扑克牌

时间:2012-12-29 17:56:45

标签: python loops poker

我一直在努力为IRC制作扑克游戏机器人,但我似乎无法理解这些卡片。

我知道这个算法效率很低,但是我能用最新的Python技能做到最好。欢迎任何改进!

玩家是一个字典,其中键是玩家的昵称,价值是他们拥有的金额。

当代码运行时,如果只有1个播放器,则它会提供5张卡片。但是如果有2个玩家,则每个玩家可以生成4到6张牌。我还没有测试更多的玩家。

预先初始化的一些变量:

numberOfPlayers = 0 #The numerical value of the amount of players in the game
players = {} #The nickname of each player and the amount of money they have
bets = {} #How much each player has bet
decks = 1 #The number of decks in play
suits = ["C","D","H","S"] #All the possible suits (Clubs, Diamonds, Hearts, Spades)
ranks = ["2","3","4","5","4","6","7","8","9","J","Q","K","A"] #All the possible ranks (Excluding jokers)
cardsGiven = {} #The cards that have been dealt from the deck, and the amount of times they have been given. If one deck is in play, the max is 1, if two decks are in play, the max is 2 and so on...
hands = {} #Each players cards

代码:

def deal(channel, msgnick):
    try:
        s.send("PRIVMSG " + channel + " :Dealing...\n")
        for k, v in players.iteritems():
               for c in range(0, 5):
                suit = random.randrange(1, 4)
                rank = random.randrange(0,12)
                suit = suits[suit]
                rank = ranks[rank]
                card = rank + suit
                print(card)
                if card in cardsGiven:
                    if cardsGiven[card] < decks:
                        if c == 5:
                            hands[k] = hands[k] + card
                            cardsGiven[card] += 1
                        else:
                            hands[k] = hands[k] + card + ", "
                            cardsGiven[card] += 1
                    else:
                        c -= 1
                else:
                    if c == 5:
                        hands[k] = hands[k] + card
                        cardsGiven[card] = 1
                    else:
                        hands[k] = hands[k] + card + ", "
                        cardsGiven[card] = 1
            s.send("NOTICE " + k + " :Your hand: " + hands[k] + "\n")
    except Exception:
        excHandler(s, channel)

如果需要任何示例或进一步说明,请询问:)

6 个答案:

答案 0 :(得分:4)

for循环

for c in range(0, 5):

...

    c -= 1

不幸的是,这不是for循环在Python中的工作方式 - 递减c不会导致循环的另一次转变。 for循环遍历在循环开始之前修复的一组项目(例如range(0,5)是在循环期间未修改的5个项目的固定范围。)

如果你想做你正在做的事情,你需要使用while循环(它通过一个变量和条件,在循环过程中可以被修改) :

c = 0
while c < 5:
    c += 1

    ...

    c -= 1

range()编号

if c == 5:

此案例目前尚未被点击,因为range(N)生成的数字序列从0变为N-1 - 例如range(5)生成0,1,2,3,4

答案 1 :(得分:2)

我会使用itertools.product将卡片的可能值放入列表中,然后随机播放,并为每个玩家提供5张卡片。

from itertools import product
from random import shuffle

suits = ["C","D","H","S"] 
ranks = ["2","3","4","5","4","6","7","8","9","J","Q","K","A"]

cards = list(r + s for r, s in product(ranks, suits))
shuffle(cards)

print cards[:5], cards[5:10] # change this into a suitable for loop to slice
['4D', 'KC', '5H', '9H', '7D'] ['2D', '4S', '8D', '8S', '4C']

您可以使用itertools中的以下食谱来获取接下来的5张牌,具体取决于玩家的数量。

def grouper(n, iterable, fillvalue=None):
    from itertools import izip_longest
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

hand = grouper(5, cards) 
for i in xrange(5): # deal for 5 players...
    print next(hand) # each time we call this, we get another 5 cards

('4D', 'KC', '5H', '9H', '7D')
('2D', '4S', '8D', '8S', '4C')
('AD', '2H', '4S', 'KS', '9S')
('6H', 'AH', '4H', '5S', 'KD')
('6S', 'QD', '3C', 'QC', '8H')

答案 2 :(得分:0)

使用切片来实现这一目标的简单方法可能是:

num_players = 5
num_cards_per_player = 5
remaining_cards = list(range(100)) # Imagine a list backing a Deck object
num_cards_to_deal = num_players * num_cards_per_player
cards_to_deal, remaining_cards = (remaining_cards[0:num_cards_to_deal],
        remaining_cards[num_cards_to_deal:])
cards_for_each_player = [cards_to_deal[player_num::num_players] for
        player_num in range(num_players)]
cards_for_each_player
[[0, 5, 10, 15, 20], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]]

对于特定类型的套牌,您可以实现Deck对象并使用稍微修改的上述代码以用于方法。套牌对象将需要处理剩余卡片数量不足的情况:),这可能与您正在玩的游戏有关。

答案 3 :(得分:0)

#! /usr/bin/python3.2

import random

players = ['Alice', 'Bob', 'Mallroy']
suits = ["C","D","H","S"]
ranks = ["2","3","4","5","4","6","7","8","9","J","Q","K","A"]
decks = 2
cards = ['{}{}'.format (s, r)
         for s in suits
         for r in ranks
         for d in range (decks) ]

random.shuffle (cards)
for player in players:
    print ('{}\'s hand is {}'.format (player, cards [:5] ) )
    cards = cards [5:]

答案 4 :(得分:0)

只需使用Python deuces库,它专为此类用途而构建:

from deuces import Card
from deuces import Deck

# create deck and shuffle it
deck = Deck()
deck.shuffle()

# play a texas hold 'em game with two players
board = deck.draw(5)
player1_hand = deck.draw(2)
player2_hand = deck.draw(2)

# now see which hand won
from deuces import Evaluator
evaluator = Evaluator()
p1handscore = evaluator.evaluate(board, player1_hand)
p2handscore = evaluator.evaluate(board, player2_hand)

答案 5 :(得分:0)

from random import randint

# This code below creates a deck
cards = []
for suit in ["diamond","club","heart","spade"]:
    for card in ['A','2','3','4','5','6','7','8','9','10','J','Q','K']:
        cards.append(card+' '+suit)
# To deal the cards we will take random numbers
for i in range(5):
    a = randint(0,len(cards)-1)
    print cards(a)
    del cards[a] # We will delete the card which drew

首先我们创建一个套牌,然后我们用randint随机抽取一个随机数,然后我们用随机数画一张卡

我有一个程序来抽出翻牌和手牌

def create_card():
    cards = []
    for suit in   [r'$\diamondsuit$',r'$\clubsuit$',r'$\heartsuit$',r'$\spadesuit$']:
        for card in  ['A','2','3','4','5','6','7','8','9','10','J','Q','K']:
            cards.append(card+suit)
    return cards

def create_board_and_hand():
    cards = create_card()
    board = []
    for i in [0,1,2,3,4]:
    a  = randint(0,len(cards)-1)
    board.append(cards[a])
    del cards[a]
    hand = []
    for i in [0,1]:
        a  = randint(0,len(cards)-1)
        hand.append(cards[a])
        del cards[a]
    return board,hand

board,hand = create_board_and_hand()