スライドパズル(JSF) †JavaServer? Facesで4×4のスライドパズルを作成する。 import javax.inject.Named; import javax.enterprise.context.SessionScoped; import java.io.Serializable; import java.util.Random; import javax.annotation.PostConstruct; @Named(value = "puzzle") @SessionScoped public class Puzzle implements Serializable { private static final int SIZE = 4; private final int[][] blocks = new int[SIZE][SIZE]; private boolean finished; public Puzzle() { } // getter省略 private int get(int x, int y) { if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) { return -1; } return blocks[x][y]; } private void set(int x, int y, int value) { blocks[x][y] = value; } @PostConstruct public void shuffle() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { set(j, i, i * SIZE + j); } } Random r = new Random(); int x = 0; int y = 0; for (int i = 0; i < 1000; i++) { switch (r.nextInt(4)) { case 0: if (get(x - 1, y) > 0) { // 左 swap(x, y, x - 1, y); x = x - 1; } break; case 1: if (get(x + 1, y) > 0) { // 右 swap(x, y, x + 1, y); x = x + 1; } break; case 2: if (get(x, y - 1) > 0) { // 上 swap(x, y, x, y - 1); y = y - 1; } break; case 3: if (get(x, y + 1) > 0) { // 下 swap(x, y, x, y + 1); y = y + 1; } break; } } finished = false; } public void move(int x, int y) { if (!finished) { if (get(x - 1, y) == 0) { // 左 swap(x, y, x - 1, y); } else if (get(x + 1, y) == 0) { // 右 swap(x, y, x + 1, y); } else if (get(x, y - 1) == 0) { // 上 swap(x, y, x, y - 1); } else if (get(x, y + 1) == 0) { // 下 swap(x, y, x, y + 1); } if (checkFinished()) { finished = true; } } } private boolean checkFinished() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (get(j, i) != i * SIZE + j) { return false; } } } return true; } private void swap(int x1, int y1, int x2, int y2) { int v1 = get(x1, y1); int v2 = get(x2, y2); set(x1, y1, v2); set(x2, y2, v1); } } 続いて、パズルの画面をFaceletsで作成する。 #ref(): File not found: "sp1.jpg" at page "スライドパズル(JSF)" 各ピースを表に配置する。ピースとピースの間に隙間を作らないために、tableタグにcellpadding="0" cellspacing="0"を指定している。 <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"> <h:head> <title>スライドパズル</title> </h:head> <h:body> <h:form> <table cellpadding="0" cellspacing="0"> <c:forEach var="i" begin="0" end="3"> <tr> <c:forEach var="j" begin="0" end="3"> <td> <h:commandButton action="#{puzzle.move(j, i)}" image="image/pz#{(not puzzle.finished) and (puzzle.blocks[j][i] eq 0) ? 'bg' : puzzle.blocks[j][i]}.jpg" style="vertical-align:bottom"> <f:ajax render="@form"/> </h:commandButton> </td> </c:forEach> </tr> </c:forEach> </table> <h:commandButton value="シャッフル" action="#{puzzle.shuffle()}"> <f:ajax render="@form"/> </h:commandButton> </h:form> </h:body> </html> コメント † |