重置纸牌游戏的方法?

时间:2015-01-19 18:13:07

标签: java swing

我正在制作类似于纸牌的游戏,当用户认出他们已经丢失时,我有一个按钮来重置游戏。目前我不确定如何重置游戏。我知道不得不制作一个新牌组并清除我的阵列以重新创建所有内容,就好像游戏是第一次启动一样,但我不知道如何做到这一点。当用户按下重置时如何重置我的游戏?

/**
 * This is a class that tests the Deck class.
 */
public class DeckTester {

    /**
     * The main method in this class checks the Deck operations for consistency.
     *  @param args is not used.
     */

    public static void main(String[] args) {

        Board board = new Board();
        board.startGame();


    }

}

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * The Deck class represents a shuffled deck of cards.
 * It provides several operations including
 *      initialize, shuffle, deal, and check if empty.
 */
public class Deck {

    /**
     * cards contains all the cards in the deck.
     */
    private List<Card> cards;

    /**
     * size is the number of not-yet-dealt cards.
     * Cards are dealt from the top (highest index) down.
     * The next card to be dealt is at size - 1.
     */
    private int size;


    /**
     * Creates a new <code>Deck</code> instance.<BR>
     * It pairs each element of ranks with each element of suits,
     * and produces one of the corresponding card.
     * @param ranks is an array containing all of the card ranks.
     * @param suits is an array containing all of the card suits.
     * @param values is an array containing all of the card point values.
     */
    ArrayList<Card> cardList = new ArrayList<>();
    String[] ranks = {"Ace","Two","Three","Four","Five","Six" , "Seven" , "Eight","Nine","Ten", "Jack", "Queen","King"};
    String[] suits = {"spades" , "diamonds" , "clubs" , "hearts"};
    int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
    boolean selected = false;

    public Deck() {
        cards = new ArrayList<Card>();
        for (int j = 0; j < ranks.length; j++) {
            for (String suitString : suits) {
                cards.add(new Card(ranks[j], suitString, values[j], selected));
            }
        }
        size = cards.size();
    }

    public Card nextCard() {

        if(cards.size() > 0) {
            System.out.println(cards.get(0).toString());
            return cards.remove(0);
        }else{
            return null;
        }

    }


    /**
     * Determines if this deck is empty (no undealt cards).
     * @return true if this deck is empty, false otherwise.
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Accesses the number of undealt cards in this deck.
     * @return the number of undealt cards in this deck.
     */
    public int size() {
        return cards.size();
    }

    /**
     * Randomly permute the given collection of cards
     * and reset the size to represent the entire deck.
     */
    List<Card> shuffledDeck;

    ArrayList<Integer> usedNumbers = new ArrayList<Integer>();

    public void shuffle() {

            shuffledDeck = new ArrayList<>();
            Random random = new Random();

            for(usedNumbers.size(); usedNumbers.size() < 52;) {


                int randomNum = random.nextInt(52);

                if(!usedNumbers.contains(randomNum)) {

                    shuffledDeck.add(usedNumbers.size(), cards.get(randomNum));
                    usedNumbers.add(randomNum); 
                }

            }
            size = shuffledDeck.size();
            cards = shuffledDeck;
    }

    /**
     * Generates and returns a string representation of this deck.
     * @return a string representation of this deck.
     */
    @Override
    public String toString() {
        String rtn = "size = " + size + "\nUndealt cards: \n";

        for (int k = cards.size() - 1; k >= 0; k--) {
            rtn = rtn + cards.get(k);
            if (k != 0) {
                rtn = rtn + ", ";
            }
            if ((size - k) % 2 == 0) {
                // Insert carriage returns so entire deck is visible on console.
                rtn = rtn + "\n";
            }
        }

        rtn = rtn + "\nDealt cards: \n";
        for (int k = cards.size() - 1; k >= size; k--) {
            rtn = rtn + cards.get(k);
            if (k != size) {
                rtn = rtn + ", ";
            }
            if ((k - cards.size()) % 2 == 0) {
                // Insert carriage returns so entire deck is visible on console.
                rtn = rtn + "\n";
            }
        }

        rtn = rtn + "\n";
        return rtn;
    }

}

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class Board extends JFrame implements ActionListener {

    Deck deck = new Deck();
    Card card;

    JPanel buttonPanel = new JPanel();
    JPanel menuPanel = new JPanel();

    JButton cardOne = new JButton();
    JButton cardTwo = new JButton();
    JButton cardThree = new JButton();
    JButton cardFour = new JButton();
    JButton cardFive = new JButton();
    JButton cardSix = new JButton();
    JButton cardSeven = new JButton();

    JButton[] buttons = {cardOne, cardTwo, cardThree, cardFour, cardFive, cardSix, cardSeven};

    int winCount = 0;
    int lossCount = 0;
    int deckCount = 52;

    JButton replace = new JButton("Replace");
    JButton reset = new JButton("Reset");
    JLabel cardsLeft = new JLabel("Cards left:" + deckCount);
    JLabel winLossLabel = new JLabel("Win: " + winCount + "\tLoss: " + lossCount);



    public Board() {
        initGUI();  
    }

    ArrayList<Card> boardArray = new ArrayList<>();

    public void startGame() {
        deck.shuffle();
        Card card;

        for(int i = 0 ; i <=6 ; i++) {
            boardArray.add(card = deck.nextCard());
            buttons[i].setIcon(card.cardImage);
        }
    }

    public void initGUI() {
        setTitle("Elevens");
        setLayout(new GridLayout(1,2));
        buttonPanel.setLayout(new GridLayout(2,4));
        menuPanel.setLayout(new GridLayout(4,1));
        setResizable(false);

        buttonPanel.add(cardOne);
        buttonPanel.add(cardTwo);
        buttonPanel.add(cardThree);
        buttonPanel.add(cardFour);
        buttonPanel.add(cardFive);
        buttonPanel.add(cardSix);
        buttonPanel.add(cardSeven);

        menuPanel.add(replace);
        menuPanel.add(reset);
        menuPanel.add(cardsLeft);
        menuPanel.add(winLossLabel);

        add(buttonPanel);
        add(menuPanel);

        for(int i = 0; i < buttons.length; i++){
            buttons[i].addActionListener(this);
        }
        replace.addActionListener(this);
        reset.addActionListener(this);

        replace.setSize(new Dimension (100,10));

        pack();
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(600,300);

    }

    ImageIcon selectedIcon;
    Boolean selected = false;
    String newPathString;
    int buttonNumber;

    public void getPath(int buttonNumber) {

        String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";

        if(boardArray.get(buttonNumber).rank() == "Ace" || boardArray.get(buttonNumber).rank() == "Jack" || boardArray.get(buttonNumber).rank() == "Queen" || boardArray.get(buttonNumber).rank() == "King") {
            newPathString = path + boardArray.get(buttonNumber).rank() + boardArray.get(buttonNumber).suit() + "S.GIF";
        }else{
            newPathString = path + Integer.toString(boardArray.get(buttonNumber).pointValue()) + boardArray.get(buttonNumber).suit() + "S.GIF";
        }
        selectedIcon = new ImageIcon(newPathString);
    }

    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == cardOne) {
            if(boardArray.get(0).selected == false) {
                getPath(0);
                buttons[0].setIcon(selectedIcon);
                boardArray.get(0).selected = true;

            }else{
                boardArray.get(0).selected = false;
                buttons[0].setIcon(boardArray.get(0).cardImage);
            }

        }
        if(e.getSource() == cardTwo) {
            if(boardArray.get(1).selected == false) {
                getPath(1);
                buttons[1].setIcon(selectedIcon);
                boardArray.get(1).selected = true;
            }else{
                boardArray.get(1).selected = false;
                buttons[1].setIcon(boardArray.get(1).cardImage);
            }

        }
        if(e.getSource() == cardThree) {
            if(boardArray.get(2).selected == false) {
                getPath(2);
                buttons[2].setIcon(selectedIcon);
                boardArray.get(2).selected = true;
            }else{
                boardArray.get(2).selected = false;
                buttons[2].setIcon(boardArray.get(2).cardImage);
            }

        }
        if(e.getSource() == cardFour) {
            if(boardArray.get(3).selected == false) {
                getPath(3);
                buttons[3].setIcon(selectedIcon);
                boardArray.get(3).selected = true;
            }else{
                boardArray.get(3).selected = false;
                buttons[3].setIcon(boardArray.get(3).cardImage);
            }

        }
        if(e.getSource() == cardFive) {
            if(boardArray.get(4).selected == false) {
                getPath(4);
                buttons[4].setIcon(selectedIcon);
                boardArray.get(4).selected = true;

            }else{
                boardArray.get(4).selected = false;
                buttons[4].setIcon(boardArray.get(4).cardImage);
            }

        }
        if(e.getSource() == cardSix) {
            if(boardArray.get(5).selected == false) {
                getPath(5);
                buttons[5].setIcon(selectedIcon);
                boardArray.get(5).selected = true;
            }else{
                boardArray.get(5).selected = false;
                buttons[5].setIcon(boardArray.get(5).cardImage);
            }

        }
        if(e.getSource() == cardSeven) {
            if(boardArray.get(6).selected == false) {
                getPath(6);
                buttons[6].setIcon(selectedIcon);
                boardArray.get(6).selected = true;
            }else{
                boardArray.get(6).selected = false;
                buttons[6].setIcon(boardArray.get(6).cardImage);
            }

        }
        if(e.getSource() == replace) {
            checkWin();
        }
        if(e.getSource() == reset) {
            System.out.println("Feature In Progress. Exit game to reset.");

        }


    }
    int total;
    int buttonsSelected = 0;

    public void checkWin() {
        for(int i = 0; i <= 6; i++) {
            if(boardArray.get(i).selected == true) {
                int pointValue = boardArray.get(i).pointValue();
                total = total + pointValue;
                buttonsSelected++;
                }
            }
            if((buttonsSelected == 3 && total == 36) || (buttonsSelected == 2 && total == 11)) {
            for(int i = 0; i <= 6; i++) {
                if(boardArray.get(i).selected == true) {
                    boardArray.set(i, deck.nextCard());
                    buttons[i].setIcon(boardArray.get(i).cardImage);
                    deckCount--;
                    cardsLeft.setText("Cards left:" + deckCount);
                }
            }
        }
        total = 0;
        buttonsSelected = 0;
    }

}

import javax.swing.ImageIcon;

/**
 * Card.java
 *
 * <code>Card</code> represents a playing card.
 */
public class Card {

    /**
     * String value that holds the suit of the card
     */
    private String suit;

    /**
     * String value that holds the rank of the card
     */
    private String rank;

    /**
     * int value that holds the point value.
     */
    private int pointValue;

    /**
     * Creates a new <code>Card</code> instance.
     *
     * @param cardRank
     *            a <code>String</code> value containing the rank of the card
     * @param cardSuit
     *            a <code>String</code> value containing the suit of the card
     * @param cardPointValue
     *            an <code>int</code> value containing the point value of the
     *            card
     */

    ImageIcon cardImage;
    Card card;
    Boolean selected = false;

    int picNumber = 1;

    public Card(String cardRank, String cardSuit, int cardPointValue, Boolean selected) {
        // initializes a new Card with the given rank, suit, and point value
        rank = cardRank;
        suit = cardSuit;
        pointValue = cardPointValue;
        selected = false;

        String pointString = Integer.toString(pointValue);
        String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";

        if (cardPointValue >= 2 && cardPointValue <= 10) {
            String cardImageString = path + pointString + cardSuit + ".GIF";
            cardImage = new ImageIcon(cardImageString);
        }
        if (cardPointValue == 1) {

        }
        switch (pointValue) {

        case 1:
            cardImage = new ImageIcon(path + "ace" + cardSuit + ".GIF");
            break;
        case 11:
            cardImage = new ImageIcon(path + "jack" + cardSuit + ".GIF");
            break;
        case 12:
            cardImage = new ImageIcon(path + "queen" + cardSuit + ".GIF");
            break;
        case 13:
            cardImage = new ImageIcon(path + "king" + cardSuit + ".GIF");
            break;

        }

    }

    public String getCardImage() {
        return cardImage.toString();
    }

    /**
     * Accesses this <code>Card's</code> suit.
     * 
     * @return this <code>Card's</code> suit.
     */
    public String suit() {
        return suit;
    }

    /**
     * Accesses this <code>Card's</code> rank.
     * 
     * @return this <code>Card's</code> rank.
     */
    public String rank() {
        return rank;
    }

    /**
     * Accesses this <code>Card's</code> point value.
     * 
     * @return this <code>Card's</code> point value.
     */
    public int pointValue() {
        return pointValue;
    }

    /**
     * Compare this card with the argument.
     * 
     * @param otherCard
     *            the other card to compare to this
     * @return true if the rank, suit, and point value of this card are equal to
     *         those of the argument; false otherwise.
     */
    public boolean matches(Card otherCard) {
        return otherCard.suit().equals(this.suit())
                && otherCard.rank().equals(this.rank())
                && otherCard.pointValue() == this.pointValue();
    }

    /**
     * Converts the rank, suit, and point value into a string in the format
     * "[Rank] of [Suit] (point value = [PointValue])". This provides a useful
     * way of printing the contents of a <code>Deck</code> in an easily readable
     * format or performing other similar functions.
     *
     * @return a <code>String</code> containing the rank, suit, and point value
     *         of the card.
     */
    @Override
    public String toString() {
        return rank + " of " + suit + " (point value = " + pointValue + ")";
    }
}

4 个答案:

答案 0 :(得分:2)

当它重置时,它基本上与你开始新游戏时的状态相同。

开始新游戏时:

1) Create deck
2) Shuffle deck
3) Draw images(cards) or reset the image in swing

因此,当您重置时,基本上您重复上述相同的过程。

你可以这样:

public static void startNewGame()  //use this for reset
{
    ArrayList<Card> deck = createNewDeck();
    ShuffleCards(deck);  
    ResetImages(deck);   //reset card images
    ResetComponents();   //reset all buttons/display to initial state
}

答案 1 :(得分:0)

您可以指定board = new Board();,但需要在主类中将其设为静态。

最好的方法是使用

public class DeckTester {
    .
    .
    private static Board board;

    public static void newBoard(){
        board = new Board();
    }

然后,刷新你需要的东西。

答案 2 :(得分:0)

这样的事情:

board.this.setVisible(false);
board.this.dispose();
new Board();

答案 3 :(得分:0)

你需要做的就是重新启动属性,就像你在开始时那样重新定义属性,所以如果你填充一个套牌并在启动时将其洗牌,你应该在重启时这样做。尝试在两个场景中使用一个函数,我将给你一个通用的例子。

public void setup() {
    populate() // populate deck
    shuffle() // and shuffle it

    // anything else like ...

    score = 0;
}