Я написал игру в блэкджек для школьного проекта. Мой учитель ответил мне и попросил реализовать в коде наследование и обработку файлов. Я не совсем уверен, как это сделать в проекте такого типа.
public class Card {
String value;
String type;
// Constructor to create a card with value and type
public Card(String value, String type) {
this.value = value;
this.type = type;
}
// Override the toString method to return the card's value and type as a string
@Override
public String toString() {
return value + "-" + type;
}
// Method to get the card's value in points
public int getValue() {
// Check if the value is one of AJQK
if ("AJQK".contains(value)) {
if (value.equals("A")) {
return 11; // Ace is worth 11 points
}
return 10; // J, Q, and K are worth 10 points
}
// If it's a numeric value, return it as an int
return Integer.parseInt(value);
}
// Method to check if the card is an ace
public boolean isAce() {
return value.equals("A");
}
// Method to get the path to the card's image
public String getImagePath() {
return "./cards/" + toString() + ".png";
}
}
import java.util.ArrayList;
import java.util.Random;
public class Deck {
ArrayList deck;
Random random = new Random();
// Dealer
Card hiddenCard;
ArrayList dealerHand;
int dealerSum;
int dealerAceCount;
// Player
ArrayList playerHand;
int playerSum;
int playerAceCount;
// Constructor to build and shuffle the deck, and deal the initial cards
public Deck() {
buildDeck();
shuffleDeck();
dealerHand = new ArrayList();
dealerSum = 0;
dealerAceCount = 0;
// Deal the first card to the dealer (hidden card)
hiddenCard = deck.remove(deck.size() - 1);
dealerSum += hiddenCard.getValue();
dealerAceCount += hiddenCard.isAce() ? 1 : 0;
// Deal the second card to the dealer
Card card = deck.remove(deck.size() - 1);
dealerSum += card.getValue();
dealerAceCount += card.isAce() ? 1 : 0;
dealerHand.add(card);
System.out.println("DEALER:");
System.out.println(hiddenCard);
System.out.println(dealerHand);
System.out.println(dealerSum);
System.out.println(dealerAceCount);
// Initialize the player's hand and deal two cards to the player
playerHand = new ArrayList();
playerSum = 0;
playerAceCount = 0;
for (int i = 0; i < 2; i++) {
card = deck.remove(deck.size() - 1);
playerSum += card.getValue();
playerAceCount += card.isAce() ? 1 : 0;
playerHand.add(card);
}
System.out.println("PLAYER:");
System.out.println(playerHand);
System.out.println(playerSum);
System.out.println(playerAceCount);
}
// Method to build the deck with all 52 cards
public void buildDeck() {
deck = new ArrayList();
String[] values = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
String[] types = {"C", "D", "H", "S"};
for (int i = 0; i < types.length; i++) {
for (int j = 0; j < values.length; j++) {
Card card = new Card(values[j], types[i]);
deck.add(card);
}
}
System.out.println("BUILD DECK:");
for (Card card : deck) {
System.out.println(card);
}
}
// Method to shuffle the deck
public void shuffleDeck() {
for (int i = 0; i < deck.size(); i++) {
int j = random.nextInt(deck.size());
Card currCard = deck.get(i);
Card randomCard = deck.get(j);
deck.set(i, randomCard);
deck.set(j, currCard);
}
System.out.println("AFTER SHUFFLE");
System.out.println(deck);
}
}
Я попытался создать два новых класса Player.java и Dealer.java, которые наследуются от card.java. Но я просто не мог заставить его работать. Также я попытался создать класс FileHandler для изображений, но не смог загрузить изображения. Есть идеи, что я могу сделать?
Я написал игру в блэкджек для школьного проекта. Мой учитель ответил мне и попросил реализовать в коде наследование и обработку файлов. Я не совсем уверен, как это сделать в проекте такого типа. [code]import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
public class BlackjackGUI { public JFrame frame; public JPanel gamePanel;
// Define the dimensions of the game board public int boardWidth = 600; public int boardHeight = boardWidth; // This will be 600
int cardWidth = 110; int cardHeight = 154;
Deck deck; Card card;
JButton hitButton; JButton stayButton;
public BlackjackGUI() { frame = new JFrame("Blackjack"); frame.setSize(boardWidth, boardHeight); // Set the size of the frame frame.setLocationRelativeTo(null); // Center the frame frame.setResizable(false); // Make the frame non-resizable frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set default close operation
deck = new Deck(); // Create a new deck and initialize the game
// Create and configure the game panel gamePanel = new JPanel() { @Override public void paintComponent(Graphics g) { super.paintComponent(g);
try { Image hiddenCardImage = new ImageIcon(getClass().getResource("./cards/BACK.png")).getImage(); if (!stayButton.isEnabled()) { hiddenCardImage = new ImageIcon(getClass().getResource(deck.hiddenCard.getImagePath())).getImage(); } g.drawImage(hiddenCardImage, 20, 20, cardWidth, cardHeight, null);
for (int i = 0; i < deck.dealerHand.size(); i++) { Card card = deck.dealerHand.get(i); // Test// System.out.println(card.getImagePath()); Image cardImg = new ImageIcon(getClass().getResource(card.getImagePath())).getImage();
gamePanel.add(buttonPanel, BorderLayout.SOUTH); // Add the button panel to the game panel
// Add the game panel to the frame frame.add(gamePanel);
// Check if the dealer has blackjack immediately after the initial deal if (deck.dealerSum == 21) { hitButton.setEnabled(false); stayButton.setEnabled(false); gamePanel.repaint(); } else if (deck.playerSum == 21) { hitButton.setEnabled(false); stayButton.setEnabled(false); }
frame.setVisible(true); // Make the frame visible }
private void hit() { // Example action for the hit button System.out.println("Hit button pressed");
public static void main(String[] args) { SwingUtilities.invokeLater(() -> new BlackjackGUI()); } }
[/code] [code]public class Card { String value; String type;
// Constructor to create a card with value and type public Card(String value, String type) { this.value = value; this.type = type; }
// Override the toString method to return the card's value and type as a string @Override public String toString() { return value + "-" + type; }
// Method to get the card's value in points public int getValue() { // Check if the value is one of AJQK if ("AJQK".contains(value)) { if (value.equals("A")) { return 11; // Ace is worth 11 points } return 10; // J, Q, and K are worth 10 points } // If it's a numeric value, return it as an int return Integer.parseInt(value); }
// Method to check if the card is an ace public boolean isAce() { return value.equals("A"); }
// Method to get the path to the card's image public String getImagePath() { return "./cards/" + toString() + ".png"; } }
[/code] Я попытался создать два новых класса Player.java и Dealer.java, которые наследуются от card.java. Но я просто не мог заставить его работать. Также я попытался создать класс FileHandler для изображений, но не смог загрузить изображения. Есть идеи, что я могу сделать?