Example #1
0
 def reset_bot(self):
     """
     Resets the bot client's state to initial values, preparing it for a new session.
     """
     self.players.clear()
     self.channel = None
     self.dealer = _dealer.Dealer(self.user)
Example #2
0
        def get_setMode(self):
            global d, statusFlag, dealerRunning, playerList

            if logDirectory is None:
                setError("Project dir must be set...")
                return

            if not playersRunning:
                setError("No players running...")
                return

            print "OPG: Mode chosen: ", self.optionVar.get()
            mode = self.optionVar.get()

            # set log file in dibas.conf

            print playerList
            setMsg("Initializing dealer...")
            d = dealer.Dealer()
            d.remove_active_player("BANKA")  # by default A is already there.
            d.add_active_player(*playerList)
            setMsg("Setting mode to %s" % mode)
            d.set_mode(mode=mode)
            dealerRunning = True
            clearStatus()
Example #3
0
 def test_return_cards(self):
     test_deck = deck.Deck()
     deal = dealer.Dealer()
     play = player.Player()
     deal.deal(test_deck, play)
     deal.return_cards(test_deck, play)
     self.assertEqual(len(test_deck.discarded), 4)
Example #4
0
 def __init__(self):
     """ crea una cuenta de banco por jugador y un pinta cartas """
     self.dealer_player = dealer.Dealer(5000)
     self.jugadores = []
     self.otro = 'S'
     self.errorEntrada = False
     self.baraja = []
 def get_setMode(self):
     print "OPG: Mode chosen: ", self.optionVar.get()
     mode = self.optionVar.get()
     global d
     d=dealer.Dealer()
     d.add_active_player(*cg.getActiveBanks()) # *d.list_avaliable_players()
     d.set_mode(mode=mode)
    def test_determine_a_winner(self, mock_print):

        testdeck = Deck()
        testdeck.shuffle()

        testPlayers = []

        # Watch your names. You are assiging the player module to be a new Player() object
        # which is causing a weird test failure.

        humanPlayer = player.Player('testMike')
        testPlayers.append(humanPlayer)
        humanPlayer.getValue = 20  #  problem: is this the right thing to do to set the player's value?

        testdealer = dealer.Dealer('testDealer')
        estdealer.getValue = 19  # Same here  - find another way to force the player to have a certain value

        # Same here - dealer is a module, not a dealer object
        game.determine_a_winner(
            testPlayers, testdealer, testdeck, d=True
        )  # getting int object is not callable - related to the player.setvalue = 20 calls above. Review and revise these

        call_args = mock_print.call_args_list

        mock_print.assert_any_call('testDealer has a totoal of: 19')
        mock_print.assert_any_call('testMike wins!')
Example #7
0
    def setUp(self):
        self.player = player.Player(1, [], 0)
        self.strat = strategy.Strategy()

        self.carnivore = species.Species(0, 1, 1, [])
        self.carnivore.setTraits([trait.Trait.carnivore])
        self.fat_carnivore = species.Species(0, 1, 1, [])
        self.fat_carnivore.setTraits([trait.Trait.carnivore])
        self.fat_carnivore.setBodySize(5)

        self.herbavore = species.Species(0, 1, 1, [])
        self.fat_herbavore = species.Species(0, 1, 1, [])
        self.fat_herbavore.setBodySize(4)

        self.fat_tissue = species.Species(0, 1, 1, [])
        self.fat_tissue.setBodySize(3)
        self.fat_tissue.setTraits([trait.Trait.fat_tissue])
        self.fat_fat_tissue = species.Species(0, 1, 1, [])
        self.fat_fat_tissue.setBodySize(6)
        self.fat_fat_tissue.setTraits([trait.Trait.fat_tissue])

        self.opherb = species.Species(0, 1, 1, [])
        self.opfatherb = species.Species(0, 1, 1, [])
        self.opfatherb.setBodySize(4)

        self.opponent1 = player.Player(1, [], 0)
        self.opponent1.setSpeciesBoards([self.opherb, self.opfatherb])
        self.opponents = [self.opponent1]

        self.dealer = dealer.Dealer()
        self.dealer.setListOfPlayers([self.player, self.opponent1])
        self.dealer.setWateringHole(4)
Example #8
0
 def test_get_winner_dealer(self):
     test_dealer = dealer.Dealer()
     test_player = player.Player()
     test_dealer.hand = [deck.Card(5, 0)]
     test_player.hand = [deck.Card(4, 0)]
     test_game = game.Game()
     winner, score = test_game.get_winner(test_dealer, test_player)
     self.assertEqual(winner, test_dealer)
Example #9
0
    def startRound(self):
        dealer = dealer.Dealer(players_list)
        self.dealer = dealer

        for player in players_list:
            player.setHand(dealer.dealFirst())

        dealer.setStacks()

        for player in players_list:
            player.setCurrentStacks(dealer.getStacks())
Example #10
0
 def test_get_winner_dealer_bust(self):
     test_dealer = dealer.Dealer()
     test_player = player.Player()
     test_player.hand = [deck.Card(8, 0)]
     test_dealer.hand = [
         deck.Card(10, 0),
         deck.Card(10, 0),
         deck.Card(10, 0)
     ]
     test_game = game.Game()
     winner, score = test_game.get_winner(test_dealer, test_player)
     self.assertEqual(score, -1)
Example #11
0
 def __init__(self):
     super().__init__()
     self.in_session = False
     self.players = list()
     self.channel = None
     self.dealer = _dealer.Dealer(self.user)
     if not os.path.isfile("users.db"):
         file = open("users.db", 'a')
         file.close()
         self.sqlite_conn = sqlite3.connect("users.db")
         self.conn_cursor = self.sqlite_conn.cursor()
         self.conn_cursor.execute(
             '''CREATE TABLE users (id text, bank integer)''')
     else:
         self.sqlite_conn = sqlite3.connect("users.db")
         self.conn_cursor = self.sqlite_conn.cursor()
Example #12
0
    def test_dealer_paga_apuesta(self):
        """ se pagan apuesta a jugadores ganadores """
        # se crea dealer
        d = dealer.Dealer(100)
        self.assertEqual(d.nombre, 'Dealer')

        # se crea agregan 3 apostadores
        d.registra_apuesta('Domingo', 20)
        d.registra_apuesta('Natahsa', 20)
        d.registra_apuesta('Puggy', 50)

        # se pagan las apuestas
        pag1 = d._paga_apuesta('Domingo')
        pag2 = d._paga_apuesta('Natahsa')
        pag3 = d._paga_apuesta('Puggy')

        # saldo de la cuenta del dealer despues de pagar
        self.assertEqual(d.cuenta.saldo, 10)
Example #13
0
    def __init__(self, players, deck_amount, pen_amount):
        """
        - Pass how many decks will be in the shoe.
        - Ensure dealer knows how many players are playing via 'confirm_player'
        """
        self.decks = sh.Shoe(deck_amount)
        self.decks.shuffle()

        self.dealer = dl.Dealer(self.decks)
        self.set_deck_threshold()

        self.players = players
        self.confirm_players(self.players)

        # Holds cards cleared at the end of each round
        self.trash_pile = []

        # Average shoe penetration in Blackjack is usually 25% (0.25)
        self.pen = len(self.decks) * (pen_amount / 100)
Example #14
0
def main(url):
    global ctx, D, auto_set

    keys = {"ScanCoordinator.ScanCoordinator:P:state": state_callback,
            "ScanCoordinator.ScanCoordinator:P:startTime": start_time_callback}
    ctx = zmq.Context()
#    D = DealerProxy(ctx, url)
    D = dealer.Dealer()
    D.add_active_player('BANKB', 'BANKC', 'BANKD')
    # Real ScanCoordinator
    # req_url = "tcp://gbtdata.gbt.nrao.edu:5559"
    # Simulator ScanCoordinator
    req_url = "tcp://toe.gb.nrao.edu:5559"
    subscriber = ctx.socket(zmq.SUB)
    D.set_mode('FLAG_CALCORR_MODE')
    start_time = start_time = datetime.utcnow().replace(tzinfo=pytz.utc)
    print start_time
    D.start(start_time)

    for key in keys:
        print key
        major, minor = key.split(':')[0].split('.')
        print major, minor
        #params = get_every_parameter(ctx,major,minor)
        #print params
        sub_url, _, _ = get_service_endpoints(ctx, req_url, major, minor, 0)
        print sub_url
        subscriber.connect(sub_url)
        subscriber.setsockopt(zmq.SUBSCRIBE, key)
    while (auto_set):
        key, payload = subscriber.recv_multipart()
        df = PBDataField()
        df.ParseFromString(payload)
        f = keys[key]

        try:
            f(df)
        except ZMQJSONProxyException, e:
            print "Caught exception from Dealer", e
Example #15
0
 def setUp(self):
     self.dealerEmpty1 = dealer.Dealer([])
     self.dealerEmpty2 = dealer.Dealer([])
Example #16
0
        d.startin(startTime, scanLength)

    def sendStop(self, event):
        d.stop()

    def update(self, event):
        for playerName in d.list_available_players():
            if playerName in d.list_active_players():
                info = d.players[playerName].url
            else:
                info = "INACTIVE"
            self.portInfo[playerName].SetValue(info)
            if playerName in d.list_active_players():
                if (d.players[playerName]._initialized):
                    if (d.players[playerName].get_mode() != None):
                        status_mem = d.players[playerName].get_status()
                        for i in range(0, 6):
                            try:
                                self.statusBox[i][playerName].SetValue(
                                    str(status_mem[
                                        self.statusNames[i].GetValue()]))
                            except Exception, e:
                                self.statusBox[i][playerName].SetValue("N/A")
                                pass


d = dealer.Dealer()
app = wx.App(False)
frame = MyFrame(None, "FLAG Control Interface")
app.MainLoop()
Example #17
0
        if type(chips) == float:
            raise ValueError
        buying_chips_check = False
        print("Chips bought:",chips)
    except ValueError as v:
        print("Invalid entry! The number of chips must be an integer.")
player1 = player.Player(chips, [])

game_loop_check = True
while game_loop_check and  player1.chips>= 5:                   #(2l)the main loop that runs the game
    player1.player_hand = []
    print("You have {} chips.".format(player1.chips))
    wager_check = True   
    Cards = deck.Deck(ranks, suits)             #creates card rank and suits, store card values as values of the keys ranks 
    Deck = Cards.deckShuffle(Cards.deckCreator())
    Dealer = dealer.Dealer([])
    #print(Deck)
    while wager_check:                         #(3l)makes sure that wager is in the correct format and within the bounds
        try:
            wager = int(input("Please enter your wager:\n"))
            if wager < 5:
                raise(errors.SmallerThan5("Your wager must be at least 5 chips!"))
            elif wager > player1.chips:
                raise(errors.ChipOverFlow("Your wager cannot be bigger than the number of chips you have!"))

            wager_check = False
            player1.chips -= wager
            print("Wager: {}\nRemanining chips: {}".format(wager, player1.chips))

        except errors.SmallerThan5 as s5:
            print(s5)
Example #18
0
import deck_of_cards as deck
import player
import dealer

#create playerss
dealer = dealer.Dealer("Dealer")
player_1 = player.Player("Player 1")

#create a deck of cards
main_deck = deck.Deck()
main_deck.shuffle()

#create variables
player_turn = True
dealer_turn = True


#initial draw sequence between platyer_1 and dealer
def draw_sequence():
    #add input for more players to play
    player_1.draw(main_deck)
    dealer.draw(main_deck)
    player_1.draw(main_deck)
    dealer.draw(main_deck)


#prints the card values at play
def cards_on_table(player):
    print("===============================================")
    #dealer hand
    if player_turn == False:
Example #19
0
 def __init__(self):
     self.rounds = 1
     self.players = []
     self.dealer = dealer.Dealer()
Example #20
0
class Game:

    shoe = []
    players = []
    dealer = d.Dealer(17)
    results_filepath = "results.txt"
    csv_file = "results.csv"

    def __init__(self, num_players, default_aggression, num_decks_in_shoe,
                 num_simulated_rounds):
        self.num_players = int(num_players)
        self.default_aggression = int(default_aggression)
        self.num_decks_in_shoe = int(num_decks_in_shoe)
        self.num_simulated_rounds = int(num_simulated_rounds)
        for i in range(self.num_players):
            self.players.append(player.Player(self.default_aggression))

        self.start_sim()

    def new_shoe(self):
        new_shoe = []
        for i in range(self.num_decks_in_shoe):
            for j in range(52):
                if (j < 4): card = Card.Card('2', 2)
                elif (j >= 4 and j < 8): card = Card.Card('3', 3)
                elif (j >= 8 and j < 12): card = Card.Card('4', 4)
                elif (j >= 12 and j < 16): card = Card.Card('5', 5)
                elif (j >= 16 and j < 20): card = Card.Card('6', 6)
                elif (j >= 20 and j < 24): card = Card.Card('7', 7)
                elif (j >= 24 and j < 28): card = Card.Card('8', 8)
                elif (j >= 28 and j < 32): card = Card.Card('9', 9)
                elif (j >= 32 and j < 36): card = Card.Card('T', 10)
                elif (j >= 36 and j < 40): card = Card.Card('J', 10)
                elif (j >= 40 and j < 44): card = Card.Card('Q', 10)
                elif (j >= 44 and j < 48): card = Card.Card('K', 10)
                elif (j >= 48 and j < 52): card = Card.Card('A', 11)

                new_shoe.append(card)
        random.shuffle(new_shoe)

        self.shoe = new_shoe

    def new_hand(self):

        for p in self.players:
            tmp_hand = []
            tmp_hand.append(self.shoe.pop())
            tmp_hand.append(self.shoe.pop())
            p.new_hand(tmp_hand)

        dealer_hand = []
        dealer_hand.append(self.shoe.pop())
        dealer_hand.append(self.shoe.pop())
        self.dealer.new_hand(dealer_hand)

        for p in self.players:
            while (p.get_playing()):
                if (p.decision()):
                    p.hit(self.shoe.pop())

        while (self.dealer.get_playing()):
            if (self.dealer.decision()):
                self.dealer.hit(self.shoe.pop())

        if (self.dealer.is_busted()):
            for play in self.players:
                if (not play.is_busted()):
                    play.wins += 1
                    play.set_result("Win. Dealer bust.")
        else:
            for player in self.players:
                if (not player.is_busted()):
                    if (player.get_hand_value() >
                            self.dealer.get_hand_value()):
                        player.wins += 1
                        player.set_result("Win. Closer to 21 than dealer.")
                    elif (player.get_hand_value() <
                          self.dealer.get_hand_value()):
                        self.dealer.wins += 1
                        player.set_result("Loss. Dealer had better hand.")
                    else:
                        player.set_result("Push. Same score as dealer.")
                else:
                    self.dealer.wins += 1

        self.report_hand()

    def report_hand(self):
        results_file = open(self.results_filepath, "a")
        results_file.write("===== New Hand =====\n")
        results_file.write("Number of players: " + str(self.num_players) +
                           " \n")
        i = 0
        for p in self.players:
            i += 1
            results_file.write("Player: " + str(i) + " ")
            results_file.write(p.get_result())
            results_file.write(p.hand_to_string())
        results_file.write("Dealer hand: " + self.dealer.hand_to_string())
        results_file.write("\n===== End of Hand =====\n")
        results_file.close()

    def start_sim(self):

        for i in range(self.num_simulated_rounds):
            if (len(self.shoe) < 50):
                self.new_shoe()
            self.new_hand()

        results_file = open(self.results_filepath, "a")
        dealer_result_string = ("Dealer won " + str(self.dealer.wins) +
                                " hands.")
        print(dealer_result_string)
        results_file.write(dealer_result_string)
        j = 0
        for p in self.players:
            j += 1
            tmp_player_res_string = ("Player " + str(j) + " won  " +
                                     str(p.wins) + " hands. ")
            print(tmp_player_res_string)
            results_file.write(tmp_player_res_string)
        print("\n")
        results_file.close()
Example #21
0
 def test_deal(self):
     test_deck = deck.Deck()
     deal = dealer.Dealer()
     play = player.Player()
     deal.deal(test_deck, play)
     self.assertEqual(len(play.hand), 2)
Example #22
0
import time

print("Hello, Player! Welcome to text-based BlackJack!")

got_amount = False

while not got_amount:
    try:
        money_to_table = chipbank.ChipBank(int(input("Enter the amount of dollars you're bringing to the table: ")))
        if hasattr(money_to_table,"_balance"):
            you = player.Player(money_to_table)
            got_amount = True
    except ValueError:
        print("Must enter a number! Try again!")

dealer = dealer.Dealer()

print("\nLet's get playing!")

playing = True
reset = True
while playing:
    try:
        if you.get_chips().get_balance() == 0:
            print("Zero Dollars!?")
            print("Come back when you get some money, buddy!")
            playing == False
            break
        wager_request = input("\nWager this hand, or quit with 'q': ")
        if wager_request == 'q':
            print("Taking the money and running, huh?")
Example #23
0
 def dealer_check_winner(self):
     npc = dealer.Dealer()
     play1 = [["Aces", [1, 11], "A"], ["Nine", 9, "9"]]
     play2 = [["Nine", 9, "9"], ["Ten", 10, "10"]]
     result = npc.check_winner(play1, play2)
     self.assertEqual(result, 'h1')
Example #24
0
 def dealer_check_balance(self):
     npc = dealer.Dealer()
     result = npc.check_balance(100, 200)
     self.assertEqual(result, True)
Example #25
0
def the_game():
    #init elements of the game
    my_dealer = dealer.Dealer()
    my_player = player.Player()
    my_deck = deck.Deck()

    #asks player if they want to play again or else exit
    action = main_menu()

    #shows wallet, allows player to repeat this as much as wanted
    while action == 2:
        if action == 2:
            print(f"Wallet contains ${my_player.wallet()}")
        action = main_menu()

    while action == 1:
        my_deck.shuffle()

        #gives the player 2 cards and the dealer 2 cards
        my_player.add_card(my_deck.deal())
        my_dealer.add_card(my_deck.deal())
        my_player.add_card(my_deck.deal())
        my_dealer.add_card(my_deck.deal())

        #shows cards that have been dealt, need to show one dealer card
        display_player_cards(my_player)
        display_dealer_cards(my_dealer, False)

        #this allows the player to place a bet
        bet_amt = place_bet(my_player)

        #player can decide to add more cards until they bust
        action = play_action()
        player_bust = False
        while action == 1:
            if my_player.add_card(my_deck.deal()):
                display_player_cards(my_player)
                action = play_action()
            else:
                #TODO round should end if player busts
                print("You busted!")
                display_player_cards(my_player)
                action = 2
                player_bust = True
        
        #calculates dealers hand
        if player_bust is False:
            dealer_bust = dealer_action(my_dealer, my_deck)
        else:
            dealer_bust = False

        #display all cards in dealers hand
        display_dealer_cards(my_dealer, True)

        if dealer_bust:
            #player wins
            print("Dealer busted!")
            my_player.update_money(bet_amt)
            print(f"You win :) Your wallet contains ${my_player.wallet()}.")
        elif player_bust:
            #dealer wins
            my_player.update_money(-bet_amt)
            print(f"You lost :( Your wallet contains ${my_player.wallet()}.")
        else:
            #calculate who wins
            if my_dealer.value() == my_player.value():
                #tie, return player bet
                print(f"You tied with the dealer :| Your wallet contains ${my_player.wallet()}.")
            elif my_dealer.value() > my_player.value():
                #dealer wins
                my_player.update_money(-bet_amt)
                print(f"You lost :( Your wallet contains ${my_player.wallet()}.")
            else:
                #player wins
                my_player.update_money(bet_amt)
                print(f"You win :) Your wallet contains ${my_player.wallet()}.")

        #ends round by clearing out players hands
        my_player.clear_hand()
        my_dealer.clear_hand()

        #allows player to exit or play again
        action = main_menu()
        #shows wallet, allows player to repeat this as much as wanted
        while action == 2:
            if action == 2:
                print(f"Wallet contains ${my_player.wallet()}")
            action = main_menu()

    #print out stats, num rounds, total winnings..., #blackjacks (reached 21)
    print(f"Total winnings: ${my_player.wallet() - 10}")
Example #26
0
 def test_draw_up_high(self):
     test_deck = deck.Deck()
     deal = dealer.Dealer()
     deal.hand = [deck.Card(10, 0), deck.Card(7, 0)]
     deal.draw_up(test_deck)
     self.assertEqual(len(deal.hand), 2)
Example #27
0
 def __init__(self, dev_mode=False):
     self.dev_mode = dev_mode
     self.player = player.Player(dev_mode)
     self.dealer = dealer.Dealer(dev_mode)
Example #28
0
import deck
import dealer
import player as p

deck_of_cards = deck.CardDeck()

dealer = dealer.Dealer(deck_of_cards)


def check_dealer_against_player(dealer, player):
    if dealer.evaluate_hand_blackjack(player.hand) > dealer.evaluate_hand_blackjack(dealer.hand):
        print('Player wins!')
    elif dealer.evaluate_hand_blackjack(dealer.hand) == dealer.evaluate_hand_blackjack(player.hand):
        print('Push! Neither wins!')
    else:
        print('Dealer wins!')


def main():
    print('Welcome to CLI BlackJack! Single Deck, 1 Player')
    name = input('What is your name?\n')

    player = p.Player(name)

    print('Dealing initial hand of cards to {} and dealer...'.format(player.name))
    player.add_to_hand(dealer.draw_card(), dealer.draw_card())
    dealer.add_to_hand(dealer.draw_card(), dealer.draw_card())

    print('Player hand is: {} Value: {}'.format(player.show_hand(), dealer.evaluate_hand_blackjack(player.hand)))
    print('Showing one of two dealer hand: {}'.format(dealer.show_initial_hand()))