Skip to content

Instantly share code, notes, and snippets.

@sonOfRa
Last active February 12, 2020 11:22
Show Gist options
  • Save sonOfRa/96a8e25f88d9c82f16dab98c0c1f8b64 to your computer and use it in GitHub Desktop.
Save sonOfRa/96a8e25f88d9c82f16dab98c0c1f8b64 to your computer and use it in GitHub Desktop.
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
/**
* This class uses a graph and the gestures given in the GestureType Enumeration
* to decide which gesture beats another one.
*
*
*/
public class Decider {
public enum Result {
WIN, DRAW, LOSS
}
/**
* The relations between gestures will be stored in a directed graph like
* the Paper-Scissors-Rock chart on this page:
* http://en.wikipedia.org/wiki/Rock-paper-scissors
*/
DirectedGraph<GestureType, DefaultEdge> graph;
/**
* Decides which gesture wins
*
* @param t1
* The first given Gesture
* @param t2
* The first given Gesture
* @return Result.WIN if t1 is winning against t2, Result.LOSS if t1 looses
* against t2, Result.WIN if t2 is GestureType.NONE, Result.LOSS if
* t1 is GestureType.NONE, Result.DRAW otherwise
*
*/
public Result decideWinner(GestureType t1, GestureType t2) {
// The result of equal gestures is a DRAW
if (t1 == t2)
return Result.DRAW;
// Handle empty (NONE) Gestures
if (t2 == GestureType.NONE)
return Result.WIN;
if (t1 == GestureType.NONE)
return Result.LOSS;
// If an Edge is directed from Gesture1 to Gesture2, it means that
// Gesture1 beats Gesture2. Return WIN in this case, LOSS otherwise.
if (this.graph.containsEdge(t1, t2)) {
return Result.WIN;
}
return Result.LOSS;
}
/**
* Constructor for the class. This method will create the graph.
*/
public Decider() {
this.graph = new DefaultDirectedGraph<GestureType, DefaultEdge>(
DefaultEdge.class);
// add the Gestures as Nodes/Vertices
this.graph.addVertex(GestureType.ROCK);
this.graph.addVertex(GestureType.PAPER);
this.graph.addVertex(GestureType.SCISSORS);
this.graph.addVertex(GestureType.LIZARD);
this.graph.addVertex(GestureType.SPOCK);
// Scissor beats paper/lizard
this.graph.addEdge(GestureType.SCISSORS, GestureType.PAPER);
this.graph.addEdge(GestureType.SCISSORS, GestureType.LIZARD);
// Paper beats Rock/Spock
this.graph.addEdge(GestureType.PAPER, GestureType.ROCK);
this.graph.addEdge(GestureType.PAPER, GestureType.SPOCK);
// Rock beats Scissors/Lizard
this.graph.addEdge(GestureType.ROCK, GestureType.SCISSORS);
this.graph.addEdge(GestureType.ROCK, GestureType.LIZARD);
// Lizard beats paper/Spock
this.graph.addEdge(GestureType.LIZARD, GestureType.PAPER);
this.graph.addEdge(GestureType.LIZARD, GestureType.SPOCK);
// Spock beats scissors/rock
this.graph.addEdge(GestureType.SPOCK, GestureType.SCISSORS);
this.graph.addEdge(GestureType.SPOCK, GestureType.ROCK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment