Repository navigation
Expand file tree
/
Copy pathGame.java
More file actions
1994 lines (1701 loc) · 58.5 KB
/
Copy pathGame.java
File metadata and controls
1994 lines (1701 loc) · 58.5 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
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
// Apache POI: Allows high score to be saved in
// Excel spreadsheet for later reference
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class Game {
// Standard deck of 52 playing cards (Requirement 1.0.0)
/* There is a space in front of all cards besides the 10 of each suit
* for output alignment in the tableau pile.
* The 10 occupies 3 places, i.e. "10D", while the rest of the cards
* occupy only 2 spaces, i.e. "AS"
*/
static String[] cards = { " AS", " 2S", " 3S", " 4S", " 5S", " 6S", " 7S",
" 8S", " 9S", "10S", " JS", " QS", " KS", " AC", " 2C", " 3C",
" 4C", " 5C", " 6C", " 7C", " 8C", " 9C", "10C", " JC", " QC",
" KC", " AH", " 2H", " 3H", " 4H", " 5H", " 6H", " 7H", " 8H",
" 9H", "10H", " JH", " QH", " KH", " AD", " 2D", " 3D", " 4D",
" 5D", " 6D", " 7D", " 8D", " 9D", "10D", " JD", " QD", " KD" };
static int[] random = new int[52];
static ArrayList<Integer>[] layout = (ArrayList<Integer>[]) new ArrayList[7];
static Stack<Integer>[] foundationStacks = (Stack<Integer>[]) new Stack[4];
static Stack<Integer> drawPile = new Stack<Integer>();
static Stack<Integer> drawnCards = new Stack<Integer>();
static ArrayList<Integer> faceUp = new ArrayList<Integer>();
/** Cards the human or AI has actually seen (dealt face up, drawn, or revealed). */
static boolean[] seenCards = new boolean[52];
static Long dealSeed = null;
static boolean headless = false;
static boolean gameWon = false;
static int[] switches = new int[52];
static boolean[] kingsPiles = new boolean[4];
static int highestScore = 0;
static int nDrawPileRestarts = 0;
static int nKings = 0;
/* The game can be exited or restarted if the user desires.
* (Requirements 6.3.0 and 6.4.0) */
static Scanner scanner = new Scanner(System.in);
static int points = 0;
static int highScore = 0;
static int leaderboardSize = 10;
static Integer[] top10Scores = new Integer[leaderboardSize];
static String[] top10Names = new String[leaderboardSize];
static boolean noWinnable = false;
// Output when player wins solitaire
static String asciiArtSmiley = "888888888888888888888888888888888\n"
+ "88888888888888888____88888____888\n"
+ "8888888888888888______888_____888\n"
+ "8888888888888888______888_____888\n"
+ "8888888888888888______888_____888\n"
+ "8888888888888888______88_____8888\n"
+ "8888888888888888______88_____8888\n"
+ "8888888888888888______88_____8888\n"
+ "8888888888_____8______88_____8888\n"
+ "8888___88______8______8_____88888\n"
+ "888_____8______8______8_____88888\n"
+ "888_____8______8______8_____88888\n"
+ "888_____8______8______8_____88888\n"
+ "888_____8____88888888888888888888\n"
+ "8_8_____8___88________________888\n"
+ "8_8_____8__88__________________88\n"
+ "8__888888_888_________888_______8\n"
+ "8_________88________8___________8\n"
+ "8____________8888888____________8\n"
+ "88_____________88_______________8\n"
+ "88_______________88_____________8\n"
+ "888______________8_____________88\n"
+ "888_______________8___________888\n"
+ "88888_____________8__________8888\n"
+ "888888_____________________888888\n"
+ "888888____________________8888888\n";
static HSSFWorkbook workbook;
static HSSFSheet sheet;
static HSSFRow row;
static String fileName = ".scores.xls";
static File excelSpreadsheet = new File(fileName);
static int lastRow = -1;
public static void main(String[] args) {
if (args.length >= 2 && args[0].equals("--benchmark-legacy")) {
int n = Integer.parseInt(args[1]);
long startSeed = args.length > 2 ? Long.parseLong(args[2]) : 1L;
runLegacyBenchmark(n, startSeed);
return;
}
// If a spreadsheet with the high score exists,
// get the current sheet and row
if (excelSpreadsheet.exists()) {
try {
workbook = new HSSFWorkbook(new FileInputStream(fileName));
sheet = workbook.getSheetAt(0);
row = sheet.getRow(0);
} catch (IOException ioe) {
}
}
// If the spreadsheet with the high score does not exist,
// create a workbook, sheet, and row.
else {
workbook = new HSSFWorkbook();
sheet = workbook.createSheet();
row = sheet.createRow(0);
}
startGame();
}
/**
* Plays the original hint-based AI on seeded deals with no console and no
* spreadsheet. A strict win is four kings on the foundations. An
* autocomplete-ready loss is a position the human prompt would offer to finish.
*/
static void runLegacyBenchmark(int n, long startSeed) {
headless = true;
java.io.PrintStream previous = System.out;
System.setOut(new java.io.PrintStream(java.io.OutputStream.nullOutputStream()));
workbook = new HSSFWorkbook();
sheet = workbook.createSheet();
row = sheet.createRow(0);
int wins = 0;
int exposed = 0;
int errors = 0;
long started = System.nanoTime();
for (int i = 0; i < n; i++) {
dealSeed = Long.valueOf(startSeed + i);
gameWon = false;
nKings = 0;
try {
startGame();
highestScore = 0;
hint(1);
} catch (Throwable t) {
errors++;
}
if (gameWon || nKings >= 4) {
wins++;
} else if (winnable()) {
exposed++;
}
}
System.setOut(previous);
double seconds = (System.nanoTime() - started) / 1e9;
System.out.println("Game.java legacy AI: " + wins + "/" + n
+ " strict wins, " + exposed + " autocomplete-ready losses, "
+ errors + " errors, " + String.format("%.1f", seconds) + "s, seeds "
+ startSeed + "-" + (startSeed + n - 1));
}
/*
* startGame() is called from:
* - main(): to start the game
* - print(): when the user has won and chooses to play again
* - playGame(choice): when the user chooses to restart the game (choice == 5)
*/
static void startGame() {
ArrayList<Integer> scoresAL = new ArrayList<Integer>();
ArrayList<String> namesAL = new ArrayList<String>();
// Get previous top 10 scores and names from Excel spreadsheet
// and store them into scores and names ArrayLists
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
HSSFRow newRow = sheet.getRow(i);
HSSFCell scoreCell = newRow.getCell(0);
HSSFCell nameCell = newRow.getCell(1);
int score = 0;
if (scoreCell != null) {
// If a score is invalid (spreadsheet has been tampered with),
// skips over that score
try {
score = (int) scoreCell.getNumericCellValue();
} catch (Exception nfe) {
continue;
}
}
String name = "";
if (nameCell != null) {
name = nameCell.getStringCellValue();
}
if (score > 0 && name.length() > 0) {
scoresAL.add(score);
namesAL.add(name);
}
}
// Convert scores and names ArrayLists to arrays
Integer[] scores = new Integer[scoresAL.size()];
scoresAL.toArray(scores);
String[] names = new String[namesAL.size()];
namesAL.toArray(names);
// Sort scores (and names) in descending order from
// highest to lowest
sortScoresAndNames(scores, names);
// Initialize point total to 0
points = 0;
noWinnable = false;
// Clear draw pile, drawn cards, and face up cards
// just in case if a previous game was played
drawPile.clear();
drawnCards.clear();
faceUp.clear();
gameWon = false;
for (int i = 0; i < seenCards.length; i++) {
seenCards[i] = false;
}
// "Shuffle the deck" by generating 52 random numbers from 0-51 and
// doling the cards out in that order
// (Requirement 2.5.0)
Random rng = dealSeed == null ? new Random() : new Random(dealSeed.longValue());
random = rng.ints(0, 52).distinct().limit(52).toArray();
// Take the last 24 cards and place them into the draw pile
// (the first 28 cards are used for the tableau piles)
// (Requirement 2.3.0)
for (int i = 28; i < random.length; i++) {
int key = random[i];
drawPile.push(key);
}
// layout is an array of ArrayLists that keeps track of the tableau
// piles in Solitaire
// This loop initializes an ArrayList for each tableau pile
for (int i = 0; i < layout.length; i++) {
layout[i] = new ArrayList<Integer>();
}
// foundationStacks is an array of Stacks that keeps track of the
// foundation stack in Solitaire
// This loop initializes an empty stack for each foundation stack
// (Requirement 2.2.0)
for (int i = 0; i < foundationStacks.length; i++) {
foundationStacks[i] = new Stack<Integer>();
}
int deckSize = 1;
int cardIndex = 0;
// Initialize the tableau layout in Solitaire, with piles of 1, 2, 3,
// 4, 5, 6, 7 cards each
// (Requirement 2.1.0)
for (int deck = 0; deck < layout.length; deck++) {
// Add cards to each pile, in line with the necessary deck size
for (int card = 0; card < deckSize; card++) {
// Cards are added to each pile according to the randomly
// generated array of 52 integers
layout[deck].add(random[cardIndex]);
// If the card is the bottom card in the tableau pile,
// the card is turned face up
// (Requirement 2.1.1)
if ((card + 1) == deckSize) {
faceUp.add(random[cardIndex]);
seenCards[random[cardIndex]] = true;
}
cardIndex++;
}
// For each pile in the tableau, the deck size is increased
// progressively from 1-7
deckSize++;
}
for (int i = 0; i < switches.length; i++) {
switches[i] = -1;
}
for (int i = 0; i < kingsPiles.length; i++) {
kingsPiles[i] = false;
}
highestScore = 0;
nDrawPileRestarts = 0;
nKings = 0;
if (!headless) {
System.out.println("Welcome to Solitaire!");
// Outputs the Solitaire tableau layout
// 0 is normal mode
print(0, false);
}
}
/*
* print() shows the board and, unless mode is 1, asks for the next action.
* Called from startGame(), playGame(), draw(), and the exit/restart prompt.
*/
static boolean revealHiddenTableau = false;
/** Print a rejected move or similar result so it stands out from the prompt. */
static void printNotice(String message) {
System.out.println("*** " + message + " ***");
}
static void print(int mode, boolean AI) {
// Outputs the Solitaire tableau layout
if (headless) {
nKings = 0;
for (int checkStack = 0; checkStack < foundationStacks.length; checkStack++) {
Stack<Integer> currentStack = foundationStacks[checkStack];
if (!currentStack.empty() && currentStack.peek() % 13 == 12) {
nKings++;
}
}
if (nKings >= 4) {
gameWon = true;
}
return;
}
// Do not continue printing the layout if game has been won
// (4 kings in foundation stacks)
if (nKings >= 4) {
return;
}
/* Checks if a game is winnable and if the user has not already chosen
* to win manually (Requirement 5.4.1)
*/
if (!AI && winnable() && !noWinnable) {
System.out.println();
// Reprints tableau layout
// print(1);
int finishGame = 0;
/* If game is winnable, prompt user if they want to the program to
* automatically fill in all the foundation stacks.
*
* If the user accidentally enters invalid input, the program
* should reprompt them for valid input. (Requirement 6.1.0)
*/
while (finishGame < 1 || finishGame > 2) {
System.out.println("You can win Solitaire right now.\n"
+ "Do you want to automatically fill all the foundation stacks? 1) Yes 2) No");
try {
finishGame = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
System.out.println("Please enter a number from 1-2.\n");
continue;
}
// If user enters number not equal to 1 or 2,
// re-prompt them
if (finishGame < 1 || finishGame > 2) {
System.out.println("Please enter a number from 1-2.\n");
}
}
// If user says yes,
// add kings to every foundation stack
if (finishGame == 1) {
int[] kings = {12, 25, 38, 51};
int king = 0;
for (int stack = 0; stack < foundationStacks.length; stack++) {
foundationStacks[stack].push(kings[king]);
king++;
}
/* Count up the number of cards in the tableau piles
* and multiply by 10 to figure out the number that should be
* added to the user's score.
*/
int addedPts = numFaceUpCards() * 10;
// Add to the user's score
points += addedPts;
// Output message
System.out.println("\nAll cards moved to foundation stack. Points +" + addedPts + ".");
}
// If user chooses to win manually,
else {
// prevent program from prompting them again to win automatically
noWinnable = true;
System.out.println("You chose not to fill in all the foundation stacks automatically.\n");
}
}
System.out.print("\nDrawn: ");
// If cards have been drawn, the program shows that card to the
// user.
if (!drawnCards.empty()) {
int card = drawnCards.peek();
System.out.print(cards[card] + " ");
} else {
System.out.print("[none] ");
}
System.out.print("Foundation Stacks: ");
nKings = 0;
// Checks if foundation stacks have cards in them
// If so, outputs the top card in the stack
for (int checkStack = 0; checkStack < foundationStacks.length; checkStack++) {
Stack<Integer> currentStack = foundationStacks[checkStack];
if (!currentStack.empty()) {
// If the foundation stack is not empty, prints the top card
int card = currentStack.peek();
// If the top card is a king, counts it
if (card % 13 == 12) {
nKings++;
}
// Add a space in front of the card if number is 10
// The 10 card uses all three available spaces "10S"
// (compared with other cards, which only take 2
// spaces: " AS")
if (card % 13 == 9) {
System.out.print(" ");
}
System.out.print(cards[card]);
/* When all 4 foundation piles are completely filled
* (A - K), the game ends in a win.
* (Requirement 5.4.0)
*/
// If the number of kings in all the stacks equal 4, the
// user has won and the current game ends
if (nKings == 4) {
// Output awesome ASCII art smiley
System.out.println("\n\n" + asciiArtSmiley);
System.out
.println("You won Solitaire! Congratulations!");
// Save score into Excel spreadsheet
saveScore(points);
int playAgain = 0;
/* If the user accidentally enters invalid input, the program should
* reprompt them for valid input.
* (Requirement 6.1.0)
*/
do {
// Ask user if they want to play again, taking in 1
// or 2
System.out
.println("Do you want to play again? 1) Yes 2) No");
try {
playAgain = Integer
.parseInt(scanner.nextLine());
System.out.println();
}
// If user enters a non-numeric character,
// re-prompts them
catch (NumberFormatException nfe) {
System.out
.println("Please enter a number from 1-2.\n");
continue;
}
// If user enters number not equal to 1 or 2,
// re-prompts them
if (playAgain < 1 || playAgain > 2) {
System.out
.println("Please enter a number from 1-2.\n");
}
} while (playAgain < 1 || playAgain > 2);
// Start game if user chooses to play again
if (playAgain == 1) {
startGame();
}
// End game if user chooses to
else {
System.out.println("Thank you for playing Solitaire.");
}
return;
}
}
}
System.out.println(" Points: " + points);
// Find the longest tableau pile
// Tableau piles are output to the console using a 2D array
// The number of rows in the 2D array is determined by the longest
// tableau pile
int longestPileLength = 1;
for (int pile = 0; pile < layout.length; pile++) {
int length = layout[pile].size();
if (length > longestPileLength) {
longestPileLength = length;
}
}
// 2D array for output to the console
// # rows = longest tableau pile
// # columns = 7 (# of tableau piles)
String[][] layoutArr = new String[longestPileLength + 1][layout.length];
for (int row = 0; row < layoutArr.length; row++) {
for (int col = 0; col < layoutArr[row].length; col++) {
// Cells in top row of 2D array: displays the tableau pile
// number for referencing when the player wants to move a card
if (row == 0) {
layoutArr[row][col] = " " + (col + 1) + " ";
}
// Cells in the other rows are initialized to 3 spaces
// so that the card values in each tableau pile are lined up
// even if there are empty cells
else {
layoutArr[row][col] = " ";
}
}
}
// Take card values from the array of ArrayLists that store the cards
// that are in the tableau piles
// and place them into the 2D array for output
for (int deck = 0; deck < layout.length; deck++) {
// The first card in the tableau pile is always placed in the first
// row
int row = 1;
// Iterate through tableau pile
for (int card = 0; card < layout[deck].size(); card++) {
// Get the index of the card in the pile
int key = layout[deck].get(card);
// Save the card's name, i.e. AS
String cardName = cards[key];
// If the card is not supposed to be shown, obfuscate it
// unless Warp is playing and hidden tableau cards should be visible.
if (!isFaceUp(key) && !revealHiddenTableau) {
cardName = "---";
}
// Save card's name or obfuscated representation to 2D array
layoutArr[row][deck] = cardName;
// Increment the row number for the next card
row++;
}
}
// Output the 2D array with the tableau piles to the console
for (int row = 0; row < layoutArr.length; row++) {
for (int col = 0; col < layoutArr[row].length; col++) {
System.out.print(layoutArr[row][col] + " ");
}
System.out.println();
}
System.out.println();
// Mode 1 is for methods that want to show the tableau piles to
// the user but continue to take in their own input (i.e. pickPile())
if (mode == 1) {
return;
}
// Prompt the user for their next move
// (Requirement 5.0.0)
play();
}
/*
* play() is called from print(): to prompt user for input as to what
* they want to do next
*/
static void play() {
int choice = 0;
int upperLimit = 5;
/* If the user accidentally enters invalid input, the program should
* reprompt them for valid input.
* (Requirement 6.1.0)
*/
do {
// 1) draw, 2) pick a card (destination is chosen automatically),
// 3) hint, 4) exit, or 5) restart (Requirement 5.0.0)
System.out.println("Would you like to draw or pick a card?");
System.out.println("1) draw 2) pick card 3) hint 4) exit 5) restart");
System.out.println("Computer play: \"player\" or \"warp\". Add \" slow\" to pause between moves.");
try {
// Take in user's choice and make it uppercase
String choiceStr = scanner.nextLine().trim().toUpperCase();
if (choiceStr.length() == 0) {
continue;
}
boolean slow = choiceStr.endsWith(" SLOW");
String modeName = slow ? choiceStr.substring(0, choiceStr.length() - 5).trim() : choiceStr;
// "AI", "START", and "LEGAL PLAYER" remain aliases for Player.
if (choiceStr.equals("AI") || choiceStr.equals("START") || modeName.equals("PLAYER") || modeName.equals("LEGAL PLAYER")) {
SmartAI.runCli(slow || choiceStr.equals("START"), false);
return;
}
if (modeName.equals("WARP") || modeName.equals("WARP MODE")) {
SmartAI.runCli(slow, true);
return;
}
// "2QH" picks QH from the menu. The destination is automatic.
if (choiceStr.length() > 1 && choiceStr.charAt(0) == '2') {
String rest = choiceStr.substring(1).trim();
if (isCard(rest)) {
System.out.println();
playGame(2, rest, false);
return;
}
}
choice = Integer.parseInt(choiceStr);
}
// If the user enters non-numeric input,
// loop continues and user is reprompted
catch (NumberFormatException nfe) {
System.out.println("Please enter a number from 1-" + upperLimit + ", or type player or warp.\n");
continue;
}
// If the user enters a number out of range,
// loop continues and user is reprompted
if (choice < 1 || choice > upperLimit) {
System.out.println("Please enter a number from 1-" + upperLimit + ", or type player or warp.\n");
} else {
System.out.println();
}
} while (choice < 1 || choice > upperLimit);
// Call a different playGame method with the user's choice as a
// parameter
playGame(choice, null, false);
}
/*
* playGame(choice) is called from
* - play(): to continue the game after the user has chosen what
* they want to do
* - print(): when the user has won and they choose to leave the game.
* The exit option (choice == 4) is called.
*/
static void playGame(int choice, String shortcutCard, boolean AI) {
int AInum = 0;
if (AI) {
AInum = 1;
}
// User chooses to draw a card
if (choice == 1) {
// When the user asks to draw a card and the draw pile is empty,
// the cards in the drawn cards pile should be placed back into the
// draw pile in reverse order compared to the way the cards were drawn.
// (Requirement 3.3.1)
if (drawPile.empty()) {
// If there are no cards in either the draw pile or the drawn cards
// pile, prevent the user from drawing more cards
// (Requirement 3.3.2)
if (drawnCards.empty()) {
printNotice("There are no cards left to draw.");
print(0, AI);
return;
}
int yesNo = 0;
if (!AI) {
/* If the user accidentally enters invalid input, the program should
* reprompt them for valid input.
* (Requirement 6.1.0)
*/
do {
// prompts the user for valid input
// to see if they would like to restart the draw pile
System.out
.println("All cards have been drawn. Would you like to restart the draw pile? 1) Yes 2) No");
System.out.println("Your points will be deducted by 25.");
try {
yesNo = Integer.parseInt(scanner.nextLine());
System.out.println();
} catch (NumberFormatException nfe) {
System.out.println("Please enter a number from 1-2.\n");
continue;
}
if (yesNo < 1 || yesNo > 2) {
System.out.println("Please enter a number from 1-2.\n");
}
} while (yesNo < 1 || yesNo > 2);
} else {
yesNo = 1;
}
// If the user chooses to restart the draw pile,
// the game takes all the cards that have been drawn,
// places them into the draw pile, and draws a card
if (yesNo == 1) {
nDrawPileRestarts++;
while (!drawnCards.empty()) {
int card = drawnCards.pop();
drawPile.push(card);
}
System.out.println("You have restarted the draw pile. Points -25.");
// Deduct 25 points for restarting draw pile
// (Requirement 4.4.0)
points -= 25;
// Draw new card
draw(AInum);
}
// If the user chooses not to restart the draw pile,
// prints out tableau pile and continues the game
else {
System.out
.println("You chose not to restart the draw pile.");
print(0, AI);
}
}
// If there are cards to draw, a card is drawn
else {
draw(AInum);
}
}
// User picks a card. A legal foundation build is taken when one exists.
// Otherwise the card moves to the next legal tableau pile to the right
// of where it sits, wrapping around to the leftmost legal pile.
else if (choice == 2) {
int[] result = pickACard(shortcutCard);
if (result != null) {
autoMove(result[0], result[1]);
}
print(0, AI);
}
// User asks for hint. The suggestion names a card to pick, or a draw.
else if (choice == 3) {
SmartAI.hintCli();
return;
}
/* The game can be exited if the user desires.
* (Requirement 6.3.0)
*/
// User chooses to exit
else if (choice == 4) {
// Make sure user did not accidentally chose to exit
// (Requirement 6.2.0)
int areYouSure = areYouSure(1);
// If user wants to exit, end the game.
if (areYouSure == 1) {
saveScore(points);
System.out.println("You have chosen to leave Solitaire.");
System.out.println("Thank you for playing Solitaire.");
System.out
.println("\nThis window will close automatically in 5 seconds.");
// Add 5 second delay, so command prompt does not immediately
// close after the user exits the game.
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
// Terminates all program execution
// http://stackoverflow.com/questions/7600812/which-method-is-used-to-terminate-the-execution-of-java-program-in-between
System.exit(0);
}
}
/* The game can be restarted by a redeal if the user desires.
* (Requirement 6.4.0)
*/
// User chooses to restart
else if (choice == 5) {
// Make sure user did not accidentally chose to restart
// (Requirement 6.2.0)
int areYouSure = areYouSure(2);
// If user wants to restart, restart the game
if (areYouSure == 1) {
// Save score
saveScore(points);
System.out.println("You have chosen to restart the game.");
// Restart game
startGame();
}
}
}
/*
* canMoveToFoundation() is called from playGame(choice) when the user
* chooses to move a card to a foundation stack to check if that card can be
* moved
*/
static boolean canMoveToFoundation(int card) {
// Check if a card can be placed into a foundation stack
// Determine which foundation stack (spades, clubs, hearts, diamonds)
// the card should be placed into
// and the value of the ace for that suit
int[] result = findStack(card);
int stackNum = result[0];
int ace = result[1];
Stack<Integer> currentStack = foundationStacks[stackNum];
// If there are cards in the stack,
// the card at the top should be one less than the card
// the player wants to place on the stack
// (Requirement 3.2.0)
if (!currentStack.empty()) {
int topCard = currentStack.peek();
if ((card - 1) == topCard) {
return true;
}
}
// If the stack is empty,
// the card must be the ace for that suit
// (Requirement 3.2.1)
if (card == ace) {
return true;
}
return false;
}
/*
* moveToFoundation() is called from playGame(choice) when the user chooses
* to move a card to a foundation stack if that card can be moved
*/
static void moveToFoundation(int card, int drawnFoundation) {
// Move card to foundation stack
String cardOutput = removeUnnecessarySpace(cards[card]);
System.out.println(cardOutput
+ " moved to foundation stack. Points +10.");
// Moving a card to a foundation stack adds 10 points to the score
// (Requirement 4.2.0)
points += 10;
// If the card was drawn, remove card from drawn cards pile
if (drawnFoundation == 1) {
drawnCards.pop();
}
// If the card is in a tableau pile,
else {
// find which pile the card is in and remove the card from that
// pile.
int pile = findPile(card);
int cardIndex = layout[pile].lastIndexOf(card);
layout[pile].remove(cardIndex);
// find the index of the card directly above it in the tableau pile
int nextCardIndex = layout[pile].size() - 1;
// If the card exists, the card gets turned face up
if (nextCardIndex >= 0) {
revealNextCard(pile, nextCardIndex);
}
}
// Determine which foundation stack the chosen card should
// be placed into (spades, clubs, hearts, diamonds)
int[] result = findStack(card);
int stackNum = result[0];
// Places the chosen card into that stack
Stack<Integer> currentStack = foundationStacks[stackNum];
currentStack.push(card);
}
/*
* findStack() is called to determine which suit stack a card should be
* moved to from canMoveToFoundation() and moveToFoundation()
*/
static int[] findStack(int card) {
// Determine which foundation stack (spades, clubs, hearts, diamonds)
// the card should be placed into
// and the value of the ace for that suit
int stackNum = -1;
int ace = -1;
// spade
if (card < 13) {
stackNum = 0;
ace = 0;
}
// clubs
else if (card < 26) {
stackNum = 1;
ace = 13;
}
// hearts
else if (card < 39) {
stackNum = 2;
ace = 26;
}
// diamonds
else {
stackNum = 3;
ace = 39;
}
return new int[] { stackNum, ace };
}
/*
* pickACard() is called from playGame(choice) when the user picks a card.
* Returns {card, origin} or null. Origin is 0 for a tableau card, 1 for the
* waste top, and 2 for a foundation top. The destination is not chosen here.
*/
static int[] pickACard(String shortcutCard) {
HashMap<String, Integer> cardsAndCardNames = new HashMap<String, Integer>();
int firstCard = -1;
int drawnCard = -1;
ArrayList<Integer> foundationCards = new ArrayList<Integer>();
if (!drawnCards.empty()) {
int card = drawnCards.peek();
cardsAndCardNames.put(cards[card], card);
drawnCard = card;
}
for (int deck = 0; deck < layout.length; deck++) {
for (int cardIndex = 0; cardIndex < layout[deck].size(); cardIndex++) {
int card = layout[deck].get(cardIndex);
// Only face-up cards can be picked. A face-up card may head a run.
if (isFaceUp(card)) {
cardsAndCardNames.put(cards[card], card);
firstCard = card;
}
}
}
for (int checkStack = 0; checkStack < foundationStacks.length; checkStack++) {
if (!foundationStacks[checkStack].empty()) {
int card = foundationStacks[checkStack].peek();
cardsAndCardNames.put(cards[card], card);
foundationCards.add(card);
}
}
if (firstCard < 0 && drawnCard >= 0) {
firstCard = drawnCard;
}