本文通過實現一個簡單的“石頭剪刀布”程序,熟悉Java枚舉類型(enum)多路分發的使用。
需要用到的類主要是以下四個:
- 遊戲主體RoShamBo:包括ROCK,SCISSORS,PAPER三種動作;
- 對戰結果Outcome:包括WIN,LOSE,DRAW三種對戰結果;
- 對戰接口Competitor:包括對戰方法compete();
- 邏輯驗證RoShamBoSample:隨機生成對戰數據,驗證對戰結果。
1,Outcome.java:
package com.sample.roshambo;
public enum Outcome {
WIN, LOSE, DRAW;
}
2,Competitor.java:package com.sample.roshambo;
public interface Competitor<T extends Competitor<T>> {
Outcome compete(T competitor);
}
3,RoShamBo.java:package com.sample.roshambo;
public enum RoShamBo implements Competitor<RoShamBo> {
ROCK(Outcome.DRAW, Outcome.WIN, Outcome.LOSE), SCISSORS(Outcome.LOSE, Outcome.DRAW, Outcome.WIN), PAPER(
Outcome.WIN, Outcome.LOSE, Outcome.DRAW);
private Outcome vsRock, vsScissors, vsPaper;
private RoShamBo(Outcome vsRock, Outcome vsScissors, Outcome vsPaper) {
this.vsRock = vsRock;
this.vsScissors = vsScissors;
this.vsPaper = vsPaper;
}
@Override
public Outcome compete(RoShamBo competitor) {
switch (competitor) {
default:
case ROCK:
return vsRock;
case SCISSORS:
return vsScissors;
case PAPER:
return vsPaper;
}
}
}
4,RoShamBoSample:
package com.sample.roshambo;
import java.util.Random;
public class RoShamBoSample {
private static final int MATCH_NUM = 10;
private static <T extends Enum<T>> T random(Class<T> enumClass) {
T[] values = enumClass.getEnumConstants();
if (values.length < 1) {
throw new IllegalArgumentException(enumClass.getSimpleName() + " has no constant");
}
return values[new Random().nextInt(values.length)];
}
private static <T extends Enum<RoShamBo> & Competitor<T>> Outcome match(T competitor1, T competitor2) {
Outcome outcome = competitor1.compete(competitor2);
System.out.println(competitor1 + " VS " + competitor2 + " : " + outcome);
return outcome;
}
public static void main(String[] args) {
for (int i = 0; i < MATCH_NUM; i++) {
RoShamBo roShamBo1 = random(RoShamBo.class);
RoShamBo roShamBo2 = random(RoShamBo.class);
match(roShamBo1, roShamBo2);
}
}
}
其中一次的驗證數據如下:SCISSORS VS SCISSORS : DRAW
PAPER VS SCISSORS : LOSE
PAPER VS ROCK : WIN
SCISSORS VS ROCK : LOSE
SCISSORS VS SCISSORS : DRAW
PAPER VS ROCK : WIN
PAPER VS PAPER : DRAW
PAPER VS ROCK : WIN
SCISSORS VS ROCK : LOSE
PAPER VS ROCK : WIN