Skip to content

Instantly share code, notes, and snippets.

@Charlie-robin
Last active October 4, 2023 08:45
Show Gist options
  • Save Charlie-robin/21eecc73c427cc8dcf0b98547355b6f8 to your computer and use it in GitHub Desktop.
Save Charlie-robin/21eecc73c427cc8dcf0b98547355b6f8 to your computer and use it in GitHub Desktop.
Basic snap logic
package org.example;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> computersDeck = new ArrayList<>(List.of("a", "b", "c"));
List<String> playersDeck = new ArrayList<>(computersDeck);
// Collections.shuffle(playersDeck); // COMMENTED TO FORCE A SNAP
String player = "";
String computer = "";
boolean isPlaying = true;
List<String> deckToDrawFrom = computersDeck;
String currentPlayer = "Computer";
Scanner scanner = new Scanner(System.in);
while (isPlaying) {
System.out.println("-----");
if (deckToDrawFrom.isEmpty()) {
System.out.println("Deck Empty :S");
break;
}
String cardDrawn = deckToDrawFrom.remove(0);
if (!computer.isEmpty()) {
System.out.println("Previous card : " + (currentPlayer.equals("Computer") ? player : computer));
}
System.out.println(currentPlayer + " Draws : " + cardDrawn);
System.out.println("Enter snap for a match or hit enter to draw your card?");
long startCount = new Date().getTime(); // GET TIMESTAMP BEFORE INPUT
String userInput = scanner.nextLine();
boolean snapMatch = computer.equals(cardDrawn) || player.equals(cardDrawn);
if (snapMatch && userInput.equals("snap")) {
long endCount = new Date().getTime(); // GET TIMESTAMP AFTER INPUT
long seconds = (endCount - startCount) / 1000; // CONVERT TO SECONDS
System.out.println("You took " + seconds + " seconds...");
String message = seconds < 2 ? "Player Wins" : "Computer Wins";
System.out.println(message);
isPlaying = false; // DOESNT HAVE TO END COULD LOOP AGAIN
} else if (snapMatch && !userInput.equals("snap")) {
System.out.println("You missed a snap....");
} else if (userInput.equals("snap")) {
System.out.println("Come on now, this is not snap....");
}
if (currentPlayer.equals("Computer")) { // SWITCH PLAYERS & TEMPORARY VARIABLES
currentPlayer = "Player";
deckToDrawFrom = playersDeck;
computer = cardDrawn;
} else {
currentPlayer = "Computer";
deckToDrawFrom = computersDeck;
player = cardDrawn;
}
}
System.out.println("-----");
System.out.println("Game over....");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment