Created
September 8, 2012 08:39
-
-
Save madan712/3672818 to your computer and use it in GitHub Desktop.
JSP page which generates Jigsaw puzzle with the help of javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@ page import="java.util.*"%> | |
<% | |
int row = 4; | |
int col = 3; | |
//List of images | |
ArrayList<String> allImages = new ArrayList<String>(); | |
for (int i = 0; i < row; i++) { | |
for (int j = 0; j < col; j++) { | |
if (i == (row - 1) && j == (col - 1)) | |
allImages.add("no_image");//add a blank location in last row last column | |
else | |
allImages.add("temp/TajMahal" + i + j + ".jpg"); | |
} | |
} | |
//shuffle the list to generate random puzzle every time | |
Collections.shuffle(allImages); | |
//to get the location of blank after shuffling | |
int iBlank = 0; | |
int jBlank = 0; | |
int in = 0; | |
OUTERLOOP: for (int i = 0; i < row; i++) { | |
for (int j = 0; j < col; j++) { | |
//if got the blank location, set iBlank, jBlank and break the loop | |
if (allImages.get(in).equals("no_image")) { | |
iBlank = i; | |
jBlank = j; | |
break OUTERLOOP; | |
} | |
in++; | |
} | |
} | |
%> | |
<html> | |
<head> | |
<title>Jigsaw Puzzle</title> | |
<script type="text/javascript"> | |
var iBlank = <%=iBlank%>; | |
var jBlank = <%=jBlank%>; | |
function slide(i,j,image) { | |
if(isValidMove(i,j,iBlank,jBlank)) { | |
//exchange the blank with the image | |
document.getElementById("id"+i+j).innerHTML = " "; | |
document.getElementById("id"+iBlank+jBlank).innerHTML = "<img src='"+image+"' onclick='slide("+iBlank+","+jBlank+",\""+image+"\");' />"; | |
iBlank = i; | |
jBlank = j; | |
} | |
}; | |
//only the adjacent image to the blank is valid to move | |
function isValidMove(x,y,xBlank,yBlank) { | |
if(x == xBlank || y == yBlank) { | |
if((xBlank - 1) == x || (xBlank + 1) == x || (yBlank - 1) == y || (yBlank + 1) == y) | |
return true; | |
else | |
return false; | |
} | |
else { | |
return false; | |
} | |
}; | |
</script> | |
</head> | |
<body> | |
<table border="1"> | |
<% | |
in = 0; | |
for (int i = 0; i < row; i++) { | |
%> | |
<tr> | |
<% | |
for (int j = 0; j < col; j++) { | |
%> | |
<td id="id<%=i%><%=j%>"> | |
<% | |
if (allImages.get(in).equals("no_image")) { | |
%> <% | |
} else { | |
%> <img src="<%=allImages.get(in)%>" | |
onclick="slide(<%=i%>,<%=j%>,'<%=allImages.get(in)%>');" /> <% | |
} | |
%> | |
</td> | |
<% | |
in++; | |
} | |
%> | |
</tr> | |
<% | |
} | |
%> | |
</table> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment