Example #1
0
def startRound(numplayers, cardsperplayer):  #startRound(3,[1,2,4])
    deck = standardDeck()
    print "Shuffling..."
    shuffle(deck)
    print "Dealing..."
    players = dealUneven(deck, numplayers, cardsperplayer)
    return players
Example #2
0
def deal_cards():
    deck1 = deck.Deck()
    deck.shuffle()
    list1 = []
    list2 = []
    for x in range(5):
        card1 = deck1.draw_a_card()
        card2 = deck1.draw_a_card()
        list1.append(card1)
        list2.append(card2)
    return list1, list2
Example #3
0
def test_deck_shuffle():
    """Want to be able to shuffle it"""
    deck = Deck()
    with pytest.raises(TypeError):
        deck.shuffle(1)  # No values (for now)
    unmoved_cards = 0
    deck.shuffle()
    for i in xrange(52):
        card = deck.deal()
        if card == Card(i // 13, i % 13):
            unmoved_cards += 1
    print unmoved_cards
    assert unmoved_cards < 5  # It would be weird if this was higher
 def test_Three_Cards(self):
     deck = ["A", "B", "C"]
     inRange = True
     i = 0
     combos = list()
     for k in range(6):
         combos.append(0)
     while (i < 1000):
         deck = d.shuffle(deck)
         if (deck == ["A", "B", "C"]):
             combos[0] = combos[0] + 1
         elif (deck == ["A", "C", "B"]):
             combos[1] = combos[1] + 1
         elif (deck == ["B", "A", "C"]):
             combos[2] = combos[2] + 1
         elif (deck == ["B", "C", "A"]):
             combos[3] = combos[3] + 1
         elif (deck == ["C", "B", "A"]):
             combos[4] = combos[4] + 1
         elif (deck == ["C", "A", "B"]):
             combos[5] = combos[5] + 1
         i += 1
     for j in range(6):
         if (combos[j] < 50 or combos[j] > 282):
             inRange = False
     self.assertEquals(inRange, True)
     #Checks to see if the deck items are altered
     deck.sort()
     self.assertEquals(deck, ["A", "B", "C"])
Example #5
0
def reset_cards(MainWindow):
    #reshuffle deck obviously and remove card images
    global global_c_count
    global_c_count = 0
    deck.shuffle()
    for x in card_widgets:
        x.hide()
        x.destroy()
    print("here1")
    print(card_widgets)
    print("here2")
    card_widgets.clear()
    comm_cards.clear()
    plyr_ranks.clear()
    plyr_cards.clear()
    print(card_widgets)
 def test_Two_Cards(self):
     deck = ["A", "B"]
     notDifferent = True
     i = 0
     while (notDifferent and i < 1000):
         if (d.shuffle(deck) != ["A", "B"]):
             notDifferent = False
         i += 1
     self.assertEquals(notDifferent, False)
     #Checks to see if the deck items are altered
     deck.sort()
     self.assertEquals(deck, ["A", "B"])
 def test_Full_Deck(self):
     deck = [
         "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS",
         "QS", "KS", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H",
         "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C",
         "8C", "9C", "10C", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D",
         "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD"
     ]
     freshDeck = [
         "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS",
         "QS", "KS", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H",
         "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C",
         "8C", "9C", "10C", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D",
         "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD"
     ]
     notDifferent = True
     i = 0
     while (notDifferent and i < 10):
         if (d.shuffle(deck) != freshDeck):
             notDifferent = False
         i += 1
     self.assertEquals(notDifferent, False)
Example #8
0
def init():
  playingDeck = deck.createDeck()
  playingDeck = deck.shuffle(playingDeck)
  canvas.data.playingDeck = playingDeck #stores list of cards in deck
  canvas.data.playerHand = []#stores list of cards in player's hand
  canvas.data.dealerHand = []#stores list of cards in dealer's hand
  canvas.data.playerCardImages = []#stores list of images in player's hand
  canvas.data.playerHandVal = 0#stores value of player's hand
  canvas.data.totalAmount = 1000#stores value of money in the bank
  canvas.data.bet = 0#stores the value of the bet
  canvas.data.dealerHandVal = 0#stores value of dealer hand
  canvas.data.dealerCardImages = []#stores list of images in dealer's hand
  canvas.data.topCard = PhotoImage(file = "155.gif")#stores the image of the top of the card
  canvas.data.dealerDone = False#stores the boolean value to determine if the dealer is done playing
  canvas.data.playerDone = False#stores the boolean value to determine if the player is done playing
  canvas.data.playerBusted = False#stores the boolean value to determine if the player busted
  canvas.data.dealerBusted = False#stores the boolean value to the determine if the dealer busted
  promptForBet()#gets and stores the bet
  drawTable()#draws the green table and also the bank amount and bet amount
  setUpBoard()#hits the player twice, hits the dealer once
  drawValueOfPlayerHand()#draws the value of the player's hand
  drawValueOfDealerHand()#draws the value of teh dealer's hand
Example #9
0
def resetGame():
  if(canvas.data.totalAmount > 0 and canvas.data.playerDone and canvas.data.dealerDone):
    playingDeck = deck.createDeck()
    playingDeck = deck.shuffle(playingDeck)
    canvas.data.playingDeck = playingDeck #stores list of cards in deck
    canvas.data.playerHand = []#stores list of cards in player's hand
    canvas.data.dealerHand = []#stores list of cards in dealer's hand
    canvas.data.playerCardImages = []#stores list of images in player's hand
    canvas.data.playerHandVal = 0#stores value of player's hand
    canvas.data.bet = 0#stores the value of the bet
    canvas.data.dealerHandVal = 0#stores value of dealer hand
    canvas.data.dealerCardImages = []#stores list of images in dealer's hand
    canvas.data.dealerDone = False
    canvas.data.playerDone = False
    canvas.data.playerBusted = False
    canvas.data.dealerBusted = False
    promptForBet()
    drawTable()
    setUpBoard()
    drawValueOfPlayerHand()
    drawValueOfDealerHand()
  elif(canvas.data.totalAmount <= 0 and canvas.data.playerDone and canvas.data.dealerDone):
    tkMessageBox.showinfo(title = "You Lost", message = "Congratulations! You are bad at gambling!\nThis game will now exit.")
    root.destroy()
Example #10
0
def create_deck():
    deck = Deck()
    deck.shuffle()
    return deck
Example #11
0
e = 9999
i = 0
tries = 1000
results = {
    "HIGH_CARD": 0,
    "ONE_PAIR": 0,
    "TWO_PAIR": 0,
    "THREE_OF_A_KIND": 0,
    "STRAIGHT": 0,
    "FLUSH": 0,
    "FULL_HOUSE": 0,
    "FOUR_OF_A_KIND": 0,
    "STRAIGHT_FLUSH": 0
}
for i in range(0, tries):
    deck.shuffle(d)
    if i % 10000 == 0:
        print(i, "finished")
    for j in range(0, 7):
        aHand = [
            d[0 + j * 7], d[1 + j * 7], d[2 + j * 7], d[3 + j * 7],
            d[4 + j * 7], d[5 + j * 7], d[6 + j * 7]
        ]
        e = poker.eval7hand(aHand)
        results[poker.valueDescriptor(e)] += 1

for key in results:
    print("RESULTS", key, results[key])
    print("EXPECTED:", key, tables.prob[key] * tries * 7)

Example #12
0
async def on_message(message):
    # don't respond to self, empty messages, or things that don't start with a bang
    if message.author == client.user or \
       len(message.content) == 0 or \
       message.content[0] != "!":
        return

    # we've got a potential command, format it
    cmd = cleanMessage(message.content)
    intArg = 0
    outStr = None

    # extract any integer argument passed in
    if re.search(intRegEx, cmd) != None:
        intArg = int(re.search(intRegEx, cmd)[0])

    # bot info
    if cmd == "thingroller":
        outStr = msgDict["botInfo"]
        for key in msgDict["recognizedCommands"]:
            outStr += "\n  " + key + " " + msgDict["recognizedCommands"][key]
        outStr += "\n" + msgDict["commandNotes"]
    elif cmd == "status":
        outStr = msgDict["goodStatus"]
        addr = getIPAddress()
        outStr = "{}\nHostname: {}\nIP Address: {}".format(
            outStr, addr[0], addr[1])

    # dice expression examples
    if cmd == "examples":
        outStr = "__Examples of Things I Can Calculate__:\n"
        outStr += msgDict["formatExamples"] + "\n"
        outStr += msgDict["formatNotes"]

    # stat block
    if cmd == "stat block":
        outStr = rollStatBlock()

    # roll tavern
    if re.search("^tavern", cmd):
        outStr = generateTavern(intArg)

    # roll interlude
    if cmd == "interlude":
        outStr = generateInterlude()

    #roll some dice and/or calculate
    if re.search(shouldCalcRegEx, cmd) != None:
        outStr = resolveDiceExpr(cmd.replace("*", "x"))
        if outStr == None:
            outStr = msgDict["parsingFailure"].format(cmd)

    #relic generator
    if cmd == "relic":
        outStr = generateRelic()

    #draw cards
    if re.search("^draw", cmd):
        num_to_draw = max(1, intArg)
        num_to_draw = min(52, num_to_draw)
        outStr = ""
        for i in range(num_to_draw):
            outStr = outStr + str(deck.drawCard()) + " "

    #generate quests
    if re.search("^quest", cmd):
        num_of_quests = max(1, intArg)
        num_of_quests = min(5, num_of_quests)
        outStr = ""
        for i in range(num_of_quests):
            outStr = outStr + quest_gen.generate() + "\n"
        outStr = outStr.strip()

    #shuffle cards
    if cmd == "shuffle":
        deck.shuffle()
        outStr = "Deck reshuffled"
    if cmd == "shuffle jokers" or cmd == "jokers":
        deck.shuffle(True)
        outStr = "Deck reshuffled (jokers included)"
    if cmd == "shuffle no jokers" or cmd == "no jokers":
        deck.shuffle(False)
        outStr = "Deck reshuffled (jokers excluded)"

    #name generator
    if re.search("^name", cmd):
        outStr = generateNames(cmd, intArg)

    if outStr != None:
        await message.channel.send(outStr)
Example #13
0
import card
import deck
import hand
import balance
import game
import go

# Start game
game = game.Game()

# Create Deck and shuffle
deck = deck.Deck()
deck.createDeck()
deck.shuffle()

# Bring in starting stack
stack = input("How much would you like to bring to the table? ")
player_balance = balance.Balance(int(stack))

while not game.is_finished:

    print("Your balance is: {}".format(player_balance.get_balance()))

    bet = input("What would you like to bet? ")
    bet = int(bet)
    r = go.Round(bet)
    if not player_balance.bet_accepted(r.bet):
        print('Bet too much! Please choose a smaller amount')
        while not player_balance.bet_accepted(r.bet):
            bet = input("What would you like to bet? ")
            bet = int(bet)
Example #14
0
import deck
import time

###### initializing ######
print("Innitializing Game")
print("Lets play a game of 20 Points")
print("I'll be your dealer today.")
print("I'm opening a pack of regular poker cards")
main_deck = deck.populatePokerDeck()
time.sleep(3)  # delays for 5 seconds

print("Shuffling them now.")
deck.shuffle(main_deck)
time.sleep(5)  # delays for 5 seconds
print("Laying out cards now")
inventory = deck.split(main_deck, 10)
negative_pile = []
positive_pile = []
hand = []
print(
    "Hand is empty. 10 cards in inventory. Positive and Negative Piles are empty"
)
operation = "A"
while operation != "Q":
    print("l to look at inventory")
    print("t to take card from main deck")
    print("Q to quit")
    operation = input("What action do you want to take?")
    print("You chose " + operation)
    if operation == "l":
        deck.revealAll(inventory)
Example #15
0
'''
War Card Game
'''
import card
import deck


def deal(new_deck):
    player1 = new_deck[1::2]
    player2 = new_deck[0::2]
    return [player1, player2]


def play_round(hands):
    if hands[0][1].value > hands[1][0].value:
        card = hands[1].pop()
        hands[0].append(card)
    elif hands[0][1].value < hands[1][0].value:
        card = hands[0].pop()
        hands[1].append(card)
    else:
        war(hands)


new_deck = deck.Deck().all_cards
deck.shuffle(new_deck)

hands = deal(new_deck)
print(hands[0][0].value)
print(hands[1][0].value)
Example #16
0
players = {}
player_list = []
# group = input("number of players>")
# for i in range(0, int(group)):
    # name = input("Player Name>")
    # players[i] = player.Player(name)
    # player_list.append(i)

players["Todd"] = player.Player("Todd")
player_list.append("Todd")
players["Anish"] = player.Player("Anish")
player_list.append("Anish")
kitty = player.Player("Kitty")

deck = deck.Deck()
deck.shuffle(7)

# opening deal
print("Opening deal!  3 cards to each player, and the Kitty")
for p in players:
    players[p].draw(deck, 3)
    # print(f"{players[p].name}\'s hand")
    # players[p].showHand()

kitty.draw(deck, 3)
print("Kitty Drawn, 3 Cards Face Down")
# kitty.showHand()

print("Opening deal!  Now, 2 cards to each player.")
for p in player_list:
    players[p].draw(deck, 2)
Example #17
0
    async def poker(self, ctx, arg: str = None):
        """["join/leave/deal"] Play poker against other users"""
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()
        embed = discord.Embed(color=0x228b22, title="Poker Table")
        if arg == None:
            cursor.execute(
                f'SELECT user_id, jacks, poker FROM main WHERE poker > 0')
            results = cursor.fetchall()
            if len(results) != 0:
                players = []
                for result in results:
                    players.append(
                        f'{self.client.get_user(int(result[0]))} \u2022 {result[1]} chips'
                    )
                output = ""
                for player in range(len(players)):
                    output += players[player] + "\n"
                embed.add_field(name="Poker players",
                                value=output,
                                inline=False)
            else:
                embed.add_field(name="Empty",
                                value="There is no one at the table now")
            await ctx.send(content=None, embed=embed)
        elif arg.lower() == "join":
            cursor.execute(
                f'SELECT user_id, jacks, poker FROM main WHERE user_id = {ctx.author.id}'
            )
            result = cursor.fetchone()
            if result is None:
                embed.add_field(
                    name="Error!",
                    value="You must register before you can play this game",
                    inline=False)
            else:
                if result[2] is None or int(result[2]) != 1:
                    sql = ("UPDATE main SET poker = ? WHERE user_id = ?")
                    val = (1, ctx.author.id)
                    cursor.execute(sql, val)
                    db.commit()
                    embed.add_field(
                        name="Success!",
                        value="You have successfully joined the poker table",
                        inline=False)
                    embed.set_footer(
                        text=f"You have {result[1]} chips to play with")
                else:
                    embed.add_field(
                        name="Error:",
                        value="You are already sitting at the poker table",
                        inline=False)
            await ctx.send(content=None, embed=embed)
        elif arg.lower() == "leave":
            cursor.execute(
                f'SELECT user_id, jacks, poker FROM main WHERE user_id = {ctx.author.id}'
            )
            result = cursor.fetchone()
            if result is None:
                embed.add_field(
                    name="Error!",
                    value="You must register before you can play this game",
                    inline=False)
            else:
                if result[2] > 0:
                    sql = ("UPDATE main SET poker = ? WHERE user_id = ?")
                    val = (0, ctx.author.id)
                    cursor.execute(sql, val)
                    db.commit()
                    embed.add_field(name="Success!",
                                    value="You have left the table",
                                    inline=False)
                else:
                    embed.add_field(name="Error:",
                                    value="You are not at the poker table",
                                    inline=False)
            await ctx.send(content=None, embed=embed)
        elif arg.lower() == "deal":
            cursor.execute(
                f'SELECT user_id, jacks, poker FROM main WHERE user_id = {ctx.author.id}'
            )
            result = cursor.fetchone()
            if result[2] is None or int(result[2]) == 0:
                embed.add_field(
                    name="Error:",
                    value="Only someone at the poker table can start the game")
                await ctx.send(content=None, embed=embed)
            elif result[2] == 2:
                embed.add_field(name="Error:",
                                value="You are already in a game!")
                await ctx.send(content=None, embed=embed)
            else:
                deck = pydealer.Deck(rebuild=True,
                                     re_shuffle=True,
                                     ranks=POKER_RANKS)
                deck.shuffle()
                cursor.execute(
                    f'SELECT user_id, jacks, poker FROM main WHERE poker = 1')
                results = cursor.fetchall()
                if len(results) == 1:
                    embed.add_field(
                        name="Error:",
                        value=
                        "You cannot start a poker game without any other players",
                        inline=False)
                    await ctx.send(content=None, embed=embed)
                else:
                    hands = []
                    for result in results:
                        sql = (
                            f"UPDATE main SET poker = {2} WHERE user_id = {result[0]}"
                        )
                        cursor.execute(sql)
                        db.commit()
                        player = self.client.get_user(int(result[0]))
                        hand = pydealer.Stack()
                        hand.add(deck.deal(2))
                        hands.append(hand)
                        embed.add_field(name="Your hand:",
                                        value=f"{hand}",
                                        inline=False)
                        await player.send(content=None, embed=embed)
                        embed.remove_field(0)
                    river = pydealer.Stack()
                    river.add(deck.deal(3))
                    # Loop through users prompt to raise/call/fold
                    calls = 0
                    checks = 0
                    pot = 0
                    player_hand = 0
                    bid = 0
                    while len(results) > 1 and len(river) < 5:
                        for result in results:
                            player = self.client.get_user(int(result[0]))
                            embed.add_field(name="River:",
                                            value=f"{river}")  #field(0)
                            embed.add_field(name="Pot:",
                                            value=f'{pot}')  #field(1)
                            embed.add_field(
                                name=f"{player}'s turn:",
                                value=
                                f"{player.mention}! Would you like to `raise (+ bid)`, `fold`, `check`, or `call`?",
                                inline=False)  #field(2)
                            await ctx.send(content=None, embed=embed)
                            msg = await self.client.wait_for(
                                'message',
                                check=lambda message: message.author == player)
                            if msg.content.startswith("raise"):
                                bid = int(''.join(x for x in msg.content
                                                  if x.isdigit()))
                                if bid is None or bid < 0:
                                    bid = 20
                                elif bid > int(result[1]):
                                    bid = int(result[1])
                                sql = (
                                    f"UPDATE main SET jacks = {int(result[1]) - bid} WHERE user_id = {result[0]}"
                                )
                                cursor.execute(sql)
                                db.commit()
                                checks = 0
                                calls = 0
                                embed.remove_field(2)
                                embed.add_field(
                                    name=f"{player}'s turn:",
                                    value=
                                    f"{player} has raised <:chip:657253017262751767> **{bid}** chips",
                                    inline=False)
                                await ctx.send(content=None, embed=embed)
                                pot += bid
                            elif msg.content == "fold":
                                sql = (
                                    f"UPDATE main SET poker = {1} WHERE user_id = {result[0]}"
                                )
                                cursor.execute(sql)
                                db.commit()
                                # Remove player from results
                                results.remove(result)
                                del hands[player_hand]
                                embed.remove_field(2)
                                embed.add_field(name=f"{player}'s turn:",
                                                value=f"{player} has folded",
                                                inline=False)
                                await ctx.send(content=None, embed=embed)
                            else:
                                if bid == 0 or bid is None:
                                    checks += 1
                                    embed.remove_field(2)
                                    embed.add_field(
                                        name=f"{player}'s turn:",
                                        value=f"{player} has checked",
                                        inline=False)
                                    await ctx.send(content=None, embed=embed)
                                    if checks == len(results):
                                        river.add(deck.deal(1))
                                        checks = 0
                                else:
                                    if bid > int(result[1]):
                                        bid = result[1]
                                    sql = (
                                        f"UPDATE main SET jacks = {int(result[1]) - bid} WHERE user_id = {result[0]}"
                                    )
                                    cursor.execute(sql)
                                    db.commit()
                                    embed.remove_field(2)
                                    embed.add_field(
                                        name=f"{player}'s turn:",
                                        value=
                                        f"{player} has called the <:chip:657253017262751767> **{bid}** chip bid",
                                        inline=False)
                                    await ctx.send(content=None, embed=embed)
                                    pot += bid
                                    calls += 1
                                    if calls == len(results) - 1:
                                        calls = 0
                                        bid = 0
                            embed.remove_field(2)
                            embed.remove_field(1)
                            embed.remove_field(0)
                            player_hand = 0
                    # Announce winner of the round
                    if len(results) == 1:
                        await ctx.send(
                            'Only 1 player remains, all others have folded')
                    j = 0
                    for result in results:
                        sql = (
                            f"UPDATE main SET poker = {1} WHERE user_id = {result[0]}"
                        )
                        cursor.execute(sql)
                        db.commit()
                        # prints hands, I want to change that
                        player = self.client.get_user(int(result[0]))
                        embed.add_field(name=f"{player}'s hand:",
                                        value=f'{hands[j]}',
                                        inline=False)
                        j += 1
                    await ctx.send(content=None, embed=embed)

        cursor.close()
        db.close()
Example #18
0
#Allows the user to set up the bank for bets in the future
while(totalAmount == 0):
  print "How much would you like to have in the bank? (enter a number): ",
  try:
    totalAmount = int(raw_input())
  except:
    totalAmount = 0
    continue

print "You are playing with %d decks and have $%d to bet." % (numDecks, totalAmount)

#Creates by playingDeck by adding and shuffling x number of decks as specified by the user
for x in range(0, numDecks):
  playingDeck += deck.createDeck()
  playingDeck = deck.shuffle(playingDeck)

#Makes the user place their bet
while(bet == 0):
  print "How much would you like to bet? (enter a number): ",
  try:
    bet = int(raw_input())
  except:
    bet == 0
    continue

dealerHand = dealer.init(playingDeck)

playerCommands.hitMe(playingDeck, playerHand)
playerCommands.hitMe(playingDeck, playerHand)