Simple Blackjack Simulation in MATLAB

52 visualizaciones (últimos 30 días)
Sam
Sam el 19 de Nov. de 2020
Editada: James Tursa el 19 de Nov. de 2020
I'm trying to write a code to simulate the game of blackjack. The game is played only between the player and the dealer and I'm assuming the player can't see either of the dealer's cards. Two decks (104 cards) are played at a time and the game runs twelve times. My initial strategy is to "hit" if the total value of the player's hand is less than 21, but I want to vary this eleven times at an interval of one card, so that the player continues to hit if the total value of their hand is less than 20, 19, 18, and so on down to 10, in order to determine the optimum strategy assuming the dealer's cards cannot be seen.
This is what I have so far. I'm having trouble figuring out how to implement my strategy. Thank you so much in advance for any help!
clc;clear variables;close all;
deck = [1,2,3,4,5,6,7,8,9,10,10,10,10]; %values of cards in a deck
N = 12; %number of hands played
n = 104; %number of cards played in one set (two decks)
score = 0; %initialize score
x = 0; %initialize players hand
y = 0; %initialize dealers hand
bet = 2; %bet placed is always $2
for j = 1:N
for i = 1:n-1
if x(i) >= 21
break
else
pos = randi(length(deck));
card = deck(pos);
x1 = card;
pos = randi(length(deck));
card = deck(pos);
x2 = card;
x(i+1) = x1 + x2;
pos = randi(length(deck));
card = deck(pos);
y1 = card;
pos = randi(length(deck));
card = deck(pos);
y2 = card;
y(i+1) = y1 + y2;
if x(i+1) == 21 && y(i+1) == 21
score(i+1) = score(i)
elseif x(i+1) == 21
score(i+1) = score(i) + 1.5*bet;
else y(i+1) == 21
score(i+1) = score(i) - 1.5*bet;
end
end
end
result = score;
end
performance = mean(result)

Respuestas (1)

James Tursa
James Tursa el 19 de Nov. de 2020
Editada: James Tursa el 19 de Nov. de 2020
A few things ...
Seems like you should have this:
deck = repmat([1,2,3,4,5,6,7,8,9,10,10,10,10],1,8); % two decks worth of cards
and this:
pos = randi(length(deck));
card = deck(pos);
deck(pos) = []; % delete the card just dealt from the deck
Also it seems like you would need to change this:
for i = 1:n-1
into a while loop
while( true )
And then you might want to wrap the entire code in a loop to Monte Carlo several runs.
You haven't mentioned the dealer strategy. What will that be for your runs? You would need a separate while loop for the dealer strategy.

Categorías

Más información sobre Card games en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by