Memory game
Posted: Fri Jan 09, 2009 7:16 am
Hi,
I'm currently coding a memory game to practise some JS. I got stuck pretty fast however and need some input to move forward.
Instead of using an html form I wanted to try using JS instead so clicking on an image displays the image randomly generated. I now need to:
1. When 2 images are displayed and dont' match, go back to default image (blank image).
2. When 2 images are displayed and match, OK, move forward.
Very simple things, but I'm not that savy with JS.
I've tried a couple of different solutions, but as the html code doesn't change I don't really know what to look for when validating my matches.
I'm currently coding a memory game to practise some JS. I got stuck pretty fast however and need some input to move forward.
Instead of using an html form I wanted to try using JS instead so clicking on an image displays the image randomly generated. I now need to:
1. When 2 images are displayed and dont' match, go back to default image (blank image).
2. When 2 images are displayed and match, OK, move forward.
Very simple things, but I'm not that savy with JS.
I've tried a couple of different solutions, but as the html code doesn't change I don't really know what to look for when validating my matches.
Code: Select all
<?php
/*
SPECS
- A grid on 4x3, 4x4 or 4x5 (12,16,20)
- 20 different icons.
- Match icons 2 and 2.
*/
class Memory {
public $icons = array();
function __Construct($grid_size) {
$this->grid_size = $grid_size;
$this->icons = $this->generateGrid();
}
public function displayGrid() {
for($i=0; $i<$this->grid_size; $i++) {
if($i%4 == 0) echo "<br />\n";
echo "<a href=\"#\" onclick=\"showIcon(".$this->icons[$i].", $i)\"><img src=\"./icons/icon_back.png\" id=\"icon".$i."\" width=\"32\" height=\"32\" alt=\"icon\" title=\"icon\" border=\"0\" /></a>\n";
}
}
public function generateGrid() {
$icons = range(1,20);
shuffle($icons);
$icons = array_slice($icons, 0, $this->grid_size / 2);
return array_merge($icons, $icons);;
}
}
//THE GAME
$m = new Memory(20);
print_r($m->icons);
?>
<html>
<head>
<title>Memory</title>
</head>
<body>
<?php $m->displayGrid(); ?>
<script type="text/javascript">
function showIcon(img, id) {
var image = document.getElementById("icon"+id);
image.src="./icons/"+img+".png";
}
</script>
</body>
</html>