user4258987
user4258987

Reputation:

Way to reset card game?

I'm making a game similar to solitaire, and when the user recognizes they have lost I have a button to reset the game. Currently I'm unsure how I can reset the game. I know ill have to make a new deck and clear my array to recreate everything as if the game was starting for the first time, but I don't know how to do this. How can I reset my game when a user presses reset?

/**
 * 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 + ")";
    }
}

Upvotes: 1

Views: 1726

Answers (4)

Malik Brahimi
Malik Brahimi

Reputation: 16721

All you have to do to restart is redefine the attributes as you would at the beginning so if you populate a deck and shuffle it at startup, you should so the same at restart. Try using a function for both scenarios, I'll give you a generic example.

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

    // anything else like ...

    score = 0;
}

Upvotes: 0

roeygol
roeygol

Reputation: 5048

You can assign board = new Board(); but you need to make it static in the main class.

The best way is to make it using

public class DeckTester {
    .
    .
    private static Board board;

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

Then, refresh what you need.

Upvotes: 0

savantKing
savantKing

Reputation: 89

Something like this:

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

Upvotes: 0

user3437460
user3437460

Reputation: 17474

When it resets, it is basically same as the state when you start a new game.

When starting a new game:

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

So when you reset, basically you repeat the same process as above.

You can have something like this:

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
}

Upvotes: 2

Related Questions