-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAssig5 Phase 3.java
More file actions
1428 lines (1262 loc) · 38.3 KB
/
Copy pathAssig5 Phase 3.java
File metadata and controls
1428 lines (1262 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ----------------------------------------------------------------------------------------------------------------
Nautilus Group
Caleb Allen
Daisy Mayorga
David Harrison
Dustin Whittington
Michael Cline
CST 338
M5: GUI Card Java Program
30 May 2017
PURPOSE
Over several phases, we will be using the classes we wrote from M3 (Card, Hand, and Deck) and adding to those classes
the a GUI framework. To do this we will use some additional classes and create some of our own.
This is the third phase out of three. This third and final phase The final phase will add the CardGameFramework
class so that your card tools can be combined with your GUI tools to create a GUI program that has real computational
power for a GUI card game, "High Card".
----------------------------------------------------------------------------------------------------------------- */
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Date;
import javax.swing.*;
import java.util.Random;
public class Assig5
{
static final int NUM_CARDS_PER_HAND = 7;
static final int NUM_PLAYERS = 2;
static JLabel[] computerLabels = new JLabel[NUM_CARDS_PER_HAND];
static JLabel[] humanLabels = new JLabel[NUM_CARDS_PER_HAND];
static JLabel[] playedCardLabels = new JLabel[NUM_PLAYERS];
static JLabel[] playLabelText = new JLabel[NUM_PLAYERS];
static int playedCardID = -1;
static void playCardFromUI(String cardID)
{
/*
* This function is here for cardPlayListener to use
* to pass the index of a card that the player wishes
* to play from their hand.
*/
int id = Integer.parseInt(cardID);
if(id >= 0 && id < NUM_CARDS_PER_HAND)
{
playedCardID = Integer.parseInt(cardID);
}
}
private static void fillHandPanels(Hand hand, JLabel[] labels, CardTable playTable, boolean isComputer)
{
/*
* This function adds card images to the player and computer hands
*/
for (int count = 0; count < hand.getNumCards(); count++)
{
if(isComputer)
{
//fill card area with card backs
labels[count] = new JLabel(GUICard.getBackCardIcon());
playTable.pnlComputerHand.add(labels[count]);
}
else
{
//fills card area with card images
labels[count] = new JLabel(GUICard.getIcon(hand.inspectCard(count)));
//Make button with Action Command that corresponds to the index of card in hand.
JButton buttonWrapper = new JButton(new Integer(count).toString());
buttonWrapper.addActionListener(new cardPlayListener());
//Wrap button around the Card Image.
buttonWrapper.add(labels[count]);
playTable.pnlHumanHand.add(buttonWrapper);
}
}
}
private static void fillPlayAreaPanels(Card computerCard, Card humanCard, CardTable table)
{
/*
* This function fills the Play Area panel with the appropriate Labels
*
* Displays card image if available, card back if given a Card variable
* that is null.
*/
//Clear the table
table.pnlPlayArea.removeAll();
table.pnlPlayArea.validate();
//Create grid layout
table.pnlPlayArea.setLayout(new GridLayout(2,2));
//Add label for each played card.
JLabel humanLabel;
if(humanCard == null)
{
humanLabel = new JLabel(); //leaves play area blank until a card is played
}
else
{
humanLabel = new JLabel(GUICard.getIcon(humanCard));
}
//Add label for each played card.
JLabel computerLabel;
if(computerCard == null)
{
computerLabel = new JLabel(); //leaves play area blank until a card is played
}
else
{
computerLabel = new JLabel(GUICard.getIcon(computerCard));
}
//Prepare the table
table.pnlPlayArea.add(computerLabel);
table.pnlPlayArea.add(humanLabel);
//Add text label for played cards
JLabel computerText = new JLabel("Computer",JLabel.CENTER);
table.pnlPlayArea.add(computerText);
//Add text label for played cards
JLabel playerText = new JLabel("You",JLabel.CENTER);
table.pnlPlayArea.add(playerText);
}
private static int computerTurn(Hand computerHand, Card opponentCard)
{
/*
* Game AI for Computer if the computer is going second.
*
* Returns the index of the card in hand that the computer
* wishes to play.
*/
int bestOptionIndex = -1;
int bestOptionDifference = 1000;
int lowestCardIndex = -1;
int lowestCardDifference = 1000;
//compare each card in hand to the player's.
for(int i = 0; i < computerHand.getNumCards(); i++)
{
int difference = compareCards(computerHand.inspectCard(i),opponentCard);
//Find the card that is closest to, but still beats, the opponent.
if(difference > 0 && difference < bestOptionDifference)
{
bestOptionIndex = i;
bestOptionDifference = difference;
}
//While we're here, find the lowest card in hand.
if(difference <= 0 && difference < lowestCardDifference)
{
lowestCardIndex = i;
lowestCardDifference = difference;
}
}
//If we have a card that beats the opponent's, play it. No hoarding.
if(bestOptionIndex >= 0)
{
return bestOptionIndex;
}
//If we don't have a card that can win, burn the lowest card.
else
{
return lowestCardIndex;
}
}
private static int compareCards(Card cardOne, Card cardTwo)
{
/*
* Compares two cards.
*
* Returns a positive number if cardOne > cardTwo
* Returns a negative number if cardOne < cardTwo
* Returns zero if cardOne is equal to cardTwo
*/
//If the cards are the same.
if(cardOne.equals(cardTwo))
{
return 0;
}
//If values are the same, only suits matter.
else if(cardOne.getValue() == cardTwo.getValue())
{
int indexOne = -1;
int indexTwo = -1;
for(int i = 0; i < Card.suitRanks.length; i++)
{
if(cardOne.getSuit() == Card.suitRanks[i])
{
indexOne = i;
}
if(cardTwo.getSuit() == Card.suitRanks[i])
{
indexTwo = i;
}
}
return indexOne - indexTwo;
}
//compare card value primarily
else
{
int indexOne = -1;
int indexTwo = -1;
for(int i = 0; i < Card.valuRanks.length; i++)
{
if(cardOne.getValue() == Card.valuRanks[i])
{
indexOne = i;
}
if(cardTwo.getValue() == Card.valuRanks[i])
{
indexTwo = i;
}
}
return indexOne - indexTwo;
}
}
public static void main(String[] args)
{
//Constants from spec
int numPacksPerDeck = 1;
int numJokersPerPack = 0;
int numUnusedCardsPerPack = 0;
Card[] unusedCardsPerPack = null;
//Variables for High Card game
int humanHandID = 1;
int computerHandID = 0;
Card lastHumanCard = new Card('X',Card.Suit.clubs);
Card lastComputerCard = new Card('X',Card.Suit.spades);
//loop flags for game operation
boolean isComputerFirst = false;
boolean isComputerFinished = true;
//Variables to track winnings.
Card[] playerWinnings = new Card[numPacksPerDeck*56];
int playerWinningsCount = 0;
Card[] computerWinnings = new Card[numPacksPerDeck*56];
int computerWinningsCount = 0;
//Create highCardGame handler
CardGameFramework highCardGame = new CardGameFramework(
numPacksPerDeck, numJokersPerPack,
numUnusedCardsPerPack, unusedCardsPerPack,
NUM_PLAYERS, NUM_CARDS_PER_HAND);
//Create game table as in previous phases.
CardTable myCardTable = new CardTable("CardTable", NUM_CARDS_PER_HAND, NUM_PLAYERS);
myCardTable.setSize(900, 600);
myCardTable.setLocationRelativeTo(null);
myCardTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Deal cards to players.
highCardGame.deal();
//Fills the panels for the game GUI
fillHandPanels(highCardGame.getHand(computerHandID),computerLabels,myCardTable,true);
fillHandPanels(highCardGame.getHand(humanHandID),humanLabels,myCardTable,false);
fillPlayAreaPanels(null,null,myCardTable);
//Make everything visible
myCardTable.setVisible(true);
//Timer to allow for game to timeout if ignored.
long activityTimer = (new Date().getTime())/1000;
//While the program has not timed out. (5 minutes)
//and there are more cards to play.
while(((((new Date().getTime())/1000) - activityTimer) < 300) &&
highCardGame.getHand(humanHandID).getNumCards() > 0)
{
if(isComputerFirst && !isComputerFinished)
{
//run the computer's AI. Play as if trying to beat a card of average value.
int computerIndex =
computerTurn(highCardGame.getHand(computerHandID),new Card('8',Card.Suit.spades));
//set computer's card choice.
lastComputerCard = highCardGame.playCard(computerHandID, computerIndex);
isComputerFinished = true;
//change play area to show computer's card only
fillPlayAreaPanels(lastComputerCard,null,myCardTable);
myCardTable.setVisible(true);
}
if(playedCardID >= 0)
{
//We play the card clicked by the player onto the board.
lastHumanCard = highCardGame.playCard(humanHandID, playedCardID);
//Choose computer card if the computer is going second.
if(!isComputerFirst)
{
//run the computer's AI.
int computerIndex =
computerTurn(highCardGame.getHand(computerHandID),lastHumanCard);
//set computer's card choice.
lastComputerCard = highCardGame.playCard(computerHandID, computerIndex);
}
//Clear PlayArea for Display
myCardTable.pnlPlayArea.removeAll();
//Re-add the card icons.
JLabel humanLabel = new JLabel(GUICard.getIcon(lastHumanCard));
JLabel computerLabel = new JLabel(GUICard.getIcon(lastComputerCard));
myCardTable.pnlPlayArea.add(computerLabel);
myCardTable.pnlPlayArea.add(humanLabel);
//Figure out who won and store winnings
if(compareCards(lastHumanCard,lastComputerCard) > 0)
{
playerWinnings[playerWinningsCount++] = lastHumanCard;
playerWinnings[playerWinningsCount++] = lastComputerCard;
//Display game message to player
JLabel computerText = new JLabel("Computer LOSES!",JLabel.CENTER);
JLabel playerText = new JLabel("You WIN!",JLabel.CENTER);
myCardTable.pnlPlayArea.add(computerText);
myCardTable.pnlPlayArea.add(playerText);
myCardTable.setVisible(true);
//Give player 1 second to read message.
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
}
//make player go first next round
isComputerFirst = false;
isComputerFinished = false;
}
else if(compareCards(lastHumanCard,lastComputerCard) < 0)
{
computerWinnings[computerWinningsCount++] = lastHumanCard;
computerWinnings[computerWinningsCount++] = lastComputerCard;
//Display game message to player
JLabel computerText = new JLabel("Computer WINS!",JLabel.CENTER);
JLabel playerText = new JLabel("You LOSE!",JLabel.CENTER);
myCardTable.pnlPlayArea.add(computerText);
myCardTable.pnlPlayArea.add(playerText);
myCardTable.setVisible(true);
//Give player 1 second to read message.
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
}
//make computer go first next round
isComputerFirst = true;
isComputerFinished = false;
}
//Clear Panel Contents:
myCardTable.pnlComputerHand.removeAll();
myCardTable.pnlHumanHand.removeAll();
myCardTable.pnlPlayArea.removeAll();
myCardTable.validate();
//Fills the panels for the game GUI
fillHandPanels(highCardGame.getHand(computerHandID),computerLabels,myCardTable,true);
fillHandPanels(highCardGame.getHand(humanHandID),humanLabels,myCardTable,false);
fillPlayAreaPanels(null,null,myCardTable);
//Make everything visible
myCardTable.setVisible(true);
//Loop Housekeeping, reset timer and checked ID.
playedCardID = -1;
activityTimer = (new Date().getTime())/1000;
}
}
//Game over. Display winnings
//Clear card table to display winnings.
myCardTable.pnlComputerHand.removeAll();
myCardTable.pnlPlayArea.removeAll();
myCardTable.pnlHumanHand.removeAll();
myCardTable.validate();
//Output message to player about winning/losing
JLabel playerText, computerText;
if(playerWinningsCount > computerWinningsCount)
{
playerText = new JLabel("You WIN! You have won " +
Integer.toString(playerWinningsCount) + " cards.",JLabel.CENTER);
computerText = new JLabel("Computer LOSES! Computer has won " +
Integer.toString(computerWinningsCount) + " cards.",JLabel.CENTER);
}
else if(playerWinningsCount < computerWinningsCount)
{
playerText = new JLabel("You LOSE! You have won " +
Integer.toString(playerWinningsCount) + " cards.",JLabel.CENTER);
computerText = new JLabel("Computer WINS! Computer has won " +
Integer.toString(computerWinningsCount) + " cards.",JLabel.CENTER);
}
else
{
playerText = new JLabel("It's a TIE! You have won " +
Integer.toString(playerWinningsCount) + " cards.",JLabel.CENTER);
computerText = new JLabel("It's a TIE! Computer has won " +
Integer.toString(computerWinningsCount) + " cards.",JLabel.CENTER);
}
//Add relevant text to player hand area.
myCardTable.pnlComputerHand.add(computerText);
myCardTable.pnlHumanHand.add(playerText);
//Create grid to display winnings.
myCardTable.pnlPlayArea.setLayout(new GridLayout(2,1));
//Create panel to display the computer's won cards
JPanel computerCards = new JPanel();
computerCards.setBorder(BorderFactory.createTitledBorder("Computer's Won Cards"));
//Create panel to display the player's won cards
JPanel playerCards = new JPanel();
playerCards.setBorder(BorderFactory.createTitledBorder("Player's Won Cards"));
//Fill computerCards panel with images of the computer's won cards.
for(int i = 0; i < computerWinningsCount; i++)
{
JLabel cardLabel = new JLabel(GUICard.getIcon(computerWinnings[i]));
computerCards.add(cardLabel);
}
//Fill playerCards panel with images of the player's won cards.
for(int i = 0; i < playerWinningsCount; i++)
{
JLabel cardLabel = new JLabel(GUICard.getIcon(playerWinnings[i]));
playerCards.add(cardLabel);
}
//Add the panels to the play area and display winnings.
myCardTable.pnlPlayArea.add(computerCards);
myCardTable.pnlPlayArea.add(playerCards);
myCardTable.setVisible(true);
}
}
//ActionListener to allow the player to play the card they click on.
class cardPlayListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String cardID = e.getActionCommand();
Assig5.playCardFromUI(cardID);
}
}
class CardTable extends JFrame
{
static final int MAX_CARDS_PER_HAND = 56;
static final int MAX_PLAYERS = 2;
private int numCardsPerHand;
private int numPlayers;
public JPanel pnlComputerHand, pnlHumanHand, pnlPlayArea;
public CardTable(String title, int numCardsPerHand, int numPlayers)
{
/*
* We will use three Public JPanels, one for each hand (player-bottom and computer-top)
* and a middle "playing" JPanel. The client (below) will generate the human's cards at
* random and will be visible in the bottom JPanel, while the computer's cards will be
* chosen (again, by the client) to be all back-of-card images in the top JPanel. The
* middle JPanel will display cards that are "played" by the computer and human during
* the conflict. Let's assume that each player plays one card per round, so for a
* 2-person game (computer + human) there will be exactly two cards played in the central
* region per round of battle. My client chose a joker for the two central cards, just so
* we would have something to see in the playing region.
*/
// computer's hand
pnlComputerHand = new JPanel();
pnlComputerHand.setBorder(BorderFactory.createTitledBorder("Computer Hand"));
// player's hand
pnlHumanHand = new JPanel();
pnlHumanHand.setBorder(BorderFactory.createTitledBorder("Your Hand"));
// play area
pnlPlayArea = new JPanel();
pnlPlayArea.setBorder(BorderFactory.createTitledBorder("Play Area"));
// layout for JPanels
add(pnlComputerHand,BorderLayout.NORTH);
add(pnlHumanHand,BorderLayout.SOUTH);
add(pnlPlayArea,BorderLayout.CENTER);
}
public int getNumCardsPerHand()
{
/*
* Accessor to get the number of cards per hand
*/
return this.numCardsPerHand;
}
public int getNumPlayers()
{
/*
* Accessor to get the number of players
*/
return this.numPlayers;
}
}
class GUICard
{
private static Icon[][] iconCards = new ImageIcon[14][4]; // 14 = A thru K + joker
private static Icon iconBack;
static boolean iconsLoaded = false;
// loads all of the card images into a 2D array one time only
static void loadCardIcons()
{
if(!iconsLoaded)
{
for(int j = 0; j <= 3; j++)
{
for(int k = 0; k <= 13; k++)
{
iconCards[k][j] = new ImageIcon("images/" + turnIntIntoCardValue(k) + turnIntIntoCardSuit(j) + ".gif");
}
}
iconBack = new ImageIcon("images/BK.gif"); //loads the back of card image
iconsLoaded = true; //this keeps array from loading more than once
}
}
// accessor for front card image (56 possibilities)
static public Icon getIcon(Card card)
{
loadCardIcons(); // only instantiates one time
return iconCards[valueAsInt(card)][suitAsInt(card)];
}
// accessor for back of card image
static public Icon getBackCardIcon()
{
loadCardIcons(); // only instantiates one time
return iconBack;
}
// turns value into an int
private static int valueAsInt(Card card)
{
char cardsValue = card.getValue();
switch (cardsValue)
{
case 'A':
return 0;
case '2':
return 1;
case '3':
return 2;
case '4':
return 3;
case '5':
return 4;
case '6':
return 5;
case '7':
return 6;
case '8':
return 7;
case '9':
return 8;
case 'T':
return 9;
case 'J':
return 10;
case 'Q':
return 11;
case 'K':
return 12;
case 'X':
return 13;
}
return 0;
}
// turns suit into an int
private static int suitAsInt(Card card)
{
Card.Suit cardsSuit = card.getSuit();
switch (cardsSuit)
{
case clubs:
return 0;
case diamonds:
return 1;
case hearts:
return 2;
case spades:
return 3;
}
return 3;
}
// turns 0 - 13 into "A", "2", "3", ... "Q", "K", "X"
static String turnIntIntoCardValue(int k)
{
switch (k)
{
case 0:
return "A";
case 1:
return "2";
case 2:
return "3";
case 3:
return "4";
case 4:
return "5";
case 5:
return "6";
case 6:
return "7";
case 7:
return "8";
case 8:
return "9";
case 9:
return "T";
case 10:
return "J";
case 11:
return "Q";
case 12:
return "K";
case 13:
return "X";
}
return "A";
}
// 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";
}
return "S";
}
}
class Card
{
/*
* CARD UPDATES REQUIRED
* Values need to be updated to include Joker
* public static char[] valuRanks //used to rank the cards from low to high
* static void arraySort(Card[], int arraySize) //use a bubble sort routine to sort an array of cards
*/
//Enumerator for the card's suit
public enum Suit
{
clubs, diamonds, hearts, spades
};
//For card ranking purposes
public static char[] valuRanks = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A', 'X' };
public static Suit[] suitRanks = { Suit.clubs, Suit.diamonds, Suit.hearts,Suit.spades };
//Private instance variables
private char value;
private Suit suit;
private boolean errorFlag;
//Default constructor for card overloaded to return A of spades
public Card()
{
this.value = 'A';
this.suit = Suit.spades;
}
//Parameterized constructor for card that accepts value and suit
public Card(char value, Suit suit)
{
set(value, suit);
}
//Parameterized constructor for card that accepts value, suit,
//and errorFlag
public Card(char value, Suit suit, boolean errorFlag)
{
set(value, suit);
this.errorFlag = errorFlag;
}
//If error flag is false, returns value and suit of card in a single
//string, otherwise returns invalid
public String toString()
{
if (errorFlag == false)
{
return this.value + " of " + this.suit;
}
else
{
return "[ invalid ]";
}
}
//Mutator to set value and suit for a card
public boolean set(char value, Suit suit)
{
if (isValid(value, suit))
{
this.value = value;
this.suit = suit;
this.errorFlag = false;
return true;
}
else
{
this.errorFlag = true;
return false;
}
}
//Accessor for card suit
public Suit getSuit()
{
return this.suit;
}
public char getValue()
{
/*
* Accessor for Value
*/
return this.value;
}
public boolean getErrorFlag()
{
/*
* Accessor for errorFlag
*/
return this.errorFlag;
}
private boolean isValid(char value, Suit suit)
{
/*
* a private helper method that returns true or false, depending on the
* legality of the parameters. Note that, although it may be impossible
* for suit to be illegal (due to its enum-ness), we pass it, anyway, in
* anticipation of possible changes to the type from enum to, say, char
* or int, someday. We only need to test value, at this time.
*/
char[] cardType = { 'A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'X' };
for (int i = 0; i < cardType.length; i++)
{
if (value == cardType[i])
{
return true;
}
}
return false;
}
//method that returns true if all members are equal, false otherwise
public boolean equals(Card card)
{
if (card == this)
{
return true;
}
else
{
return (card.getValue() == this.getValue()) &&
(card.getSuit().equals(this.getSuit())) &&
(card.getErrorFlag() == this.getErrorFlag());
}
}
// Find the card index
private static int cardIndex(Card card)
{
for(int i = 0; i < valuRanks.length; i++)
{
if(card.getValue() == valuRanks[i])
return i;
}
return -1;
}
// Use the bubble sort for sorting the array
public static void arraySort(Card[] cardArray, int arraySize)
{
Card temp;
for(int i = 0; i < arraySize; i++)
{
for(int j = 1; j < arraySize - i; j++)
{
if(cardIndex(cardArray[j-1]) > cardIndex(cardArray[j]))
{
temp = cardArray[j-1];
cardArray[j-1] = cardArray[j];
cardArray[j] = temp;
}
}
}
}
}
class Hand
{
/*
* HAND UPDATES REQUIRED
* void sort() //sorts the hand by calling the arraySort method for the Card class
* "myCards.arraySort()"
*/
//Safeguard to prevent a runaway program from creating a monster array
public final static int MAX_CARDS = 50;
//private data members
private Card[] myCards;
private int numCards;
public Hand()
{
/*
* Default Constructor;
*/
this.numCards = 0;
this.myCards = new Card[MAX_CARDS];
}
public void resetHand()
{
/*
* remove all cards from the hand (in the simplest way).
*/
//Remove all reference to the old hand.
this.myCards = new Card[MAX_CARDS];
//Reset the card counter.
this.numCards = 0;
}
public boolean takeCard(Card card)
{
/*
* adds a card to the next available position in the myCards array. This
* is an object copy, not a reference copy, since the source of the Card
* might destroy or change its data after our Hand gets it -- we want
* our local data to be exactly as it was when we received it.
*/
//Make sure we're not above our hand size limit.
if (numCards < MAX_CARDS)
{
//Create a copy of the taken card and advance the card counter.
myCards[numCards++] = new Card(card.getValue(), card.getSuit());
return true;
}
else
{
return false;
}
}
public Card playCard()
{
/*
* returns and removes the card in the top occupied position of the
* array.
*/
if (numCards > 0)
{
//Make a copy of the card in the myCards array.
Card playedCard = new Card(myCards[numCards - 1].getValue(), myCards[numCards - 1].getSuit());
//Decrement card counter. Remove the topmost card from the array.
myCards[--numCards] = null;
return playedCard;
}
else
{
//Returns an invalid card to be consistent with inspectCard()
return new Card('Q', Card.Suit.hearts, true);
}
}
public Card playCard(int cardIndex)
{
/*
* returns and removes the card in the top occupied position of the
* array.
*/
if (numCards > 0 && cardIndex < numCards)
{
//Get the card we are playing.
Card playedCard = new Card(myCards[cardIndex].getValue(), myCards[cardIndex].getSuit());
//Temporary container for cards in hand.
Card[] tempCards = new Card[numCards - 1];
//Add cards up until index to temporary array
for(int i = 0; i < cardIndex; i++)
{
tempCards[i] = myCards[i];
}
//Add cards after index to temporary array
for(int i = cardIndex + 1; i < numCards; i++)
{
tempCards[i - 1] = myCards[i];
}
//Reset the player's hand
resetHand();
//Copy temporary references to the hand
for(int i = 0; i < tempCards.length; i++)
{
myCards[i] = tempCards[i];
}
numCards = tempCards.length;
return playedCard;
}
else
{
//Returns an invalid card to be consistent with inspectCard()
return new Card('Q', Card.Suit.hearts, true);
}
}
public String toString()
{
/*
* a stringizer that the client can use prior to displaying the entire
* hand
*/
String output = "( ";
for (int i = 0; i < numCards; i++)
{
//print the card.
output += this.myCards[i].toString();
//add a comma to every card except the last.
if (i + 1 < numCards)
{
output += ", ";
}
}
return output + " )";
}
public int getNumCards()
{
/*
* Accessor for numCards
*/
return this.numCards;
}
public Card inspectCard(int k)