Skip to content

Instantly share code, notes, and snippets.

@twh270
Last active April 21, 2020 03:50
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 twh270/14fa26267b0702cf26ed9f85b46a1d4b to your computer and use it in GitHub Desktop.
Save twh270/14fa26267b0702cf26ed9f85b46a1d4b to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class CardFlip {
static boolean DEBUG = false;
private enum CardValue {
A, B, C, D;
}
private static class Card {
final CardValue cardValue;
boolean flipped = false;
public Card(CardValue cardValue) {
this.cardValue = cardValue;
}
void setFlipped(boolean flipped) {
this.flipped = flipped;
}
boolean isFlipped() {
return flipped;
}
}
private final Card[] cards;
private int firstFlip = -1;
public boolean isGameOver() {
for (int i = 0; i < cards.length; i++) {
if (!cards[i].isFlipped()) {
return false;
}
}
return true;
}
// If the result of the flip is desired, add a FlipResult enum with values
// INVALID (< 0 || > n)
// FIRST_FLIP (1st card successfully flipped)
// ALREADY_FLIPPED (card is already flipped over)
// MATCH (the two selected cards matched)
// MISMATCH (the two selected cards did not match)
// SAME_CARD (tried to match with same card)
// Change this method to return a FlipResult
public void flip(int card) {
if (card < 0 || card > cards.length -1) {
return;
}
if (firstFlip == -1) {
firstFlip = card;
cards[firstFlip].setFlipped(true);
} else {
if (firstFlip != card && cards[firstFlip].cardValue == cards[card].cardValue) {
cards[card].setFlipped(true);
firstFlip = -1;
} else {
cards[firstFlip].setFlipped(false);
firstFlip = -1;
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Card card : cards) {
sb.append(card.isFlipped() ? card.cardValue.toString() : DEBUG ? card.cardValue.toString().toLowerCase() : '?');
}
return sb.toString();
}
public CardFlip(int sets) {
cards = new Card[sets * 4];
for (int i = 0; i < sets * 4; i++) {
cards[i] = new Card(CardValue.values()[i % 4]);
}
}
public static void main(String[] args) {
if (args.length > 0 && args[0].toLowerCase().equals("--debug")) {
CardFlip.DEBUG = true;
}
CardFlip theGame = new CardFlip(4);
Scanner scanner = new Scanner(System.in);
while (!theGame.isGameOver()) {
System.out.println(theGame.toString());
System.out.print("\nCard to flip> ");
theGame.flip(scanner.nextInt());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment