Ejemplo n.º 1
0
 def assert_game_result(self, game: Game,
                        test_case: unittest.TestCase) -> None:
     test_case.assertEqual(self.deuce, game.deuce())
     test_case.assertEqual(self.player_busts, game.player_busts())
     test_case.assertEqual(self.croupier_busts, game.croupier_busts())
     test_case.assertEqual(self.croupier_wins, game.croupier_wins())
     test_case.assertEqual(self.player_wins, game.player_wins())
Ejemplo n.º 2
0
class Strategy(object):
    def __init__(self):
        self.game = Game(mode="automated", print_games=False)
        self.result = self.play()

    def play(self):
        while True:
            game_result = self.decide()

            if game_result:
                break

        return game_result

    def decide(self):
        raise NotImplementedError

    def issue_command(self, cmd, game=None):
        try:
            if game:
                game.dealer_command(cmd)
            else:
                self.game.dealer_command(cmd)
            return None

        except PlayerWins:
            return "win"

        except DealerWins:
            return "lose"

        except Push:
            return "draw"

        return None
Ejemplo n.º 3
0
    def test_setup_new_game(self):
        """The method used to make sure that a new game can be properly set up."""

        # Create a new game and make sure it has the correct settings
        game = Game()
        game.setup_new_game()
        self.assertTrue(game.dealer is not None, msg="The dealer of the game was not created.")
        self.assertEqual(game.dealer.cards, [])
        self.assertEqual(game.state.name, "get_number_of_packs", msg="The initial game state was not correctly set.")
Ejemplo n.º 4
0
def main():
    keep_playing = True
    while keep_playing:
        game = Game()
        game.play()
        answer = input(
            "Do you want to play one more game? Type 'y' or 'n': ").lower().strip()
        if answer == 'n':
            keep_playing = False
        print()
Ejemplo n.º 5
0
def test_start_ace_low():
    # give
    deck = _create_deck([1, 1], [3])
    game = Game(deck)

    # when
    state = game.start()

    # then
    assert state['player_score'] == 12
    assert state['player_has_ace'] == True
Ejemplo n.º 6
0
def test_start_state2():
    # give
    deck = [2, 3, 4]
    game = Game(deck)

    # when
    state = game.start()

    # then
    assert state['player_score'] == 6
    assert state['player_has_ace'] == False
    assert state['dealer_score'] == 3
Ejemplo n.º 7
0
def test_start():
    # give
    deck = _create_deck([2, 4], [3])
    game = Game(deck)

    # when
    state = game.start()

    # then
    assert state['player_score'] == 6
    assert state['player_has_ace'] == False
    assert state['dealer_score'] == 3
Ejemplo n.º 8
0
def simulateGames(n, model):
    games = [0, 0, 0]
    for i in range(n):
        game = Game()
        game.deal()

        while hit(game.state(), model):
            game.pPlay()
            if game.player.bust():
                break
        game.dPlay()

        games[game.result()] += 1
    print(games)
Ejemplo n.º 9
0
async def blackjack(ctx):

    server = ctx.message.server
    server_id = ctx.message.server.id
    player_id = ctx.message.author.id

    game = Game(server, server_id, player_id, bot)
    game.deal()
    await game.play(ctx)

    updated_money = Decimal(game.player.money).quantize(Decimal('.01'),
                                                        rounding=ROUND_DOWN)
    db.update_money(server_id, player_id, updated_money)
    return
Ejemplo n.º 10
0
    def getSimulator(self, simulator):
        if simulator == "logistics":
            return Logistics(start=True)

        elif simulator == "pong":
            return Pong(start=True)

        elif simulator == "tetris":
            return Tetris(start=True)

        elif simulator == "wumpus":
            return Wumpus(start=True)

        elif simulator == "blocks":
            return Blocks_world(start=True)

        elif simulator == "blackjack":
            return Game(start=True)

        elif simulator == "50chain":
            return Chain(start=True)

        elif simulator == "net_admin":
            return Admin(start=True)
        else:
            print('{} is not a supported simulation'.format(simulator))
            raise NameError()
Ejemplo n.º 11
0
class TestGame(unittest.TestCase):

    def setUp(self):
        self.player_hands = 4
        self.game = Game(self.player_hands)
   
    def test_deck(self):
        self.assertEqual(self.game.deck.__class__, Deck)

    def test_player_hands(self):
        self.game.initial_deal()
        self.assertEqual(self.player_hands, len(self.game.player_hands))
        for hand in self.game.player_hands:
            self.assertEqual(2, len(hand))

    def test_dealer_hand(self):
        self.game.initial_deal()
        self.assertEqual(1, len(self.game.dealer_hand))

    def test_initial_deal(self):
        dealt_cards = self.game.deck.cards[0:9]
        
        self.game.initial_deal()

        self.assertEqual(dealt_cards[0], self.game.player_hands[0][0])
        self.assertEqual(dealt_cards[1], self.game.player_hands[1][0])
        self.assertEqual(dealt_cards[2], self.game.player_hands[2][0])
        self.assertEqual(dealt_cards[3], self.game.player_hands[3][0])
        self.assertEqual(dealt_cards[4], self.game.dealer_hand[0])
        self.assertEqual(dealt_cards[5], self.game.player_hands[0][1])
        self.assertEqual(dealt_cards[6], self.game.player_hands[1][1])
        self.assertEqual(dealt_cards[7], self.game.player_hands[2][1])
        self.assertEqual(dealt_cards[8], self.game.player_hands[3][1])
Ejemplo n.º 12
0
class TestGame(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.game = Game()

    def test_generate_deck(self):
        self.assertEqual(len(self.game.card_deck), 52)

    def test_deal_hand(self):
        hand = self.game.deal_hand()
        self.assertEqual(len(hand), 2)
        self.assertEqual(len(self.game.card_deck), 50)
Ejemplo n.º 13
0
 def parse_mentions(self):
     mentions = list(self.reddit.inbox.unread())
     for mention in mentions:
         user = sql.get_user(mention.author.name)
         if 'deal me in' in mention.body.lower():
             if not user.game:
                 logging.info('Dealing new hand to %s', user.name)
                 user.game = Game()
                 user.game.game_id = self.sql.insert_new_game(user)
                 self.sql.charge_user(user)
                 user.game.deal()
             else:
                 self.generate_error_message(
                     mention,
                     "Invalid action - user already has game active")
         # Write logic for variable bets here
         # Need to find "bet" in string, then parse out the following int
         if re.match(r"\bhit\b", mention.body.lower()):
             if user.game and user.game.can_hit():
                 logging.info('%s hits', user.name)
                 user.game.player_hit()
             else:
                 logging.info('%s invalid hit', user.name)
                 self.generate_error_message(
                     mention,
                     "Invalid action - Hit not allowed in game state")
         if re.match(r"\bstay\b", mention.body.lower()):
             logging.info('%s stays', user.name)
             if user.game:
                 user.game.player_stay()
                 user.game.dealer_play()
             else:
                 logging.info('%s invalid stay', user.name)
                 self.generate_error_message(
                     mention,
                     "Invalid action - Stay not allowed without active game"
                 )
         if user.game:
             mention.reply(self.generate_reply(user.game))
             # print(self.generate_reply(user.game))
             self.sql.store_hand_state(user)
             if user.game.game_complete:
                 logging.info('Game complete. User: %s - Game ID: %s',
                              user.name, user.game.game_id)
                 self.sql.pay_user(user)
             mention.mark_read()
Ejemplo n.º 14
0
def simulateGames():
    game = Game()
    game.deal()
    game.dPlay()
    while True:
        #cardState = game.state()
        ########################################################
        """
        hard, value = hardValue(game.player)
        deal = game.dealer.value()
        if hard:
            if value <= 11:
                hit = 1
            elif value == 12:
                if 4 <= deal <= 6:
                    hit = 0
                else:
                    hit = 1
            elif 13 <= value <= 16:
                if 2 <= deal <= 6:
                    hit = 0
                else:
                    hit = 1
            elif value >= 17:
                hit = 0
        else:
            if value <= 17:
                hit = 1
            elif value == 18:
                if deal in [9,10,11]:
                    hit = 1
                else:
                    hit = 0
            else:
                hit = 0
        """
        state, hit = strat(game)
        states.append(state)
        hits.append(hit)
        ########################################################
        if game.player.bust():
            break
        game.pPlay()
Ejemplo n.º 15
0
    def parse():
        f = open("log.txt")
        line = f.readline()

        while line != "":
            hand, dealer, move, outcome = line.split(" ")
            key = hand, dealer
            move_key = int(float(move))
            outcome_key = int(float(outcome))

            if key not in Parser.freq:
                Parser.freq[key] = {
                    Player.move("HIT"): [0,0],
                    Player.move("STAY"): [0,0]
                    }

            if outcome_key == Game.round_outcome("WIN"):
                Parser.freq[key][move_key][0] += 1

            Parser.freq[key][move_key][1] += 1

            line = f.readline()
        f.close()
 def __init__(self, strategy="advanced"):
     self.strategy = Strategy(strategy)
     Game.__init__(self)
Ejemplo n.º 17
0
 def test_deal(self):
     rand.seed(7)
     game = Game()
     game.deal()
     result = game.dealer.hand[1].val == 3
     self.assertTrue(result)
Ejemplo n.º 18
0
def game():
    game = Game()
    return game
Ejemplo n.º 19
0
    def test_set_pack_number(self):
        """The method used to make sure that the number of packs of cards used in the deck can be set."""

        # Setup new games and attempt to set their number of packs
        valid_packs = [
            1,
            2,
            3,
            4,
            5,
            100,
        ]
        for packs in valid_packs:
            game = Game()
            game.setup_new_game()
            self.assertEqual(game.state.name, "get_number_of_packs", msg="The initial game state was not correctly set.")
            game.set_pack_number(packs)
            self.assertEqual(len(game.deck), packs * 52, msg="The number of packs was not correctly set with " + str(packs) + " packs.")

            # Make sure that the new game state was correctly set
            self.assertEqual(game.state.name, "get_player_chips", msg="The game state after setting the number of packs was not correctly set.")

        # Try to set invalid pack numbers
        invalid_packs = [
            -1,
            0,
            -100,
            1.5,
        ]
        for packs in invalid_packs:
            game = Game()
            game.setup_new_game()
            self.assertEqual(game.state.name, "get_number_of_packs", msg="The initial game state was not correctly set.")
            success = False
            try:
                game.set_pack_number(packs)
            except InvalidPackNumber:
                success = True
            self.assertTrue(success, msg="An invalid number of packs " + str(packs) + " was able to be set.")

        # Try to reset the number of packs to throw an error
        game = Game()
        game.setup_new_game()
        self.assertEqual(game.state.name, "get_number_of_packs", msg="The initial game state was not correctly set.")
        game.set_pack_number(1)
        success = False
        try:
            game.set_pack_number(1)
        except InvalidGameMethodOrder:
            success = True
        self.assertTrue(success, msg="The number of packs in a deck was incorrectly able to be reset.")
Ejemplo n.º 20
0
from blackjack import Game

blackjack_game = Game()
blackjack_game.start_game()
blackjack_game.stop_game()
Ejemplo n.º 21
0
    def test_set_starting_chips(self):
        """The method used to make sure that the number of starting chips for each player can be set."""

        # Setup new game and attempt to set their valid number of starting chips
        valid_chips = [
            1,
            10,
            100,
            9999,
        ]
        for chips in valid_chips:
            game = Game()
            game.setup_new_game()
            game.set_pack_number(1)
            game.set_starting_chips(chips)
            self.assertEqual(game.starting_chips, chips, msg="The number of player starting chips was not correctly set with " + str(chips) + " chips.")

            # Make sure that the new game state was correctly set
            self.assertEqual(game.state.name, "get_number_of_players", msg="The game state was not correctly set after setting the number of starting chips.")

        # Try to set invalid chip numbers
        invalid_chips = [
            0,
            -1,
            -100,
            1.5,
            -1.5,
        ]
        for chips in invalid_chips:
            game = Game()
            game.setup_new_game()
            game.set_pack_number(1)
            success = False
            try:
                game.set_starting_chips(chips)
            except InvalidGameStartingChips:
                success = True
            self.assertTrue(success, msg="An invalid number of starting chips " + str(chips) + " was able to be set.")

        # Try to reset the number of starting chips to throw an error
        game = Game()
        game.setup_new_game()
        game.set_pack_number(1)
        game.set_starting_chips(100)
        success = False
        try:
            game.set_starting_chips(200)
        except InvalidGameMethodOrder:
            success = True
        self.assertTrue(success, msg="The number of starting chips was incorrectly able to be reset.")
    def compute_transfer_model(self):
        X,Y,bk = [],[],[]
        i = 0
        values = {}
        while i < self.transfer+1: #at least one iteration burn in time
            if self.simulator == "logistics":
                state = Logistics(number = self.state_number,start=True)
                if not bk:
                    bk = Logistics.bk
            elif self.simulator == "pong":
                state = Pong(number = self.state_number,start=True)
                if not bk:
                    bk = Pong.bk
            elif self.simulator == "tetris":
                state = Tetris(number = self.state_number,start=True)
                if not bk:
                    bk = Tetris.bk
            elif self.simulator == "wumpus":
                state = Wumpus(number = self.state_number,start=True)
                if not bk:
                    bk = Wumpus.bk
            elif self.simulator == "blocks":
                state = Blocks_world(number = self.state_number,start=True)
                if not bk:
                    bk = Blocks_world.bk
            elif self.simulator == "blackjack":
                state = Game(number = self.state_number,start=True)
                if not bk:
                    bk = Game.bk
            elif self.simulator == "50chain":
                state = Chain(number = self.state_number,start=True)
                if not bk:
                    bk = Chain.bk
            elif self.simulator == "net_admin":
                state = Admin(number = self.state_number,start=True)
                if not bk:
                    bk = Admin.bk
            with open(self.simulator+"_transfer_out.txt","a") as f:
                if self.transfer:
                    f.write("start state: "+str(state.get_state_facts())+"\n")
                time_elapsed = 0
                within_time = True
                start = clock()
                trajectory = [(state.state_number,state.get_state_facts())]
                while not state.goal():
                    if self.transfer:
                        f.write("="*80+"\n")
                    state_action_pair = state.execute_random_action()
                    state = state_action_pair[0] #state
                    if self.transfer:
                        f.write(str(state.get_state_facts())+"\n")
                    trajectory.append((state.state_number,state.get_state_facts()))
                    end = clock()
                    time_elapsed = abs(end-start)
                    if self.simulator == "logistics" and time_elapsed > 0.5:
                        within_time = False
                        break
                    elif self.simulator == "pong" and time_elapsed > 1000:
                        within_time = False
                        break
                    elif self.simulator == "tetris" and time_elapsed > 1000:
                        within_time = False
                        break
                    elif self.simulator == "wumpus" and time_elapsed > 1:
                        within_time = False
                        break
                    elif self.simulator == "blocks" and time_elapsed > 1:
                        within_time = False
                        break
                    elif self.simulator == "blackjack" and time_elapsed > 1:
                        within_time = False
                        break
                    elif self.simulator == "50chain" and time_elapsed > 2:
                        within_time = False
                        break
                    elif self.simulator == "net_admin" and time_elapsed > 1:
                        within_time = False
                        break
                if within_time:
                    self.compute_value_of_trajectory(values,trajectory)
		    self.state_number += len(trajectory)+1
                    for key in values:
                        state = list(key[1])
                        value = values[key]
                        X.append(state)
                        Y.append(value)
                    '''
                    for key in values:
                        facts += list(key[1])
                        example_predicate = "value(s"+str(key[0])+") "+str(values[key])
                        examples.append(example_predicate)
                    '''
                    i += 1
        npX = np.array(X)
        npY = np.array(Y)
	if not self.transfer:
		npY = np.zeros(len(npY))
        model = MLPRegressor(hidden_layer_sizes=(25,),
                             activation="logistic",
                             solver="lbfgs",
                             alpha=0.0001,
                             batch_size="auto",
                             learning_rate="constant",
                             learning_rate_init=0.001,
                             power_t=0.5,
                             max_iter=200,
                             shuffle=True,
                             random_state=None,
                             tol=0.0001,
                             verbose=False,
                             warm_start=False,
                             momentum=0.9,
                             nesterovs_momentum=True,
                             early_stopping=False,
                             validation_fraction=0.1,
                             beta_1=0.9,
                             beta_2=0.999,
                             epsilon=1e-08)
        print (npX)
	model.fit(npX,npY)
        #reg = GradientBoosting(regression = True,treeDepth=2,trees=self.trees,sampling_rate=0.7,loss=self.loss)
        #reg.setTargets(["value"])
        #reg.learn(facts,examples,bk)
        self.model = model
        self.AVI()
Ejemplo n.º 23
0
    def test_set_player_names(self):
        """The method used to make sure that the names of the players in the game can be set."""

        # Setup new games and attempt to set their players' names
        valid_players = [
            ["Bob", "Sam", "Cal", "Kris"],
            ["Player 1", "Player 2", "Player 3", "Player 4", "Player 5"],
            ["Bot"],
            ["P1", "P2", "P3"],
        ]
        for players in valid_players:
            game = Game()
            game.setup_new_game()
            game.set_pack_number(1)
            game.set_starting_chips(100)
            game.set_players_number(len(players))
            game.set_player_names(players)
            self.assertEqual(game.player_names, players, msg="The game's player names were not correctly set with: " + str(players))

            # Make sure that the new game state is corectly set
            self.assertEqual(game.state.name, "start_game", msg="The game's state was not correctly set after setting the player names.")

        # Try to set invalid players
        invalid_players = [
            None,
            [None, None],
            [123, 456, 789],
            ["Bob", "Sam", 123],
            ["John", ""],
        ]
        for players in invalid_players:
            game = Game()
            game.setup_new_game()
            game.set_pack_number(1)
            game.set_starting_chips(100)
            game.set_players_number(len(players or "1"))
            success = False
            try:
                game.set_player_names(players)
            except InvalidGamePlayerNames:
                success = True
            self.assertTrue(success, msg="The following invalid series of player names was able to be set: " + str(players))

        # Test the case where the number of players given is not the same as the number of names given
        game = Game()
        game.setup_new_game()
        game.set_pack_number(1)
        game.set_starting_chips(100)
        game.set_players_number(2)
        success = False
        try:
            game.set_player_names(["P1", "P2", "P3"])
        except InvalidGamePlayerNames:
            success = True
        self.assertTrue(success, msg="A number of player names unequal to the number to the number of players in the game was able to be set.")

        # Try to reset the names of the players to throw an error
        game = Game()
        game.setup_new_game()
        game.set_pack_number(1)
        game.set_starting_chips(100)
        game.set_players_number(3)
        game.set_player_names(["P1", "P2", "P3"])
        success = False
        try:
            game.set_player_names(["P01", "P02", "P03"])
        except InvalidGameMethodOrder:
            success = True
        self.assertTrue(success, msg="The names of the players was incorrectly able to be reset.")
Ejemplo n.º 24
0
    loops = 0
    while True:
        loops += 1
        print("Loop {}".format(loops))
        try:
            for subreddit in config.SUBREDDITS:
                sub = reddit.subreddit(subreddit)
                for post in sub.new():
                    # TODO: Check if the post itself contains a summon
                    for comment in post.comments:
                        for summon in config.SUMMON_STRINGS:
                            if summon in comment.body.lower():
                                # TODO: Check if bot has already responded to this comment
                                print(
                                    "Summoned by {} in thread {}. Comment ID: {}"
                                    .format(comment.author, post.title,
                                            comment.id))
                                d = Game()
                                d.deal()
                                reply = d.get_reddit_reply()
                                comment.reply(reply)
        except KeyboardInterrupt:
            sys.exit()
        except praw.exceptions.APIException as e:
            # TODO: Investigate if this catches only rate limit exceptions, or more
            print(e)
            print("Rate limit exceeded. Sleeping for 10 minutes.")
            time.sleep(60)
        except Exception as e:
            print("EXCEPTION: {}".format(e))
Ejemplo n.º 25
0
 def setUp(self):
     self.game = Game()
     self.game_10_decks = Game(number_of_decks=10)
Ejemplo n.º 26
0
import random
import time
import io

import pandas as pd

from blackjack import Game
from strategy import HitStandTrainStrategy, HitStandTestStrategy

if __name__ == '__main__':
    algorithm = "OriginalPrototypeRandomExploration"
    test_train_iterations_to_run = 100000
    seconds_to_run = 60
    original_prototype_seconds_to_run = time.time()

    game = Game(1, reset_on_dealer_blackjack=True)

    # Train by playing X games randomly, then use that knowledge to play another X games intelligently
    if algorithm == "TrainAndTest":
        # Generating a
        training_results = [[{
            'STAND': {
                'WIN': 0,
                'LOSE': 0,
                'DRAW': 0
            },
            'HIT+STAND': {
                'WIN': 0,
                'LOSE': 0,
                'DRAW': 0
            }
Ejemplo n.º 27
0
def test_a_game_has_many_players():
    players = [Player(), Player(), Player()]
    game = Game(*players)
    assert set(game.players) == set(players)
Ejemplo n.º 28
0
def main():
    player_original_cash_balance = 200
    blackjack = Game(name_player='player',
                     player_cash_balance=player_original_cash_balance,
                     dealer_cash_balance=1000,
                     number_of_decks=1)
    blackjack.welcome()

    round_number = 1
    while blackjack.player_cash_balance >= blackjack.player.minimum_bet:
        print(f'''
                    ********************
                          ROUND {round_number}
                    ********************
              ''')

        (player_bet, dealer_bet) = blackjack.bets()
        blackjack.deal_cards()

        blackjack.player.show_balance()
        blackjack.player.show_player_card_values()
        if blackjack.player.hand.get_card_value() < 21:
            blackjack.adjust_player_hand()
        blackjack.adjust_dealer_hand()
        blackjack.dealer.show_dealer_card_values()
        blackjack.blackjack_result(player_bet, dealer_bet)
        exit_game = blackjack.exit_game()
        if exit_game == True:
            print('Thank you for playing with us')
            if blackjack.gain_losses(player_original_cash_balance) > 0:
                print(
                    f'You gained: {blackjack.gain_losses(player_original_cash_balance)} $.'
                )
            elif blackjack.gain_losses(player_original_cash_balance) < 0:
                print(
                    f'You lost: {blackjack.gain_losses(player_original_cash_balance)} $.'
                )
            elif blackjack.gain_losses(player_original_cash_balance) == 0:
                print(f'You broke even.')
            sys.exit()
        discard_pot = blackjack.collect_and_discard_card()
        blackjack.return_cards_to_deck_and_reshuffle(discard_pot)
        round_number += 1
    else:
        'Sorry you no longer have a balance to play. You lost everything.'
Ejemplo n.º 29
0
from blackjack import MCPolicyEvaluationAgent, Game

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pylab as plt
import numpy as np

player = MCPolicyEvaluationAgent()

game = Game(player=player)
game.verbose = False

for n in range(200000):
    game.init()
    game.play()

print(player.values)
print(player.counts)

faceup = range(1, 11)
sum = range(12, 22)

X, Y = np.meshgrid(sum, faceup)

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal')
ax.plot_wireframe(X, Y, player.values[0], label='No Usable Ace')
ax.plot_wireframe(X, Y, player.values[1], color='red', label='Usable Ace')
ax.set_zlim(-1, 1)
ax.set_xticks(sum)
Ejemplo n.º 30
0
 def setUp(self):
     self.game = Game()
Ejemplo n.º 31
0
def test_a_game_auto_plays_until_someone_has_zero_dollars():
    game = Game(Player(), Player(), Player())
    turns = game.auto_play()
    assert turns > 0

    assert any(p.bank == 0 for p in game.players)
Ejemplo n.º 32
0
def main():
    """Plays the Game"""
    os.system('clear')
    player_name = input("Please enter your name: ")
    p1 = HumanPlayer(player_name, BlackjackHand())

    print("\nWelcome to Bull City Bets - an exclusive Blackjack Casino!\n\n")

    while True:
        d1 = Dealer("dealer", BlackjackHand())
        deck = Deck()
        g = Game(p1, d1, deck)
        print("\nAnte Up!")
        p1.place_bet()
        g.add_bet()
        print("Total Pot: {} Player Purse: {}".format(g.pot, p1.purse))

        if not g.check_initial_blackjack():
            g.player_turn()
            g.dealer_turn()

        g.print_results()

        g.play_again()
Ejemplo n.º 33
0
def contGame(model):
    while True:
        game = Game()
        game.deal()

        printLine()
        game.printResult()
        printLine()
        while hit(game.state(), model):
            game.pPlay()
        game.dPlay()
        game.printResult()
        printLine()

        n = input("\n\nQuit?(y/n):")
        if n == "y":
            break
Ejemplo n.º 34
0
from blackjack import Game

game = Game()

game.verbose = True

game.init()
game.play()

print(game.player.history)
print(game.dealer.history)
Ejemplo n.º 35
0
class TestGame(unittest.TestCase):
    def setUp(self):
        self.game = Game()
        self.game_10_decks = Game(number_of_decks=10)

    def tearDown(self):
        del self.game
        del self.game_10_decks

    def test_game_blackjack_check_numbers_of_decks(self):
        self.assertEqual(len(self.game_10_decks.dealer.deck), 520,
                         'Number of decks is not correct.')

    def test_game_blackjack_payout_dealer_bet_float(self):
        self.assertEqual(type(self.game.blackjack_payout(10.00)), int,
                         'Blackjack payout not returning int.')

    def test_game_blackjack_payout_dealer_bet_int(self):
        self.assertEqual(type(self.game.blackjack_payout(10)), int,
                         'Blackjack payout not returning int.')

    def test_game_blackjack_payout_dealer_bet_negative(self):
        self.assertGreaterEqual(
            self.game.blackjack_payout(-10), 15,
            'Blackjack payout not returning positive 3:2 blackjack payout.')

    def test_game_blackjack_payout_dealer_bet_zero(self):
        self.assertEqual(
            self.game.blackjack_payout(0), 0,
            'Blackjack payout not returning zero whe zero inputed.')

    def test_game_blackjack_payout_dealer_bet_positive(self):
        self.assertGreaterEqual(
            self.game.blackjack_payout(10), 15,
            'Blackjack payout not returning 3:2 blackjack payout.')

    def test_game_blackjack_result_blackjack_player_wins_dealer_hand_value_less_than_21(
            self):
        self.game.player.hand.add_card(
            [Card('Hearts', 'Ace'),
             Card('Spades', 'King')])
        self.game.dealer.hand.add_card([
            Card('Hearts', 'Three'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Queen')
        ])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.player.cash_balance, 125,
            'Blackjack result is not working for player balckjack.')

    def test_game_blackjack_result_blackjack_player_wins_dealer_hand_value_more_than_21(
            self):
        self.game.player.hand.add_card(
            [Card('Hearts', 'Ace'),
             Card('Spades', 'King')])
        self.game.dealer.hand.add_card([
            Card('Hearts', 'Three'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Queen')
        ])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.player.cash_balance, 125,
            'Blackjack result is not working for player blackjack.')

    def test_game_blackjack_result_player_bust_dealer_less_than_21(self):
        self.game.player.hand.add_card([
            Card('Hearts', 'Queen'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Four')
        ])
        self.game.dealer.hand.add_card(
            [Card('Hearts', 'Two'),
             Card('Spades', 'Queen')])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.dealer.cash_balance, 120,
            'Blackjack result not working when player busts and dealer has low card values'
        )

    def test_game_blackjack_result_player_bust_dealer_more_than_21_equal_to_hand_player(
            self):
        self.game.player.hand.add_card([
            Card('Hearts', 'Two'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Queen')
        ])
        self.game.dealer.hand.add_card([
            Card('Hearts', 'Two'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Queen')
        ])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.dealer.cash_balance, 120,
            'Blackjack result not working when player busts and dealer has equal card values'
        )

    def test_game_blackjack_result_player_bust_dealer_more_than_21_superior_to_hand_player(
            self):
        self.game.player.hand.add_card([
            Card('Hearts', 'Two'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Queen')
        ])
        self.game.dealer.hand.add_card([
            Card('Hearts', 'Four'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Queen')
        ])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.dealer.cash_balance, 120,
            'Blackjack result not working when player busts and dealer has higher card values'
        )

    def test_game_blackjack_result_player_wins_dealer_bust_higher_than_21(
            self):
        self.game.player.hand.add_card(
            [Card('Hearts', 'King'),
             Card('Spades', 'Eight')])
        self.game.dealer.hand.add_card([
            Card('Hearts', 'Four'),
            Card('Spades', 'King'),
            Card('Diamonds', 'Queen')
        ])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.player.cash_balance, 120,
            'Blackjack result not working when player wins, dealer busts with card values superior to 21.'
        )

    def test_game_blackjack_result_player_wins_dealer_bust_21(self):
        self.game.player.hand.add_card(
            [Card('Hearts', 'King'),
             Card('Spades', 'Eight')])
        self.game.dealer.hand.add_card(
            [Card('Hearts', 'Ace'),
             Card('Spades', 'King')])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.player.cash_balance, 120,
            'Blackjack result not working when player wins, dealer busts with card values equal to 21.'
        )

    def test_game_blackjack_result_dealer(self):
        self.game.player.hand.add_card(
            [Card('Hearts', 'King'),
             Card('Spades', 'Eight')])
        self.game.dealer.hand.add_card(
            [Card('Hearts', 'King'),
             Card('Spades', 'Nine')])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.dealer.cash_balance, 120,
            'Blackjack result not working when dealer wins and player card values less than 21.'
        )

    def test_game_blackjack_result_tie_blackjack(self):  # == > tie not working
        self.game.player.hand.add_card(
            [Card('Hearts', 'Ace'),
             Card('Spades', 'King')])
        self.game.dealer.hand.add_card(
            [Card('Diamonds', 'Ten'),
             Card('Clubs', 'Ace')])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.player.cash_balance, self.game.dealer.cash_balance,
            'Blackjack result not working when dealer and player tie at 21.')

    def test_game_blackjack_result_tie_less_than_blackjack(self):
        self.game.player.hand.add_card(
            [Card('Hearts', 'Seven'),
             Card('Spades', 'King')])
        self.game.dealer.hand.add_card(
            [Card('Diamonds', 'Ten'),
             Card('Clubs', 'Seven')])
        self.game.blackjack_result(10, 10)
        self.assertEqual(
            self.game.player.cash_balance, self.game.dealer.cash_balance,
            'Blackjack result not working when dealer and player tie at value less than 21.'
        )
Ejemplo n.º 36
0
 def __init__(self):
     self.game = Game(mode="automated", print_games=False)
     self.result = self.play()
    def AVI(self):
        for i in range(self.number_of_iterations):
            j = 0
            X,Y,bk = [],[],[]
            values = {}
            fitted_values = {}
            while j < self.batch_size:
                if self.simulator == "logistics":
                    state = Logistics(number = self.state_number,start=True)
                    if not bk:
                        bk = Logistics.bk
                elif self.simulator == "pong":
                    state = Pong(number = self.state_number,start=True)
                    if not bk:
                        bk = Pong.bk
                elif self.simulator == "tetris":
                    state = Tetris(number = self.state_number,start=True)
                    if not bk:
                        bk = Tetris.bk
                elif self.simulator == "wumpus":
                    state = Wumpus(number = self.state_number,start=True)
                    if not bk:
                        bk = Wumpus.bk
                elif self.simulator == "blocks":
                    state = Blocks_world(number = self.state_number,start=True)
                    if not bk:
                        bk = Blocks_world.bk
                elif self.simulator == "blackjack":
                    state = Game(number = self.state_number,start=True)
                    if not bk:
                        bk = Game.bk
                elif self.simulator == "50chain":
                    state = Chain(number = self.state_number,start=True)
                    if not bk:
                        bk = Chain.bk
                elif self.simulator == "net_admin":
                    state = Admin(number = self.state_number,start=True)
                    if not bk:
                        bk = Admin.bk
                with open(self.simulator+"_FVI_out.txt","a") as fp:
                    fp.write("*"*80+"\nstart state: "+str(state.get_state_facts())+"\n")
                    time_elapsed = 0
                    within_time = True
                    start = clock()
                    trajectory = [(state.state_number,state.get_state_facts())]
                    while not state.goal():
                        fp.write("="*80+"\n")
                        state_action_pair = state.execute_random_action()
                        state = state_action_pair[0]
                        fp.write(str(state.get_state_facts())+"\n")
                        trajectory.append((state.state_number,state.get_state_facts()))
                        end = clock()
                        time_elapsed = abs(end-start)
                        if self.simulator == "logistics" and time_elapsed > 0.5:
                            within_time = False
                            break
                        elif self.simulator == "pong" and time_elapsed > 1000:
                            within_time = False
                            break
                        elif self.simulator == "tetris" and time_elapsed > 10:
                            within_time = False
                            break
                        elif self.simulator == "wumpus" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "blocks" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "blackjack" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "50chain" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "net_id" and time_elapsed > 1:
                            within_time = False
                    if within_time:
			if i > 0:
                            self.compute_value_of_trajectory(values,trajectory,AVI=True)
                        else:
                            self.compute_value_of_trajectory(values,trajectory,AVI=False)
			self.state_number += 1
                        for key in values:
                            state = list(key[1])
                            value = values[key]
                            #X.append(state)
                            fitted_values[key] = self.model.predict(np.array([state]))
                            #Y.append([value])
                        '''
                        for key in values:
                            facts += list(key[1])
                            example_predicate = "value(s"+str(key[0])+") "+str(values[key])
                            examples.append(example_predicate)
                        '''
                        j += 1
            #fitted_values = self.model.predict(np.array(X))
            bellman_error = self.compute_bellman_error(values,fitted_values)
            with open(self.simulator+"_BEs.txt","a") as f:
                f.write("iteration: "+str(i)+" average bellman error: "+str(bellman_error)+"\n")
            for key in values:
                X.append(list(key[1]))
                Y.append(values[key])
            npX = np.array(X)
            npY = np.array(Y)
            self.model.fit(npX,npY)
Ejemplo n.º 38
0
    def decide(self):
        moves = ["hit", "stay"]
        results_by_first_move = {
            "hit": {
                "games": 0,
                "wins": 0,
            },
            "stay": {
                "games": 0,
                "wins": 0,
            }
        }
        for _ in range(100):

            # clone the current game, using list() so we don't pass references
            simulated_game = Game(mode="automated")
            simulated_game.dealer_hand = list(self.game.dealer_hand)
            simulated_game.player_hand = list(self.game.player_hand)

            self.debug(simulated_game)

            # make a first move, see if the game ends
            first_move = random.choice(moves)
            self.debug("- first move {}".format(first_move))
            game_result = self.issue_command(first_move, game=simulated_game)
            if game_result:
                results_by_first_move[first_move]["games"] += 1
                if game_result == "win":
                    self.debug(" - won on first move")
                    results_by_first_move[first_move]["wins"] += 1
                else:
                    self.debug(" - lost on first move")

            else:  # continue playing the game randomly and see what happens

                while True:
                    game_result = self.issue_command(random.choice(moves),
                                                     game=simulated_game)
                    if game_result:
                        break

                results_by_first_move[first_move]["games"] += 1
                if game_result == "win":
                    self.debug(" - won on subsequent move")
                    results_by_first_move[first_move]["wins"] += 1
                else:
                    self.debug(" - lost on subsequent move")

            # print simulated_game

        self.info("=============")
        self.info(results_by_first_move)

        # calculate the win pct for both first moves
        hit_win_pct = results_by_first_move["hit"]["wins"] / float(
            results_by_first_move["hit"]["games"])
        stay_win_pct = results_by_first_move["stay"]["wins"] / float(
            results_by_first_move["stay"]["games"])

        # issue the winning command
        if hit_win_pct > stay_win_pct:
            self.info("=> choosing to 'hit' with a {}% win rate".format(
                hit_win_pct * 100))
            return self.issue_command("hit")
        else:
            self.info("=> choosing to 'stay' with a {}% win rate".format(
                stay_win_pct * 100))
            return self.issue_command("stay")
Ejemplo n.º 39
0
 def setUp(self):
     self.player_hands = 4
     self.game = Game(self.player_hands)
Ejemplo n.º 40
0
    def test_set_players_number(self):
        """The method used to make sure that the number of players in the game can be set."""

        # Setup new games and attempt to set thier number of players
        valid_players = [
            1,
            2,
            10,
            999,
        ]
        for players in valid_players:
            game = Game()
            game.setup_new_game()
            game.set_pack_number(1)
            game.set_starting_chips(100)
            game.set_players_number(players)
            self.assertEqual(game.players_number, players, msg="The number of players was not correctly set with " + str(players) + " players.")

            # Make sure that the new game state is correctly set
            self.assertEqual(game.state.name, "get_player_names", msg="The game state was not correctly set after setting the number of players in the game.")

        # Try to set invalid player numbers
        invalid_players = [
            0,
            -1,
            -100,
            1.5,
        ]
        for players in invalid_players:
            game = Game()
            game.setup_new_game()
            game.set_pack_number(1)
            game.set_starting_chips(100)
            success = False
            try:
                game.set_players_number(players)
            except InvalidGamePlayersNumber:
                success = True
            self.assertTrue(success, msg="An invalid number of players " + str(players) + " was able to be set.")

        # Try to reset the number of players to throw an error
        game = Game()
        game.setup_new_game()
        game.set_pack_number(1)
        game.set_starting_chips(100)
        game.set_players_number(3)
        success = False
        try:
            game.set_players_number(2)
        except InvalidGameMethodOrder:
            success = True
        self.assertTrue(success, msg="The number of players was incorrectly able to be reset.")