Question

Java BlackJack Game:

Help with 1-4 using the provided code below

1. Design First: Sketch on paper what you want the screen to look like. Draw it at the start of the game (empty card hands),

Source code for Project3.java:

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

public class Project3 extends JFrame implements ActionListener {

private static int winxpos = 0, winypos = 0; // place window here

private JButton exitButton, hitButton, stayButton, dealButton, newGameButton;
private CardList theDeck = null;
private JPanel northPanel;
private MyPanel centerPanel;
private static JFrame myFrame = null;

private CardList playerHand = new CardList(0);
private CardList dealerHand = new CardList(0);
private int playerScore;
private int dealerScore;
private int playerNumWins = 0;
private int dealerNumWins = 0;
private String message = "";
//private boolean playerTurn;//true if player turn, false if dealer turn
//private boolean playerStay = false;//true if stay button has been hit, false otherwise
private boolean gameOver = true;//true if game is over
private boolean deal = false;//check if cards have been dealt yet

//////////// MAIN ////////////////////////
public static void main(String[] args) {
Project3 tpo = new Project3();
}

//////////// CONSTRUCTOR /////////////////////
public Project3() {
myFrame = this; // need a static variable reference to a JFrame object
northPanel = new JPanel();
northPanel.setBackground(Color.white);
dealButton = new JButton("Deal");
northPanel.add(dealButton);
dealButton.addActionListener(this);
hitButton = new JButton("Hit");
northPanel.add(hitButton);
hitButton.addActionListener(this);
stayButton = new JButton("Stay");
northPanel.add(stayButton);
stayButton.addActionListener(this);
newGameButton = new JButton("New Game");
northPanel.add(newGameButton);
newGameButton.addActionListener(this);
exitButton = new JButton("Exit");
northPanel.add(exitButton);
exitButton.addActionListener(this);
getContentPane().add("North", northPanel);

centerPanel = new MyPanel();
getContentPane().add("Center", centerPanel);

//theDeck = new CardList(52);
newGame();
setSize(800, 700);
setLocation(winxpos, winypos);

setVisible(true);
}

//////////// BUTTON CLICKS ///////////////////////////
public void actionPerformed(ActionEvent e) {

if (e.getSource() == exitButton) {
dispose();
System.exit(0);
}
if (e.getSource() == hitButton) {
if (gameOver == false && deal == true) {
message = "";
dealCard(playerHand);
repaint();
} else if (gameOver == true) {
message = "Press NEW GAME.";
repaint();
} else if (deal == false) {
message = "Press DEAL.";
repaint();
}

}
if (e.getSource() == stayButton) {
if (gameOver == false && deal == true) {
message = "";
while (true) {
if (addScore(dealerHand) < 17) {
dealCard(dealerHand);
} else {
break;
}
}
gameOver = true;
repaint();
} else if (gameOver == true) {
message = "Press NEW GAME.";
repaint();
} else if (deal == false) {
message = "Press DEAL.";
repaint();
}

}
if (e.getSource() == dealButton) {
if (gameOver == false && (playerHand.getNumCards() == 0) && (dealerHand.getNumCards() == 0 && (deal == false))) {
message = "";
dealCard(playerHand);
dealCard(dealerHand);
dealCard(playerHand);
dealCard(dealerHand);
playerScore = addScore(playerHand);
dealerScore = addScore(playerHand);
gameOver = false;
deal = true;
repaint();
} else if (gameOver == true) {
message = "Press NEW GAME.";
repaint();
} else {
message = "Press HIT or STAY.";
repaint();
}
}
if (e.getSource() == newGameButton) {
if (gameOver == true) {
message = "";
//add point to winner for win-counter
if (addScore(playerHand) > 21) {
dealerNumWins++;
} //dealer bust
else if (addScore(dealerHand) > 21) {
playerNumWins++;
} //player total greater than dealer total
else if (addScore(playerHand) > addScore(dealerHand)) {
playerNumWins++;
} //dealer total greater than or equal to player total
else if (addScore(playerHand) <= addScore(dealerHand)) {
dealerNumWins++;
}

newGame();
} else {
message = "Please finish the game or EXIT.";
}
repaint();
}
}

// This routine will load an image into memory
//
public static Image load_picture(String fname) {
// Create a MediaTracker to inform us when the image has
// been completely loaded.
Image image;
MediaTracker tracker = new MediaTracker(myFrame);

// getImage() returns immediately. The image is not
// actually loaded until it is first used. We use a
// MediaTracker to make sure the image is loaded
// before we try to display it.
image = myFrame.getToolkit().getImage(fname);

// Add the image to the MediaTracker so that we can wait
// for it.
tracker.addImage(image, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException e) {
System.err.println(e);
}

if (tracker.isErrorID(0)) {
image = null;
}
return image;
}
// -------------- end of load_picture ---------------------------

public void newGame() {
theDeck = new CardList(52);//resets deck
playerHand = new CardList(0);//resets player hand
dealerHand = new CardList(0);//resets enemy hand
theDeck.shuffle();//shuffles deck
//playerScore = 0;//resets scores
// dealerScore = 0;//resets scores
gameOver = false;
deal = false;

}

public void startGame() {
theDeck = new CardList(52);
theDeck.shuffle();
playerHand = new CardList(0);
dealerHand = new CardList(0);
gameOver = false;
dealCard(playerHand);
dealCard(dealerHand);
dealCard(playerHand);
dealCard(dealerHand);
playerScore = addScore(playerHand);
dealerScore = addScore(playerHand);
// playerTurn = true;
}

public void dealCard(CardList hand) {
if (theDeck.getNumCards() != 0) {
Card current = theDeck.deleteCard(0);
hand.insertCard(current);
if (addScore(hand) > 21) {
gameOver = true;
}
}
}

public int addScore(CardList hand) {
int score = 0;
int numAce = 0;
Card current = hand.getFirstCard();
while (current != null) {
if ((current.getCardNumber() % 13) == 0) {
numAce++;
score = score + 11;
} else if ((current.getCardNumber() % 13) < 10)//card values 2-10
{
score = score + (current.getCardNumber() % 13 + 1);
} else if ((current.getCardNumber() % 13) >= 10) {//card values Jack, Queen, King
score = score + 10;
}
current = current.getNextCard();
}
if (score > 21) {
score = score - (numAce * 10);
}
return score;
}

public String checkWin() {
//player bust
if (addScore(playerHand) > 21) {
// dealerNumWins++;
return "PLAYER LOSES: Player busts with " + addScore(playerHand);
}
//dealer bust
if (addScore(dealerHand) > 21) {
// playerNumWins++;
return "PLAYER WINS: Dealer busts with " + addScore(dealerHand);
}
if (gameOver == true) {
//player total greater than dealer total
if (addScore(playerHand) > addScore(dealerHand)) {
// playerNumWins++;
return "PLAYER WINS: " + addScore(playerHand) + "-" + addScore(dealerHand);
} //dealer total greater than or equal to player total
else if (addScore(playerHand) <= addScore(dealerHand)) {
// dealerNumWins++;
return "PLAYER LOSES: " + addScore(playerHand) + "-" + addScore(dealerHand);
}
}
return "";
}

class MyPanel extends JPanel {

//////////// PAINT ////////////////////////////////
public void paintComponent(Graphics g) {
//each card is 80 x 105
//grid is 800 x 700
g.drawString("--------------------------------------", 400, 10);
g.drawString("WELCOME TO BLACKJACK", 400, 25);
g.drawString("--------------------------------------", 400, 40);
g.drawString("PLAYER SCORE: " + playerNumWins, 350, 55);
g.drawString("DEALER SCORE: " + dealerNumWins, 500, 55);
g.drawString("Player Cards:", 25, 100);
g.drawString("Dealer Cards:", 25, 300);
g.drawString("Player score: " + addScore(playerHand), 25, 225);
g.drawString("Dealer score: ", 25, 425);
if (gameOver == true) {
g.drawString("Dealer score: " + addScore(dealerHand), 25, 425);
}
g.drawString(message, 400, 550);
g.drawString(checkWin(), 400, 600);

//if the deck is null, skip the card setup
int xpos = 25, ypos = 110;
if (theDeck == null) {
return;
}

//player hand setup
Card current = playerHand.getFirstCard();
while (current != null) {
Image tempimage = current.getCardImage();
g.drawImage(tempimage, xpos, ypos, this);
// note: tempimage member variable must be set BEFORE paint is called
xpos += 80;
if (xpos > 700) {
xpos = 25;
ypos += 105;
}
current = current.getNextCard(); //while
}

//dealer hand setup
int newXpos = 25, newYpos = 310;
current = dealerHand.getFirstCard();
if (current != null && gameOver == false) {

Image flipped = Project3.load_picture("images/gbCard52.gif");//faced down card
// dealerHand.getFirstCard().setCardImage(flipped);

g.drawImage(flipped, 25, 310, this);

current = current.getNextCard();
newXpos = 115;
}
while (current != null) {
Image tempimage = current.getCardImage();
// Image flippedCard = Project4.load_picture("images/gbCard52.gif");
g.drawImage(tempimage, newXpos, newYpos, this);
// if (dealerTurn == false && newXpos > 25) {
// g.drawImage(flippedCard, newXpos, newYpos, this);
// }
// note: tempimage member variable must be set BEFORE paint is called
newXpos += 80;
if (newXpos > 700) {
newXpos = 25;
newYpos += 105;
}
current = current.getNextCard(); //while
}

}

}

}

Source code for Link.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Link {
protected Link next;

public Link getNext() { return next; }
public void setNext(Link newnext) { next = newnext; }

} // end class Link

Source code for Card.java:

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

class Card extends Link {
private Image cardimage;
private int cardnumber;//to keep track of the card numbers
private int cardValue;
private String cardWord;
  
public Card (int cardnum) {
/*switch (cardnum % 13) {
case 0:
cardWord = "Ace";
cardValue = 11;
break;
case 1:
cardWord = "Two";
cardValue = 2;
break;
case 2:
cardWord = "Three";
cardValue = 3;
break;
case 3:
cardWord = "Four";
cardValue = 4;
break;
case 4:
cardWord = "Five";
cardValue = 5;
break;
case 5:
cardWord = "Six";
cardValue = 6;
break;
case 6:
cardWord = "Seven";
cardValue = 7;
break;
case 7:
cardWord = "Eight";
cardValue = 8;
break;
case 8:
cardWord = "Nine";
cardValue = 9;
break;
case 9:
cardWord = "Ten";
cardValue = 10;
break;
case 10:
cardWord = "Jack";
cardValue = 10;
break;
case 11:
cardWord = "Queen";
cardValue = 10;
break;
case 12:
cardWord = "King";
cardValue = 10;
break;
}*/
cardimage = Project3.load_picture("images/gbCard" + cardnum + ".gif");
cardnumber = cardnum;
// code ASSUMES there is an images sub-dir in your project folder
if (cardimage == null) {
System.out.println("Error - image failed to load: images/gbCard" + cardnum + ".gif");
System.exit(-1);
}
}
public Card getNextCard() {
return (Card)next;
}
public Image getCardImage() {
return cardimage;
}
public int getCardValue(){
return cardValue;
}
public String getCardWord(){
return cardWord;
}
public int getCardNumber(){
return cardnumber;
}
//set image (for changing image to facedown card)
//implement control for data in later
/*public void setCardImage(Image x){
cardimage = x;
}*/
} //end class Card

Source code for CardList.java:

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

class CardList {
private Card firstcard = null;
private int numcards=0;

public CardList(int num) {
numcards = num; //set numcards in the deck
for (int i = 0; i < num; i++) { // load the cards
Card temp = new Card(i);
if (firstcard != null) {
temp.setNext(firstcard);
}
firstcard = temp;
}
}

public Card getFirstCard() {
return firstcard;
}

public Card deleteCard(int cardnum) {
Card target, targetprevious;

if (cardnum > numcards)
return null; // not enough cards to delete that one
else
numcards--;

target = firstcard;
targetprevious = null;
while (cardnum-- > 0) {
targetprevious = target;
target = target.getNextCard();
if (target == null) return null; // error, card not found
}
if (targetprevious != null)
targetprevious.setNext(target.getNextCard());
else
firstcard = target.getNextCard();
return target;
}

public void insertCard(Card target) {
numcards++;
if (firstcard != null)
target.setNext(firstcard);
else
target.setNext(null);
firstcard = target;
}

public void shuffle() {
for ( int i = 0; i < 300; i++) {
int rand = (int)(Math.random() * 100) % numcards;
Card temp = deleteCard(rand);
if (temp != null) insertCard(temp);
} // end for loop
} // end shuffle

public int getNumCards(){
return numcards;
}
} // end class CardList

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Working code implemented in Java and appropriate comments provided for better understanding:

Here I am attaching code for these files:

  • Project3.java
  • Link.java
  • Card.java
  • CardList.java

Source code for Project3.java:

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

public class Project3 extends JFrame implements ActionListener {

private static int winxpos = 0, winypos = 0; // place window here

private JButton exitButton, hitButton, stayButton, dealButton, newGameButton;
private CardList theDeck = null;
private JPanel northPanel;
private MyPanel centerPanel;
private static JFrame myFrame = null;

private CardList playerHand = new CardList(0);
private CardList dealerHand = new CardList(0);
private int playerScore;
private int dealerScore;
private int playerNumWins = 0;
private int dealerNumWins = 0;
private String message = "";
//private boolean playerTurn;//true if player turn, false if dealer turn
//private boolean playerStay = false;//true if stay button has been hit, false otherwise
private boolean gameOver = true;//true if game is over
private boolean deal = false;//check if cards have been dealt yet

//////////// MAIN ////////////////////////
public static void main(String[] args) {
Project3 tpo = new Project3();
}

//////////// CONSTRUCTOR /////////////////////
public Project3() {
myFrame = this; // need a static variable reference to a JFrame object
northPanel = new JPanel();
northPanel.setBackground(Color.white);
dealButton = new JButton("Deal");
northPanel.add(dealButton);
dealButton.addActionListener(this);
hitButton = new JButton("Hit");
northPanel.add(hitButton);
hitButton.addActionListener(this);
stayButton = new JButton("Stay");
northPanel.add(stayButton);
stayButton.addActionListener(this);
newGameButton = new JButton("New Game");
northPanel.add(newGameButton);
newGameButton.addActionListener(this);
exitButton = new JButton("Exit");
northPanel.add(exitButton);
exitButton.addActionListener(this);
getContentPane().add("North", northPanel);

centerPanel = new MyPanel();
getContentPane().add("Center", centerPanel);

//theDeck = new CardList(52);
newGame();
setSize(800, 700);
setLocation(winxpos, winypos);

setVisible(true);
}

//////////// BUTTON CLICKS ///////////////////////////
public void actionPerformed(ActionEvent e) {

if (e.getSource() == exitButton) {
dispose();
System.exit(0);
}
if (e.getSource() == hitButton) {
if (gameOver == false && deal == true) {
message = "";
dealCard(playerHand);
repaint();
} else if (gameOver == true) {
message = "Press NEW GAME.";
repaint();
} else if (deal == false) {
message = "Press DEAL.";
repaint();
}

}
if (e.getSource() == stayButton) {
if (gameOver == false && deal == true) {
message = "";
while (true) {
if (addScore(dealerHand) < 17) {
dealCard(dealerHand);
} else {
break;
}
}
gameOver = true;
repaint();
} else if (gameOver == true) {
message = "Press NEW GAME.";
repaint();
} else if (deal == false) {
message = "Press DEAL.";
repaint();
}

}
if (e.getSource() == dealButton) {
if (gameOver == false && (playerHand.getNumCards() == 0) && (dealerHand.getNumCards() == 0 && (deal == false))) {
message = "";
dealCard(playerHand);
dealCard(dealerHand);
dealCard(playerHand);
dealCard(dealerHand);
playerScore = addScore(playerHand);
dealerScore = addScore(playerHand);
gameOver = false;
deal = true;
repaint();
} else if (gameOver == true) {
message = "Press NEW GAME.";
repaint();
} else {
message = "Press HIT or STAY.";
repaint();
}
}
if (e.getSource() == newGameButton) {
if (gameOver == true) {
message = "";
//add point to winner for win-counter
if (addScore(playerHand) > 21) {
dealerNumWins++;
} //dealer bust
else if (addScore(dealerHand) > 21) {
playerNumWins++;
} //player total greater than dealer total
else if (addScore(playerHand) > addScore(dealerHand)) {
playerNumWins++;
} //dealer total greater than or equal to player total
else if (addScore(playerHand) <= addScore(dealerHand)) {
dealerNumWins++;
}

newGame();
} else {
message = "Please finish the game or EXIT.";
}
repaint();
}
}

// This routine will load an image into memory
//
public static Image load_picture(String fname) {
// Create a MediaTracker to inform us when the image has
// been completely loaded.
Image image;
MediaTracker tracker = new MediaTracker(myFrame);

// getImage() returns immediately. The image is not
// actually loaded until it is first used. We use a
// MediaTracker to make sure the image is loaded
// before we try to display it.
image = myFrame.getToolkit().getImage(fname);

// Add the image to the MediaTracker so that we can wait
// for it.
tracker.addImage(image, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException e) {
System.err.println(e);
}

if (tracker.isErrorID(0)) {
image = null;
}
return image;
}
// -------------- end of load_picture ---------------------------

public void newGame() {
theDeck = new CardList(52);//resets deck
playerHand = new CardList(0);//resets player hand
dealerHand = new CardList(0);//resets enemy hand
theDeck.shuffle();//shuffles deck
//playerScore = 0;//resets scores
// dealerScore = 0;//resets scores
gameOver = false;
deal = false;

}

public void startGame() {
theDeck = new CardList(52);
theDeck.shuffle();
playerHand = new CardList(0);
dealerHand = new CardList(0);
gameOver = false;
dealCard(playerHand);
dealCard(dealerHand);
dealCard(playerHand);
dealCard(dealerHand);
playerScore = addScore(playerHand);
dealerScore = addScore(playerHand);
// playerTurn = true;
}

public void dealCard(CardList hand) {
if (theDeck.getNumCards() != 0) {
Card current = theDeck.deleteCard(0);
hand.insertCard(current);
if (addScore(hand) > 21) {
gameOver = true;
}
}
}

public int addScore(CardList hand) {
int score = 0;
int numAce = 0;
Card current = hand.getFirstCard();
while (current != null) {
if ((current.getCardNumber() % 13) == 0) {
numAce++;
score = score + 11;
} else if ((current.getCardNumber() % 13) < 10)//card values 2-10
{
score = score + (current.getCardNumber() % 13 + 1);
} else if ((current.getCardNumber() % 13) >= 10) {//card values Jack, Queen, King
score = score + 10;
}
current = current.getNextCard();
}
if (score > 21) {
score = score - (numAce * 10);
}
return score;
}

public String checkWin() {
//player bust
if (addScore(playerHand) > 21) {
// dealerNumWins++;
return "PLAYER LOSES: Player busts with " + addScore(playerHand);
}
//dealer bust
if (addScore(dealerHand) > 21) {
// playerNumWins++;
return "PLAYER WINS: Dealer busts with " + addScore(dealerHand);
}
if (gameOver == true) {
//player total greater than dealer total
if (addScore(playerHand) > addScore(dealerHand)) {
// playerNumWins++;
return "PLAYER WINS: " + addScore(playerHand) + "-" + addScore(dealerHand);
} //dealer total greater than or equal to player total
else if (addScore(playerHand) <= addScore(dealerHand)) {
// dealerNumWins++;
return "PLAYER LOSES: " + addScore(playerHand) + "-" + addScore(dealerHand);
}
}
return "";
}

class MyPanel extends JPanel {

//////////// PAINT ////////////////////////////////
public void paintComponent(Graphics g) {
//each card is 80 x 105
//grid is 800 x 700
g.drawString("--------------------------------------", 400, 10);
g.drawString("WELCOME TO BLACKJACK", 400, 25);
g.drawString("--------------------------------------", 400, 40);
g.drawString("PLAYER SCORE: " + playerNumWins, 350, 55);
g.drawString("DEALER SCORE: " + dealerNumWins, 500, 55);
g.drawString("Player Cards:", 25, 100);
g.drawString("Dealer Cards:", 25, 300);
g.drawString("Player score: " + addScore(playerHand), 25, 225);
g.drawString("Dealer score: ", 25, 425);
if (gameOver == true) {
g.drawString("Dealer score: " + addScore(dealerHand), 25, 425);
}
g.drawString(message, 400, 550);
g.drawString(checkWin(), 400, 600);

//if the deck is null, skip the card setup
int xpos = 25, ypos = 110;
if (theDeck == null) {
return;
}

//player hand setup
Card current = playerHand.getFirstCard();
while (current != null) {
Image tempimage = current.getCardImage();
g.drawImage(tempimage, xpos, ypos, this);
// note: tempimage member variable must be set BEFORE paint is called
xpos += 80;
if (xpos > 700) {
xpos = 25;
ypos += 105;
}
current = current.getNextCard(); //while
}

//dealer hand setup
int newXpos = 25, newYpos = 310;
current = dealerHand.getFirstCard();
if (current != null && gameOver == false) {

Image flipped = Project3.load_picture("images/gbCard52.gif");//faced down card
// dealerHand.getFirstCard().setCardImage(flipped);

g.drawImage(flipped, 25, 310, this);

current = current.getNextCard();
newXpos = 115;
}
while (current != null) {
Image tempimage = current.getCardImage();
// Image flippedCard = Project4.load_picture("images/gbCard52.gif");
g.drawImage(tempimage, newXpos, newYpos, this);
// if (dealerTurn == false && newXpos > 25) {
// g.drawImage(flippedCard, newXpos, newYpos, this);
// }
// note: tempimage member variable must be set BEFORE paint is called
newXpos += 80;
if (newXpos > 700) {
newXpos = 25;
newYpos += 105;
}
current = current.getNextCard(); //while
}

}

}

}

Source code for Link.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Link {
protected Link next;

public Link getNext() { return next; }
public void setNext(Link newnext) { next = newnext; }

} // end class Link

Source code for Card.java:

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

/*****************************************************************
Class Card, the derived class each card is one object of type Card
May be placed in a file named Card.java
******************************************************************/

class Card extends Link {
private Image cardimage;
private int cardnumber;//to keep track of the card numbers
private int cardValue;
private String cardWord;
  
public Card (int cardnum) {
/*switch (cardnum % 13) {
case 0:
cardWord = "Ace";
cardValue = 11;
break;
case 1:
cardWord = "Two";
cardValue = 2;
break;
case 2:
cardWord = "Three";
cardValue = 3;
break;
case 3:
cardWord = "Four";
cardValue = 4;
break;
case 4:
cardWord = "Five";
cardValue = 5;
break;
case 5:
cardWord = "Six";
cardValue = 6;
break;
case 6:
cardWord = "Seven";
cardValue = 7;
break;
case 7:
cardWord = "Eight";
cardValue = 8;
break;
case 8:
cardWord = "Nine";
cardValue = 9;
break;
case 9:
cardWord = "Ten";
cardValue = 10;
break;
case 10:
cardWord = "Jack";
cardValue = 10;
break;
case 11:
cardWord = "Queen";
cardValue = 10;
break;
case 12:
cardWord = "King";
cardValue = 10;
break;
}*/
cardimage = Project3.load_picture("images/gbCard" + cardnum + ".gif");
cardnumber = cardnum;
// code ASSUMES there is an images sub-dir in your project folder
if (cardimage == null) {
System.out.println("Error - image failed to load: images/gbCard" + cardnum + ".gif");
System.exit(-1);
}
}
public Card getNextCard() {
return (Card)next;
}
public Image getCardImage() {
return cardimage;
}
public int getCardValue(){
return cardValue;
}
public String getCardWord(){
return cardWord;
}
public int getCardNumber(){
return cardnumber;
}
//set image (for changing image to facedown card)
//implement control for data in later
/*public void setCardImage(Image x){
cardimage = x;
}*/
} //end class Card

Source code for CardList.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/*****************************************************************
Class CardList, A Linked list of playing cards
May be placed in a file named CardList.java

Note : This class can be used to create a 'hand' of cards
Just Create another CardList object, and delete cards from
'theDeck' and insert the into the new CardList object

******************************************************************/

class CardList {
private Card firstcard = null;
private int numcards=0;

public CardList(int num) {
numcards = num; //set numcards in the deck
for (int i = 0; i < num; i++) { // load the cards
Card temp = new Card(i);
if (firstcard != null) {
temp.setNext(firstcard);
}
firstcard = temp;
}
}

public Card getFirstCard() {
return firstcard;
}

public Card deleteCard(int cardnum) {
Card target, targetprevious;

if (cardnum > numcards)
return null; // not enough cards to delete that one
else
numcards--;

target = firstcard;
targetprevious = null;
while (cardnum-- > 0) {
targetprevious = target;
target = target.getNextCard();
if (target == null) return null; // error, card not found
}
if (targetprevious != null)
targetprevious.setNext(target.getNextCard());
else
firstcard = target.getNextCard();
return target;
}

public void insertCard(Card target) {
numcards++;
if (firstcard != null)
target.setNext(firstcard);
else
target.setNext(null);
firstcard = target;
}

public void shuffle() {
for ( int i = 0; i < 300; i++) {
int rand = (int)(Math.random() * 100) % numcards;
Card temp = deleteCard(rand);
if (temp != null) insertCard(temp);
} // end for loop
} // end shuffle

public int getNumCards(){
return numcards;
}
} // end class CardList

Output Screenshots:

Deal Hit Stay New Game Exit WELCOME TO BLACKJACK PLAYER SCORE: 1 DEALER SCORE: 0 Player Cards 16 Player score: 16 Dealer Card

Hope it helps, if you like the answer give it a thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • please help me to creating UML class diagrams. Snake.java package graphichal2; import java.awt.Color; import java.awt.Font; import...

    please help me to creating UML class diagrams. Snake.java package graphichal2; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; enum Dir{L, U, R, D}; class Food { public static int FOODSTYLE = 1; private int m = r.nextInt(Yard.WIDTH / Yard.B_WIDTH); private int n = r.nextInt(Yard.HEIGHT / Yard.B_WIDTH - 30/Yard.B_WIDTH) + 30/Yard.B_WIDTH;// 竖格 public static Random r = new Random(); public int getM() { return m; } public void setM(int m)...

  • Computer Science 182 Data Structures and Program Design Programming Project #3 – Link List Card Games...

    Computer Science 182 Data Structures and Program Design Programming Project #3 – Link List Card Games One of the nice things about Java is it is very easy to do fun things with graphics. The start code provided here will display a deck of cards on the screen and shuffle them. Your mission, is to start with this code and build a card game. Blackjack, poker solitaire, what ever your heart desires. Blackjack is the easiest. Obviously any program you...

  • NEED HELP TO CREATE A BLACKJACK GAME WITH THE UML DIAGRAM AND PROBLEM SOLVING TO GET...

    NEED HELP TO CREATE A BLACKJACK GAME WITH THE UML DIAGRAM AND PROBLEM SOLVING TO GET CODE TO RUN!! THANKS Extend the DeckofCards and the Card class in the book to implement a card game application such as BlackJack, Texas poker or others. Your game should support multiple players (up to 5 for BlackJack). You must build your game based on the Cards and DeckofCards class from the book. You need to implement the logic of the game. You can...

  • [JS] [HTML] wanting to add this logic to existing code(see below) of a blackjack game, where...

    [JS] [HTML] wanting to add this logic to existing code(see below) of a blackjack game, where it will show the Suit emblem instead of spelled out suit name. example: display 7 ♣ instead of 7 clubs. //this is the logic, main obj is to display suits emblems to existing code if (card.Suit == 'Hearts') icon='&hearts;'; else if (card.Suit == 'Spades') icon = '&spades;'; else if (card.Suit == 'Diamonds') icon = '&diams;'; else icon = '&clubs;'; //existing code blackjack.js //variables for...

  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

  • Introduction to Java Programming Question: I’m doing a java game which user clicks on two different...

    Introduction to Java Programming Question: I’m doing a java game which user clicks on two different blocks and see the number and remember their locations and match the same number. I’m basically looking for codes that could make my memory match game more difficult or more interesting.(a timer, difficulty level, color, etc.) GUI must be included in the code. Here is what I got so far: package Card; import javax.swing.JButton; public class Card extends JButton{    private int id;   ...

  • in java coorect this code & screenshoot your output ---------------------------------------------------------------------- public class UNOGame {     /**...

    in java coorect this code & screenshoot your output ---------------------------------------------------------------------- public class UNOGame {     /**      * @param args the command line arguments      */         public static void main(String[] args) {       Scanner input=new Scanner(System.in);          Scanner input2=new Scanner(System.in);                             UNOCard c=new UNOCard ();                UNOCard D=new UNOCard ();                 Queue Q=new Queue();                           listplayer ll=new listplayer();                           System.out.println("Enter Players Name :\n Click STOP To Start Game..");        String Name = input.nextLine();...

  • Given these three classes: Card, DeckOfCards, and DeckOfCardsTest. Extend the DeckofCards class to implement a BlackJack...

    Given these three classes: Card, DeckOfCards, and DeckOfCardsTest. Extend the DeckofCards class to implement a BlackJack class, which implements a BlackJack game. Please do not use any java applet on the coding. Hint: Use a test class to test above classes. Pulic class Card {    private final String face; // face of card ("Ace", "Deuce", ...)    private final String suit; // suit of card ("Hearts", "Diamonds", ...)    // two-argument constructor initializes card's face and suit    public...

  • need help with code it won't compile. import java.util.ArrayList; /** * Counts the ranks of cards...

    need help with code it won't compile. import java.util.ArrayList; /** * Counts the ranks of cards in a hand. * * @author (your name) * @version (a version number or a date) */ public class CountRank { // instance variables - replace the example below with your own private int rankCount[]; private Hand hand; private int count; /** * Constructor for objects of class CountRank */ public CountRank(Hand h) { // initialise instance variables hand = h; rankCount = new...

  • Introduction to Java Programming Question: I’m doing a java game which user clicks on two different blocks and see the number and remember their locations and match the same number. I’m basically look...

    Introduction to Java Programming Question: I’m doing a java game which user clicks on two different blocks and see the number and remember their locations and match the same number. I’m basically looking for codes that could make my memory match game more difficult or more interesting.(a timer, difficulty level, color, etc.) GUI must be included in the code. Here is what I got so far: package Card; import javax.swing.JButton; public class Card extends JButton{    private int id;    private boolean...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT