Reputation: 81
I am doing a fifteen puzzle game and I want that you only can click on a number next to the empty box, but now you can click everywhere...how to change this? I have thought that you can make an if- statement for columns and rows..
<!DOCTYPE html>
<html>
<head>
<title>The Fifteen Puzzle Game</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var currentBoard = new Array(' ','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
for(i=0 ; i++<100 ; x = Math.floor(Math.random()*16), y = Math.floor(Math.random()*16), currentBoard[x] = currentBoard.splice(y, 1, currentBoard[x])[0]);
repaint(); // Redraw puzzle board
//
// Funktion repaint()
// Redraw puzzle board
function repaint(){
currentString = "";
for(i=1;i<17;i++){
currentString += "<input type='button' id='" + i + "' value='" + currentBoard[i-1] + "' />";
if ( (i%4) == 0 ) currentString += "<br />";
}
$("#board").html(currentString);
}
function swapArrElems(index_a, index_b) {
var temp = currentBoard[index_a];
currentBoard[index_a] = currentBoard[index_b];
currentBoard[index_b] = temp;
}
$('#board').click(function(event){
current = $(event.target).attr("id")-1;
for(i=0;i<16;i++) if( currentBoard[i]==0 ) zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
});
});
</script>
<style>
input[type="button"] { width: 80px; height: 80px; font-size: 30px; }
</style>
</head>
<body>
<div id="board">
</div>
</body>
</html>
Upvotes: 3
Views: 1780
Reputation: 11
for (i = 0; i < 16; i++) {
if (currentBoard[i] == 0) {
if ((i - current) == 4 || (current - i) == 4 || (current - i) == 1 || (i - current) == 1) {
zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
}
}
}
Upvotes: 1
Reputation: 162
From the way I understood your code, you have 16 buttons id'ed by rows of 4. Each time a button is clicked, the array value of that button and the blank button swap. You're almost there. The detail that is the most important here is the button ID's, which stay the same throughout.
You need to add a comparison between the ID of the clicked button, and that of the blank button, which requires a conditional.
I'm not going to provide the code for you, because I don't want to just give away the answer. I'm going to give you the logic instead:
In your last function, after if( currentBoard[i]==0 ) zeroIndex = i;
**Else if** the id(clicked button) == id(blank button)-1. OR id(blank button)+1. OR
id(blank button)-4. OR id(blank button)+4 ........
Swap the elements.
Else
don't swap the elements.
Good luck! Hope this helps.
Upvotes: 2