Программа Блэкджек, не знаю, с чего начать
Итак, у меня есть задание на программирование для создания программы блэкджека. Все, что мне нужно сделать, это создать методы для класса BlackJackHand. Я довольно потерян. Верны ли мои переменные, которые у меня есть? Вот BlackJackHand: пакет блэкджек;
public class BlackjackHand {
static final int MAX_HAND_SIZE = 5;
public PlayingCard[] hand;
public int numCards;
private DeckOfCards[] deck;
// an array of cards
// number of cards in the hand
// the deck this hand draws cards from
// This constructor creates a new BlackjackHand using the provided deck.
// Tip: Initialize all data fields, allocate space for the array of 5 cards,
// then deal two cards from the deck into cards[0] and cards[1].
// You'll have 2 cards in your hand, at this point.
public BlackjackHand(DeckOfCards deck) {
deck = new DeckOfCards();
hand = new PlayingCard[5];
hand[0] = deck.dealACard();
hand[1] = deck.dealACard();
}
// This method returns the point value of the hand. It is a simple sum
// of the PlayingCard values in the hand, except that an ace can count as
// either 1 or 11 points.
// Tip: Pretend the ace rule doesn;t exist, and sum up your card values.
// If the sum is < 12, and there is an ace in the hand, then increment the
// point value by 10 before returning it.
public int valueOfHand() {
return (0);
}
// Print out the names of all cards in the hand.
// Tip: Don't iterate through all 5 cards, necessarily. Use numCards
// as the bound in your loop.
public void printHand() {
}
// Return the number of cards in the hand.
public int sizeOfHand() {
return 0;
}
// Return the most recently dealt card in the hand.
// Tip: That'll be the card at index numCards-1
PlayingCard mostRecentCard() {
return null;
}
// Draw a card from the deck. If the hand already had 5 cards,
// print out an error message instead.
// Tip: Put the card from the deck into the array of cards at
// index numCards, then increment numCards.
public void hitMe() {
if (numCards == 5){
System.out.println("You already have 5 cards.");
}//if
else {
}//else
}//hitMe
Вот класс PlayingCards
package blackjack;
public class PlayingCard {
private String suit; // "clubs", "diamonds", "hearts" or "spades"
private int cardFace; // the value on the card. 1 for ace, 2 for 2, 13 for king, etc
// constructor
public PlayingCard(int v, String s) {
cardFace = v;
suit = s;
}
// Is this card an Ace?
boolean isAce() {
if(cardFace == 1) {
return true;
} else {
return false;
}
}
// return the blackjack point value of this card
public int pointValue() {
if(cardFace > 10) {
return 10;
} else {
return cardFace;
}
}
// make a string of the name of the card
public String name() {
String temp = "";
// concatenate the String equivalent of cardFace to temp
if(cardFace == 1) {
temp += "Ace";
} else if(cardFace == 11) {
temp += "Jack";
} else if(cardFace == 12) {
temp += "Queen";
} else if(cardFace == 13) {
temp += "King";
} else { // a number card
temp += cardFace; // implcit type conversion of cardFace into String
}
// concatenate the name together
temp = temp + " of " + suit;
return temp;
}
}
Вот класс DeckOfCards:
пакет блэкджек; импорт java.util.Random;
открытый класс DeckOfCards {
private PlayingCard[] cards;
private int topOfDeck; // array index that's "the top of the deck"
public DeckOfCards() {
cards = new PlayingCard[52];
for (int i = 1; i <= 13; i++) { // make all the "hearts" cards
cards[i - 1] = new PlayingCard(i, "hearts");
}
for (int i = 1; i <= 13; i++) { // make all the "hearts" cards
cards[i - 1 + 13] = new PlayingCard(i, "clubs");
}
for (int i = 1; i <= 13; i++) { // make all the "hearts" cards
cards[i - 1 + 26] = new PlayingCard(i, "diamonds");
}
for (int i = 1; i <= 13; i++) { // make all the "hearts" cards
cards[i - 1 + 39] = new PlayingCard(i, "spades");
}
topOfDeck = 51;
}
public PlayingCard dealACard() {
PlayingCard temp = cards[topOfDeck];
topOfDeck--;
return temp;
}
public void shuffle() {
PlayingCard[] tempArray = new PlayingCard[52];
Random r = new Random();
for (int i = topOfDeck; i >= 0; i--) {
int index = r.nextInt(i + 1); // the index of a random card in the deck
tempArray[i] = cards[index];
// swap cards[i] with cards[index]
PlayingCard tempCard = cards[i];
cards[i] = cards[index];
cards[index] = tempCard;
}
// at this point, tempArray has all the cards selected in random order
cards = tempArray;
}
}
И, наконец, основной класс BlackJack:
package blackjack;
public class Blackjack {
static final int WINNING_LIMIT = 21;
static final int STAND_VALUE = 17;
public static void main(String[] args) {
DeckOfCards deck = new DeckOfCards();
deck.shuffle();
// dealer's starting hand
System.out.println("Let's play a hand of Blackjack!\nFirst, it's Dealer's turn.");
BlackjackHand theDealer = new BlackjackHand(deck);
System.out.println("Dealer begins with a hand of value " + theDealer.valueOfHand() + ":");
theDealer.printHand();
// dealer hits until he stands
while (theDealer.valueOfHand() < STAND_VALUE) {
if (theDealer.sizeOfHand() >= BlackjackHand.MAX_HAND_SIZE) { // 5 cards under 21: auto-win
System.out.println("Dealer has drawn a hand of 5 cards, of value " + theDealer.valueOfHand() + ". Automatic win!");
theDealer.printHand();
return;
}
theDealer.hitMe();
System.out.println("Dealer draws a " + theDealer.mostRecentCard().name() + ", and now has " + theDealer.valueOfHand() + " points.");
}
// check to see if dealer busts
if (theDealer.valueOfHand() > WINNING_LIMIT) {
System.out.println("Dealer busts. Player 2 wins!");
return;
}
System.out.println("Dealer stands with a hand of value " + theDealer.valueOfHand() + ":");
theDealer.printHand();
// player 2's starting hand
System.out.println("Now, it's player 2's turn.");
BlackjackHand player2 = new BlackjackHand(deck);
System.out.println("Player 2 begins with a hand of value " + player2.valueOfHand() + ":");
player2.printHand();
// player 2 hits until he stands. Beat the dealer's hand, or bust.
while (player2.valueOfHand() < theDealer.valueOfHand()) {
if (player2.sizeOfHand() >= BlackjackHand.MAX_HAND_SIZE) { // 5 cards under 21: auto-win
System.out.println("Player 2 has drawn a hand of 5 cards, of value " + player2.valueOfHand() + ". Automatic win!");
player2.printHand();
return;
}
player2.hitMe();
System.out.println("Player 2 draws a " + player2.mostRecentCard().name() + ", and now has " + player2.valueOfHand() + " points.");
}
// check to see if Player 2 busts
if (player2.valueOfHand() > WINNING_LIMIT) {
System.out.println("Player 2 busts. Dealer wins!");
return;
}
System.out.println("The hand is over.");
System.out.println("Dealer's hand has value " + theDealer.valueOfHand() + ":");
theDealer.printHand();
System.out.println("Player 2's hand has value " + player2.valueOfHand() + ":");
player2.printHand();
// figure out who won
if (theDealer.valueOfHand() >= player2.valueOfHand()) {
System.out.println("Dealer wins!");
} else {
System.out.println("Player 2 wins!");
}
}//main
}//Blackjack
Я знаю, насколько это сложно, но мне действительно нужна небольшая помощь. Я не хочу, чтобы это было сделано для меня, я хочу помочь понять это.
3 ответа
Вы можете использовать Enums для костюма и / или карты.
Я не уверен, если ваш shuffle
Метод достаточно случайный - я думаю, что у вас есть большой уклон к обмену элементами в начале массива, в то время как конец массива не будет так сильно рандомизирован. Вы можете исправить это, используя ArrayList для вашей колоды вместо массива, или же создать временный ArrayList, используя Arrays.asList
; создайте временный ArrayList, затем remove
случайные элементы из исходного списка и add
их до конца временного списка (tempList.add(originalList.remove(r.nextInt(originalList.size())))
), наконец, скопируйте временный список обратно в массив (если вы все еще используете массив для колоды) или установите originalList = tempList
(если вы используете ArrayList для колоды). В качестве альтернативы вы можете использовать Collections.shuffle вместо своего пользовательского метода shuffle.
public int valueOfHand() {
}
Начни там. Как вы определяете ценность руки в блэк джек? Сначала вы определяете стоимость каждой карты. Класс PlayingCard удобно хранит целочисленное значение для каждой карты. Создайте переменную с именем handsum и добавьте в нее hand[0].cardFace. Хотя сначала нужно проверить, равно ли значение 1, а затем добавить еще 10 к ручной сумме (согласно инструкциям). Затем добавьте значение hand [0] к handsum, еще раз проверив сначала значение 1.
Я бы лично начал с функции hitMe(), где другой ответ сказал вам, как нарисовать карту. Оттуда все, что вам нужно сделать, это хранить в массиве карты дилеров и отдельно карты игроков. Оттуда вы можете легко получить размер массива (java отслеживает размер массива для вас), а также самую последнюю карту (должна быть самой последней добавленной картой в массиве). Оттуда все, что вам нужно сделать, это распечатать массив и записать valueOfHand().