def __init__(self, pcard1=0, pcard2=0, pcard3=0, pcard4=0, pcard5=0, dcard1=0, dcard2=0, dcard3=0, dcard4=0, dcard5=0, qdecks=1): self.pcard1 = pcard1 self.pcard2 = pcard2 self.pcard3 = pcard3 self.pcard4 = pcard4 self.pcard5 = pcard5 self.dcard1 = dcard1 self.dcard2 = dcard2 self.dcard3 = dcard3 self.dcard4 = dcard4 self.dcard5 = dcard5 self.qdecks = qdecks self.main() self.blackjack = Blackjack(self.pcard1, self.pcard2, self.pcard3, self.pcard4, self.pcard5, self.dcard1, self.dcard2, self.dcard3, self.dcard4, self.dcard5, self.qdecks) self.inicio_partida()
def _newGame(self): """Instantiates the model and establishes the GUI""" self._model = Blackjack() #Refresh the card panes #Player Cards self._playerImages = list( map(lambda card: PhotoImage(file=card.getFilename()), self._model.getPlayerCards())) self._playerLabels = list( map(lambda i: Label(self._playerPane, image=i), self._playerImages)) for col in range(len(self._playerLabels)): self._playerLabels[col].grid(row=0, column=col) #Dealer Cards self._dealerImages = list( map(lambda card: PhotoImage(file=card.getFilename()), self._model.getDealerCards())) self._dealerLabels = list( map(lambda i: Label(self._dealerPane, image=i), self._dealerImages)) for col in range(len(self._dealerLabels)): self._dealerLabels[col].grid(row=0, column=col) #Re-enable the buttons and clear the status field self._hitButton["state"] = NORMAL self._passButton["state"] = NORMAL self._statusVar.set("")
def main(): banker = Player("Banker", 100) player = Player("Player", 100) game = Blackjack([banker, player]) game.init_game() while True: game.run_one_round()
def run_Black_Jack_environment(self, q_t, q_c, mode): # Start a new game game = Blackjack(mode) state = game.get_state() rl_state = self.get_rl_state(state, game) # Convert to condensed RL state # Create dictionary to temporarily hold the current game's state-actions returns = {} # (state, decision): reward while game.get_status() == 1: # While game state is not terminal # Epsilon-greedy action selection action_probs = self.get_q_reward(rl_state, q_t) if random.random() < EPSILON: decision = random.randint(0, 1) else: decision = np.argmax( action_probs ) # Select an action with the highest probability sa = (rl_state, decision) # Add an action-value pair to returns list. Default value is 0 returns[sa] = 0 q_c[sa] += 1 # Increment average counter game.play_game(decision) # Make a move state = game.get_state() # Get the new game state rl_state = self.get_rl_state(state, game) # Compress state # After a game is finished, assign rewards to all state-actions that took place in the game for key in returns: returns[key] = self.get_reward(state[2]) q_t = self.update_table(q_t, q_c, returns) return q_t, q_c
def iniciarServidor(): # Se carga el diccionario a partir de un archivo files = os.listdir("lenguaje") for f in files: with open(os.path.join("lenguaje", f)) as json_file: name = Path(f).resolve().stem diccionario[name] = json.load(json_file) puerto = 3039 # Se inicia la instancia del juego de Blackjack que es compartida por todos los threads blackGame = Blackjack(diccionario) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', puerto)) print(crearMensajeLog("Socket bindeado")) sock.listen(5) print(crearMensajeLog("Socket escuchando")) while True: cliente, direccionCliente = sock.accept() print(cliente) print(crearMensajeLog("Nuevo jugador desde: " + direccionCliente[0])) # Se inicia un thread por cada cliente conectado. Este thread tiene acceso a la instancia de blackjack. start_new_thread(inicializarCliente, (cliente, blackGame)) sock.close()
def setUp(self): self.blackjack = Blackjack() self.deck = self.blackjack.deck self.suits = ["♣", "♦", "♥", "♠"] self.numbers = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Q", "J", "K" ]
def start_game(bot, update): global bjack bjack = Blackjack() c = bjack.pop_card() global user_cards user_cards = [c] update.message.reply_text("Hai tirato su %s" % str(c)) update.message.reply_text("Vuoi contuinuare?")
def runPlays(times): blackjack = Blackjack(1, 1) blackjack.shuffle() for i in range(times): if i % 100000 == 0: print(i) blackjack.play() print(blackjack)
def test_score_21_with_only_numbers(self): cards = [ Card(rank='10', suit='♠'), Card(rank='5', suit='♠'), Card(rank='6', suit='♠') ] blackjack = Blackjack() self.assertEqual(21, blackjack.score(cards))
def test_score_21_with_as_worth_11(self): cards = [ Card(rank='A', suit='♠'), Card(rank='8', suit='♠'), Card(rank='2', suit='♠') ] blackjack = Blackjack() self.assertEqual(21, blackjack.score(cards))
def __init__(self): self.bj = Blackjack() self.root = Tk() self.canvas = Canvas(self.root, width = 900, height = 600) self.canvas.pack() self.canvas.configure(background='green') self.addInputs() self.addButtons() self.addLables() self.addDeck() self.root.mainloop()
def test_state(self): play = Blackjack('You') assert play.player.stat is None play.player.draw_card(0) play.player.draw_card(10) play._check_points(play.player) assert play.player.stat == 'blackjack' play.player.draw_card(11) play.player.draw_card(12) play._check_points(play.player) assert play.player.stat == 'bust'
def _newGame(self): self.destroy() Frame.__init__(self) self.master.title("Blackjack") self.grid() #Add the command buttons self._hitButton = Button(self, text="Hit", command=self._hit) self._hitButton.grid(row=0, column=0) self._passButton = Button(self, text="Pass", command=self._pass) self._passButton.grid(row=0, column=1) self._newGameButton = Button(self, text="New Game", command=self._newGame) self._newGameButton.grid(row=0, column=2) #Add the status field self._statusVar = StringVar() self._statusField = Entry(self, textvariable=self._statusVar) self._statusField.grid(row=1, column=0, columnspan=3) #Add the panes for the player and dealer cards self._playerPane = Frame(self) self._playerPane.grid(row=2, column=0, columnspan=3) self._dealerPane = Frame(self) self._dealerPane.grid(row=3, column=0, columnspan=3) ## self._model = Blackjack() #Refresh the card panes #Player Cards self._playerImages = list( map(lambda card: getCardImage(card), self._model.getPlayerCards())) self._playerLabels = list( map(lambda i: Label(self._playerPane, image=i), self._playerImages)) for col in range(len(self._playerLabels)): self._playerLabels[col].grid(row=0, column=col) #Dealer Cards self._dealerImages = list( map(lambda card: getCardImage(card), self._model.getDealerCards())) self._dealerLabels = list( map(lambda i: Label(self._dealerPane, image=i), self._dealerImages)) for col in range(len(self._dealerLabels)): self._dealerLabels[col].grid(row=0, column=col) #Re-enable the buttons and clear the status field self._hitButton["state"] = NORMAL self._passButton["state"] = NORMAL self._statusVar.set("")
def test_check_draw(self): #Testing if the game ends when there's a draw deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", "Jack", 10)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", "Jack", 10)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertFalse(bj.game_running, "Game should be over since the game drawed")
def run(): game = Blackjack() print('This is a simple reinforcement learning based blackjack game') train_ai(game) while True: try: userInput = int( input( "Great ! Would you like to play yourself or let the AI do the work ? \n1. AI\n2. Self\n" )) except ValueError: print("Not an integer! Try again.") continue else: if userInput == 1 or userInput == 2: break else: print("Not a valid option ! Please enter 1 or 2") continue if userInput == 1: game.play_ai() else: game.play() while True: print("\n\nCurrent scores:") print("Player: {}".format(game.player_score)) print("Dealer: {}\n\n".format(game.dealer_score)) while True: try: userInput = int( input( "What do we do now ? \n1. AI Play\n2. Self Play\n3. Improve Model\n4. Exit\n" )) except ValueError: print("Not an integer! Try again.") continue else: if userInput >= 1 or userInput <= 4: break else: print("Not a valid option ! Please enter 1 or 2") continue if userInput == 1: game.play_ai() elif userInput == 2: game.play() elif userInput == 3: train_ai(game) elif userInput == 4: break return 0
def inicio_partida(self): self.pcard1 = input('Digite a sua primeira carta: ') self.pcard2 = input('Digite a sua segunda carta: ') self.dcard1 = input('Digite a carta revelada do Dealer: ') self.qdecks = input('Digite a quantidade de baralhos: ') self.blackjack = Blackjack(self.pcard1, self.pcard2, self.pcard3, self.pcard4, self.pcard5, self.dcard1, self.dcard2, self.dcard3, self.dcard4, self.dcard5, self.qdecks) self.main() self.escolher_sugestao()
def test_check_dealer_win( self): #Testing if the game ends if the dealer wins deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", 2, 2)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", 7, 7)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertFalse(bj.game_running, "Game should be over since the dealer won")
def do_PUBLISH(self): """ When the shuffled and encrypted deck is published """ data.deck = [Card(e) for e in self.body_json()['deck']] # We can do our round of decryption now for (key, card) in zip(data.card_keys, data.deck): card.decrypt(key) self.send_response(HTTPStatus.OK) self.end_headers() # Initialize game mechanics data.mechanics = Blackjack(data.players, data.deck, data.key_pair, data.name)
def test_check_keeps_going( self ): #Testing if the game keeps running even if the dealer has more value than the player (dealer has to keep hitting till he hits atleast 17) deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", 2, 2)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", 4, 4)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertTrue( bj.game_running, "Game should keep running since the dealer hasn't hit atleast 17 value yet" )
def func(args): # # generate epsiode # blackjack = Blackjack() (episode, reward) = blackjack.play() logging.info('{1} -> {2:2d} [ {0} ]'.format(args, blackjack, reward)) # # calculate returns # returns = Returns() for (state, _) in episode: returns[state.ace][state].append(reward) return returns
def __init__(self): self.pack = Pack() self.blackjack = Blackjack() self.players = [] available_players = random.sample([HumanPlayer, CpuPlayer], k=2) for available_player in available_players: player = available_player() player.cards = self.init_deck() obj_player = { 'player': player, 'cards': player.cards, 'score': player.score, 'name': str(uuid.uuid4()) } self.players.append(obj_player) self.main()
def test_get_final_result_splits(self): blackjack = Blackjack() blackjack.bet = 10 blackjack.spec_player_add_hand([0, 9]) # A, 10: 21 blackjack.spec_player_add_hand([9, 9]) # 20 blackjack.spec_house_set_hand([9, 7]) # 18 result, net_money = blackjack.get_final_result(1) self.assertEqual(result, Blackjack.PlayResult.WIN) self.assertEqual(net_money, 10) blackjack.spec_player_add_hand([27, 37, 44]) # 2D, QD, 6C: 18 result, net_money = blackjack.get_final_result(2) self.assertEqual(result, Blackjack.PlayResult.PUSH) self.assertEqual(net_money, 0) blackjack.spec_player_add_hand([51, 13]) # KC, AS: 21 result, net_money = blackjack.get_final_result(3) self.assertEqual(result, Blackjack.PlayResult.BLACKJACK) self.assertEqual(net_money, 15)
def test_get_final_result_basic(self): blackjack = Blackjack() blackjack.bet = 10 blackjack.spec_player_add_hand([0, 9]) # A, 10: 21 blackjack.spec_house_set_hand([9, 4]) # 10, 5: 15 result, net_money = blackjack.get_final_result(0) self.assertEqual(result, Blackjack.PlayResult.BLACKJACK) self.assertEqual(net_money, 15) blackjack.clear() blackjack.spec_player_add_hand([4, 9]) # 15 blackjack.spec_house_set_hand([9, 9]) # 20 result, net_money = blackjack.get_final_result(0) self.assertEqual(result, Blackjack.PlayResult.LOSS) self.assertEqual(net_money, -10) blackjack.clear() blackjack.spec_player_add_hand([9, 9]) # 20 blackjack.spec_house_set_hand([9, 6]) # 17 result, net_money = blackjack.get_final_result(0) self.assertEqual(result, Blackjack.PlayResult.WIN) self.assertEqual(net_money, 10) blackjack.clear() blackjack.spec_player_add_hand([9, 9]) # 20 blackjack.spec_house_set_hand([9, 9]) # 20 result, net_money = blackjack.get_final_result(0) self.assertEqual(result, Blackjack.PlayResult.PUSH) self.assertEqual(net_money, 0) blackjack.clear() blackjack.spec_player_add_hand([9, 9, 3]) # 22 blackjack.spec_house_set_hand([9, 9]) # 20 result, net_money = blackjack.get_final_result(0) self.assertEqual(result, Blackjack.PlayResult.BUST) self.assertEqual(net_money, -10)
def __init__(self, master=None): super().__init__(master) self.master = master self.master.title("Blackjack - Basic Strategy") # self.master.iconbitmap('out3_nr3_icon.ico') self.master.geometry("900x500") self.pack(fill="both", expand=1) self.game = Blackjack() self.bg_color = "#006644" self.t_color = "#fcf403" self.h_color = "#005634" self.card_width = 100 self.card_height = 145 self.display_hidden_house = False self.game_finished = True self.images_load() self.widgets_create() self.scene_update()
def func(args): (games, gamma) = args state = State(13, 2, True) actions = (True, False) b = 1 / len(actions) Q = cl.defaultdict(float) C = cl.defaultdict(int) ordinary = [] weighted = [] for i in range(games): blackjack = Blackjack(state, RandomPlayer) (episode, reward) = blackjack.play() G = 0 W = 1 for e in it.takewhile(lambda _: W, reversed(episode)): G = gamma * G + reward C[e] += W Q[e] += (W / C[e]) * (G - Q[e]) (s, a) = e # player = Player(s.player, 2, s.ace) # action = player.hit(s.dealer) action = bj.fairmax(Q, s) if a != action: break W *= 1 / b ordinary.append(W * G) weighted.append(W) r = sum(rewards) return (r / x for x in (len(rewards), sum(weighted)))
def __init__(self): self.game = Blackjack(6)
from blackjack import Deck, Player, Blackjack #The classes are instantiated deck = Deck() deck.shuffle() player = Player("Mikkel") dealer = Player("dealer") bj = Blackjack(player, dealer, deck) while bj.game_running == True: #A loop that keeps the game running untill the player decides he wants to quit bj.run_game() #The game is started if bj.player.cash == 0: print("Your balance is 0 and you will have to rebuy to play again.") if input("Play again? Press any key to play or press q to quit! ") == "q": #If the player presses "q" the game stops - if not the game starts again quit() else: #The else block resets the game bj.game_running = True player.hand = [] dealer.hand = []
self.dealer_hit_value) > 21: print("Dealer Busts! You win!") total() play_again() if sum(deck.dealer_hand_values + self.dealer_hit_value) >= 17: if self.user_hit_or_stay == "hit": continue elif sum(deck.dealer_hand_values + self.dealer_hit_value) < sum(deck.user_hand_values + self.hit_value): print("You win!") total() play_again() elif sum(deck.dealer_hand_values + self.dealer_hit_value) == sum(deck.user_hand_values + self.hit_value): print("Draw!") total() play_again() else: print("Dealer wins!") total() play_again() Blackjack() Game()
def setUp(self): self.game = Blackjack()
def to_action(self, action): if Blackjack.HITS == action: return "HITS" elif Blackjack.STICK == action: return "STICK" elif Blackjack.USE_ACE == action: return "USE_ACE" elif Blackjack.IDLE_ACE == action: return "IDLE_ACE" else: return "ANON" if __name__ == '__main__': bj = Blackjack(1000) state = bj.reset() print('deck = ', bj.show_deck()) print('dealer top card: %d' % bj.dealer_top_card()) print('player cards : %s' % str(bj.player_cards())) print('player hand : %d' % bj.player_hand()) print('start state = %s' % str(state)) terminate = False while not terminate: action = np.random.randint(0, 4) state, reward, terminate = bj.step(action) print('action = ', bj.to_action(action), ' next state = ', state,