Advertisement
codyyoung

Solitaire class

Oct 20th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.34 KB | None | 0 0
  1. import java.util.ArrayList;
  2. /**
  3.  * Solitaire
  4.  * Defines and creates objects of the solitaire class using array lists.
  5.  * @Cody Young
  6.  * @October 27, 2016
  7.  */
  8. public class Solitaire
  9. {
  10.     //Instance variable for piles array list
  11.     private ArrayList<Integer> piles = new ArrayList<>();
  12.    
  13.     /**
  14.      * Constructor method for Solitaire class objects. Initializes card piles to random sizes.
  15.      */
  16.     public Solitaire()
  17.     {
  18.        int piles_total = 0; //Variable that tracks running total number of cards across piles
  19.        
  20.        while (piles_total < 45)
  21.        {
  22.            //Generate random number, subtract max
  23.            int rand_number = (int) (Math.random () * (45 - piles_total)) + 1;
  24.            piles.add(rand_number);
  25.            piles_total += rand_number;  //Add # of cards in each pile to total - must equal 45
  26.        }
  27.     }
  28.    
  29.     /**
  30.      * Method returning true if solitaire game is over, false by default.
  31.      */  
  32.     public Boolean over()      
  33.     {
  34.         for(int i = 1; i < 10; i++)
  35.         {
  36.            if (piles.indexOf(i) == -1) //Checks if value at index is 1-9; if not, continues
  37.            {
  38.                return false;
  39.            }
  40.         }
  41.         return true;        //If no values return -1, game is over
  42.     }    
  43.    
  44.     /**
  45.      * Method that draws one card from each pile and adds to a new pile.
  46.      * Each iteration represents one round.
  47.      */
  48.     public void round()
  49.     {
  50.       int newpile_total = 0;        //Running total of cards taken from piles
  51.      
  52.       for (int i = 0; i < piles.size(); i++)
  53.         {
  54.            int pile_sub = piles.get(i) - 1;     //Variable for pile subtraction
  55.            piles.set(i, pile_sub);              //Gets pile value, subtracts one and places back into pile
  56.            if (piles.get(i) == 0)
  57.             {
  58.                piles.remove(i);      //If value at index i = 0, remove pile
  59.                i--;                  //Decrement i after removing piles
  60.             }
  61.            newpile_total += 1;       //Tracks how many cards are subtracted, adds to total
  62.         }
  63.         piles.add(newpile_total);    //Adds total cards pulled from piles, appends list
  64.     }
  65.    
  66.     /**
  67.      * Returns a string representation of a Solitaire object.
  68.      */
  69.     public String toString()
  70.     {
  71.         return piles.toString();
  72.     }  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement