-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTable.java
More file actions
119 lines (107 loc) · 3.27 KB
/
Table.java
File metadata and controls
119 lines (107 loc) · 3.27 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
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.lang.Thread;
public class Table implements Runnable{
Player p1;
Player dealer;
ArrayList<Card> deck = new ArrayList<>();
String[] suits = new String[]{"Spades", "Diamonds", "Hearts", "Clubs"};
Random rand = new Random();
private Thread thr;
public void run() {
try{
while (true) {
if (p1.getScore() > 21 && p1.holdAce()){
for (int i = 0; i < p1.getCards().size(); i++){
if (p1.getCards().get(i).getNum() == 11){
p1.getCards().get(i).setNum(1);
}
}
}
if (dealer.getScore() > 21 && dealer.holdAce()){
for (int i = 0; i < dealer.getCards().size(); i++){
if (dealer.getCards().get(i).getNum() == 11){
dealer.getCards().get(i).setNum(1);
}
}
}
}
}catch(Exception e) {
}
}
public Table(String p1){
this.p1 = new Player(p1);
this.dealer = new Player("Dealer");
initDeck();
thr = new Thread(this);
thr.start();
}
//helper method
private void drawCard(Player p){
int cardIndex = rand.nextInt(deck.size());
Card card = deck.get(cardIndex);
p.addCard(card);
deck.remove(cardIndex);
if (deck.size() < 15){
initDeck();
}
}
private void initDeck(){
for (int s = 0; s < 4; s++){
for (int j = 0; j < 4; j++){
for (int i = 1; i <= 13; i++){
deck.add(new Card(i, suits[j]));
}
}
}
}
public void startGame(){
drawCard(p1);
drawCard(dealer);
drawCard(p1);
p1.displayCards();
dealer.displayCards();
drawCard(dealer);
}
public void play(Player p){
System.out.println("what would " + p.getName() + " like to do? (hit/stay)");
Scanner scan = new Scanner(System.in);
String move = scan.next();
while(p.getScore() < 21 && !move.equals("stay")){
while (!move.equals("hit") && !move.equals("stay")){
System.out.println("must input either hit or stay");
move = scan.next();
}
if (move.equals("stay")){
break;
}
drawCard(p);
p.displayCards();
}
scan.close();
}
private void dealerPlay(){
while(dealer.getScore() < 17){
drawCard(dealer);
}
}
public void checkWin(Player p1, Player p2){
if (p1.getScore() > p2.getScore()){
System.out.println(p1 + "wins!");
}
else System.out.println(p2 + "wins!");
}
//used to test
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Input player name:");
String name = scan.nextLine();
Table table = new Table(name);
table.startGame();
table.play(table.p1);
table.dealerPlay();
table.checkWin(table.p1, table.dealer);
scan.close();
}
}