介绍

大家好!我是一个老程序员,三年没有编程,只是在我的大学里开始学习Java(现在上课已经两周了。)

我编写了一个二十一点程序,我想知道是否有任何方法可以减少二十一点类中的代码,不确定是否只有我自己,但是看起来又长又乱。我编程很草率,在需要时输入值并加以破解。我希望可以得到您的建议和更改,以便我可以在我的程序中使用它们,并在将来继续在学校学习:)

注意:它也是重击,而不是软击,因此玩家的机会略少。

谢谢!

跑课

import java.util.Scanner;

public class Run
{
    // instance variables - replace the example below with your own
    public static void main (String[] args)
    {
        try
        {
            Blackjack.blackjack();
        } catch(Exception e) {}
    }

}


大酒杯类

import java.util.Scanner;
import java.util.Objects;

public class Blackjack
{
    public static void blackjack () throws InterruptedException
    {
        // TO SLEEP
        // Thread.sleep(x);
        // Total seconds to sleep = x/1000
        ///////////////////////////////


        // Variables
        String[] deck = Deck.generateDeck();
        String[] player = new String[6];
        String[] dealer = new String[6];
        int money = 0, bet = 0, deckNumber = 0, handNumber = 0, stay = 0, cardTotal = 0, i = 0, totalValue = 0, totalValueAce = 0;
        boolean win = false, lose = false, quit = false, play = false, betTrue = false, blackJack = false;
        String enter = "";

        // Scanner
        Scanner input = new Scanner(System.in);

        System.out.println("///// Blackjack //////");
        System.out.print("Enter starting money: $");
        money = input.nextInt();
        System.out.println("//////////////////////\n");
        System.out.println("Current cash amount: $" + money);
        while (quit == false)
        {
            while (quit == false && play == false)
            {
                System.out.print("Would you like to play? (yes/no): ");
                player[0] = input.next();
                if (Objects.equals(player[0], "yes"))
                {
                    play = true;
                    System.out.print("\n");
                }
                else if (Objects.equals(player[0], "no"))
                {
                    quit = true;
                }
                else
                {
                    System.out.println("Error enter either yes/no!");
                }
            }

            while (betTrue == false && quit == false)
            {
                System.out.print("Enter bet amount: $");
                bet = input.nextInt();
                if (bet > money)
                {
                    System.out.println("Error, you entered more money than you had!\n");
                }
                else if (bet < 0)
                {
                    System.out.println("You can't bet negative dollars silly!\n");
                }
                else
                {
                    betTrue = true;
                }
                System.out.println("Good luck!\n");
            }

            betTrue = false;
            // Deal format:
            // Deck.deal(cardPlace to deal, player cardHand#, certain deck, player name);
            //
            // Randomize Cards in Deck
            Deck.totalRandom(deck,1000);

            Deck.deal(0,0,deck,player);
            Deck.deal(1,1,deck,player);
            Deck.deal(2,0,deck,dealer);
            Deck.deal(3,1,deck,dealer);

            // Total cards in player hand, used in loop
            cardTotal = 2;

            // Next hand number, used in equation
            handNumber = 2;

            // Tells to deal the fourth card of deck next
            deckNumber = 4;

            // Player Turn Loop
            while (stay == 0 && lose == false && win == false && quit == false)
            {
                System.out.print("You've gotten the cards: ");
                i = (cardTotal - 1);
                while (i > -1)
                {
                    System.out.print(player[i]);
                    if (i > 1)
                    {
                        System.out.print(", ");
                    }
                    else if (i > 0)
                    {
                        if (handNumber > 3)
                        {
                            System.out.println(",");
                        }
                        System.out.print(" and ");
                    }
                    else
                    {
                        System.out.println(".");
                    }
                    --i;
                }
                if (((Deck.checkValue(player[0]) == -1)) && ((Deck.checkValue(player[1])) == 10) || ((Deck.checkValue(player[1]) == -1)) && ((Deck.checkValue(player[0])) == 10))
                {
                    win = true;
                    blackJack = true;
                }
                else
                {
                    i = cardTotal;
                    totalValue = 0;
                    totalValueAce = 0;
                    while (i>0)
                    {
                        --i;
                        if (Deck.checkValue(player[i]) == -1)
                        {
                            totalValueAce = totalValue + 1;
                            totalValue += 11;
                        }
                        else
                        {
                            totalValue+=Deck.checkValue(player[i]);
                            if (totalValueAce != 0)
                            {
                                totalValueAce+=Deck.checkValue(player[i]);
                            }
                        }

                    }
                    if (totalValue == 21 || totalValueAce == 21)
                    {
                    }
                    else if (totalValueAce == 0 && totalValue > 21)
                    {
                        lose = true;
                    }
                    else if (totalValueAce > 21)
                    {
                        lose = true;
                    }
                    else if (handNumber == 5)
                    {
                        lose = true;
                    }
                }
                if (totalValue > 21 && totalValueAce != 0)
                {
                    totalValue = totalValueAce;
                    totalValueAce = 0;
                }
                if (totalValueAce == 0)
                {
                    System.out.println("You have the total value: " + totalValue);
                }
                else
                {
                    System.out.println("You have total value of either " + totalValue + " or " + totalValueAce);
                }
                if (lose == false && win == false)
                {
                    System.out.println("\nDealer has face up card: " + dealer[0]);
                    System.out.println("Would you like to hit or stay?");
                    enter = input.next();
                    System.out.println("");
                    if (Objects.equals(enter, "hit"))
                    {
                        Deck.deal(deckNumber,handNumber,deck,player);
                        ++deckNumber;
                        ++handNumber;
                        ++cardTotal;
                    }
                    else if (Objects.equals(enter, "stay"))
                    {
                        stay = 1;
                    }
                    else
                    {
                        System.out.println("Invalid value!\n");
                    }
                }
            }

            stay = 0;
            cardTotal = 2;
            handNumber = 2;
            int totalValueDealer = 0;
            int totalValueDealerAce = 0;

            // Dealer Turn Loop
            while (stay == 0 && lose == false && win == false && quit == false && (totalValueDealer < totalValue ||
            totalValueDealerAce < totalValueAce || totalValueDealer < totalValueAce || totalValueDealerAce < totalValue))
            {
                System.out.print("Dealer has the cards: ");
                i = (cardTotal - 1);
                while (i > -1)
                {
                    System.out.print(dealer[i]);
                    if (i > 1)
                    {
                        System.out.print(", ");
                    }
                    else if (i > 0)
                    {
                        if (handNumber == 3)
                        {
                            System.out.print(",");
                        }
                        else if (handNumber > 3)
                        {
                            System.out.println(",");
                        }
                        System.out.print(" and ");
                    }
                    else
                    {
                        System.out.println(".");
                    }
                    --i;
                }

                if (((Deck.checkValue(dealer[0]) == -1)) && ((Deck.checkValue(dealer[1])) == 10))
                {
                    System.out.println("You lose");
                }
                else
                {
                    totalValueDealer = 0;
                    totalValueDealerAce = 0;
                    i = cardTotal;
                    while (i>0)
                    {
                        --i;
                        if (Deck.checkValue(dealer[i]) == -1)
                        {
                            totalValueDealerAce = totalValueDealer + 1;
                            totalValueDealer += 11;
                        }
                        else
                        {
                            totalValueDealer+=Deck.checkValue(dealer[i]);
                            if (totalValueDealerAce != 0)
                            {
                                totalValueDealerAce+=Deck.checkValue(dealer[i]);
                            }
                        }
                    }
                    if (totalValueDealer > 21 && totalValueAce != 0)
                    {
                    totalValueDealer = totalValueDealerAce;
                    totalValueDealerAce = 0;
                    }
                    if (totalValueDealer == 21 || totalValueDealerAce == 21)
                    {
                    }
                    else if (totalValueDealerAce == 0 && totalValueDealer > 21)
                    {
                        win = true;
                    }
                    else if (totalValueDealerAce > 21)
                    {
                        win = true;
                    }
                    else if (handNumber == 5)
                    {
                        lose = true;
                    }
                }
                if (totalValueDealerAce == 0)
                {
                    System.out.println("Dealer has the total value: " + totalValueDealer);
                }
                else
                {
                    System.out.println("Dealer has total value of either " + totalValueDealer + " or " + totalValueDealerAce);
                }
                System.out.println("");
                Thread.sleep(3000);
                if (totalValueDealer < 17 || (totalValueDealerAce != 0 && totalValueDealerAce < 17))
                {
                    Deck.deal(deckNumber,handNumber,deck,dealer);
                    ++deckNumber;
                    ++handNumber;
                    ++cardTotal;
                }
                else
                {
                    stay = 1;
                }
            }
            if (play == true)
            {
                if (win == true && lose == false)
                {
                    System.out.println("You win!\n");
                    if (blackJack == true)
                    {
                        System.out.println("BLACK JACK!!! Amount won: " + (bet * 1.5));
                        money += (bet * 1.5);
                    }
                    else
                    {
                        money += bet;
                    }
                }
                else if ((totalValueDealer == totalValue && totalValue > totalValueDealerAce || totalValueDealer == totalValueAce && totalValueAce != 0))
                {
                    System.out.println("It's a tie!\n");
                }
                else if ((totalValueDealer > totalValue && totalValueDealer > totalValueAce && totalValueDealer < 22) || (totalValueDealerAce > totalValue && totalValueDealerAce > totalValueAce) || lose == true)
                {
                    System.out.println("You lose!\n");
                    money -= bet;
                }
                else
                {
                    System.out.println("You win!\n");
                    if (blackJack == true)
                    {
                        System.out.println("BLACK JACK!!! Amount won: " + (bet * 1.5));
                        money += (bet * 1.5);
                    }
                    else
                    {
                        money += bet;
                    }
                }
                blackJack = false;
                play = false;
                lose = false;
                win = false;
                stay = 0;
                if (money < 1)
                {
                    quit = true;
                    System.out.println("You've lost all your money!");
                }
                else
                {
                    System.out.println("Current cash amount: $" + money);
                }
            }
            /* Print Deck
            for (int i=0;i<52;i++)
            {
                System.out.println(deck[i]);
            }
            */
        }
    }
}


甲板类

(不更改,但如果需要功能请在此处检查)

import java.util.Random;
import java.util.Objects;

public class Deck
{

    // Generate Deck
    // Description: Used to generate an array with a length of 52 that holds each card of a deck of cards.
    // Tip: To use in program, set a string array equal to this method.
    public static String[] generateDeck()
    {
        // Variables
        int i = 0;

        // Initialize deck
        String[] deck = new String[52];
        deck[0] = "Ace of spades";
        for (i=1; i<12; i++)
        {
            deck[i] = Integer.toString(i + 1) + " of spades";
        }
        deck[10] = "Jack of spades";
        deck[11] = "Queen of spades";
        deck[12] = "King of spades";
        deck[13] = "Ace of hearts";
        for (i=1; i<12; i++)
        {
            deck[(i + 13)] = Integer.toString(i + 1) + " of hearts";
        }
        deck [23] = "Jack of hearts";
        deck [24] = "Queen of hearts";
        deck [25] = "King of hearts";
        deck [26] = "Ace of clubs";
        for (i=1; i<12; i++)
        {
            deck[(i + 26)] = Integer.toString(i + 1) + " of clubs";
        }
        deck [36] = "Jack of clubs";
        deck [37] = "Queen of clubs";
        deck [38] = "King of clubs";
        deck [39] = "Ace of diamonds";
        for (i=1; i<12; i++)
        {
            deck[(i + 39)] = Integer.toString(i + 1) + " of diamonds";
        }
        deck [49] = "Jack of diamonds";
        deck [50] = "Queen of diamonds";
        deck [51] = "King of diamonds";

        return deck;
    }

    // Shuffle one card of the deck with another
    // Description: Not much use, but it helps to see how one might swap two random cards with each other.
    public static void oneCardShuffle(String[] deck)
    {
        Random randomGenerator = new Random();

        // Generates number from 0 to 51
        int cardFirst = randomGenerator.nextInt(52);
        int cardSecond = randomGenerator.nextInt(52);

        // Swap
        String card = deck[cardSecond];
        deck[cardSecond] = deck[cardFirst];
        deck[cardFirst] = card;

    }

    // The standard riffle shuffle
    // Description: It cuts the deck into two pieces and lays on card on top of other.
    // Tip: To use in program, simply call the method with the deck you generated earlier.
    // WARNING: If you riffleShuffle enough, it will go back to the order it started out in. To fix, use the "totalRandom" method.
    public static void riffleShuffle(String[] deck)
    {
        String[] cutOne = new String[26];
        String[] cutTwo = new String[26];
        for (int i=0;i<26;i++)
        {
            cutOne[i] = deck[i];
        }
        for (int i=0;i<26;i++)
        {
            cutTwo[i] = deck[i+26];
        }
        for (int i=0;i<26;i++)
        {
            deck[2*i] = cutOne[i];
            deck[2*i + 1] = cutTwo[i];
        }

    }

    // Shuffle from top to bottom
    // Description: Takes the top card of deck and bottom card and swaps them, moving down to the center of the deck.
    public static void topBottomShuffle(String[] deck)
    {
        for (int i=0;i<26;i+=1)
        {
            String card = deck[51 - i];
            deck [51 - i] = deck[i];
            deck [i] = card;
        }
    }

    // Cut
    // Description: Cuts the deck through the middle
    // Tip: Just use if there is a specific need for you to cut your deck, otherwise pointless.
    public static void cut(String[] deck)
    {
       String[] cut = new String[26];

       for (int i=0;i<26;i++)
        {
            cut[i] = deck[i];
        }
        for (int i=0;i<26;i++)
        {
            deck[i] = deck[i+26];
        }
        for (int i=1;i<27;i++)
        {
            deck[i+25] = cut[i - 1];
        }
    }

    // Random Shuffle
    // Description: Like the oneCardShuffle except repeated a certain number of times
    // Tip: Use this method to shuffle, may not be the fastest (not noticeable however), but it makes your deck totally randomized.
    public static void totalRandom(String[] deck, int times)
    {
        // Random Initialize
        Random randomGenerator = new Random();

        // Variables
        int cardFirst = 0;
        int cardSecond = 0;

        // Swap
        for (int i=0;i<times;i++)
        {
            // Generates number from 0 to 51
            cardFirst = randomGenerator.nextInt(52);
            cardSecond = randomGenerator.nextInt(52);
            String card = deck[cardSecond];
            deck[cardSecond] = deck[cardFirst];
            deck[cardFirst] = card;
        }
    }

    // Deal
    // Description: Function which deals a certain object which is holding cards a card out of the deck.
    public static void deal(int cardPlace, int handNumber, String[] deck, String[] holder)
    {
        holder[handNumber] = deck[cardPlace];
    }

    // Check Value of Card
    // Description: This checks the value of the card, and turns it from a string into an integer. Aces come back as -1, so if you need to you can read as 1 or 11.
    // Every other card will either be the number or if it is a face card, 10.
    // Tip: Use if you need to value cards and have a face card or ace equal 1 || 10 || 11.
    public static int checkValue(String card)
    {
        String[] name = card.split(" ");
        if (Objects.equals(name[0], "Jack") || (Objects.equals(name[0], "Queen"))
        || (Objects.equals(name[0], "King")))
        {
            return 10;
        }
        else if (Objects.equals(name[0], "Ace"))
        {
            return -1;
        }
        else
        {
            return Integer.parseInt(name[0]);
        }
    }

    // Check the value order
    // Description: Used to check the order in which cards should lay if they are one after another
    public static int checkValueOrder(String card)
    {
        String[] name = card.split(" ");
        switch(name[0])
        {
            case "Jack":
            return 11;
            case "Queen":
            return 12;
            case "King":
            return 13;
            case "Ace":
            return 1;
            default:
            return Integer.parseInt(name[0]);
        }
    }

    // Check Suit of Card
    // Description: This checks the suit of a cartain card in your deck, or in other words it cuts off the first part of the card, and only returns the suit.
    // Tip: Use if you need to check for card combinations which require same suit.
    public static String checkSuit(String card)
    {
        String[] name = card.split(" ");
        return name[2];
    }

    // Sorts cards from smallest to greatest
    // Description: Use if you need to know the NUMBERED order of cards.
    // Tip: Can be used with any size string of cards.
    public static void sortCards (String[] card)
    {
        String sortingCard = "";
        int sortingCount = 0;
        int cardsTotal = card.length;
        do
        {
            sortingCount = 0;
            for (int i = 0; i<cardsTotal-1; i++)
            {
                if (checkValueOrder(card[i]) > checkValueOrder(card[i+1]))
                {
                    sortingCard = card[i+1];
                    card[i+1] = card[i];
                    card[i] = sortingCard;
                }
                else
                {
                    ++sortingCount;
                }
            }
        } while (sortingCount != cardsTotal-1);
    }
}

最佳答案

以下是我所做的一些观察,这也可以使您使用许多内置的Java API


在许多地方,您曾使用过String Array,而您可能曾经使用过collections API。
如果有其他条件,可以用三元运算符代替。
可以使用诸如Arrays.sort(),collections.sort()等内置函数来完成排序。
可以在类中编写更多功能,而不是拥有单个功能。
除非必要,否则避免使用String,而应使用Stringbuilder或StringBuffer。

关于java - 二十一点游戏,需要样式帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33050819/

10-08 22:52