Skip to content

Instantly share code, notes, and snippets.

@hiroshi-cl
Last active December 18, 2015 05:49
Show Gist options
  • Save hiroshi-cl/5735466 to your computer and use it in GitHub Desktop.
Save hiroshi-cl/5735466 to your computer and use it in GitHub Desktop.
Dice library [Licence: NYSL Version 0.9982]
public class DiceBuilder {
private final boolean[][] dat = new boolean[6][4];
private final boolean[] visited = new boolean[6];
private static final String[] map = { "4...", "0123", "5..." };
private int si = 1, sj = 0;
public boolean[][] build(boolean[][] in) {
dfs(new DiceState(), si, sj, in);
return dat;
}
void dfs(DiceState ds, int i, int j, boolean[][] in) {
if (inRec(i, j) && map[i].charAt(j) != '.' && !visited[ds.cf]) {
visited[ds.cf] = true;
for (int d = 0; d < 4; d++)
dat[ds.cf][(ds.cd + d) % 4] = in[map[i].charAt(j) - '0'][d];
for (int d = 0; d < 4; d++)
dfs(ds.roll(d), i + di[d], j + dj[d], in);
}
}
private static final int[] di = { -1, 0, 1, 0 };
private static final int[] dj = { 0, -1, 0, 1 };
private static boolean inRec(int i, int j) {
return i >= 0 && j >= 0 && i < map.length && j < map[0].length();
}
}
public class DiceState {
private static final int[][] FM = { { 4, 5, 1, 2 }, { 4, 2, 1, 5 } };
private static final int[][] DR = { { 1, 3, 3, 3 }, { 3, 1, 1, 1 } };
// { 1, 2, 3, 6, 5, 4 } { U, L, D, R }
public final int cf, cd;
private DiceState(int cf, int cd) {
this.cf = cf;
this.cd = cd;
}
public DiceState() {
this(0, 0);
}
public DiceState roll(int d) {
int f = cf % 2;
int c = (cd + d) % 4;
return new DiceState((cf + FM[f][c]) % 6, (cd + DR[f][c]) % 4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment