Given the following code, how would I finish tileClick()
in order to change the clicked image from "tileBack.jpg" to instead show the image that was assigned to that specific div
in shuffleDeck()
? What I mean is, the tileClick()
function is supposed to take a tile that is currently showing the tileBack image, and, when clicked, show the image that is on the "reverse side" of that tile.
So far, you can see how I've tried to target the specific tile being clicked, though I'm uncertain this.
is being used correctly here. On the other side of that statement, I've tried to do things like = "../img/tile_"+tiles[i]+".png";
but obviously the issue there is that i
does not exist within that function's scope. My problem is that I can't figure out how to restructure my code so that I can access the image that was previously assigned to a given div
. For reference, the "other side" of the tiles are named as "tile_##.png" where '##' is a 2-digit number (01-12).
I am very new to JS and programming in general, so please keep your answers simple enough for me to understand and implement.
var deck = [];
var tiles = [];
var sources = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" ];
var images = [];
const WIDTH = 100;
const HEIGHT = 100;
const NUMTILES = 24;
loadImages();
buildDeck();
shuffleDeck(7);
printDeck();
function loadImages() {
for (var i = 0; i < sources.length; i++) {
images[i] = "../img/tile_"+sources[i]+".png";
}
}
function buildDeck() {
for (var i = 0; i < 2; i++) {
for (var j = 0; j < sources.length; j++) {
var tempTile = {};
tempTile.val = sources[j];
tempTile.img = images[j];
deck.push(tempTile);
}
}
}
function shuffleDeck (numTimes) {
for (var i = 0; i < numTimes; i++) {
for (var j = 0; j < deck.length; j++) {
var tempTile = deck[j];
var randI = j;
while ( randI == j ) {
randI = Math.floor(Math.random() * deck.length );
}
deck[j] = deck[randI];
deck[randI] = tempTile;
}
}
}
function printDeck() {
for (var i = 0; i < NUMTILES; i++) {
tiles[i] = document.getElementById("tile"+i);
console.log(deck[i].img);
tiles[i].style.backgroundImage = "../img/tileBack.jpg";
}
}
function tileClick() {
document.querySelector(".tile").addEventListener("mousedown", function () {
this.style.backgroundImage =
});
}
JS Fiddle link: http://jsfiddle.net/Leor6jqr/
Add the event listener and bind
the index to the calling event in your Deck printing.
function printDeck() {
for (var i = 0; i < NUMTILES; i++) {
tiles[i] = document.getElementById("tile"+i);
console.log(deck[i].img);
tiles[i].style.backgroundImage = "url('../img/tileBack.jpg')";
tiles[i].addEventListener("mousedown", tileClick.bind(this, i));
}
}
// *** Game Functions *** //
function tileClick(index) {
console.log('img', event, index, deck[index].img);
tiles[index].style.backgroundImage = "url('"+deck[index].img+"')";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With