I am making a set of minigames for my major project, have being following a tutorial on the internet to make a memory game for one of them.
The code works up to where I generate a new board but the rest of the code doesn't seem to work. Have I done something wrong in my scipting? Can anyone tell me where I'm going wrong?
This is my code for the memory minigame.
$(document).ready(function() {
//speech
var progress = 0;
var txt;
$('#complete, #speech').hide();
function eventHandler() {
switch (progress) {
case 0:
txt = "Complete";
break;
case 1:
txt = "Move on the the next game";
$('#speech').click(function() {
window.location.href = "minigame4.html"; //next minigame
});
break;
}
progress++;
$('#speech').html(txt);
}
$('#speech').click(eventHandler);
// Memory Game //
var memory_array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
//shuffle method
Array.prototype.memory_tile_shuffle = function() {
var i = this.length,
j, temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
//generate new board
function newBoard() {
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for (var i = 0; i < memory_array.length; i++) {
output += '<div id="tile_' + i + '" onclick="memoryFlipTile(this,\'' + memory_array[i] + '\')" class="tiles"></div>';
}
$('#memory_board').html(output);
}
newBoard();
//
// all code works up to here
function memoryFlipTile(tile, val) {
// When tile is clicked, change colour to white along with its letter
if (tile.html == "" && memory_values.length < 2) {
tile.style.background = '#FFF';
tile.html = val;
// If no tiles are flipped
if (memory_values.length == 0) {
memory_values.push(val);
memory_tile_ids.push(tile.id);
// If one tile is already flipped
} else if (memory_values.length == 1) {
memory_values.push(val);
memory_tile_ids.push(tile.id);
// See if both tiles are a match
if (memory_values[0] == memory_values[1]) {
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
// then display complete
if (tiles_flipped == memory_array.length) {
$("#complete").show(0, function() {
eventHandler()
$('#speech').show();
});
}
} else {
function flip2Back() {
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
tile_1.html = "";
tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
tile_2.html = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
});
div#memory_board {
padding: 24px;
margin: 0px auto;
width: 456px;
height: 300px;
}
div#memory_board div {
float: left;
margin: 10px;
padding: 28px;
font-size: 50px;
cursor: pointer;
text-align: center;
background-image: url(images/puzzle5/blank.png);
}
#complete {
position: absolute;
width: 105px;
height: 25px;
top: 240px;
left: 289px;
background-color: black;
color: white;
font-size: 20px;
padding: 10px;
border-style: solid;
border-width: 5px;
border-color: white;
z-index: 5;
}
#speech {
position: absolute;
width: 655px;
height: 100px;
top: 330px;
left: 15px;
background-color: black;
color: white;
font-size: 25px;
padding: 10px;
border-style: solid;
border-width: 5px;
border-color: white;
z-index: 99;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MAS340</title>
<link href="styles.css" rel="stylesheet" />
<script src="jquery-3.1.1.min.js"></script>
<script>
//javascript goes here
</script>
</head>
<body>
<div id="stage">
<div id="memory_board"></div>
</div>
</body>
</html>
Apart from mentioned changes by some users, there are also other changes required in your script. As you are already using jQuery why don't utilize it fully?
Also have attached the event using jQuery like below as I suspect its able to see the function defined in the script while putting elements in dom. (Not sure about reason though yet)
I have changed your code in below fiddle. please check if its work for you (just corrected the syntax and replace some javascript code with jquery)
$(document).on('click','.tiles',function(){
memoryFlipTile($(this),$(this).data("memchar"))
})
Check Fiddle
There is still a scope to optimize the code.
You have syntax errors in line 93 and 95. In addition, html should be innerHTML
Change
tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
tile_1.html = "";
tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
tile_2.html = "";
To
tile_1.style.['background-image'] = 'url(images/puzzle5/blank.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.['background-image'] = 'url(images/puzzle5/blank.png) no-repeat';
tile_2.innerHTML = "";
Related
I'm able to loop a function to display 5 random images. Now I want to use the same 5 images and shuffle them, where each image appears only once (giving 5! = 120 permutations).
I've found plenty of tips on how to shuffle and display random numbers (not images), but where I think my issue is is setting and then calling functions. How do I do that?
Assumptions:
Between my <style> tags I need to define my shuffle function
My array of images can remain as it is (since it's the same ones, clearly making sure to update any changed references form the new URL)
The shuffle function gets called in the body of my page (I'm not sure about this bit)
In simple English I'm trying to achieve:
"Take the five images in the collection and put them, once only, into any order."
What happens:
Five images appear, often images are repeated.
The successful webpage has this:
</style>
<script type="text/javascript">
// place your images in this array
var random_images_array = ['Weare.jpg', 'Always.jpg', 'There.jpg', 'For.jpg', 'You.jpg'];
function getRandomImage(imgAr, path) {
path = path || '../Public/images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
</script>
</head>
<body>
And then this (which is, I assume the calling of the function)
<div>
<!-- This script segment displays an image from the array -->
<script type="text/javascript">for (i = 0; i < 5; i++) getRandomImage(random_images_array, 'images/')</script>
</div>
How can I fix this?
The following shuffles an array of image URLs, and then adds those URLs as images to the DOM, one by one.
const $ = document.querySelector.bind(document)
function shuffle(arr) {
for (let curr = arr.length - 1; curr >= 0; --curr) {
const random = ~~(Math.random() * curr)
;[arr[random], arr[curr]] = [arr[curr], arr[random]]
}
return arr
}
function render(arr) {
let html = "";
for (let el of arr) {
html += img`${el}`
}
$("#images").innerHTML = html
}
function img(_, url) {
return `<img style="background:url(${url}); background-size:cover;"/>`
}
const arr = [
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX//wCKxvRFAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUA/wA0XsCoAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/AAAZ4gk3AAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg=="
]
$("button").addEventListener("click", () => render(shuffle(arr)))
render(shuffle(arr))
body {
font-family: sans-serif;
font-size: 0;
}
img {
display: inline-block;
width: 170px;
height: 60px;
box-shadow: 0 0 0 2px white inset;
padding: 0;
margin: 0;
}
button:focus { outline: none }
button {
font-size: 1rem;
border: none;
background: rgb(0, 200, 200);
border-radius: 5px;
cursor: pointer;
line-height: 40px;
height: 40px;
width: 340px;
padding: 0;
margin: 0;
color: white;
-webkit-user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
box-shadow: 0 0 0 2px white inset;
}
#images {
box-shadow: 0 0 0 2px silver inset;
width:340px;
height:120px;
}
<button>Shuffle!</button>
<section id="images"></section>
A kind commenter who deleted their answer gave me the following:
var random_images_array = ['Weare.jpg', 'Always.jpg', 'There.jpg', 'For.jpg', 'You.jpg'];
function shuffleArray(arr) {
for (var i = arr.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Shuffle images here
shuffleArray(random_images_array);
function getRandomImage(imgAr, path) {
path = path || '../Public/images/'; // default path here
for (var i = 0; i < imgAr.length; i++) {
var img = imgAr[i];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr);
document.close();
}
}
getRandomImage(random_images_array, 'images/')
And it worked! Thank you, mystery helper!
I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)
var pass = 'budi baj baj bastajpan';
var vpass = '';
var password = document.querySelector('#password-field');
function getPassword() {
vpass = Array.from(pass);
for (i = 0; i < vpass.length; i++) {
if (vpass[i] === ' ') {
vpass[i] = ' ';
} else {
vpass[i] = '_';
}
}
password.innerHTML = vpass;
addLetters();
}
var lettersField = document.querySelector('#letters');
var alfabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z'];
function addLetters() {
var letters = '';
for (i = 0; i < 25; i++) {
letters = letters + '<span class="letter" id="let' + i + '" onclick="checkLetter(' + i + ')">' + alfabet[i] + '</span>';
}
lettersField.innerHTML = letters;
}
function checkLetter(nr) {
passArr = Array.from(pass);
for (i = 0; i < 25; i++) {
if (passArr[i] == alfabet[nr]) {
document.querySelector("#let" + nr).style.background = "green";
vpass[i] = alfabet[nr];
password.innerHTML = vpass;
} else {
document.querySelector("#let" + nr).style.background = "red";
}
}
}
window.onload = getPassword;
/*
So, basically i know i probably made ton of mistakes but can u explain me why does this two rows:
vpass[i] = alfabet[nr];
password.innerHTML = vpass;
Work exactly as i want that means it only changes the password when i click on right letter.
But background changes to red whatever letter i click. (every style i put to ELSE work on every letter but styles in IF work fine.
*/
#game {
width: 600px;
height: 400px;
margin: 20px auto;
border: 3px solid green;
}
#password-field {
width: 100%;
height: 100px;
background: dimgray;
color: white;
box-sizing: border-box;
border-bottom: 2px solid white;
display: flex;
justify-content: center;
align-items: center;
}
#status {
width: 50%;
height: 300px;
background: lightgray;
position: relative;
left: 0;
box-sizing: border-box;
border-right: 1px solid white;
}
#letters {
width: 50%;
height: 300px;
background: lightgray;
position: relative;
left: 50%;
top: -300px;
box-sizing: border-box;
border-left: 1px solid white;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
.letter {
width: 40px;
height: 40px;
margin: 5px;
border: 1px solid white;
text-align: center;
line-height: 2;
border-radius: 10px;
font-size: 20px;
transition: .5s;
}
.letter:hover {
background: lightblue;
border-color: blue;
transition: none;
cursor: pointer;
}
<!DOCTYPE HTML>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>Ramphastos Toco</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="game">
<div id="password-field"></div>
<div id="status"></div>
<div id="letters"></div>
</div>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="main.js"></script>
</body>
</html>
var pass = 'budi baj baj bastajpan';
var vpass = '';
var password = document.querySelector('#password-field');
function getPassword() {
vpass = Array.from(pass);
for (i = 0; i < vpass.length; i++) {
if (vpass[i] === ' ') {
vpass[i] = ' ';
} else {
vpass[i] = '_';
}
}
password.innerHTML = vpass;
}
var lettersField = document.querySelector('#letters');
var alfabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z'];
function addLetters() {
var letters = '';
for (i = 0; i < 25; i++) {
letters = letters + '<span class="letter" id="let' + i + '" onclick="checkLetter(' + i + ')">' + alfabet[i] + '</span>';
}
lettersField.innerHTML = letters;
}
function checkLetter(nr) {
passArr = Array.from(pass);
for (i = 0; i < 25; i++) {
if (passArr[i] === alfabet[nr]) {
document.querySelector("#let" + nr).style.background = "green";
vpass[i] = alfabet[nr];
password.innerHTML = vpass;
} else {
document.querySelector("#let" + nr).style.background = "red";
}
}
}
Can u explain me why does this two rows:
vpass[i] = alfabet[nr];
password.innerHTML = vpass;
Work exactly as i want that means it only changes the password when i click on right letter.
But background changes to red whatever letter i click. (every style i put to ELSE work on every letter but styles in IF work fine).
Stackoverflow wants me to put some more details if i want to add snippet so i will just put some text cuz i dont know what more can i really say about...
I'm glad you edited your question a bit further, it was hard to understand.
Your problem is exacly the "for" loop.
You iterate through every letter of the password, so:
else {
document.querySelector("#let" + nr).style.background = "red";
}
Will always be executed for all the letters of the alphabet that don't match the letter of the password you're evaluating. And this will override any previously made match!
So, if the current letter you're evaluating is not a "z", the background will always be red!
My correction suggestion:
function checkLetter(nr) {
let flag=0;
passArr = Array.from(pass);
for (i = 0; i < 25; i++) {
if (passArr[i] === alfabet[nr]) {
document.querySelector("#let" + nr).style.background = "green";
flag=1; //if the letter is found, stop checking for the background
vpass[i] = alfabet[nr];
password.innerHTML = vpass;
} else {
if(flag==0)
document.querySelector("#let" + nr).style.background = "red";
}
}
}
EDIT:
Now the code uses a flag, to stop changing the background as soon as a letter is found. So the cycle runs the full way, but on the first letter found it switches the color to green. Otherwise, it will always be red.
There are a few issues with the code below. The original code was written by a gentleman named Adam Khoury, and I have tried to find him, but I am unable to do so. The code creates a visual memory game with letters 'A' through 'L'. I wanted to modify it to apply to fractions. So '1/4' and 25% would match. Or '33%' and '0.33' etc.
I am in way over my head. I am very rusty in javascript and while I understand most of what is happening, I am quite lost about how to make it work.
My solution was as follows. I added a new array "memory_array2" with corresponding values of fractions/decimals/percentages in pairs. I parse both memory_array and memory_array2 to the memoryFlipTile function. The idea was to "show" the second array, but use the values from the first array to match corresponding pairs.
I tried replacing "val" in line 55 with val2, and while that does replace the values in the board with array2, it a) creates them side by side, and b) even if the corresponding tiles are flipped, they do not stay flipped.
I also don't quite understand what the function of memory_values and memory_values.length is exactly.
I DO fully understand how the code clears arrays once two cards are flipped, checks to see if the board is cleared and creates a new board, and flips cards back if they do not match.
Your help would be greatly appreciated!
<!DOCTYPE html>
<html>
<head>
<style>
div#memory_board{
background:#CCC;
border:#999 1px solid;
width:795px;
height:340px;
padding:10px;
margin:0px auto;
}
div#memory_board > div{
background: url(tile_bg.jpg) no-repeat;
border:#000 1px solid;
width:90px;
height:43px;
float:left;
margin:10px;
padding:10px;
font-size:36px;
cursor:pointer;
text-align:center;
}
</style>
<script>
// Scripted By Adam Khoury in connection with the following video tutorial:
// http://www.youtube.com/watch?v=c_ohDPWmsM0
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J','K','K','L','L'];
var memory_array2 = ['13%','0.13','25%','1/4','1/3','0.33','0.7','70%','.5','1/2','1/8','12.5%','2/5','40%','3/4','75%','3/5','0.60','20%','0.20','1/10','10%','30%','0.30'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\',\''+memory_array2[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
}
function memoryFlipTile(tile,val,val2){
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = val;
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
alert("Board cleared... generating new board");
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flip2Back(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_bg.jpg) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_bg.jpg) no-repeat';
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
</script>
</head>
<body>
<div id="memory_board"></div>
<script>newBoard();</script>
<p id="test"></p>
</body>
</html>
Alright. What the game is currently doing is comparing string values such as 'E'=='E', however you are dealing with percentages/fractions/decimals.
You need to find a way to convert all these values to one type such that they can be compared with each other. Now that type of preference would be the decimal.
Now, what I am about to do it very dirty, and you should find a better way of doing it. I'm going to use eval[WARNING MAY BE HARMFUL] to covert the string '3/4' to 0.75.
I'm doing this because I'm lazy, but you could split the string by the / and divide the two parts against each other.
eval('3/4') == '0.75' //true
eval('3/4') === '0.75' //false
That solves our fraction issue. Now onto percentages. This code will convert from '50%' to 0.5:
parseFloat(('50%')/100.0; //0.5
I should only do this percentages, therefore I will check if each number is a percentage before doing that. That leaves us with this code:
function endsWith(str, suffix) { return str.slice(-suffix.length) === suffix }
if(endsWith(memory_values[0], '%')) {
memory_values[0] = parseFloat(memory_values[0])/100.0;
}
if(endsWith(memory_values[1], '%')) {
memory_values[1] = parseFloat(memory_values[1])/100.0;
}
Now, both our memory_values[0] and memory_values[1] are in either fraction form or decimal form.
Let us compare them(while evaling the fraction)
if(eval(memory_values[0]) == eval(memory_values[1])){
...
}
Here is the resulting, working code: http://pastebin.com/cwSjrsBD
And here it is as a website: https://dl.dropboxusercontent.com/u/182097009/working.html
Bug note: eval('1/3') != '0.33'
You will need to round your numbers.
I think some logic should be changed.
I see memory_array and memory_array2 as two different sets of memory.
The comparison method should not rely on the content of the memory, just for an example the set can contain some links to pictures, then no comparison can take place.
The order of the sets should be kept.
Only indices are used for shuffeling and for the comparing.
Comparing is done in its own function isCombination().
For better testing, I included an title attribute in every tile with the contained index.
At start, the function newBoard expect an array, which is used later, when called without any parameter.
// Scripted By Adam Khoury in connection with the following video tutorial:
// http://www.youtube.com/watch?v=c_ohDPWmsM0
var memory_array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L'],
memory_array2 = ['13%', '0.13', '25%', '1/4', '1/3', '0.33', '0.7', '70%', '.5', '1/2', '1/8', '12.5%', '2/5', '40%', '3/4', '75%', '3/5', '0.60', '20%', '0.20', '1/10', '10%', '30%', '0.30'],
memory_values = [],
memory_tile_ids = [],
tiles_flipped = 0,
actualMemory;
Array.prototype.getShuffledIndices = function () {
var indices = Array.apply(Array, { length: this.length }).map(function (_, i) { return i; }),
i = this.length, j, temp;
while (--i) {
j = Math.random() * i | 0;
temp = indices[j];
indices[j] = indices[i];
indices[i] = temp;
}
return indices;
}
function newBoard(memory) {
if (memory) {
actualMemory = memory;
}
tiles_flipped = 0;
document.getElementById('memory_board').innerHTML = actualMemory.getShuffledIndices().map(function (a) {
return '<div title="' + a + '" id="tile_' + a + '" onclick="memoryFlipTile(this, ' + a + ')"></div>';
}).join('');
}
function memoryFlipTile(tile, val) {
function isCombination(a, b) {
if (a + 1 === b || b + 1 === a) {
return (a + b - 1) % 4 === 0;
}
}
function flip2Back() {
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_bg.jpg) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_bg.jpg) no-repeat';
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
if (tile.innerHTML == "" && memory_values.length < 2) {
tile.style.background = '#FFF';
tile.innerHTML = actualMemory[val];
if (memory_values.length == 0) {
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if (memory_values.length == 1) {
memory_values.push(val);
memory_tile_ids.push(tile.id);
if (isCombination(memory_values[0], memory_values[1])) {
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if (tiles_flipped == memory_array.length) {
alert("Board cleared... generating new board");
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
setTimeout(flip2Back, 700);
}
}
}
}
// call with the wanted memory, in this case it is possible to select
// between memory_array and memory_array2
newBoard(memory_array2);
div#memory_board {
background: #CCC;
border: #999 1px solid;
width: 795px;
height: 340px;
padding: 10px;
margin: 0px auto;
}
div#memory_board > div {
background: url(tile_bg.jpg) no-repeat;
border: #000 1px solid;
width: 90px;
height: 43px;
float: left;
margin: 10px;
padding: 10px;
font-size: 36px;
cursor: pointer;
text-align: center;
}
<div id="memory_board"></div>
Hi I've got this code which is a memory board game. I would like to know if its possible to change the letters and put images instead. I am completely new to javaScript and I am trying to learn by editing and understanding open source code.. any help would be appreciated thanks!
This is the Javscript code:
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J','K','K','L','L'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
}
function memoryFlipTile(tile,val){
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = val;
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
alert("Board cleared... generating new board");
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flip2Back(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(images/logo.jpg) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(images/logo.jpg) no-repeat';
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
This is the HTML Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="memory_board"> </div>
<script> newBoard(); </script>
</body>
</html>
And finally this is the CSS code
div#memory_board{
background: #CCC;
border: #999 1px solid;
width: 800px;
height: 540px;
padding: 24px;
margin: 0px auto;
}
div#memory_board > div{
background: url(images/logo.jpg) no-repeat;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align:center;
}
Easy way to change your code to do what you want - instead of
tile.innerHTML = val;
do:
tile.innerHTML = '<img src="' + val + '.png"/>';
which should work if you have A.png, B.png and so on in the same location as index.html.
If you wanted to go more in-depth with it, I wrote a tutorial about doing this with an html5 framework some time ago (apologies for linking to our own website)