Skip to content

Instantly share code, notes, and snippets.

@bufferings
Created January 4, 2015 23:43
Show Gist options
  • Select an option

  • Save bufferings/a6905ad1ac17f87b52f9 to your computer and use it in GitHub Desktop.

Select an option

Save bufferings/a6905ad1ac17f87b52f9 to your computer and use it in GitHub Desktop.
package janken;
import java.util.EnumMap;
public class じゃんけん {
public enum Result {
あいこ, 負け, 勝ち
}
public enum Hand {
グー, チョキ, パー
}
public interface Step1 {
Step2 自分の手(Hand myHand);
}
public interface Step2 {
Step3 相手の手(Hand yourHand);
}
public interface Step3 {
Result 勝負();
}
private static class Assert {
public static void assertNotNull(Object value, String message) {
if (value == null) {
throw new NullPointerException(message);
}
}
public static void should(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
private Assert() {
}
}
private static class ResultTable {
private EnumMap<Hand, EnumMap<Hand, Result>> table = new EnumMap<>(Hand.class);
public void put(Hand key1, Hand key2, Result value) {
Assert.assertNotNull(key1, "key1 is null.");
Assert.assertNotNull(key2, "key2 is null.");
Assert.assertNotNull(value, "value is null.");
EnumMap<Hand, Result> row = table.get(key1);
if (row == null) {
row = new EnumMap<>(Hand.class);
table.put(key1, row);
}
row.put(key2, value);
}
public Result get(Hand key1, Hand key2) {
Assert.assertNotNull(key1, "key1 is null.");
Assert.assertNotNull(key2, "key2 is null.");
return table.get(key1).get(key2);
}
}
private static class Battle implements Step1, Step2, Step3 {
private static ResultTable resultTable;
static {
resultTable = new ResultTable();
resultTable.put(Hand.グー, Hand.グー, Result.あいこ);
resultTable.put(Hand.グー, Hand.チョキ, Result.勝ち);
resultTable.put(Hand.グー, Hand.パー, Result.負け);
resultTable.put(Hand.チョキ, Hand.グー, Result.負け);
resultTable.put(Hand.チョキ, Hand.チョキ, Result.あいこ);
resultTable.put(Hand.チョキ, Hand.パー, Result.勝ち);
resultTable.put(Hand.パー, Hand.グー, Result.勝ち);
resultTable.put(Hand.パー, Hand.チョキ, Result.負け);
resultTable.put(Hand.パー, Hand.パー, Result.あいこ);
}
private Hand myHand;
private Hand yourHand;
@Override
public Step2 自分の手(Hand myHand) {
Assert.assertNotNull(myHand, "myHand is null.");
this.myHand = myHand;
return this;
}
@Override
public Step3 相手の手(Hand yourHand) {
Assert.assertNotNull(yourHand, "yourHand is null.");
this.yourHand = yourHand;
return this;
}
@Override
public Result 勝負() {
Assert.should(myHand != null, "myHand is null.");
Assert.should(yourHand != null, "yourHand is null.");
Result result = resultTable.get(myHand, yourHand);
Assert.should(result != null, "Result is not found.");
return result;
}
}
public static Step1 開始() {
return new Battle();
}
private じゃんけん() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment