Example #1
0
def command_cards(intext, *args):
    if len(intext) == 0:
        return "A dry wind blows in from the west."
    intext = intext.split(" ")
    subargs = len(intext)
    subcommand = intext[0]
    try:
        # fetch deck from manager. TODO: lock here?
        data = args[0]
        deck = data.get_card_deck()
        user = args[1]
    except Exception as err:
        raise RuntimeError("Can't find cards (data manager failed?)") from err

    ret = None
    if subcommand == "draw":
        count = 1
        if subargs > 1:
            count = int(intext[1])
        drawn = cards.draw(deck, count)
        ret = f"{drawn}"
    elif subcommand == "reset":
        deck = cards.shuffle(cards.build_deck_52())
        ret = "Deck reset and shuffled."
    elif subcommand == "shuffle":
        deck = cards.shuffle(deck)
        ret = f"Deck shuffled."
    elif subcommand == "inspect":
        top = deck[len(deck) - 1] if len(deck) > 0 else None
        bot = deck[0] if len(deck) > 0 else None
        ret = f"{len(deck)} cards in deck. Top card is {top}. Bottom card is {bot}."
    elif subcommand == "history":
        count = 1
        if subargs > 1:
            count = int(intext[1])
        history = data.get_card_logs()
        numbered = [f"{i+1}: {history[i]}"
                    for i in range(len(history))][-count:]
        ret = '\n'.join(numbered)
        if len(numbered) < count:
            ret = "> start of history.\n" + ret
    else:
        return f"Unknown subcommand {codeblock(subcommand)}. {sub_help_notice('cards')}"

    # apply deck changes
    data.set_card_deck(deck)
    # update card log
    data.add_card_log(
        f"{user}: {ret if subcommand != 'history' else 'viewed history.'}")
    return ret
Example #2
0
def deal(deck, numShuffle=7):
    for y in range(numShuffle):
        deck = shuffle(deck) 
    hands = list()
    for player in range(4):
        hands.append(cardSorted([deck[x] for x in range(player, len(deck), 4)]))
    return hands
Example #3
0
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        #colors
        self.color = "#efe5b0"
        self.shadeColor = "#b97957"
        self.selectColor = "#880015"

        #misc
        self.configure(bg=self.color)
        self.cards = cards.shuffle()
        self.turn = False #false is red's turn, true is blue

        #card slots
        self.redToBlue = CardSlot(self, [self.color, self.shadeColor, self.selectColor])
        self.redToBlue.disable()

        self.blue1 = CardSlot(self, [self.color, self.shadeColor, self.selectColor])
        self.blue1.disable()

        self.red1 = CardSlot(self, [self.color, self.shadeColor, self.selectColor])

        self.blue2 = CardSlot(self, [self.color, self.shadeColor, self.selectColor])
        self.blue2.disable()

        self.red2 = CardSlot(self, [self.color, self.shadeColor, self.selectColor])

        self.blueToRed = CardSlot(self, [self.color, self.shadeColor, self.selectColor])
        self.blueToRed.disable()

        #deal the cards into the slots. Note that the redToBlue slot STAYS EMPTY
        self.blue1.changeCard(self.cards[0])
        self.red1.changeCard(self.cards[1])
        self.blue2.changeCard(self.cards[2])
        self.red2.changeCard(self.cards[3])
        self.blueToRed.changeCard(self.cards[4])

        self.selectedCardSlot = 0 #null value

        #add click handlers to all the card slots
        self.redToBlue.butt.configure(command = lambda cardSlot=self.redToBlue: self.select(cardSlot))
        self.blue1.butt.configure(command = lambda cardSlot=self.blue1: self.select(cardSlot))
        self.red1.butt.configure(command = lambda cardSlot=self.red1: self.select(cardSlot))
        self.blue2.butt.configure(command = lambda cardSlot=self.blue2: self.select(cardSlot))
        self.red2.butt.configure(command = lambda cardSlot=self.red2: self.select(cardSlot))
        self.blueToRed.butt.configure(command = lambda cardSlot=self.blueToRed: self.select(cardSlot))

        self.redToBlue.grid(column=0, row=1)
        self.blue1.grid(column=1, row=0)
        self.red1.grid(column=1, row=2)

        self.innerBoard = InnerBoard(self, [self.color, self.shadeColor, self.selectColor], self.turn)
        self.innerBoard.grid(column=2, row=0, rowspan=3)

        self.blue2.grid(column=3, row=0)
        self.red2.grid(column=3, row=2)
        self.blueToRed.grid(column=4, row=1)
Example #4
0
def prepPlayers():
    deck = cards.new_Deck()
    deck = cards.shuffle(
        randrange(20, 40), deck
    )  # call functions from the cards module to create and shuffle a new deck of cards

    deal_with_decks = cards.deal(deck, 26, 2)

    players_cards = deal_with_decks[0]
    players = []
    for player_cards in players_cards:
        h1 = fillHand(adt_.new_Queue(), player_cards)
        players.append(
            h1
        )  # Adds the element to the back of the player queue data structure

    return players
Example #5
0
def reset():
    global deck, tableau, states, stacks, undeck
    deck = cards.getSortedDeck()
    deck = cards.shuffle(deck)
    undeck = []
    tableau = []
    for col in range(7):
        tableau.append([])
        for card in range(col + 1):
            tableau[col].append(deck.pop())
    stacks = [(0,0) for x in range(4)]
    
    states = [[DOWN, DECK]]*52
    for index, col in enumerate(tableau):
        for rowIndex, card in enumerate(col):
            states[cards.getCardIndex(card)] = [DOWN, [index, rowIndex]]
            if rowIndex == len(col) - 1:
                states[cards.getCardIndex(card)][0] = UP
Example #6
0
def main(stdscr):
    init(stdscr)

    n_players = 1
    game_over = False

    players = [Player() for x in range(n_players)]
    dealer = Player()
    dealer.is_dealer = True
    dealer.name = "Dealer"

    players[0].name = "Player 1"
    players[0].starting_cash = 100000
    players[0].cash = players[0].starting_cash
    # players[1].name = "Player 2"
    # players[1].starting_cash = 5000
    # players[1].cash = players[1].starting_cash

    deck = cards.Deck()
    cards.shuffle(deck)
    discard_pile = []

    # Tests --------------------------------------------------------- |

    # deck[51] = cards.Card(10, 1)    # player 1
    # deck[50] = cards.Card(8, 2)     # player 2
    # deck[49] = cards.Card(11, 3)    # dealer
    # deck[48] = cards.Card(5, 1)     # player 1
    # deck[47] = cards.Card(8, 2)     # player 2
    # deck[46] = cards.Card(1, 3)     # dealer

    # ----------------------------------------------------------------|

    while not game_over:

        round_over = False
        print_deck(deck)

        # Get bets
        for player in players:

            clear_options()

            if player.cash > 0:
                option_list[0] = "(B)et"
                if player.bet > 0:
                    option_list[0] = "(N)ew Bet"
                    option_list[1] = "(B)et Again"
                if player.bet != max_bet and player.bet != player.cash:
                    option_list[2] = "(M)ax Bet"
                option_list[3] = "(C)ash Out"
                print_options()

                print_player_details(player)
                log("%s, place a bet or cash out:" % player.name)
                log(
                    "(Table limits: £%s to £%s)" %
                    ("{:,}".format(min_bet), "{:,}".format(max_bet)), False)

                valid_input = False
                while not valid_input:
                    input = stdscr.getkey()
                    if input == "B" or input == "b" and player.bet == 0:
                        valid_input = get_bet(player)
                    elif input == "N" or input == "n" and player.bet > 0:
                        valid_input = get_bet(player)
                    elif input == "B" or input == "b" and player.bet > 0:
                        valid_input = get_last_bet(player)
                    elif input == "M" or input == "m" and player.bet != max_bet:
                        valid_input = get_max_bet(player)
                    elif input == "C" or input == "c":
                        log("%s cashes out" % player.name)
                        print_exit_status(player)
                        player.is_playing = False
                        valid_input = True
                        stdscr.getkey()
            else:
                log("Thanks for playing, %s!" % player.name)
                print_exit_status(player)
                player.is_playing = False

        # End game if all cashed out
        playing_count = 0
        for player in players:
            if player.is_playing:
                playing_count += 1
        if playing_count == 0:
            game_over = True

        # Play round
        if not game_over:

            clear_card_windows()
            # Deal initial cards
            log("Dealing cards...")
            for i in range(2):
                for player in players:
                    deal_card(deck, player, False)
                    print_player_details(player)
                deal_card(deck, dealer, False)

            if dealer.hand[1].rank == 1:
                dealer.hand.is_insurable = True

            while not round_over:

                for player in players:

                    print_player_details(player)
                    update_hand_windows(player)
                    player.turn_active = True
                    log("Waiting on %s" % player.name)

                    while player.turn_active:

                        assess_hand(player)

                        clear_options()
                        if player.hand.is_hittable:
                            option_list[0] = "(H)it"
                            option_list[1] = "(S)tand"
                            if player.hand.is_doublable:
                                option_list[2] = "(D)ouble"
                            if player.hand.is_splittable:
                                option_list[3] = "S(p)lit"
                            if dealer.hand.is_insurable and not player.is_insured and \
                               player.cash >= player.bet and cards.count(player.hand) == 2:
                                option_list[4] = "(I)nsurance"
                            print_options()

                            valid_input = False
                            while not valid_input:
                                input = stdscr.getkey()

                                if input == "H" or input == "h" and player.hand.is_hittable:
                                    deal_card(deck, player)
                                    valid_input = True
                                elif input == "S" or input == "s" and player.hand.is_standable:
                                    log("%s stands on %d" %
                                        (player.name, player.hand.get_total()))
                                    player.turn_active = False
                                    valid_input = True
                                elif input == "D" or input == "d" and player.hand.is_doublable:
                                    double_down(player)
                                    deal_card(deck, player)
                                    valid_input = True
                                elif input == "P" or input == "p" and player.hand.is_splittable:
                                    pass
                                elif input == "I" or input == "i" and dealer.hand.is_insurable and \
                                   not player.is_insured and player.cash >= player.bet:
                                    buy_insurance(player)
                                    valid_input = True
                        else:
                            if not player.hand.is_blackjack and not player.hand.is_bust:
                                log("%s has %d" %
                                    (player.name, player.hand.get_total()))
                            player.turn_active = False

                dealer.turn_active = True
                update_hand_windows(dealer)

                while dealer.turn_active:

                    assess_hand(dealer)

                    if dealer.hand.get_total() < 17:
                        deal_card(deck, dealer)
                    else:
                        if not dealer.hand.is_blackjack and not dealer.hand.is_bust:
                            log("Dealer has %d" % dealer.hand.get_total())
                        dealer.turn_active = False

                round_over = True

            # Calculate outcome and payout bets
            for player in players:
                calc_outcome(player, dealer)
                payout(player)

            # Discard and reset hands
            for player in players:
                for i in range(cards.count(player.hand)):
                    discard_pile.append(player.hand.pop())
                player.hand.reset()
            for i in range(cards.count(dealer.hand)):
                discard_pile.append(dealer.hand.pop())
            dealer.hand.reset()
Example #7
0
)
print("usamos como base o estilo Texas Hold'em.")
print(
    "ainda não levamos em conta dados como valor de apostas e etc, apenas os turns e as mãos de cada jogador."
)

print("vamos começar com uma partida simples")

s = 's'
while s == 's':
    num_players = 0
    while num_players < 2 or num_players > 10:
        print("Informe o número de jogadores que irão jogar (2-10): ")
        num_players = int(input())

    deck = cards.shuffle()

    players = []
    player_cards = []

    while len(players) < num_players:
        players.append(player.Player([]))

    j = 0
    while j < 2:
        i = 0
        while i < num_players:
            card = deck.pop(len(deck) - 1)
            player_cards.append(card)
            players[i].hand.append(card)
            deck = deck[:-1]  # deck sem a ultima carta
Example #8
0
def newGame():
    global dealerDeck, stayed

    dealerDeck = cards.shuffle(cards.generateDeckArray())
    newHand()

    roundOver = False
    stayed = False
    exit = False

    # Keep going until the player exits or there are not enough cards in the deck
    while len(dealerDeck) > 6:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                sys.exit()  # Player exited the window

            if event.type == pg.MOUSEBUTTONUP:
                # If the round has ended, only let the player click on the deal button
                if roundOver:
                    if buttonElements[2].mouseInElement():
                        roundOver = False
                        stayed = False

                        buttonElements[2].click()
                else:
                    for button in buttonElements:
                        if button.mouseInElement():
                            button.click()

        # Write the green backdrop
        display.fill((60, 180, 45))

        # Cycle through all elements and draw them
        for element in buttonElements + dealerHandElements + playerHandElements:
            element.draw()

        # Player busted
        if handValue(playerHand) > 21:
            announcement("You went bust! Click \"Deal\" to start a new round.")
            roundOver = True

        # Player got a blackjack
        if handValue(playerHand) == 21:
            # Dealer also got a blackjack, causing a tie
            if handValue(dealerHand) == 21:
                # Only flip the card over if they tied
                if not roundOver:
                    dealerHandElements[0].flip()
                announcement(
                    "You tied with the dealer. Click \"Deal\" to start a new round."
                )
            else:
                announcement(
                    "You got a blackjack! Click \"Deal\" to start a new round."
                )

            roundOver = True

        if stayed:
            # Since the player stayed, we always flip the card
            if not roundOver:
                dealerHandElements[0].flip()

            # After staying, player has a better hand than the dealer
            if handValue(playerHand) > handValue(dealerHand):
                announcement("You won! Click \"Deal\" to start a new round.")

            # After staying, player has a worse hand than the dealer
            if handValue(playerHand) < handValue(dealerHand):
                # ...However the dealer busted
                if handValue(dealerHand) > 21:
                    announcement(
                        "Dealer busted. You win!. Click \"Deal\" to start a new round."
                    )
                else:
                    announcement(
                        "You lost. Click \"Deal\" to start a new round.")

            # After staying, player has an equivalent
            if handValue(playerHand) == handValue(dealerHand):
                announcement("You tied. Click \"Deal\" to start a new round.")

            roundOver = True

        # Add other logic here

        pg.display.flip()
Example #9
0
import sys, random

sys.path.append('C:\\Users\\Jeff Hou\\TRACTOR')
import cards, auction, trumplib, gameplay

player_levels = [0, 0, 0, 0]
hands_and_bury = cards.deck_deal(cards.shuffle(cards.deck_setup()))
for i in range(len(hands_and_bury)):
    cards.hand_sort(hands_and_bury[i])
(boss_ID, point_marker) = auction.start(random.randint(0, 3),
                                        hands_and_bury[:4])
trump_suit = trumplib.set_trump(boss_ID)
trumplib.get_trump(trump_suit, player_levels[boss_ID])
Example #10
0
 def __init__(self):
     self.card_deck = cards.shuffle(cards.build_deck_52())
     self.card_logs = []
Example #11
0
def main():
    start_time = datetime.now()
    display_title(start_time)

    # Input money & bet from user
    money = get_starting_money()
    print("PLayer's money:", lc.currency(money, grouping=True))
    print()
    while True:
        if money < 5:
            print("You are out of money.")
            buy_more = input(
                "Would you like to buy more chips? (y/n): ").lower()
            if buy_more == "y":
                money = buy_more_chips(money)
                print("Player's money: ", lc.currency(money, grouping=True))
                print()
                db.write_money(money)
            else:
                break
        bet = get_bet(money)
        if bet == "x":
            break
        deck = cards.get_deck()
        cards.shuffle(deck)
        players_hand = cards.get_empty_hand()
        dealers_hand = cards.get_empty_hand()
        cards.add_card(players_hand, cards.deal_card(deck))
        cards.add_card(dealers_hand, cards.deal_card(deck))
        cards.add_card(players_hand, cards.deal_card(deck))
        print()
        display_card(dealers_hand, "Dealer's SHOW CARD: ")
        display_card(players_hand, "YOUR CARDs: ")
        players_hand, bet = play(deck, players_hand, money, bet)
        while True:
            if cards.get_points(dealers_hand) >= 17:
                break
            else:
                cards.add_card(dealers_hand, cards.deal_card(deck))
        if cards.get_points(players_hand) > 21:
            display_card(dealers_hand, "Dealer's CARDs: ")
        else:
            display_card(dealers_hand, "Dealer's CARDs: ")
        result = compare_hands(players_hand, dealers_hand)

        if result.lower() == "blackjack":
            print("You got blackjack!")
            money += round(int(bet) * 1.5, 2)
        elif result.lower() == "win":
            #print("You won!")
            money += float(bet)
        elif result.lower() == "push":
            #print("You pushed.")
            money = money
        elif result.lower() == "lose":
            #print(" You lost.")
            money -= float(bet)
        # Printing out the money
        print("Player's Money: ", lc.currency(money, grouping=True))
        print()
        db.write_money(money)
        again = input("Play again? (y/n): ")
        if again.lower() != "y":
            print()
            print("Come again soon!")
            break

    stop_time = datetime.now()
    display_end(start_time, stop_time)
Example #12
0
def shuffleCard():
    cards.shuffle(DECK)
Example #13
0
import cards

DECK = cards.build_deck()
cards.shuffle(DECK)

PLAYER1 = cards.draw_card(DECK)
PLAYER2 = cards.draw_card(DECK)

print(PLAYER1['RANK'])
print(PLAYER2['RANK'])

for rank in cards.ranks():
    if PLAYER1['RANK'] == PLAYER2['RANK']:
        print("Tie!")
        break

    if rank == PLAYER1['RANK']:
        print("Player 2 wins...")
        break
    if rank == PLAYER2['RANK']:
        print("Player 1 wins...")
        break
"""
points = {
    'A' : 14,
    'K' : 13,
    'D' : 12,
    'J' : 11,
    '10': 10,
    '9': 9,
    '8': 8,
Example #14
0
def main():
    display_title()
    start_time = datetime.now()
    print("Start time:  ", start_time.strftime("%I:%M:%S"))
    print()

    # get starting money
    money = get_starting_money()
    print("Money:", lc.currency(money, grouping=True))

    # start loop
    while True:
        # make sure player has enough money for min bet
        if money < 5:
            print("You are out of money.")
            buy_more = input(
                "Would you like to buy more chips? (y/n): ").lower()
            if buy_more == "y":
                money = buy_more_chips(money)
                print("Money:", lc.currency(money, grouping=True))
                db.write_money(money)
            else:
                break

        # get bet amount
        bet = get_bet(money)
        print()

        deck = cards.get_deck()
        cards.shuffle(deck)

        dealer_hand = cards.get_empty_hand()
        player_hand = cards.get_empty_hand()

        # deal two cards to player and one to the dealer
        cards.add_card(player_hand, cards.deal_card(deck))
        cards.add_card(player_hand, cards.deal_card(deck))
        cards.add_card(dealer_hand, cards.deal_card(deck))

        # display cards
        display_cards(dealer_hand, "DEALER'S SHOW CARD: ")
        display_cards(player_hand, "YOUR CARDS: ")

        # get player hand
        player_hand = play(deck, player_hand)

        # get dealer hand
        while cards.get_points(dealer_hand) < 17:
            cards.add_card(dealer_hand, cards.deal_card(deck))
        display_cards(dealer_hand, "DEALER'S CARDS: ")

        print("YOUR POINTS:     " + str(cards.get_points(player_hand)))
        print("DEALER'S POINTS: " + str(cards.get_points(dealer_hand)))
        print()

        # check result of hand
        player_points = cards.get_points(player_hand)
        dealer_points = cards.get_points(dealer_hand)
        if player_points > 21:
            print("Sorry. You busted. You lose.")
            money -= bet
        elif dealer_points > 21:
            print("Yay! The dealer busted. You win!")
            money += bet
        else:
            if player_points == 21 and len(player_hand) == 2:
                if dealer_points == 21 and len(dealer_hand) == 2:
                    print("Dang, dealer has blackjack too. You push.")
                else:
                    print("Blackjack! You win!")
                    money += bet * 1.5
            elif player_points > dealer_points:
                print("Hooray! You win!")
                money += bet
            elif player_points == dealer_points:
                print("You push.")
            elif player_points < dealer_points:
                print("Sorry. You lose.")
                money -= bet
            else:
                print("I am not sure what happened.")

        # display new money amount
        money = round(money, 2)
        print("Money:", lc.currency(money, grouping=True))
        print()

        # write money to file
        db.write_money(money)

        again = input("Play again? (y/n): ").lower()
        print()
        if again != "y":
            break

    end_time = datetime.now()
    print("End time:  ", end_time.strftime("%I:%M:%S"))
    elapsed_time = end_time - start_time
    days = elapsed_time.days
    minutes = elapsed_time.seconds // 60
    seconds = elapsed_time.seconds % 60
    hours = minutes // 60
    minutes = minutes % 60
    time_object = time(hours, minutes, seconds)
    print("Elapsed time:  ", time_object)
    print("Come back soon!")
    print("Bye!")
Example #15
0
import cards
DOWN = 0
UP = 1
DECK = 0
STACKS = 2

deck = cards.getSortedDeck()
deck = cards.shuffle(deck)
undeck = []
tableau = []
for col in range(7):
    tableau.append([])
    for card in range(col + 1):
        tableau[col].append(deck.pop())
stacks = [(0,0) for x in range(4)]

states = [[DOWN, DECK]]*52
for index, col in enumerate(tableau):
    for rowIndex, card in enumerate(col):
        states[cards.getCardIndex(card)] = [DOWN, [index, rowIndex]]
        if rowIndex == len(col) - 1:
            states[cards.getCardIndex(card)][0] = UP

def getState(card):
    return states[cards.getCardIndex(card)][:]
def legalMove(moveCard, index, inTableau=True):
    if inTableau:
        if len(tableau[index]) != 0:
            toCard = tableau[index][-1]
            if (((moveCard[0] == cards.SPADES or moveCard[0] == cards.CLUBS) and
                (toCard[0] == cards.HEARTS or toCard[0] == cards.DIAMONDS)) or
Example #16
0
import cards
import sys

NB_CARDS_PER_PLAYER = 5
nbPlayers = int(sys.argv[1])


def printHand(deck, nb=1):
    for i in range(nb):
        print('\n'.join(deck[0:5]))
        deck = deck[5:]
        print('')
    return deck


if __name__ == "__main__":
    # print(cards.shuffle(cards.getDeck()))
    deck = cards.shuffle(cards.getDeck())
    printHand(deck, nbPlayers)