Question

In: Computer Science

(matlab) Since the problem is fairly complex, it may be better to complete & debug the...

(matlab) Since the problem is fairly complex, it may be better to complete & debug the program offline, then submit in Grader.

In this exercise you will complete a simplified program to play a hand of Blackjack. The goal is to complete a modular program using local and anonymous functions. Although there are several functions that must be written, they are all quite short and simple, just 1 to 4 lines. The most important learning objective is to understand how function definitions and function calls fit together.

PART 1: At the bottom of the template, complete the following local functions:

deal_hand() function

This function will generate a hand of two cards by generating two random numbers between 1 and 13.

Input argument: None

Output argument: A row vector of 2 integers between 1 and 13.

The body of the function can be implemented in a single line using the Matlab built-in function randi(). (NOTE: we are making a simplifying assumption that we have an infinite deck of cards, so we don’t have to keep track of which cards have already been dealt.)

To deal two cards, each having a value between 1 and 13, the form of the function is:

hand = randi (13, 1, 2);

display_hand() function

This function will display a blackjack hand to the screen.

input argument: a row vector containing the hand as described in 1.

output argumen: None

The contents of the display_hand() function will be as follows:

Define a row vector with characters representing the card values, like so:

cards = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'];

(this can also be written more compactly as cards='A23456789TJQK')

NOTE: Each card is represented by a single character; thus ‘T’ is used for 10.

The character corresponding to a card value is accessed by indexing. For example if the card is a ten, the corresponding character using can be displayed by:

fprintf(‘%c’,cards(10))

The entire hand can be displayed with a single fprintf() call as follows:

fprintf(‘%c ’,cards(hand))

Once the hand has been displayed, print a new line using

fprintf(‘\n’)

score_hand()function

This function calculates the score of a blackjack hand.

Input argument: a hand (row vector of numbers between 1 and 13)

Output argument: the score corresponding to that hand of cards

To keep it simple, we will only allow the Ace to have a value of 1. (Allowing it to have either a value of 1 or 11 depending on context is a challenge problem that you can try after you have the rest of the game working.)

With this restriction, the value of the card is equal to the number representing the card, with the exception of face cards (11, 12, and 13), which are worth 10. You can use the min() function and the sum()function to sum the values of the cards while limiting each card to an upper value of 10.

Since the simplified score_hand() function only requires one line of code, it can be implemented via an in-line (anonymous) function. Try implementing it that way. It can be defined anywhere in the script before it is called for the first time.

deal_card() function

This function adds a card to an existing hand. Generate a single card using randi(), and use concatenation to add it to the existing hand. For example,

new_hand = [existing_hand new_card];

Input argument: a hand (row vector of numbers between 1 and 13)

Output argument: a hand consisting of the input hand with one additional card added to it.

PART 2: Add calls to your user-defined functions in the appropriate places of the template script. So that you don't have to think much about the logic of the game for this exercise, we have provided the looping and branching code.

(Script)

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%to make an anonymous function for score_hand()

%complete this line:

score_hand = %code to calculate the score

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Testing the functions

testScore = score_hand(deal_card(deal_hand()));

testLength1=length(deal_hand());

testLength2=length(deal_card(deal_hand()));

disp('Blackjack:')

display_hand([1,13]);

%The main things that your program has to do are:

%

% Deal the cards

% Display the hand

% Calculate the score and store in the variable player_score or

% dealer_score

% display the score

%

%The other logic (when to quit the game, etc.) is already built into the

%template

%****************************************************

% ENTER YOUR CODE BETWEEN THE %XXXXXXXXXXXXXXX LINES.

%

%****************************************************

dealer_score = 0; %initialize dealer score so grader doesn't fail if player busts

disp('Your hand:')

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Deal the player's initial cards, score the hand, display the hand, display the score

player_score = 0; %Replace the 0 with a function call

fprintf('Score = %i\n', player_score);

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

hit = 1; %flag that says deal another card

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%CHANGE THE FOLLOWING LINE AFTER YOU HAVE COMPLETED THE REST OF THE SCRIPT

%CHANGE THE 1 TO A 0

busted = 1; %flag that says player is not busted

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

while busted == 0 && hit == 1 && player_score < 21

% Since this game does not use user input, use a semi-intelligent

% algorithm to decide whether the player hits:

% if his score is <15, definitely hit

% if his score is >18, do not hit

% if his score is between 15 and 18, generate a random number

% to decide if he hits.

hit = player_score<15 || 15+randi(4)>player_score;

if hit == 1

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Deal one more card and calculate the score and display the hand

% and the score

fprintf('Score = %i\n', player_score); %display the score

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

if player_score > 21

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% The player is busted and stops playing. Display a losing

% message

busted = 1;

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

end

end

end

if busted == 0

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Deal the dealer a separate hand, score it, then show it

disp('Dealer''s hand:')

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

while (dealer_score < player_score) && (dealer_score < 21)

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Deal the dealer a new card and calculate his score and display his

%new hand

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

end

if dealer_score > 21

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Show that the player wins

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

else

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Show that the dealer wins

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

end

end

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Complete these local functions

%Add input & output arguments as needed

function [] = deal_hand()

end

function [] = deal_card()

end

function [] = display_hand()

cards = 'A23456789TJQK';

end

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Solutions

Expert Solution

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%to make an anonymous function for score_hand()

%complete this line:

score_hand = @(x) sum(min(x,10)); %code to calculate the score

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Testing the functions

testScore = score_hand(deal_card(deal_hand()));
testLength1=length(deal_hand());
testLength2=length(deal_card(deal_hand()));

disp('Blackjack:')

display_hand([1,13]);

%The main things that your program has to do are:

%

% Deal the cards

% Display the hand

% Calculate the score and store in the variable player_score or

% dealer_score

% display the score

%

%The other logic (when to quit the game, etc.) is already built into the

%template

%****************************************************

% ENTER YOUR CODE BETWEEN THE %XXXXXXXXXXXXXXX LINES.

%

%****************************************************

dealer_score = 0; %initialize dealer score so grader doesn't fail if player busts

disp('Your hand:');

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Deal the player's initial cards, score the hand, display the hand, display the score
player_hand = deal_hand();
display_hand(player_hand);
player_score = score_hand(player_hand); %Replace the 0 with a function call

fprintf('Score = %i\n', player_score);

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

hit = 1; %flag that says deal another card

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%CHANGE THE FOLLOWING LINE AFTER YOU HAVE COMPLETED THE REST OF THE SCRIPT

%CHANGE THE 1 TO A 0

busted = 0; %flag that says player is not busted

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

while busted == 0 && hit == 1 && player_score < 21

% Since this game does not use user input, use a semi-intelligent

% algorithm to decide whether the player hits:

% if his score is <15, definitely hit

% if his score is >18, do not hit

% if his score is between 15 and 18, generate a random number

% to decide if he hits.

hit = player_score<15 || 15+randi(4)>player_score;

if hit == 1

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Deal one more card and calculate the score and display the hand

% and the score
player_hand = deal_card(player_hand);
display_hand(player_hand);
player_score = score_hand(player_hand);
fprintf('Score = %i\n', player_score); %display the score

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

if player_score > 21

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% The player is busted and stops playing. Display a losing

% message
disp('Player has lost the game');
busted = 1;

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

end

end

end

if busted == 0

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Deal the dealer a separate hand, score it, then show it

disp('Dealer''s hand:');
dealer_hand = deal_hand();
display_hand(dealer_hand);
dealer_score = score_hand(dealer_hand);
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

while (dealer_score < player_score) && (dealer_score < 21)

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Deal the dealer a new card and calculate his score and display his

%new hand
dealer_hand = deal_card(dealer_hand);
dealer_score = score_hand(dealer_hand);
display_hand(dealer_hand);
fprintf('Score = %i\n', dealer_score); %display the score
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

end

if dealer_score > 21

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

% Show that the player wins
disp('Player wins');
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

else

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Show that the dealer wins
disp('Dealer wins');
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

end

end

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%Complete these local functions

%Add input & output arguments as needed

function [hand] = deal_hand()
hand = randi (13, 1, 2);
end

function [newHand] = deal_card(hand)
new_card = randi(13,1,1);
newHand = [hand new_card];
end

function [] = display_hand(hand)

cards = 'A23456789TJQK';
fprintf('%c ',cards(hand));
fprintf('\n');
end

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

%end of script

Output:


Related Solutions

NEED TO DEBUG // This pseudocode should create a report that contains an // apartment complex...
NEED TO DEBUG // This pseudocode should create a report that contains an // apartment complex rental agent's commission. The // program accepts the ID number and name of the agent who // rented the apartment, and the number of bedrooms in the // apartment. The commission is $100 for renting a three-bedroom // apartment, $75 for renting a two-bedroom apartment, $55 for // renting a one-bedroom apartment, and $30 for renting a studio // (zero-bedroom) apartment. Output is the...
(MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) Please complete the following...
(MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) (MATLAB ONLY) Please complete the following Question in MATLAB ASAP, Thanks. :) 2a. Write a function that outputs the amount of freezing point depression (in degrees C) given a mass of magnesium chloride salt and a volume of water. Formula to calculate freezing point depression: ΔT = iKm in which ΔT is the change in temperature in °C, i is the van't Hoff factor, which = 3 for MgCl2 because...
megan is a rental agent for the Oxford Lake apartment complex. The work is fairly boring,...
megan is a rental agent for the Oxford Lake apartment complex. The work is fairly boring, but she’s going to school in the evening, so the quiet periods give her time to catch up on her studies, plus the discounted rent is a great help to her budget. Business has been slow since two other apartment complexes opened up, and their vacancies are starting to run a little high. The company recently appointed a new regional director to “inject some...
Describe a problem that may occur where it would be better to use Access to solve,...
Describe a problem that may occur where it would be better to use Access to solve, rather than Excel. Your initial answer must be a 2 to 3 paragraph response to the discussion question.  
topic is on FAS 133 “Reporting for Derivatives.” While derivatives are fairly complex, they have become...
topic is on FAS 133 “Reporting for Derivatives.” While derivatives are fairly complex, they have become increasingly popular over the last decade and it is very important that you have a working knowledge of what they are and why people use them. What makes something a derivative? A derivative’s underlying value is based on or tied to something else. Investors use stock options (a very common derivative instrument) to reduce the risk of investing. A stock option gives its owner...
Complete the following Complex Time Value of Money problem. Show your work. You are doing some...
Complete the following Complex Time Value of Money problem. Show your work. You are doing some long-range retirement planning. On the day you retire (28 years from now) you want to be able to withdraw $180,000. Then, you want to withdraw the following amounts at the end of each year after that (during your retirement period). Years 1-6 $140,000 Years 7-10 $160,000 Year 11 $250,000 Years 12-22 $145,000 At the end of the 22nd year in retirement, you’d like to...
The Eight Queens Problem is a fairly old problem that has been well discussed and researched....
The Eight Queens Problem is a fairly old problem that has been well discussed and researched. The first published reference to this problem was in a German Chess magazine in 1848 by Max Bezzel. In 1850, Franz Nauck published all 92 solutions of the problem for an 8x8 board. S. Gunther in 1874 suggested a method for finding solutions by using determinants and J.W.L. Glaisher extended this method. E. Dijkstra published a detailed description of the solution of the problem...
Suppose, we need to debug somebody else’s program. We suspect that there is a problem with...
Suppose, we need to debug somebody else’s program. We suspect that there is a problem with the method wizbang() in class Widget or with how that method is called. We cannot modify class Widget, nor can we modify the client code that contains the calls to Widget.wizbang(), since we don’t have those sources. However, we can modify the code where Widget objects are created and we can create new classes. In order to better understand what this method does, we...
This is a Matlab Exercise problem. Please create the Matlab code and figure for the following...
This is a Matlab Exercise problem. Please create the Matlab code and figure for the following problem using problem specifications: Plot x vs y when y=sin(x), y=cos(x), y=sin (2*x), and y=2*sin(x) when x = 1:0.1:10. Use 2 by 2 subplot, sin(x) is in location 1, cos(x) is in location 2, sin(2*x) is in location 3 and 2*sin(x) is in location 4. The plot should have: (1) x label = ‘x value’, y label = ‘y value’, legend ‘y=sin(x)’,’ y=cos(x)’,’ y=sin...
Ineslastic examples | Problem Consider collisions. Which of the following are examples of a fairly (or...
Ineslastic examples | Problem Consider collisions. Which of the following are examples of a fairly (or completely) inelastic collision? Two falcons colliding and locking their talons Firecracker exploding into many pieces Two electrons scattering off each other An asteroid coming close to Earth, being redirected on its path Two football players colliding and bouncing off each other A car crashing into a barrier Billiard balls colliding
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT