예제 #1
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
예제 #2
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()
예제 #3
0
파일: Irx.py 프로젝트: 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))