I decided it would be interesting to simulate a game of Poker. Baby steps at the moment, and eventually I'll attempt to turn it into a GUI. The code I have so far is very basic such as populating a deck, shuffling the deck, and distributing two cards to a player. Trying to understand how inheritance works, the proper use of Java generics, and grasping the concept of how powerful/fun OOP can be. The Collections Framework is also something I'm beginning to experiment with.
I would really appreciate anything that will help me better understand Java.
import java.util.*;
class Deck {
// create possible card combinations
public final String[] SUITS = { "H", "D", "C", "S" };
public final String[] RANKS = { "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2" };
// maximum number of cards
public final int deckLength = SUITS.length * RANKS.length;
public List<String> fullDeck = new ArrayList<>();
public Deck() {
for(int i = 0; i < SUITS.length; i++) {
for(int j = 0; j < RANKS.length; j++) {
fullDeck.add(RANKS[j] + SUITS[i]);
}
}
}
public Deck(List<String> fullDeck) {
this.fullDeck = fullDeck;
for(int i = 0; i < SUITS.length; i++) {
for(int j = 0; j < RANKS.length; j++) {
fullDeck.add(RANKS[j] + SUITS[i]);
}
}
}
public List<String> shuffle(List<String> fullDeck) {
this.fullDeck = fullDeck;
Collections.shuffle(fullDeck);
return fullDeck;
}
// this was mainly used for testing purposes
// to ensure shuffling was indeed taking place
public void showDeck(List<String> fullDeck) {
this.fullDeck = fullDeck;
for(int i = 0; i < deckLength; i++) {
System.out.printf("%s ",fullDeck.get(i));
}
}
}
class Hands extends Deck {
public String[] hand = new String[2];
Random random = new Random();
// select 2 cards to distribute to player
public String[] getHand(List<String> fullDeck) {
super.fullDeck = fullDeck;
for(int i = 0; i < this.hand.length; i++) {
this.hand[i] = fullDeck.get(random.nextInt(super.deckLength));
}
return this.hand;
}
// show player hand
public void showHand() {
for(int i = 0; i < this.hand.length; i++) {
System.out.printf("%s ", this.hand[i]);
}
}
}
public class Cards {
public static void main(String[] args) {
List<String> cards = new ArrayList<>();
Deck deck = new Deck(cards);
deck.shuffle(cards);
Hands hands = new Hands();
hands.getHand(cards);
hands.showHand();
}
}
showDeck
should betoString
override instead. \$\endgroup\$getHand()
method should be in theDeck
class \$\endgroup\$