Sunteți pe pagina 1din 23

Assig6.

java 7/31/2018

import javax.swing.*;
import javax.swing.text.JTextComponent;

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

///* Timer
======================================================================
class Assig6
{
//Added here so it could be used in a function and modified directly.
//In func placeNewCards()
public static Model buildGame;
public static Thread mainThread = Thread.currentThread();
public static void main(String[] args)
{
Timer timer = new Timer();
Random randomizer = new Random();
Assig6.buildGame = new Model();
ViewPlusController myView = new ViewPlusController("BUILD");
int input = -2;
Clickable.type inputType;
buildGame.framework.deal();
//System.out.print(buildGame.framework.getHand(0));
myView.update(buildGame);
while (true)
{
//Get inputs
Card playedCard = null;
Card stackCard = null;
Boolean passed = false;
int stackIndex = -1;
int cardIndex = -1;
;
while (true)
{
getInput();
input = Clickable.getInputValue();
inputType = Clickable.getInputType();
if (inputType == Clickable.type.PASS)
{
System.out.print("Cannot play pressed by human\n");
//Index 1 refers to player, index 0 is computer
buildGame.cannotPlayCount[1] += 1;
passed = true;
buildGame.consecutivePasses++;
break;
}
else if(inputType == Clickable.type.HAND)
{
//System.out.printf("Hand input: %d\n", input);
//Set card value
cardIndex = input;
playedCard = buildGame.framework.getHand(1).inspectCard(input);
}
else if(inputType == Clickable.type.STACK)
{
//System.out.printf("Stack input: %d\n", input);
//Set stack value
stackIndex = input;
stackCard = buildGame.stack[input];
}

1
Assig6.java 7/31/2018

if (playedCard != null && stackIndex != -1)


{
if (stackCard != null)
{
int valueA = Card.valueToInt(playedCard.getValue());
//Weird modulus stuff to loop around values
//To keep index in valid range
if (Card.valuRanks[(((valueA-1)%13)+13)%13] == stackCard.
getValue()
|| Card.valuRanks[(valueA+1)%13] == stackCard.getValue())
{
//System.out.println("Valid");
break;
}
}
else
{
//System.out.println("Valid");
break;
}
}

//Use input

if (passed == false)
{
//Card is played, play the card and update the model accordingly.
System.out.println("Played card "+playedCard.toString());
buildGame.framework.getHand(1).playCard(cardIndex);
buildGame.stack[stackIndex] = playedCard;
//Draw card for player
if (buildGame.framework.takeCard(1) == false)
{
//Card draw failed.
}
buildGame.consecutivePasses = 0;
}
else
{
//Player passed, check if computer passed too
if (buildGame.consecutivePasses >= 2)
{
placeNewCards();
}
}

//Computer turn, add AI code here


Hand computerHand = buildGame.framework.getHand(0);
char[] validValues = new char[4];
int[] playableIndexes = new int[10];
int[] playableToStack = new int[10];
int maxPlayableIndexes = 0;

if (buildGame.stack[0] != null && buildGame.stack[1] != null)


{
int valueIndex = Card.valueToInt(buildGame.stack[0].getValue());
validValues[0] = Card.valuRanks[(((valueIndex-1)%13)+13)%13];
validValues[1] = Card.valuRanks[(valueIndex+1)%13];
valueIndex = Card.valueToInt(buildGame.stack[1].getValue());

2
Assig6.java 7/31/2018

validValues[2] = Card.valuRanks[(((valueIndex-1)%13)+13)%13];
validValues[3] = Card.valuRanks[(valueIndex+1)%13];

for (int i = 0; i < computerHand.getNumCards(); i++)


{
Card currentCard = computerHand.inspectCard(i);

//These two loops aren't merged because a card could be


playable
//To both stacks, so it should check for that too
for (int j = 0; j < 2; j++)
{
if (currentCard.getValue() == validValues[j])
{
//Add card index as playable, and to which stack
playableIndexes[maxPlayableIndexes] = i;
playableToStack[maxPlayableIndexes] = 0;
maxPlayableIndexes++;
break;
}
}

for (int j = 2; j < 4; j++)


{
if (currentCard.getValue() == validValues[j])
{
//Add card index as playable, and to which stack
playableIndexes[maxPlayableIndexes] = i;
playableToStack[maxPlayableIndexes] = 1;
maxPlayableIndexes++;
break;
}
}
}
}
else
{
//Find which stack is blank
int selectedStack = 0;
if (buildGame.stack[0] == null)
selectedStack = 0;
else if (buildGame.stack[1] == null)
selectedStack = 1;

//Select all cards as valid, to that position.


for (int i = 0; i < buildGame.framework.getHand(0).getNumCards();i
++)
{
playableIndexes[maxPlayableIndexes] = i;
playableToStack[maxPlayableIndexes] = selectedStack;
maxPlayableIndexes++;
}
}

if (maxPlayableIndexes > 0)
{
int randomInt = randomizer.nextInt(maxPlayableIndexes);
int selectedIndex = playableIndexes[randomInt];
int selectedStack = playableToStack[randomInt];

3
Assig6.java 7/31/2018

Card computerPlayedCard =
buildGame.framework.getHand(0).playCard(selectedIndex);
buildGame.stack[selectedStack] = computerPlayedCard;
System.out.println("Computer played "+computerPlayedCard.toString
());
if (buildGame.framework.takeCard(0) == false)
{
//Card draw failed.
}
}
else
{
//No playable moves for computer, must pass
buildGame.consecutivePasses++;
buildGame.cannotPlayCount[0]++;
//If other player also passed, set down new cards if possible
if (buildGame.consecutivePasses >= 2)
{
placeNewCards();
}
}

//Check for game end states


if (buildGame.framework.getNumCardsRemainingInDeck() <= 0)
{
System.out.println("Deck empty, checking for end scenario");
//Deck and both hands empty.
if (buildGame.framework.getHand(0).getNumCards() <= 0
&& buildGame.framework.getHand(1).getNumCards() <= 0)
{
System.out.println("Both players out of cards");
break;
}
//Or deck is empty, and both players can't play
if (buildGame.consecutivePasses >= 2)
{
System.out.println("Both players passed, game ending");
break;
}
}

//Update view
myView.update(buildGame);

//if buildGame.break;
}
buildGame.gameOver = true;
System.out.print("Game ended\n");
System.out.printf("Player passes: %d\n", buildGame.cannotPlayCount[1]);
System.out.printf("Computer passes: %d\n", buildGame.cannotPlayCount[0])
;
myView.update(buildGame);
return;
}

public static void placeNewCards()


{
int cardsPlaced = 0;
System.out.println("Neither player can play,"

4
Assig6.java 7/31/2018

+ " attempting to place new cards");


for (int i = 0; i < 2; i++)
{
if (buildGame.framework.getNumCardsRemainingInDeck() > 0)
{
buildGame.stack[0] = buildGame.framework.getCardFromDeck();
cardsPlaced++;
}
}
System.out.printf("Placed %d cards\n",cardsPlaced);
}
public static void getInput()
{
Clickable.enabled = true;
try
{
Thread.sleep(Long.MAX_VALUE); //Not indefinite, but long enough
//that it doesn't matter
}
catch (InterruptedException e)
{
//Do nothing
}
Clickable.enabled = false;
}
}

class Timer extends Thread implements ActionListener


{
private Font textSize= new Font("SansSerif", Font.PLAIN, 30);
private JButton pauseResumeButton;
public JPanel timePanel;
public JLabel timerLabel = new JLabel();
int timeElasped = 0;
static boolean sleepSuccess;
long remainingDuration;
long sleepDuration;
long t0;
long t1;
public Timer()
{
JFrame TimerWindow = new JFrame();
TimerWindow.setSize(500,300);
TimerWindow.setFont(textSize);
TimerWindow.setTitle("Timer");
TimerWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TimerWindow.setLayout(new GridLayout (3, 1));

// Area that shows time


timePanel = new JPanel();
timePanel.setBackground(Color.LIGHT_GRAY);
TimerWindow.add(timePanel, BorderLayout.CENTER);

//Area for start and stop buttons


JPanel startStopButtonPanel = new JPanel();
TimerWindow.add(startStopButtonPanel);

//Add buttons to the panel


pauseResumeButton = new JButton("Stop");
pauseResumeButton.setFont(textSize);
remainingDuration = 1000;
sleepDuration = 1000;

5
Assig6.java 7/31/2018

t1=0;

//Create an anonymous class of MouseAdapter and adds it to the JButton.


pauseResumeButton.addActionListener(this);
startStopButtonPanel.add(pauseResumeButton);
this.start();
TimerWindow.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton clickedButton = ((JButton) e.getSource());
if (clickedButton.getText() == "Stop")
{
clickedButton.setText("Play");
this.interrupt();
}
else
{
clickedButton.setText("Stop");
System.out.println("Trying to Stop");
this.interrupt();
}
}
public void doNothing( long milliseconds)
{
try
{
Thread.sleep(sleepDuration);
}
catch (InterruptedException e)
{
//System.out.println("Sleep interrupted");
sleepSuccess = false;
if (pauseResumeButton.getText() == "Play")
{
System.out.println("Pausing");
//Sleep paused
t1 = System.nanoTime();

remainingDuration -= (t1-t0)/1000000;
sleepDuration = Long.MAX_VALUE;
}
else
{
System.out.println("Resuming");
//Sleep resumed
sleepDuration = remainingDuration;
}
}
}
public void run()
{
System.out.print("Running\n");

timerLabel.setFont(textSize);
timePanel.add(timerLabel);
timerLabel.setText("Time elapsed: " + timeElasped);

while(true)
{
sleepSuccess = true;
t0 = System.nanoTime();
System.out.printf("Attempting to sleep for %d\n", sleepDuration);

6
Assig6.java 7/31/2018

doNothing(sleepDuration);

//If sleep wasn't interrupted, increase counter


if (sleepSuccess)
{
System.out.println("Sleep successful");
timeElasped++;
timerLabel.setText("Time elapsed: " + timeElasped);
timePanel.repaint();
sleepDuration = 1000;
remainingDuration = 1000;
}
else
{
//Otherwise, sleep was interrupted via button press, and needs to
//resume countdown from where it left off.
//System.out.println("Sleep not successful");
}
}

}
}

//
==============================================================================
*/

class Clickable extends MouseAdapter


{
//Used to pass data by accessing the static class since the instances
cannot
//be accessed in main
private static int returnedIndex;
private static type returnedType;
public static enum type {HAND, STACK, PASS};

//Assigned value of the clickable.


public int returnVal;
public type returnType;

//Controls all clickables to be active/inactive


//Probably not humanly possible to click two cards before the game logic
runs
//But just in case it does happen, make sure nothing happens.
public static boolean enabled = true;

public static int getInputValue()


{
return returnedIndex;
}
public static type getInputType()
{
return returnedType;
}
Clickable( int i, type t)
{
this.returnVal = i;
this.returnType = t;
}
@Override
public void mouseClicked(MouseEvent e)
{

7
Assig6.java 7/31/2018

if (enabled)
{
returnedIndex = this.returnVal;
returnedType = this.returnType;
Assig6.mainThread.interrupt();
}
}

class ViewPlusController extends JFrame


{
public JPanel pnlComputerHand, pnlHumanHand, pnlPlayArea;
public JLabel labelStackA, labelStackB;
public ViewPlusController(String title)
{
super();
setSize(800, 600);

setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout (3, 1));

pnlComputerHand = new JPanel();


pnlHumanHand = new JPanel();
pnlPlayArea = new JPanel();

pnlHumanHand.setBorder(BorderFactory.createTitledBorder("Player"));
pnlComputerHand.setBorder(BorderFactory.createTitledBorder("Computer"));
pnlPlayArea.setLayout(new GridLayout(1,3));

labelStackA = new JLabel();


labelStackB = new JLabel();

labelStackA.setBorder(BorderFactory.createTitledBorder("Stack A"));
labelStackB.setBorder(BorderFactory.createTitledBorder("Stack B"));

labelStackA.setHorizontalAlignment(JLabel.CENTER);
labelStackA.setIcon(GUICard.getOutlineCardIcon());
labelStackA.addMouseListener(new Clickable(0,Clickable.type.STACK));

labelStackB.setHorizontalAlignment(JLabel.CENTER);
labelStackB.setIcon(GUICard.getOutlineCardIcon());
labelStackB.addMouseListener(new Clickable(1,Clickable.type.STACK));

pnlPlayArea.add(labelStackA);
pnlPlayArea.add(labelStackB);

JButton cannotPlay = new JButton("Cannot Play");


cannotPlay.addMouseListener(new Clickable(-1,Clickable.type.PASS));
pnlPlayArea.add(cannotPlay);

add(pnlComputerHand);
add(pnlPlayArea);
add(pnlHumanHand);
this.setVisible(true);
}

//Passing model data to view to update visual state


//Since we're using a GUI interface, view and controller are connected.
//Updates controller input labels/buttons too.
public void update(Model m)

8
Assig6.java 7/31/2018

{
int computerCards = m.framework.getHand(0).getNumCards();
int humanCards = m.framework.getHand(1).getNumCards();
pnlComputerHand.setLayout(new GridLayout(1, computerCards));
pnlHumanHand.setLayout(new GridLayout(1, humanCards));
JLabel tempLabel;
Card tempCard;

//Would be better to recycle instead of destroying and recreating


//Recycling would prevent screen flashing, and would be more efficient.
pnlComputerHand.removeAll();
for (int i = 0; i < computerCards; i++)
{
tempLabel = new JLabel();
tempLabel.setHorizontalAlignment(JLabel.CENTER);
pnlComputerHand.add(tempLabel);
tempLabel.setIcon(GUICard.getBackCardIcon());
}

pnlHumanHand.removeAll();
for (int i = 0; i < humanCards; i++)
{
tempLabel = new JLabel();
tempCard = m.framework.getHand(1).inspectCard(i);
tempLabel.addMouseListener(new Clickable(i,Clickable.type.HAND));
tempLabel.setHorizontalAlignment(JLabel.CENTER);
pnlHumanHand.add(tempLabel);
tempLabel.setIcon(GUICard.getIcon(tempCard));
}

tempCard = m.stack[0];
if (tempCard != null)
{
labelStackA.setIcon(GUICard.getIcon(tempCard));
}

tempCard = m.stack[1];
if (tempCard != null)
{
labelStackB.setIcon(GUICard.getIcon(tempCard));
}

//removeAll() doesn't force an update on a panel


//So if there are 0 cards left in the hand, the card will still be
//visible even if the label for it was removed, since the UI didn't
update
//Force an update to remove this 'phantom card'
pnlHumanHand.updateUI();

if (m.gameOver)
{
String winner = "Nobody";
if (m.cannotPlayCount[0] < m.cannotPlayCount[1])
{
winner = "Computer";
}
else if (m.cannotPlayCount[0] > m.cannotPlayCount[1])
{
winner = "Player";
}
String endMessage = "<html>";

9
Assig6.java 7/31/2018

endMessage += "Game over <br> Winner: " + winner;


endMessage += "<br> Player passes: " + m.cannotPlayCount[1];
endMessage += "<br> Computer passes: " + m.cannotPlayCount[0];
endMessage += "</html>";

pnlPlayArea.removeAll();

pnlPlayArea.add(new JLabel(endMessage));

pnlPlayArea.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlPlayArea.updateUI();
}
System.out.print("Update Complete\n");
//Add and update labels based off model.
}
}

class Model
{
public CardGameFramework framework;
public int[] cannotPlayCount;
public int consecutivePasses = 0;
public Card stack[];
public boolean gameOver = false;
Model()
{
int numPlayers = 2;
int numPacks = 1;
int numJokersPerPack = 0;
int numUnusedCardsPerPack = 4;
int numCardsPerHand = 5;
Card[] unusedCardsPerPack = {new Card('X', Card.Suit.DIAMONDS),
new Card('X', Card.Suit.CLUBS),
new Card('X', Card.Suit.HEARTS),
new Card('X', Card.Suit.SPADES)};

framework = new CardGameFramework(numPacks, numJokersPerPack,


numUnusedCardsPerPack, unusedCardsPerPack,
numPlayers, numCardsPerHand);

cannotPlayCount = new int[numPlayers]; //Java auto initializes to 0


stack = new Card[2];
}
}
//class CardGameFramework
----------------------------------------------------
class CardGameFramework
{
private static final int MAX_PLAYERS = 50;

private int numPlayers;


private int numPacks; // # standard 52-card packs per deck
// ignoring jokers or unused cards
private int numJokersPerPack; // if 2 per pack & 3 packs per deck, get 6
private int numUnusedCardsPerPack; // # cards removed from each pack
private int numCardsPerHand; // # cards to deal each player
private Deck deck; // holds the initial full deck and gets
// smaller (usually) during play
private Hand[] hand; // one Hand for each player
private Card[] unusedCardsPerPack; // an array holding the cards not used
// in the game. e.g. pinochle does
not

10
Assig6.java 7/31/2018

// use cards 2-8 of any suit

public CardGameFramework( int numPacks, int numJokersPerPack,


int numUnusedCardsPerPack, Card[] unusedCardsPerPack,
int numPlayers, int numCardsPerHand)
{
int k;

// filter bad values


if (numPacks < 1 || numPacks > 6)
numPacks = 1;
if (numJokersPerPack < 0 || numJokersPerPack > 4)
numJokersPerPack = 0;
if (numUnusedCardsPerPack < 0 || numUnusedCardsPerPack > 50) // > 1
card
numUnusedCardsPerPack = 0;
if (numPlayers < 1 || numPlayers > MAX_PLAYERS)
numPlayers = 4;
// one of many ways to assure at least one full deal to all players
if (numCardsPerHand < 1 ||
numCardsPerHand > numPacks * (56 - numUnusedCardsPerPack)
/ numPlayers )
numCardsPerHand = numPacks * (56 - numUnusedCardsPerPack) /
numPlayers;

// allocate
this.unusedCardsPerPack = new Card[numUnusedCardsPerPack];
this.hand = new Hand[numPlayers];
for (k = 0; k < numPlayers; k++)
this.hand[k] = new Hand();
deck = new Deck(numPacks);

// assign to members
this.numPacks = numPacks;
this.numJokersPerPack = numJokersPerPack;
this.numUnusedCardsPerPack = numUnusedCardsPerPack;
this.numPlayers = numPlayers;
this.numCardsPerHand = numCardsPerHand;
for (k = 0; k < numUnusedCardsPerPack; k++)
this.unusedCardsPerPack[k] = unusedCardsPerPack[k];

// prepare deck and shuffle


newGame();
}

// constructor overload/default for game like bridge


public CardGameFramework()
{
this(1, 0, 0, null, 4, 13);
}

public Hand getHand(int k)


{
// hands start from 0 like arrays

// on error return automatic empty hand


if (k < 0 || k >= numPlayers)
return new Hand();

return hand[k];
}

public Card getCardFromDeck() { return deck.dealCard(); }

11
Assig6.java 7/31/2018

public int getNumCardsRemainingInDeck() { return deck.getNumCards(); }

public void newGame()


{
int k, j;

// clear the hands


for (k = 0; k < numPlayers; k++)
hand[k].resetHand();

// restock the deck


deck.init(numPacks);

// remove unused cards


for (k = 0; k < numUnusedCardsPerPack; k++)
deck.removeCard( unusedCardsPerPack[k] );

// add jokers
for (k = 0; k < numPacks; k++)
for ( j = 0; j < numJokersPerPack; j++)
deck.addCard( new Card('X', Card.Suit.values()[j]) );

// shuffle the cards


deck.shuffle();
}

public boolean deal()


{
// returns false if not enough cards, but deals what it can
int k, j;
boolean enoughCards;

// clear all hands


for (j = 0; j < numPlayers; j++)
hand[j].resetHand();

enoughCards = true;
for (k = 0; k < numCardsPerHand && enoughCards ; k++)
{
for (j = 0; j < numPlayers; j++)
if (deck.getNumCards() > 0)
hand[j].takeCard( deck.dealCard() );
else
{
enoughCards = false;
break;
}
}

return enoughCards;
}

void sortHands()
{
int k;

for (k = 0; k < numPlayers; k++)


hand[k].sort();
}

Card playCard(int playerIndex, int cardIndex)


{

12
Assig6.java 7/31/2018

// returns bad card if either argument is bad


if (playerIndex < 0 || playerIndex > numPlayers - 1 ||
cardIndex < 0 || cardIndex > numCardsPerHand - 1)
{
//Creates a card that does not work
return new Card('M', Card.Suit.SPADES);
}

// return the card played


return hand[playerIndex].playCard(cardIndex);

boolean takeCard(int playerIndex)


{
// returns false if either argument is bad
if (playerIndex < 0 || playerIndex > numPlayers - 1)
return false;

// Are there enough Cards?


if (deck.getNumCards() <= 0)
return false;

return hand[playerIndex].takeCard(deck.dealCard());
}

class GUICard
{
private static Icon[][] iconCards = new ImageIcon[14][4]; // 14 = A thru
K + joker
private static Icon iconBack;
private static Icon iconOutline;
static boolean iconsLoaded = false;

static void loadCardIcons()


{
//int count=0; // count for indices of the array
if (!iconsLoaded)
{

for(int i=0; i<= 3; i++)


{
for(int j=0; j<=13; j++)
{
iconCards[j][i] = new ImageIcon("images\\"+turnIntIntoCardValue(j)
+
(turnIntIntoCardSuit(i))+".GIF");
//System.out.println(icon[count]);
//count++;
}
}
iconBack = new ImageIcon("images\\BK.GIF");
iconOutline = new ImageIcon("images\\OL.GIF");
iconsLoaded = true;
}
}

static String turnIntIntoCardValue(int k)


{
switch(k)

13
Assig6.java 7/31/2018

{
case 0:
return "2";
case 1:
return "3";
case 2:
return "4";
case 3:
return "5";
case 4:
return "6";
case 5:
return "7";
case 6:
return "8";
case 7:
return "9";
case 8:
return "T";
case 9:
return "A";
case 10:
return "K";
case 11:
return "Q";
case 12:
return "J";
case 13:
return "X";
default:
return "0";

}
}

// turns 0 - 3 into "C", "D", "H", "S"


static String turnIntIntoCardSuit(int j)
{
switch (j)
{
case 0:
return "C";
case 1:
return "D";
case 2:
return "H";
case 3:
return "S";
default:
return "0";
}
}

static public Icon getIcon(Card card)


{
if (iconsLoaded == false)
{
loadCardIcons();
iconsLoaded = true;
}
return iconCards[valueAsInt(card)][suitAsInt(card)];
}

14
Assig6.java 7/31/2018

static int suitAsInt(Card card)


{
Card.Suit j = card.getSuit();
switch (j)
{
case CLUBS:
return 0;
case DIAMONDS:
return 1;
case HEARTS:
return 2;
case SPADES:
return 3;
default:
return -1;
}

}
static int valueAsInt(Card card)
{
char k = card.getValue();
switch (k)
{
case '2':
return 0;
case '3':
return 1;
case '4':
return 2;
case '5':
return 3;
case '6':
return 4;
case '7':
return 5;
case '8':
return 6;
case '9':
return 7;
case 'T':
return 8;
case 'A':
return 9;
case 'K':
return 10;
case 'Q':
return 11;
case 'J':
return 12;
case 'X':
return 13;
default:
return -1;
}

static public Icon getBackCardIcon()


{
if (iconsLoaded == false)
{
loadCardIcons();

15
Assig6.java 7/31/2018

iconsLoaded = true;
}
return iconBack;
}

static public Icon getOutlineCardIcon()


{
if (iconsLoaded == false)
{
loadCardIcons();
iconsLoaded = true;
}
return iconOutline;
}

class Card
{
enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES};
private char value;
private Suit suit;
private boolean errorFlag;
public static char[] valuRanks = new char[]{'2', '3', '4', '5', '6', '7',
'8', '9', 'T', 'J', 'Q', 'K', 'A', 'X'};

public static int valueToInt(char c)


{
for (int i = 0; i < valuRanks.length; i++)
{
if (valuRanks[i] == c)
return i;
}
return -1;
}
/*Default constructor takes no parameters and sets value to "A" and suit to
"SPADES"*/
public Card()
{
value = 'A';
suit = Suit.SPADES;
}
/*Constructor with parameters for private variables value and suit*/
public Card(char newValue, Suit cardType)
{
setValue(newValue, cardType);
}

public boolean setValue(char newValue, Suit setSuit)


{
if(isValid(newValue, setSuit))
{
value = newValue;
suit = setSuit;
errorFlag = false;
return true;
}
else
{
errorFlag = true;
return false;
}
}

16
Assig6.java 7/31/2018

//accessor for value


public char getValue()
{
return value;
}

//accessor for suit


public Suit getSuit()
{
return suit;
}

public boolean getErrorFlag()


{
return errorFlag;
}

// method to convert cards value and suit to string


public String toString()
{
if (errorFlag)
{
return "Invalid card type!";
}
else
{
return value + " of " + suit;
}
}

public boolean equals(Card card)


{
if(value == card.value && suit == card.suit)
{
return true;
}
else
return false;
}

private boolean isValid(char value, Suit suit)


{
switch (value)
{
case 'X':
case 'A':
case 'K':
case 'Q':
case 'J':
case 'T':
case '9':
case '8':
case '7':
case '6':
case '5':
case '4':
case '3':
case '2':
return true;
default:
return false;
}

17
Assig6.java 7/31/2018

public static void arraySort(Card[] cards, int arraySize)


{
boolean unSorted = true;
char greaterValue = ' ';
Card copy;
while(unSorted)
{
unSorted = false;
for (int i = 0; i < arraySize - 1; i++)
{
greaterValue = compareCardValue(cards[i].getValue(), cards[i+1].
getValue());
if (cards[i].getValue() == greaterValue)
{
if (cards[i].getValue() != cards[i+1].getValue())
{
unSorted = true;
copy = new Card(cards[i].getValue(), cards[i].getSuit());
cards[i] = new Card(cards[i + 1].getValue(), cards[i + 1].
getSuit());
cards[i+1] = new Card(cards[i].getValue(), cards[i].getSuit
());
}
}
}
}
}

private static char compareCardValue(char a, char b)


{
//char aValue = a.getValue();
//char bValue = b.getValue();
if (a == b)
{
return b;
}
for (int i = 0; i < valuRanks.length; i++)
{
if (a == valuRanks[i])
{
return a;
}

else if (b == valuRanks[i])
{
return b;
}
}
return b;
}
}

class Hand
{
public static final int MAX_CARDS = 52;

private Card[] myCards = new Card[MAX_CARDS];

private int numCards;

public Hand() //Default constructor.

18
Assig6.java 7/31/2018

{
numCards = 0; //intialize the numCards variable to Zero.
}

public void resetHand() //Erases the current hand.


{
myCards = new Card[MAX_CARDS];
numCards = 0;
}

public boolean takeCard(Card card) //Takes a card object and places it at


the next highest index.
{
if (numCards < MAX_CARDS)
{
numCards = numCards + 1;
Card nextCard = new Card(card.getValue(), card.getSuit()); //Creates
a deep copy of the card.
myCards[numCards - 1] = nextCard;

return true;
}
else
{
return false;
}
}

public Card playCard()//Removes the topCard and returns it.


{
Card card = myCards[numCards - 1];
Card topCard = new Card();
topCard.setValue(card.getValue(), card.getSuit());
myCards[numCards - 1] = new Card();
numCards = numCards - 1;
return topCard;
}

public Card playCard(int i)//Removes the card at the index and returns it.
{
if (i >= 0 && i < myCards.length)
{
Card card = myCards[i];
Card selectCard = new Card();
selectCard.setValue(card.getValue(), card.getSuit());
myCards[i] = myCards[numCards - 1];
myCards[numCards - 1] = null;
numCards = numCards - 1;
return selectCard;
}
return null;
}

public String toString()//Converts the myCards array into a string.


{
String str = null;
if (numCards > 0)
{
str = ("In your hand you have the " + myCards[0].toString());

for (int i = 1; i < numCards; i++)


{
str = str + ", " + myCards[i].toString();

19
Assig6.java 7/31/2018

}
}

else
{
str = "You have an empty hand.";
}
return str;
}

public int getNumCards()//Accessor of the getNumCards variable.


{
return numCards;
}

public Card inspectCard(int k)//Determines if a given index is valid.


{
if (k > numCards || k < 0) //If the index is invalid, create a card
that is invalid and return that.
{
Card newCard = new Card('0', Card.Suit.SPADES);
return newCard;
}
else
{
return myCards[k];
}
}

public void sort()


{
Card.arraySort(myCards, myCards.length);
}
}

class Deck
{
//public data members
public final static int MAX_CARDS = 336; //MAX_PACK equal 6 decks

public final static char[] val = { //card values to initialize for


allocMasterPack()
'2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K','A','X'
};

//private data members


private static Card[] masterPack = new Card[56]; //private static Card[]
masterPack, contains all decks
private Card[] cards;
private int topCard;
private int numPacks;

//Default Deck(int numPacks) - a constructor that populates the arrays and


assigns initial values to members.
//Overload so that if no parameters are passed, 1 pack is assumed.
public Deck()
{
allocateMasterPack();
init(1);
}
//Deck() constructor
public Deck(int numPacks)

20
Assig6.java 7/31/2018

{ // an overload constructor that populates the arrays and assigns initial


values to members.
allocateMasterPack();
init(numPacks);
}
/* static void allocateMasterPack() - //Initiates 52 deck cards, master copy.
This is a private method that will be called by the constructor.
This static method will not allow itself to be executed more than once.*/

private static void allocateMasterPack()


{
int index = 0;
//if masterPack() has never been initiated, proceed.
if (masterPack[0]==null)
{
// for loops to get all cards values plus type
for(Card.Suit suit: Card.Suit.values())
{
for(char character: val)
{
masterPack[index]= new Card(character,suit);
index++;
}
}
}
}
//void init(int numPacks) - re-populate cards[] with the standard 52 ×
numPacks cards. We should not repopulate
//the static array, masterPack[], since that is done once, in the (first-
invoked) constructor and never changes.
public void init(int numPacks)
{
if (numPacks > 0 && numPacks <= MAX_CARDS/56)
{
this.numPacks = numPacks;
cards = new Card[numPacks*56];
int packCounter = 0; //
for(int i = 0; i < numPacks; i++)
{
for (Card cardListed: masterPack)
{
//for every pack, and every card in cycled masterPack assign
to cardListed
cards[packCounter++] = cardListed;
}
}
topCard = cards.length-1;
}
else
{
System.out.println("Error: The card deck cannot be initialized");
System.out.println("The number of cards maybe out of range");
System.out.println("Re-enter the number of pack of cards from 1 - 6")
;
}
}
//void shuffle() - mixes up the cards with the help of the standard random
number generator.
public void shuffle()
{
Random rand = new Random();
int x = this.topCard; //to determine length of cards remaining
for (int i = 0; i < this.topCard; i++ )

21
Assig6.java 7/31/2018

{
int r = rand.nextInt(x);
//replace cards incrementally randomly, it's possible for cards to
randomize more than once
Card temp = cards[r];
cards[r] = cards[i];
cards[i] = temp;
}
}

public int getTopCard()


{
return topCard;
}

//Card inspectCard(int k) - Accessor for an individual card. Returns a


card with errorFlag = true if k is bad.
public Card inspectCard(int k)
{
if (k <= topCard)
return cards[k];
else
return new Card('0', Card.Suit.SPADES); //invalid card response from
Card Class
}

//Card dealCard() - returns and removes the card in the top occupied
position of cards[].
//An accessor for the int topCard (no mutator).
public Card dealCard()
{
if (topCard >= 0)
{ //if there are still cards in deck
Card dealed = inspectCard(topCard);
cards[topCard] = null;
topCard = topCard - 1;
return dealed;
}
else
return new Card('0', Card.Suit.SPADES); //invalid card response from
Card Class
}

public boolean addCard(Card card)


{
boolean cardInDeck = false;
int count = 0;
while(cardInDeck == false && count <= topCard)
{
if (cards[count].getValue() == card.getValue() && cards[count].
getValue() == card.getValue())
{
cardInDeck = true;
}
count++;
}

if (cardInDeck)
{
return false;
}
else
{

22
Assig6.java 7/31/2018

topCard = topCard++;
cards[topCard] = new Card(card.getValue(), card.getSuit());
return true;
}
}

public boolean removeCard(Card card)


{
//System.out.println("Removing "+card.toString());
//System.out.println("Removing card");
boolean cardInDeck = false;
int count = 0;
while(cardInDeck == false && count <= topCard)
{
if (cards[count].equals(card))
{
cardInDeck = true;
cards[count] = new Card(cards[topCard].getValue(), cards[topCard].
getSuit());
topCard--;
}
count++;
}

if (cardInDeck)
return true;
else
return false;
}

public void sort()


{
Card.arraySort(cards, cards.length);
}

public int getNumCards()


{
return topCard + 1;
}

23

S-ar putea să vă placă și