Programming Blackjack In Java

3/18/2022by admin
Programming Blackjack In Java 3,9/5 9328 votes
Greenhorn
posted 4 years ago

Java Programming Blackjack Card Game You are to create a blackjack hand class. This class will contain a 'hand' (up to 11 cards). UML as follows: Write a driver to play Blackjack with one player. Please don't use the complex coding. Use a simple one so that I can understand. Also, please provide as much details as possible. Writing a blackjack console program in Java. Ask Question Asked 10 years, 6 months ago. Active 10 years, 6 months ago. Viewed 915 times 0. I have an assignment of making a blackjack like program in a class. My first problem I am dealing with is creating an array of the cards. The professor wants an array setup with a txt file with the following.

I am trying to code a simple blackjack game with no suits or anything. Just for number values 1-10 between the dealer and the player. I have it mostly coded out yet, for some reason, when I prompt the system to ask if you want to play again via (y/n).... I type in 'y' to play again and it will say I won - just by typing in y to play again! Its frustrating and if anyone could point me in the right direction it would be greatly appreciated.
Sheriff
posted 4 years ago
  • 1
Hi Mike,
Welcome to the Ranch!
When posting code, please UseCodeTags (←click that link to learn how). They make code so much easier to read and reference in replies because they provide line numbers to the listing. As a courtesy to a newcomer such as yourself, we will add those for you this time.

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

Sheriff
posted 4 years ago
  • 1
A few things that led you to the place where you find yourself now: painted into a corner and wondering how the heck you're going to get out of it.
1. You put everything in your main() method. We have a wiki page that explains why Main Is A Pain. You might want to read that if you want to avoid feeling that pain over and over again.
2. Because you have put all your code into the same method, you have amassed a huge amount of it. Lots of code in one method is BAD. Lots of code that does lots of things in one method is WORSE. Lots of code that does lots of things in loops that have been nested lots of times is the WORST. Wait for it...
3. Code that is not aligned properly to clearly show the different levels of logical structures of your code is the WORST of the WORST.
Ok, so there's a lot of bad stuff going on in that code and I've even barely scratched the surface.
So you don't feel too bad, let me just say that it's a pleasant surprise to see someone use something like 'n'.equals(anotherCard). There are a couple things right about that little gem in the muck around it but just look at it for a little bit if you want to feel better.
Next reply, we'll talk about what you can do to get out of that corner.

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

Sheriff
posted 4 years ago
  • 1
So, there are at least two ways you can try to get yourself out of this sticky situation you're in:
1. Hack your way out.
2. Clean your way out.
One way may get you out eventually but it's likely to leave your code in a bigger mess than it's in now.
The other way, of course, will get you out with your code in much better shape than what it's in now.
You choose. The right way is not always the easiest way though.

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

Greenhorn
posted 4 years ago
Thank you for the response, this is stressing me out to say the least. I'm gonna try to tidy it up to make it easier to understand and maybe that'll help with trying to figure out what exactly is going on with my code. I will definitely take a read at the wiki page that you linked as to avoid this pain over and over again .
Sheriff
posted 4 years ago
  • 1
Well, the first thing you want to do is reformat your code so that it's properly aligned. At least that will bump your code down from being the WORST of the WORST to just being the WORST.
In Eclipse or NetBeans, the keyboard command to autoformat your code is CTRL+SHIFT+F. That will give you something like the listing below; I added some blank lines to get separation between a few logical parts of the code (another favor... you owe us TWO now):

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

Greenhorn
posted 4 years ago
Such a simple command to format my entire code, gee that would've been nice to know... professor. Ya think she would've taught us such a simple trick!
Sheriff
posted 4 years ago

mike laww wrote:Such a simple command to format my entire code, gee that would've been nice to know... professor. Ya think she would've taught us such a simple trick!


Yeah, you'd think that would be one of the first things they teach but no. It's one of the first things I taught my son when he enrolled in his first programming course in college last year.
Have you made your choice on which way you want to go? Hack your way out or Clean your way out? Choose wisely... there is only one path down which I will be willing to go with you. Choose poorly and you're on your own.

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

Greenhorn
posted 4 years ago
I believe the best decision would be to clean my way out, as I for sure don't want to leave my code in a bigger mess than when it started.
Sheriff
posted 4 years ago
  • 1
Good deal. One more little detail to get out of the way. Have you been taught about using methods yet or is your teacher the one who's been telling you to jam everything and the kitchen sink into the main() method? Because you're going to have to create a bunch of smaller methods to separate, segregate, and compartmentalize all the different things that your program is doing right in that one main() method. That's the goal. Instead of having to cook, eat, shower, attend to bodily functions, sleep, study, exercise, and entertain in the same room of your house, i.e. your main() method, you're going to create a bunch of little 'rooms' (called 'methods') so that in each room, you can do one thing and only that one thing. So, however many 'things' it is that you want to do, that's how many 'rooms' you're going to create and that's where you're going to move all the clutter you have in main() out to. Does that make sense?

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

Greenhorn
posted 4 years ago
This is my first programming class for my major so sadly she hasn't really touched on methods. As much as you probably hate to hear it, she has just been having us cram everything into the main method so far, which after your description doesn't seem like the logical way to do it. I really like the idea of having separate methods as it would be so much easier to organize thoughts and not get lost in your own code. Your example made it very easy to understand the concept. So, would it be organized by different data types? Like a method for loops, method for if statements, method for setting and getting variables, etc?
lowercase baba
posted 4 years ago

Java Program Blackjack Code

  • 1
your methods should NOT be for loops or if statements.
methods should be broken out by actions as described in English (or whatever language you speak). Imagine you were telling a story of what happens:
Deal a card to the player
Deal a card to the dealer
Deal a card to the player
Deal a card to the dealer
ask the player what they want to do
get their answer
etc..
you do this, then look for 'actions'. So, 'deal a card' is something you DO. Note that it doesn't matter who you are dealing to, the process is the same - select a card from what's left in the deck. once you know what it is, you add it to the correct player's hand...
Methods for getting and setting variables are OK - they're sometimes called 'getters' and 'setters', or 'accessors' and 'mutators' (I think), but they are part of a class (like a Player class). I'm not sure if you're going to start defining your own classes yet...

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

Sheriff
posted 4 years ago
  • 1

mike laww wrote:So, would it be organized by different data types? Like a method for loops, method for if statements, method for setting and getting variables, etc?


As Fred said, your program is broken out by actions. I like to call them 'behaviors' because I find that helps shift your mindset to a place where it's more natural to think of the programs as living, sentient 'things', i.e. Objects. You heard that Java is an object-oriented programming language, right?
Let's not get ahead of ourselves yet though. Just think of it for now as something called 'functional decomposition' - breaking down your huge problem into smaller, more manageable problems that focus on one small part of the larger whole.

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

Sheriff
posted 4 years ago
  • 1
Also, think about it as a kind of layering and drilling down from high-level instructions to low-level detailed, step-by-step instructions. It's kind of like how your mom might ask you to cook Thanksgiving dinner. That's 'high-level' - you don't have a lot of details, just one command to do something. When you get home, you're like 'Ok, I'm here, what do I do now?' and Mom will say, 'Well, we want to prepare mashed potatoes, turkey, and bean casserole. Everybody else is bringing a different dish for dinner.' So now you have a little more detail.
This gradual breaking down of the problem from high-level to more details, then to even more details as you drill down and finally arrive at the smallest task, like 'Mom, how do I peel the potatoes?' and Mom will say, 'Go to the drawer next to the sink, pull it out, dig around for the peeler, make sure you wash the potatoes first, then get a trash bag ready, walk over to the island, set the potatoes down, then start peeling those taters!' That level of detail would not have been appropriate during that first time that she asked you to prepare Thanksgiving dinner, right?
Mom held off giving you those details until just the right moment when you were ready to follow that many detailed instructions to a Tee. Giving you all of those detailed instructions up front would have been like the mess that you find right now in your main() method, right? All jumbled up and confusing as heck. How would you ever get dinner ready that way?!
That's kind of like how you want to layer your program instructions. Start with the large one-liner command in the main() method. Ideally, it would look something like this:

That's it! And then, the play method would look something like this:

And then you just keep drilling down into more details of each of the initPlayer(), initGame(), playUntilSomebodyWins(), and other methods you see there.
It's not that complicated. It just takes a little bit of organization and logical thinking.

The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
How to Ask Questions How to Answer Questions Format Your Code

In this applet, the user plays a game of Blackjack. The computer acts as the dealer. The user plays by clicking “Hit!” and “Stand!” buttons.
The programming of this applet assumes that the applet is set up to be about 466 pixels wide and about 346 pixels high. That width is just big enough to show 2 rows of 5 cards. The height is probably a little bigger than necessary, to allow for variations in the size of buttons from one platform to another.
[sourcecode language=”java”]/*******************************************************
* MYCPLUS Sample Code – https://www.mycplus.com *
* *
* This code is made available as a service to our *
* visitors and is provided strictly for the *
* purpose of illustration. *
* *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BlackjackGUI extends JApplet {

public void init() {

// The init() method creates components and lays out the applet.
// A BlackjackCanvas occupies the CENTER position of the layout.
// On the bottom is a panel that holds three buttons. The
// BlackjackCanvas object listens for events from the buttons
// and does all the real work of the program.

setBackground( new Color(130,50,40) );

BlackjackCanvas board = new BlackjackCanvas();
getContentPane().add(board, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel();
buttonPanel.setBackground( new Color(220,200,180) );
getContentPane().add(buttonPanel, BorderLayout.SOUTH);

Programming Blackjack In Java Programming

Java

JButton hit = new JButton( “Hit!” );
hit.addActionListener(board);
buttonPanel.add(hit);

JButton stand = new JButton( “Stand!” );
stand.addActionListener(board);
buttonPanel.add(stand);

JButton newGame = new JButton( “New Game” );
newGame.addActionListener(board);
buttonPanel.add(newGame);

} // end init()

public Insets getInsets() {
// Specify how much space to leave between the edges of
// the applet and the components it contains. The background
// color shows through in this border.
return new Insets(3,3,3,3);
}

// — The remainder of this class consists of a nested class —

class BlackjackCanvas extends JPanel implements ActionListener {

// A nested class that displays the card game and does all the work
// of keeping track of the state and responding to user events.

Deck deck; // A deck of cards to be used in the game.

BlackjackHand dealerHand; // Hand containing the dealer’s cards.
BlackjackHand playerHand; // Hand containing the user’s cards.

String message; // A message drawn on the canvas, which changes
// to reflect the state of the game.

Blackjack Game In Java

boolean gameInProgress; // Set to true when a game begins and to false
// when the game ends.

Font bigFont; // Font that will be used to display the message.
Font smallFont; // Font that will be used to draw the cards.

BlackjackCanvas() {
// Constructor. Creates fonts and starts the first game.
setBackground( new Color(0,120,0) );
smallFont = new Font(“SansSerif”, Font.PLAIN, 12);
bigFont = new Font(“Serif”, Font.BOLD, 14);
doNewGame();
}

public void actionPerformed(ActionEvent evt) {
// Respond when the user clicks on a button by calling
// the appropriate procedure. Note that the canvas is
// registered as a listener in the BlackjackGUI class.
String command = evt.getActionCommand();
if (command.equals(“Hit!”))
doHit();
else if (command.equals(“Stand!”))
doStand();
else if (command.equals(“New Game”))
doNewGame();
}

void doHit() {
// This method is called when the user clicks the “Hit!” button.
// First check that a game is actually in progress. If not, give
// an error message and exit. Otherwise, give the user a card.
// The game can end at this point if the user goes over 21 or
// if the user has taken 5 cards without going over 21.
if (gameInProgress false) {
message = “Click ”New Game” to start a new game.”;
repaint();
return;
}
playerHand.addCard( deck.dealCard() );
if ( playerHand.getBlackjackValue() > 21 ) {
message = “You’ve busted! Sorry, you lose.”;
gameInProgress = false;
}
else if (playerHand.getCardCount() 5) {
message = “You win by taking 5 cards without going over 21.”;
gameInProgress = false;
}
else {
message = “You have ” + playerHand.getBlackjackValue() + “. Hit or Stand?”;
}
repaint();
}

void doStand() {
// This method is called when the user clicks the “Stand!” button.
// Check whether a game is actually in progress. If it is,
// the game ends. The dealer takes cards until either the
// dealer has 5 cards or more than 16 points. Then the
// winner of the game is determined.
if (gameInProgress false) {
message = “Click ”New Game” to start a new game.”;
repaint();
return;
}
gameInProgress = false;
while (dealerHand.getBlackjackValue() <= 16 && dealerHand.getCardCount() < 5) dealerHand.addCard( deck.dealCard() ); if (dealerHand.getBlackjackValue() > 21)
message = “You win! Dealer has busted with ” + dealerHand.getBlackjackValue() + “.”;
else if (dealerHand.getCardCount() 5)
message = “Sorry, you lose. Dealer took 5 cards without going over 21.”;
else if (dealerHand.getBlackjackValue() > playerHand.getBlackjackValue())
message = “Sorry, you lose, ” + dealerHand.getBlackjackValue()
+ ” to ” + playerHand.getBlackjackValue() + “.”;
else if (dealerHand.getBlackjackValue() playerHand.getBlackjackValue())
message = “Sorry, you lose. Dealer wins on a tie.”;
else
message = “You win, ” + playerHand.getBlackjackValue()
+ ” to ” + dealerHand.getBlackjackValue() + “!”;
repaint();
}

void doNewGame() {
// Called by the constructor, and called by actionPerformed() if
// the use clicks the “New Game” button. Start a new game.
// Deal two cards to each player. The game might end right then
// if one of the players had blackjack. Otherwise, gameInProgress
// is set to true and the game begins.
if (gameInProgress) {
// If the current game is not over, it is an error to try
// to start a new game.
message = “You still have to finish this game!”;
repaint();
return;
}
deck = new Deck(); // Create the deck and hands to use for this game.
dealerHand = new BlackjackHand();
playerHand = new BlackjackHand();
deck.shuffle();
dealerHand.addCard( deck.dealCard() ); // Deal two cards to each player.
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
if (dealerHand.getBlackjackValue() 21) {
message = “Sorry, you lose. Dealer has Blackjack.”;
gameInProgress = false;
}
else if (playerHand.getBlackjackValue() 21) {
message = “You win! You have Blackjack.”;
gameInProgress = false;
}
else {
message = “You have ” + playerHand.getBlackjackValue() + “. Hit or stand?”;
gameInProgress = true;
}
repaint();
} // end newGame();

Programming Blackjack In Java Runtime

public void paintComponent(Graphics g) {
// The paint method shows the message at the bottom of the
// canvas, and it draws all of the dealt cards spread out
// across the canvas.

super.paintComponent(g); // fill with background color.

g.setFont(bigFont);
g.setColor(Color.green);
g.drawString(message, 10, getSize().height – 10);

// Draw labels for the two sets of cards.

g.drawString(“Dealer’s Cards:”, 10, 23);
g.drawString(“Your Cards:”, 10, 153);

// Draw dealer’s cards. Draw first card face down if
// the game is still in progress, It will be revealed
// when the game ends.

Blackjack Game Program Java

Java

Simple Blackjack Java Program

g.setFont(smallFont);
if (gameInProgress)
drawCard(g, null, 10, 30);
else
drawCard(g, dealerHand.getCard(0), 10, 30);
for (int i = 1; i < dealerHand.getCardCount(); i++) drawCard(g, dealerHand.getCard(i), 10 + i * 90, 30); // Draw the user's cards. for (int i = 0; i < playerHand.getCardCount(); i++) drawCard(g, playerHand.getCard(i), 10 + i * 90, 160); } // end paint(); void drawCard(Graphics g, Card card, int x, int y) { // Draws a card as a 80 by 100 rectangle with // upper left corner at (x,y). The card is drawn // in the graphics context g. If card is null, then // a face-down card is drawn. (The cards are // rather primitive.) if (card null) { // Draw a face-down card g.setColor(Color.blue); g.fillRect(x,y,80,100); g.setColor(Color.white); g.drawRect(x+3,y+3,73,93); g.drawRect(x+4,y+4,71,91); } else { g.setColor(Color.white); g.fillRect(x,y,80,100); g.setColor(Color.gray); g.drawRect(x,y,79,99); g.drawRect(x+1,y+1,77,97); if (card.getSuit() Card.DIAMONDS card.getSuit() Card.HEARTS) g.setColor(Color.red); else g.setColor(Color.black); g.drawString(card.getValueAsString(), x + 10, y + 30); g.drawString('of', x+ 10, y + 50); g.drawString(card.getSuitAsString(), x + 10, y + 70); } } // end drawCard() } // end nested class BlackjackCanvas } // end class HighLowGUI[/sourcecode]

Comments are closed.