Skip to content

Instantly share code, notes, and snippets.

@jeffreymeng
Last active May 29, 2018 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffreymeng/1355b6387cb7cc11ded6e4eb506aa492 to your computer and use it in GitHub Desktop.
Save jeffreymeng/1355b6387cb7cc11ded6e4eb506aa492 to your computer and use it in GitHub Desktop.
package blackjack;
class Card {
public int number;//1 is ace, 2 is two, 13 is king
public int suit;//1 is club, 2 is diamond, 3 is heart, 4 is spade
public Card(int number, int suit) {//make a new card
this.number = number;
this.suit = suit;
}
}
package blackjack;
import java.util.Scanner;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
class Game {
public static void main(String[] args) {
ArrayList<Card> cards = new ArrayList<Card>();
ArrayList<Card> player1 = new ArrayList<Card>();
ArrayList<Card> player2 = new ArrayList<Card>();
for (int i = 0; i < 13; i ++) {
//loop through each number(0 is ace, 12 is king) and add a card of each suit to cards.
//cards.put adds the element to the end of the array
cards.add(new Card(i, 1));//club
cards.add(new Card(i, 2));//diamond
cards.add(new Card(i, 3));//heart
cards.add(new Card(i, 4));//spade
}
// more code here for the actual game...
// at this point, the card[] should contain all 52 cards in a deck, in random order
// To access the first element of card[], for example, you do card[0].number
// to get the number, and card[0].suit to get the suit.
// To get a word for the suit or number, you can create a static string array like
//["Clubs", "Diamonds", "Hearts", "Spades"] and get the nth element
// of that array, where N is the number of the suit
//EXAMPLE: shuffle the deck
shuffleArray(cards);
//EXAMPLE: to "deal" a card to a player:
//first, add the card to the player's "hand"
player1.add(cards.get(0));//cards.get(0) returns the zeroth element of the deck
//then, remove the first card from the deck, because it is now in someone's hand.
cards.remove(0);
//EXAMPLE: get the word for the suit and number of the first element of the array, and print it
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] numbers = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
//get the number first
String number = numbers[cards.get(0).number];
//then the suit
String suit = suits[cards.get(0).suit - 1];
//now print it
System.out.println("Your card is the " + number + " of " + suit + ".");
}
public static void shuffleArray(ArrayList<Card> array) {
Random random = ThreadLocalRandom.current();
for (int i = array.size() - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
// Simple swap
Collections.swap(array, index, i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment