Exemplo n.º 1
0
 def test_second_dealer_card_face_down(self):
     deck = Deck()
     player = Player(deck)
     dealer = Dealer(deck)
     blackjack = BlackJack(player, dealer)
     blackjack.deal()
     self.assertFalse(dealer.hand[1].face_up)
Exemplo n.º 2
0
 def test_nobody_wins(self):
     deck = []
     p = Player(deck)
     d = Dealer(deck)
     b = BlackJack(p, d)
     b.dealer.score = 19
     b.player.score = 19
     b.get_winner()
     self.assertEqual(b.winner, "Nobody")
Exemplo n.º 3
0
 def test_two_cards_for_dealer(self):
     deck = Deck()
     player = Player(deck)
     dealer = Dealer(deck)
     blackjack = BlackJack(player, dealer)
     blackjack.deal()
     dealers_hand_count = len(dealer.hand)
     expected_dealer_hand_count = 2
     self.assertEqual(dealers_hand_count, expected_dealer_hand_count)
Exemplo n.º 4
0
 def test_yes_tie(self):
     deck = Deck()
     player = Player(deck)
     dealer = Dealer(deck)
     blackjack = BlackJack(player, dealer)
     card_ten = Card("Hearts", "K", 10, True)
     player.hand.append(card_ten)
     dealer.hand.append(card_ten)
     player.score = 10
     self.assertTrue(blackjack.check_ties())
Exemplo n.º 5
0
 def test_no_tie(self):
     deck = Deck()
     player = Player(deck)
     dealer = Dealer(deck)
     blackjack = BlackJack(player, dealer)
     card_ten = Card("Hearts", "K", 10)
     card_five = Card("Hearts", "5", 5)
     player.hand.append(card_ten)
     dealer.hand.append(card_five)
     self.assertFalse(blackjack.check_ties())
Exemplo n.º 6
0
 def test_big_bang_player_winner(self):
     deck = Deck()
     p = Player(deck)
     d = Dealer(deck)
     game = BlackJack(p, d)
     c1 = Card("Hearts", "9", 9)
     c2 = Card("Spades", "9", 9)
     c3 = Card("Diamonds", "9", 9)
     p.hand.append(c1)
     p.hand.append(c2)
     d.hand.append(c3)
     p.get_score()
     d.get_score()
     game.get_winner()
     self.assertEqual(game.winner, "Player")
Exemplo n.º 7
0
 def test_natural_tie(self):
     low_deck = Deck()
     low_deck.deck.clear()
     c1 = Card("Hearts", "K", 10)
     c2 = Card("Hearts", "A", 11)
     low_deck.deck.append(c1)
     low_deck.deck.append(c2)
     natural_deck = Deck()
     natural_deck.deck.clear()
     c3 = Card("Diamonds", "10", 10)
     c4 = Card("Spades", "A", 11)
     natural_deck.deck.append(c4)
     natural_deck.deck.append(c3)
     player = Player(natural_deck)
     dealer = Dealer(low_deck)
     b = BlackJack(player, dealer)
     self.assertEqual(b.play_game(), "Nobody")
Exemplo n.º 8
0
def main():
    # logging.config.fileConfig(fname='../../conf/logging.conf', disable_existing_loggers=False)
    logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')

    # Get the logger specified in the file
    logger = logging.getLogger(__name__)

    logger.debug('This is a debug message')

    game = BlackJack("blackjack1")
    game.printname()
    game.whatsTheGame()
    game.play()
Exemplo n.º 9
0
Arquivo: Irx.py Projeto: intangere/Irx
	def __init__(self, s, nick, user, real):
		self.sendLine = s
		self.channel = ""
		self.nickname = nick
		self.realname = real
		self.username = user
		self.plugins = []
		self.commands = {}
		self.reserved_commands = [".reload", ".help", ".deal", ".join", ".hit", ".stand", ".split", ".double", ".shuffle", ".hand"]
		self.prefix = "."
		self.plugins_folder = "plugins"
		self.bjk = BlackJack()
Exemplo n.º 10
0
    def mainloop(self, stdscr):
        curses.curs_set(0)
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
        self.stdscr = stdscr
        self.screen_height, self.screen_width = self.stdscr.getmaxyx()
        self.printMenu(self.title, self.playerChoices)

        while 1:
            if self.takeKeyInput(self.printChosen):

                if self.currentRow == len(self.menu) - 1:
                    if self.confirm("Are you sure you want to exit?"):
                        break
                else:
                    for i in range(self.currentRow + 1):
                        self.currentRow = 0

                        buyInTitle = "Player " + \
                            self.mydict[str(i+1)] + \
                            ": How much are you buying in for?"

                        self.printMenu(buyInTitle, self.money)

                        while 1:
                            if self.takeKeyInput(self.addBetValues):
                                break

                            self.printMenu(buyInTitle, self.money)

                    blackjack = BlackJack(self.numOfChosenPlayers, self.stdscr,
                                          self.bettingAmounts)
                    if blackjack.mainloop():
                        self.bettingAmounts = []
                        pass

            self.printMenu(self.title, self.playerChoices)
Exemplo n.º 11
0
async def on_message(msg):
    if "심심" in msg.content:
        await msg.channel.send("$blackjack")

    if msg.content == "$blackjack":
        game = BlackJack(msg, bot)
        await game.start()

    if msg.content.startswith("$weather"):
        message = msg.content.split(" ")
        show = Weather(msg, bot)
        if (len(message) == 1):
            await show.weather()
        else:
            await show.weather(message[1])

    if "날씨" in msg.content:
        message = msg.content.split("날씨")
        city = message[0].rstrip()
        city = city.split(' ')
        city = city[-1]
        # await msg.channel.send(message)
        show = Weather(msg, bot)
        await show.weather(city)
Exemplo n.º 12
0
 def test_current_leader(self):
     game = BlackJack(self.players)
     game.deal_hand_to_players()
     test_player = game.current_leader
     self.assertIsInstance(test_player, object)
Exemplo n.º 13
0
 def test_deal_hand_to_players(self):
     game = BlackJack(self.players)
     game.deal_hand_to_players()
     self.assertTrue(game.players[0].hand.cards)
Exemplo n.º 14
0
 def test_add_player(self):
     game = BlackJack(self.players)
     game.add_player(self.new_player)
     player_names = self._get_player_names(game)
     self.assertTrue(self.new_player in player_names)
Exemplo n.º 15
0
 def test_get_player_names(self):
     game = BlackJack(self.players)
     player_names = game.player_names
     self.assertTrue(self.players[0] in player_names)
Exemplo n.º 16
0
 def test_players_house(self):
     game = BlackJack(self.players)
     player_names = self._get_player_names(game)
     self.assertTrue(self.house_player_name in player_names)
Exemplo n.º 17
0
class BlackJackSimulation(object):
    def __init__(self):
        self.the_doctor = Player("The Doctor")
        self.the_master = Player("The Master")
        self.dealer = Player("Dealer")
        self.game = BlackJack([self.the_doctor, self.the_master], self.dealer)

    def play(self):
        print ("Starting Blackjack")
        self.game.start()
        # start off by calculating the value of the players' cards
        self.calculate_hand(self.dealer)

        for player in self.game.players:
            self.calculate_hand(player)

        # for the sake of testing, we'll loop for 5 rounds
        for x in xrange(5):
            dealer_score = self.game.get_points_for_player(self.dealer)

            if dealer_score <= 15:
                self.game.hit(self.dealer)
                self.calculate_hand(self.dealer)  # reprocess the card values

            for player in self.game.players:
                if self.game.get_points_for_player(player) <= 15:
                    self.game.hit(player)
                    self.calculate_hand(player)  # reprocess the card values

        # Show final hand
        print (
            "{0}\t\t{1}\t{2}".format(
                self.dealer.name, self.game.get_points_for_player(self.dealer), self.dealer.printable_hand()
            )
        )

        for player in self.game.players:
            print (
                "{0}\t{1}\t{2}".format(player.name, self.game.get_points_for_player(player), player.printable_hand())
            )

        print ("*" * 45)

    def calculate_hand(self, player):
        """ A helper function to assist the bot in knowing when to hit
            by selecting the value of aces
        """
        total = sum([self.game.get_point_values(card) for card in player.hand if card.value != "A"])

        aces = [card for card in player.hand if card.value == "A"]

        # this is a crude method, this is NOT supposed to be a fully functioning
        # game. Just a rough demo of the code to create a game.
        def handle_aces(total, aces):
            ace_count = len(aces)

            if total <= 11 - ace_count:
                if ace_count:
                    # set the first ace to 11, the rest to 1
                    self.game.set_point_value(aces[0], 11)
                    [self.game.set_point_value(card, 1) for card in aces[1:]]

                return total + 10 + ace_count
            else:
                if ace_count:
                    [self.game.set_point_value(card, 1) for card in aces]
                return total + ace_count

        total = handle_aces(total, aces)

        return total
Exemplo n.º 18
0
from blackjack import BlackJack
import random
import time

raymond = BlackJack()

i = 1
while True:
    print("-----------------------\nGame " + str(i) +
          "\n-----------------------\n")
    done = False
    while not done:
        action = random.randint(0, 1)
        raymond.render()
        state, reward, done, _ = raymond.step(action)
        raymond.render()
        time.sleep(1)

    if reward > 0:
        print("Raymond Wins")
    else:
        print("Dealer Wins")

    i += 1
    raymond.reset()
Exemplo n.º 19
0
from deck import Card, Deck
from blackjack_player import Player
from blackjack import BlackJack

game = BlackJack()
game.play_game()
Exemplo n.º 20
0
def main():
    baralho = Baralho()
    game = BlackJack(baralho)
    game.mostra_titulo()
    game.init()
Exemplo n.º 21
0
Arquivo: Irx.py Projeto: intangere/Irx
class Irx(object):
	
	def __init__(self, s, nick, user, real):
		self.sendLine = s
		self.channel = ""
		self.nickname = nick
		self.realname = real
		self.username = user
		self.plugins = []
		self.commands = {}
		self.reserved_commands = [".reload", ".help", ".deal", ".join", ".hit", ".stand", ".split", ".double", ".shuffle", ".hand"]
		self.prefix = "."
		self.plugins_folder = "plugins"
		self.bjk = BlackJack()

	def doAction(self, data):
		pass
	
	def getMessage(self, channel, data):
		self.channel = channel
		if " :" in data:
			msg = data.split(" :")[1]
			return msg
		return ""

	def buildCommandList(self):
		for name in self.plugins:
			command = "%s%s" % (self.prefix, name)
			self.commands[command] = self.getClassByName(self.plugins[name], "%s.%s.%s" % (self.plugins_folder, name, name))

	def getClassByName(self, module, className):
		if not module:
			if className.startswith(".%s" % self.plugins_folder):
				className = className.split(".%s" % self.plugins_folder)[1]
			l = className.split(".")
			m = __services__[l[0]]
			return getClassByName(m, ".".join(l[1:]))
		elif "." in className:
			l = className.split(".")
			m = getattr(module, l[2])
			return m
		else:
			return getattr(module, className)

	def loadPlugins(self, folder):
		self.plugins_folder = folder
		res = {}
		lst = os.listdir(folder)
		dir = []
		if "__init__.py" in lst:
			for d in [p for p in lst if p.endswith(".py")]:
				dir.append(d[:-3])
		for d in dir:
			if d != "__init__":
				res[d] = __import__(folder + "." + d, fromlist = ["*"])
		self.plugins = res
		return res

	def doCommand(self, chan, user, command):
		user = user.split("!")[0]
		if command in self.reserved_commands:
			self.nativeCall(user, chan, command)
		else:
			spt = command.split(" ")
			args = [spt[0], user, chan]
			for value in spt:
				args.append(value)
			msg = self.commands[args[0]](args[1:]).run()
			self.send(chan, msg)

	def respondToPing(self, data):
		hsh = data.split(" ")[1]
		self.sendLine("PONG %s" % hsh)

	def nativeCall(self, user, chan, call):
		call = call[1:]
		if call == "reload":
			self.plugins = []
			self.commands = {}
			self.loadPlugins(self.plugins_folder)
			self.buildCommandList()
			self.send(chan, "Reloaded plugins")

		if call == "help":
			for command in self.commands:
				self.send(chan, "%s - %s " % (command, self.commands[command]([]).description))

		if call == "hit" or call == "stand":
			if call == "hit":
				res = self.bjk.hit(user)
			else:
				res = self.bjk.stand(user)
			if type(res) == type(list()):
				print res
				if len(res) == 0:
					self.send(chan, "Dealer won")
					self.send(chan, "Dealer's hand was : %s" % (self.bjk.winning_hands[0]))
				elif res[0] == "dealer":
					self.send(chan, "Dealer's hand: %s" % (self.bjk.winning_hands[0]))
					self.send(chan, "Dealer won!")
				elif res[0] == "Not standing":
					self.send(chan, "%s is now standing.." % user)
					self.send(chan, "Waiting for other players to decide...")
				elif res[0] == "pushed":
					self.send(chan, "No winners.")
					self.send(chan, "Pushed!")				
				elif len(res) > 0 and "dealer" not in res and res:
					self.send(chan, "Dealer lost!")
					if len(res) == 1:
						self.send(chan, "%s has won the round!" % (str(res)))
						self.send(chan, "%s's winning hand was: %s" % (user, self.bjk.winning_hands[0]))
				else:
					self.send(chan, "%s have won the round!" % (res))
					self.send(chan, "Winning hands were %s" % str(self.bjk.winning_hands))
				#else:
				#	self.send(chan, "No winners.")
			elif res == False:
				self.send(chan, "%s's cards: %s" % (user, str(self.bjk.players[user])))
			elif res == True:
				self.send(chan, "%s busted!" % user)
				#self.send(chan, "%s's cards were: %s" % (user, str(self.bjk.players[user]))
				self.send(chan , "%s was removed from game!" % user)
			else:
				self.send(chan, "%s won!" % user)
				self.send(chan, "%s winning hand: %s" % (user, self.bjk.winning_hands[0]))
				self.send(chan, "%s has been removed from game!" % user)
			pass

		if call == "deal":
			if len(self.bjk.players) < 2:
				self.send(chan, "No players in game..")
			else:
				res = self.bjk.deal()
				self.send(chan, "Shuffling deck...")
				self.send(chan, "Dealing cards..")
				if len(res) == 0:
					for player in self.bjk.players.keys():
						if player == "dealer":
							self.send(chan, "Dealer's cards: %s" % str(self.bjk.players["dealer"]))
						else:
							self.send(chan, "%s's cards: %s" % (player, str(self.bjk.players[player])))
				else:
					if res == "Has dealed":
						self.send(user, "The cards have already been dealed! Please wait for the next round!")
					else:
						self.send(chan, "%s has blackjack!" % res)

		if call == "double":
			self.bjk.double(user)
			pass

		if call == "join":
			res = self.bjk.addPlayerToGame(user)
			if res == True:
				self.send(chan, "%s joined the current game!" % user)
			else:
				self.send(user, "The game has already started. Please wait till next round to join!")


		if call == "shuffle":
			self.bjk.shuffle()
			self.send(chan, "Dealer shuffled deck..")

		if call == "hand":
			cards = self.bjk.getPlayerHand(user)
			self.send(chan, str("%s's cards : %s" % (user, cards)))

	def send(self, chan, msg):
		self.sendLine("PRIVMSG %s :%s" % (chan, msg))
Exemplo n.º 22
0
#init class for handling output
from consoleGui import Console

# init file for BlackJack Game
from blackjack import BlackJack

if __name__ == '__main__':
    console = Console(mode=Console.mode.DEFAULT_MODE)
    
    # TO DO : Show Menu options for player and mode inputs

    with BlackJack('Tiago', players=7, console=console, mode=BlackJack.Mode.one_up) as game:
        game.play()

    console.print("Goodbye!")
Exemplo n.º 23
0
def main():
    counting = False
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--count_type", help="supported counting strategies: 'hl': High-Low")
    args = parser.parse_args()
    strategy = BasicStrategy()
    if args.count_type == "hl":
        counting = True
        decks_remaining = input("How many decks are left? ")
        counter = HiLowCounter(decks_remaining)
        game = BlackJack(strategy, counter)
    elif args.count_type:
        print("We don't support that counting strategy yet")
    else:
        game = BlackJack(strategy)
    while True:
        dealer_showing = input("Dealer Showing: ")
        your_first_card = input("Card 1: ")
        your_second_card = input("Card 2: ")
        cards = [your_first_card, your_second_card]
        game.set_dealer_showing(dealer_showing)
        if counting:
            other_cards = raw_input("What are the other cards on the table (seperated by spaces)? ")
            other_cards = [int(x) for x in other_cards.split(" ")]
            game.count_strat.set_count(cards + other_cards)
        if your_first_card == your_second_card:
            if game.play_strat.split_recommendation(your_first_card, game.get_dealer_showing()):
                cards_1, cards_2 = game.handle_split(your_first_card)
            else:
                print("DO NOT SPLIT")
        if game.play_strat.hit_recommendation([your_first_card, your_second_card], game.get_dealer_showing()):
            game.handle_hit([your_first_card, your_second_card])
        else:
            print("STAY")
        if counting:
            print("Next round your bet should be: " + str(game.count_strat.get_bet_amount()) + " betting units.")
        if raw_input("Play Again (y/n): ") == "n":
            break
Exemplo n.º 24
0
from blackjack import BlackJack


def should_hit(player_total, dealer_card_val, player_aces):
    return player_total <= 17


g = BlackJack(should_hit, True, True)
#g.play()
g.simulate(n_games=10)
Exemplo n.º 25
0
 def test_active_players(self):
     game = BlackJack(self.players)
     game.deal_hand_to_players()
     active = game.active_players
     self.assertTrue(active)
Exemplo n.º 26
0
        elif "s" in choice.lower():
            print(f"PLAYER TURN ->{player.name} is staying!")
            done = True
        else:
            print("PLAYER TURN -> Not a valid choice! 👎")


if __name__ == "__main__":

    ##
    # Game Setup
    ##
    players = input(
        "GAME SETUP -> Type in player names separated by a space: ")
    players = players.split(" ")
    game = BlackJack(players)
    game.deck.shuffle()
    game.deal_hand_to_players()

    if check_for_natural(game):
        print("BLACKJACK! -> We have a NATURAL! 🔥")
        end_game(game)

    ##
    # Main Game Loop
    ##
    while game.game_state:
        game_status(game)
        for player in game.active_players:
            turn_player(player)
        end_game(game)
Exemplo n.º 27
0
 def test_players(self):
     game = BlackJack(self.players)
     self.assertEqual(game.players[0].name, self.players[0])
Exemplo n.º 28
0
def main():

    win = GraphWin("Play Black Jack!", 800, 600)  #make a graphical window
    win.setBackground("red")  #set the color to red
    intro = Text(Point(400, 200), "Black Jack!")  #intro to the user
    intro.setStyle("bold")  #set the style
    intro.setSize(36)  #change the size
    intro.draw(win)  #draw it
    prompt = Text(Point(400, 300), "Click to play!")  #prompt the user
    prompt.setSize(18)
    prompt.draw(win)
    startbutton = Button(win, Point(400, 400), 100, 50,
                         "Play!")  #start button to play
    startbutton.activate()
    askMoney = Text(Point(400, 500),
                    "How much money do you want to play with?")
    askMoney.draw(win)
    moneyBox = Entry(Point(400, 525), 10)
    moneyBox.draw(win)
    pt = win.getMouse()  #wait for click
    while startbutton.isClicked(
            pt
    ) == False:  #if the click is not on the button, get another click
        pt = win.getMouse()
    totalMoney = int(moneyBox.getText())
    intro.undraw()  #clear the window
    prompt.undraw()
    startbutton.rect.undraw()
    startbutton.label.undraw()
    askMoney.undraw()
    moneyBox.undraw()
    play = True  #set play to true, user wants to play
    while play == True:  #while this is true, run the game
        win.setBackground("lightblue")  #change the color
        button1 = Button(win, Point(300, 300), 100, 50, "Hit")  #set up buttons
        button2 = Button(win, Point(500, 300), 100, 50, "Stand")
        button3 = Button(win, Point(400, 500), 50, 50, "Quit")
        playagain = Button(win, Point(700, 500), 100, 100, "Play again!")
        playagain.deactivate()  #not active button
        button1.deactivate()  #deactivate buttons
        button2.deactivate()
        button3.deactivate()

        askforbet = Text(Point(700, 100), "Place bet here.")
        askforbet.draw(win)
        inputBox = Entry(Point(700, 125), 10)
        inputBox.draw(win)
        betButton = Button(win, Point(700, 200), 50, 50, "Bet!")

        dealerText = Text(Point(100, 100), "Dealer")  #set up the text
        dealerText.draw(win)
        playerText = Text(Point(100, 400), "Player")  #set up the text
        playerText.draw(win)

        deck1 = Deck()  #make the deck of cards to be used in the game
        dealerHand = []  #set up the dealer's hand
        playerHand = []  #set up the dealer's hand
        game = BlackJack(dealerHand, playerHand)  #set up the black jack game
        game.initDeal(win, 200, 100, 200,
                      400)  #deal out the first two cards to each
        dealercardHide = Image(Point(200, 100),
                               "b1fv.gif")  #back of card to hide dealer's card
        dealercardHide.draw(win)

        dealerTotal = Text(Point(100, 125),
                           "Total: " + str(game.evaluateHand(dealerHand)))
        #       dealerTotal.draw(win) #total up the hand of the dealer

        playerTotal = Text(Point(100, 425),
                           "Total: " + str(game.evaluateHand(playerHand)))
        playerTotal.draw(win)  #total up the hand of the player
        playerMoney = Text(Point(100, 550), "Money: $ " + str(totalMoney))
        playerMoney.draw(win)
        pt = win.getMouse()  #wait for mouse click

        while button1.isClicked(pt) == False and button2.isClicked(pt) == False and \
              button3.isClicked(pt) == False and betButton.isClicked(pt)==False: #if click is not on button, get another mouse click
            pt = win.getMouse()

        if betButton.isClicked(pt) == True:
            bet = inputBox.getText()
            while bet == "":
                tryAgain = Text(Point(700, 255), "You forgot to enter a bet!")
                tryAgain.draw(win)
                pt = win.getMouse()
                if betButton.isClicked(pt) == True:
                    bet = inputBox.getText()
                tryAgain.undraw()
            bet = int(bet)
            while bet > totalMoney:
                tryAgain = Text(
                    Point(700, 255),
                    "You don't have that much money. \nTry again.")
                tryAgain.draw(win)
                inputBox.setText("")
                pt = win.getMouse()
                if betButton.isClicked(pt):
                    bet = int(inputBox.getText())
                tryAgain.undraw()
            betButton.deactivate()
            playerBet = Text(Point(100, 575), "Bet:  $" + str(bet))
            playerBet.draw(win)
            button1.activate()
            button2.activate()
            button3.activate()
            pt = win.getMouse()
        xPos = 400  #set x value of cards
        cardHitlist = []  #make a list to store all new cards that are dealt
        while button1.isClicked(pt) == True:  #if a hit
            cardHit = game.hit(win, xPos, 400)  #hit
            cardHitlist.append(cardHit)  #add card to the list
            #how to get a second hit card to be next to it, not on top?
            playerTotal.undraw()
            playerTotal = Text(Point(100, 425),
                               "Total: " + str(game.evaluateHand(playerHand)))
            playerTotal.draw(win)  #update the total
            dealerCardlist = []
            if game.evaluateHand(
                    playerHand) > 21:  #if the player's score is over 21
                dealercardHide.undraw()  #show the dealers card
                dealerTotal.draw(win)
                resultText = Text(Point(400, 200),
                                  "You busted! The dealer wins.")  #busted
                resultText.setStyle("bold")
                resultText.setSize(20)
                resultText.draw(win)
                button1.deactivate()  #deactivate buttons
                button2.deactivate()
                playagain.activate()
                totalMoney = totalMoney - bet
                playerMoney.undraw()
                playerMoney = Text(Point(100, 550),
                                   "Money: $ " + str(totalMoney))
                playerMoney.draw(win)
                pt = win.getMouse()  #get another click, can play again
            elif game.evaluateHand(playerHand) == 21:  #if equal to 21
                dealercardHide.undraw()  #show dealers card
                dealerTotal.draw(win)
                resultText = Text(
                    Point(400, 200),
                    "Your total is " + str(game.evaluateHand(playerHand)) + "."
                    "  You win!")
                resultText.setStyle("bold")
                resultText.setSize(20)
                resultText.draw(win)
                button1.deactivate()  #deactivate other buttons
                button2.deactivate()
                playagain.activate()
                totalMoney = totalMoney + bet
                playerMoney.undraw()
                playerMoney = Text(Point(100, 550),
                                   "Money: $ " + str(totalMoney))
                playerMoney.draw(win)
                pt = win.getMouse()  #wait for click, can play again
            elif game.evaluateHand(
                    playerHand) < 21:  #if less than 21, can go again!
                pt = win.getMouse()
            xPos = xPos + 100  #add 100 pixels to x value so cards are not on top of each other

        while button2.isClicked(pt) == True:  #if stand
            dealerCardlist = game.dealerPlays(win, game, 400,
                                              100)  #dealer plays out hand
            dealercardHide.undraw()
            dealerTotal.undraw()
            dealerTotal = Text(Point(100, 125),
                               "Total: " + str(game.evaluateHand(dealerHand)))
            dealerTotal.draw(win)  #update dealer total
            button1.deactivate()  #deactivate buttons
            button2.deactivate()
            if game.evaluateHand(
                    dealerHand) > 21:  #if dealer hand is over 21, they busted
                dealercardHide.undraw()
                resultText = Text(Point(400, 200),
                                  "The dealer busted. You win!")  #you win yay!
                resultText.setStyle("bold")
                resultText.setSize(20)
                resultText.draw(win)
                totalMoney = totalMoney + bet
                playerMoney.undraw()
                playerMoney = Text(Point(100, 550),
                                   "Money: $ " + str(totalMoney))
                playerMoney.draw(win)
            elif game.evaluateHand(
                    dealerHand
            ) == 21:  #if dealer hand equals 21, they win. sorry
                dealercardHide.undraw()
                resultText = Text(
                    Point(400, 200), "The dealer's total is " +
                    str(game.evaluateHand(dealerHand)) + "."
                    " Your total is " + str(game.evaluateHand(playerHand)) +
                    ".  The dealer wins.")
                resultText.setStyle("bold")
                resultText.setSize(20)
                resultText.draw(win)
                totalMoney = totalMoney - bet
                playerMoney.undraw()
                playerMoney = Text(Point(100, 550),
                                   "Money: $ " + str(totalMoney))
                playerMoney.draw(win)
            elif game.evaluateHand(dealerHand) < 21 and game.evaluateHand(playerHand) > \
                game.evaluateHand(dealerHand): #player wins if their hand is bigger than dealers hand
                dealercardHide.undraw()
                resultText = Text(
                    Point(400, 200), "The dealer's total is " +
                    str(game.evaluateHand(dealerHand)) + "."
                    "Your total is " + str(game.evaluateHand(playerHand)) +
                    ".  You win!")
                resultText.setStyle("bold")
                resultText.setSize(20)
                resultText.draw(win)
                totalMoney = totalMoney + bet
                playerMoney.undraw()
                playerMoney = Text(Point(100, 550),
                                   "Money: $ " + str(totalMoney))
                playerMoney.draw(win)
            elif game.evaluateHand(dealerHand) < 21 and game.evaluateHand(playerHand) < \
                 game.evaluateHand(dealerHand): #if both hands less than 21, player hand less than dealer
                #then the dealer wins
                dealercardHide.undraw()
                resultText = Text(
                    Point(400, 200), "The dealer's total is " +
                    str(game.evaluateHand(dealerHand)) + "."
                    "Your total is " + str(game.evaluateHand(playerHand)) +
                    ".  The dealer wins.")
                resultText.setStyle("bold")
                resultText.setSize(20)
                resultText.draw(win)
                totalMoney = totalMoney - bet
                playerMoney.undraw()
                playerMoney = Text(Point(100, 550),
                                   "Money: $ " + str(totalMoney))
                playerMoney.draw(win)
            elif game.evaluateHand(dealerHand) < 21 and game.evaluateHand(playerHand) == \
                 game.evaluateHand(dealerHand): #if a tie
                dealercardHide.undraw()
                resultText = Text(Point(400, 200), "It's a tie.")  #stand off
                resultText.setStyle("bold")
                resultText.setSize(20)
                resultText.draw(win)
            playagain.activate(
            )  #activate the play again button, so they can play again
            pt = win.getMouse()  #wait for click

        if playagain.isClicked(
                pt
        ) == True:  #if the button is clicked player wants to play again
            ##            if totalMoney == 0:
            ##                resultText.undraw()
            ##                resultText = Text(Point(400, 200), "You lost all your money. Game over.") #stand off
            ##                resultText.setStyle("bold")
            ##                resultText.setSize(20)
            ##                resultText.draw(win)
            ##                playagain.rect.undraw()
            ##                playagain.label.undraw()
            ##                button1.rect.undraw()
            ##                button1.label.undraw()
            ##                button2.rect.undraw()
            ##                button2.label.undraw()
            ##                button3.activate()
            ##                dealerTotal.undraw()
            ##                playerTotal.undraw()
            ##                askforbet.undraw()
            ##                inputBox.undraw()
            ##                betButton.rect.undraw()
            ##                betButton.label.undraw()
            ##                playerMoney.undraw()
            ##                playerBet.undraw()
            ##                playerText.undraw()
            ##                dealerText.undraw()
            ##                for card in cardHitlist: #undraw the cards that were hit
            ##                    card.undraw()
            ##                for card in dealerCardlist: #undraw the cards that the dealer got
            ##                    card.undraw()
            #       else:
            play = True
            resultText.undraw()  #clear the previous game
            playagain.rect.undraw()
            playagain.label.undraw()
            button1.rect.undraw()
            button1.label.undraw()
            button2.rect.undraw()
            button2.label.undraw()
            button3.rect.undraw()
            button3.label.undraw()
            dealerTotal.undraw()
            playerTotal.undraw()
            askforbet.undraw()
            inputBox.undraw()
            betButton.rect.undraw()
            betButton.label.undraw()
            playerMoney.undraw()
            playerBet.undraw()
            playerText.undraw()
            dealerText.undraw()
            for card in cardHitlist:  #undraw the cards that were hit
                card.undraw()
            for card in dealerCardlist:  #undraw the cards that the dealer got
                card.undraw()
            #need to undraw the new cards before replaying
        if button3.isClicked(pt) == True:
            play = False  #if clicks quit, end the game
            gwin = GraphWin("Results!", 300, 300)
            gwin.setBackground("black")
            score = Text(Point(150, 100),
                         "Your score is: $" + str(totalMoney) + ".")
            score.setFill("white")
            score.draw(gwin)
            info = Text(
                Point(150, 175),
                "The high scores have been recorded in the file\n"
                "highscores.txt on your computer. See where you ranked!")
            info.setFill("white")
            info.draw(gwin)
            outputFileName = "highscores.txt"
            outputFile = open(outputFileName, "a")
            outputFile.write("\nScore:  $" + str(totalMoney) + ".")
            close = Text(Point(150, 250), "Click anywhere to close.")
            close.setFill("white")
            close.draw(gwin)
            gwin.getMouse()
            gwin.close()

    win.close()
Exemplo n.º 29
0
 def __init__(self):
     self.the_doctor = Player("The Doctor")
     self.the_master = Player("The Master")
     self.dealer = Player("Dealer")
     self.game = BlackJack([self.the_doctor, self.the_master], self.dealer)
    fig = plt.figure() 
    ax = fig.gca(projection='3d') 
    ax.plot_surface(dealer, player, values_ua,  cmap=cm.coolwarm,
                       linewidth=0)
    plt.title("State value function (usable ace)")
    plt.xlabel("Dealer showing")
    plt.ylabel("Player sum")


#%%
if __name__ ==  "__main__":   

    num_episodes = 500000
    gamma = 1
    env = BlackJack()
    states = env.state_space()
    init_policy_player = policy(states)
    
    policy_player = Monte_carlo_exploring_starts(env, states, 
                                                 init_policy_player,
                                                 num_episodes, gamma) 
    #%%
    VF = first_visit_MC_prediction(env,  states, policy_player, 
                                   num_episodes, gamma) 
    
    #%%
    plot_policy(policy_player)  
    plot_value_function(VF)
    
Exemplo n.º 31
0
from blackjack import BlackJack

if __name__ == "__main__":
    blackjack = BlackJack()