Last active
April 21, 2020 03:50
-
-
Save twh270/14fa26267b0702cf26ed9f85b46a1d4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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