This blog is created by Al Imran. Mobile:+8801721065582.
1 / 6
Now showing first image
2 / 6
Now showing second image
3 / 6
Now showing third image
4 / 6
Now showing first image
5 / 6
Now showing second image
6 / 6
Now showing third image

Game

How To Make A Simple Word Game:

From menubar in notepad++ select new from file menu.Next save as command from File menu.Then please give it a name in file name field e.g(Word Game.html).

Now you simply copy the code below & pase it in your Word Game.html.After that from run menu select any browser e.g launch in google crome

<html>

<head>
<style type="text/css">
  body
{
width: 100%;
margin: 0 auto;
padding: 0;
background-color: black;
}

.bubb

{
position: absolute;
width:30px;
height: 30px;
font: bold 14px verdana;
background-color: yellow;
text-align: center;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
vertical-align: middle;
padding: 5px;
}

#score

{
font-size:46px;
top: 25px;
right: 50px;
display: none;
text-align:right;
}

#start

{
width: 50px;
padding: 10px 15px;
text-align: center;
font:bold 15px arial;
background-color: #dedede;
color: #000;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
position: absolute;
}

#start:hover

{
cursor: pointer;
}

</style>

</head>
<body>
<div id="score">0</div>
<div id="start">Start</div>

<script type="text/javascript" src="js/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function()
{
// Getting screen resolutions and positioning the start button
var width = screen.width - 100;
var height = screen.height - 200;
var code = 0;
$('#start').css(
{
"top" : (height/2)+'px',
"left" : (width/2)+'px'
});

$('#start').click( function()

{
$(this).fadeOut('slow');
$('#score').show();
genLetter();
});

// Dealing KeyEvents and fading out matched bubble

$(document).keydown( function(event)
{
var keycode = event.keyCode;
$('.bubb'+keycode).animate(
{
"top" : height+"px", "opacity" : 0
}, 'slow');

$('.bubb'+keycode).fadeOut('slow').hide( 'slow', function()

{
code += 20;
$('#score').html(code);
$(this).remove();
}
);
});

// Generating a random alphabet between A-Z

function genLetter()
{
var color = randomColor();
var k = Math.floor(Math.random() * ( 90 - 65 + 1 )) + 65;
var ch = String.fromCharCode(k);
var top = Math.floor(Math.random() * height );
var left = Math.floor(Math.random() * width );
$('body').append('<span class="bubb bubb'+ k +'" style="left: '+ left +'; top: '+ top +'; background-color:'+ color +'">'+ ch +'</span>');
setTimeout(genLetter, 1000);
}

// Generating a random color

function randomColor()
{
var color = '';
var values = ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
for (c = 0; c < 6; c++)
{
no = Math.floor(Math.random() * 15);
color += values[no];
}
return color;
}
});
</script>
 </body>
</html>  

How To Make A Tetris Game :


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- cchd Sat, 4 Oct 2014 14:21:58 -0400 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A simple implementation of tetris using the HTML5 canvas with the option to change how new pieces are selected between random, evil, nice, or individual shapes." />
<meta name="author" content="Peter Coles" />
<title>Tetris</title>
<style>
#game-wrap {
margin: 20px 0;
border: 1px solid #ddd;
padding: 19px 20px 39px;
width: 91%;
background: #eee;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
-moz-box-shadow: 1px 1px 5px rgba(0, 0, 0, .2);
-webkit-box-shadow: 1px 1px 5px rgba(0, 0, 0, .2);
box-shadow: 1px 1px 5px rgba(0, 0, 0, .2);
}
#game { border: 2px solid #000; margin-right: 20px; background: #fff;}
html{color:#000;background:#fff;}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}
table{border-collapse:collapse;border-spacing:0;}
fieldset,img{border:0;}
address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}
li{list-style:none;}
caption,th{text-align:left;}
h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}
q:before,q:after{content:'';}
abbr,acronym{border:0;font-variant:normal;}
sup{vertical-align:text-top;}
sub{vertical-align:text-bottom;}
input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}
input,textarea,select{*font-size:100%;}
legend{color:#000;}
body,input,textarea,select{font:normal 14px/20px "Helvetica Neue",helvetica,arial,hirakakupro-w3,osaka,"ms pgothic",sans-serif;color:#333;-webkit-font-smoothing:antialiased;}
::selection{background:#ffc;}
::-moz-selection{background:#ffc;}
html{-webkit-text-size-adjust:none;}
a{color:#3681b3;text-decoration:none;}
a:hover{color:#265c80;}
a:active{color:#000;}
a:focus,input:focus,textarea:focus{outline:none;}
.strong,strong{font-weight:bold;}
.em,em{font-style:italic;}
.lost{letter-spacing:.5em;}
s,strike,del{text-decoration:line-through;}
.clr{overflow:hidden;zoom:1;}
.left{float:left;}
.right{float:right;}
.center-text,.text-center{text-align:center;}
.text-right{text-align:right;}
.br,.pad-bot{padding-bottom:20px;}
.br-top,.pad-top{padding-top:20px;}
.small{font-size:12px;}
.large{font-size:16px;}
.dim{color:#999;}
h1,h2{font-size:20px;line-height:25px;font-weight:bold;}h1.full,h2.full{line-height:40px;}h1.title{line-height:40px;padding-bottom:20px;}h3{font-size:16px;font-weight:bold;}h4{font-size:14px;font-weight:bold;}.prose ul,.prose ol{padding-left:20px;margin-bottom:20px;}.prose ul.no-disc{padding:0;margin:0;}.prose p,.prose h3,.prose h4{margin-bottom:20px;}.prose ul li{list-style:disc outside;}.prose ol li{list-style:decimal outside;}.prose ul.no-disc li{list-style:none;}.prose img.left{margin:0 15px 15px 0;}.prose img.right{margin:0 0 15px 15px;}blockquote{clear:both;padding:0 15px;margin-bottom:20px;background:#eee;-moz-border-radius:6px;-webkit-border-radius:6px;border-radius:6px;font-size:12px;}blockquote p{margin:0;padding:10px 0;}pre,code{font:normal 13px/20px consolas,monaco,courier,"courier new",fixed-width;color:#000;}strong code{font-weight:bold;}pre{clear:both;display:block;padding:17px 15px;margin-bottom:20px;background:#f3f3f3;border-top:1px solid #ccc;border-bottom:1px solid #ccc;overflow-x:auto;overflow-y:hidden;width:auto;}.comment>pre{font-size:12px;}.codehilite td.linenos{background-color:ccc;}ul.indent{padding-left:20px;}ul.activities{padding-top:10px;border-top:1px solid #f0f0f0;margin-top:9px;}ul.activities li{padding-bottom:9px;border-bottom:1px solid #f0f0f0;margin-bottom:10px;}#header,#content,#footer{position:relative;text-align:center;}#header-inner,#content-inner,#footer-inner{position:relative;margin:0 auto;padding:0 15px;max-width:830px;min-width:210px;text-align:left;}#header{border-bottom:2px solid #ddd;background:#f3f3f3;overflow:hidden;}#search-drop{display:block;height:0;position:absolute;top:0;right:0;width:330px;z-index:10;overflow:hidden;}#search-drop>div{position:relative;top:-60px;right:0;padding:10px;height:40px;background:#f3f3f3;border-radius:0 0 0 10px;-webkit-transition:top .4s ease;-moz-transition:top .4s ease;transition:top .4s ease;}body.show-nav #search-drop.show,#search-drop.show{height:60px;}body.show-nav #search-drop.show>div,#search-drop.show>div{top:0;}#search-drop input{float:left;height:27px;width:75%;margin-right:2%;}#search-drop button{float:left;width:23%;}@media(max-width:600px){#search-drop{width:100%;}#search-drop>div{border-radius:0;}}#header s{display:block;position:absolute;top:100px;left:-214px;height:75px;width:214px;background:transparent url(/media/img/sea-serpent-cutout.png) left top;-webkit-transition:.3s ease-in-out .3s;-moz-transition:.3s ease-in-out .3s;-o-transition:.3s ease-in-out .3s;transition:.3s ease-in-out .3s;}#header:hover s{left:0;top:0;}#content-inner{padding-top:20px;}#alpha,#beta,#gamma{position:relative;}body.blog #content-inner{padding-top:0;}body.blog #alpha{position:relative;float:left;width:600px;z-index:2;}body.blog #beta{position:relative;float:right;width:200px;}body.blog #beta .widget{position:relative;padding:20px 20px 19px;border-bottom:1px solid #ddd;margin-bottom:0;}body.blog #beta .widget.flush{padding-left:0;padding-right:0;}body.blog #beta .widget.last{padding-bottom:20px;border-bottom:0;}body.blog #beta .widget img{max-width:100%;}body.blog #beta .profile-img{height:60px;}body.blog #footer-inner p{padding-right:200px;}@media(max-width:850px){body.blog #footer-inner p{padding-right:0;}body.blog #alpha,body.blog #beta{float:none;width:auto;}body.blog #beta{margin-top:20px;padding-top:18px;border-top:2px solid #ddd;overflow:hidden;zoom:1;}}.shop-ad a{display:inline-block;color:#111;}.shop-ad a:hover{color:#265c80;}.shop-ad img{max-width:100%;-webkit-transition:all .3s ease-in-out;-moz-transition:all .3s ease-in-out;-o-transition:all .3s ease-in-out;}.shop-ad a:hover img{-webkit-transform:rotate(10deg);-moz-transform:rotate(10deg);-o-transform:rotate(10deg);}body.post_detail #alpha{padding-top:20px;}html,body{height:100%;}#wrapper{position:relative;min-height:100%;_height:100%;}#content{padding-bottom:100px;}#footer{height:100px;margin-top:-100px;background:url(sprite.png) repeat-x left 100px;}#footer-inner{clear:both;padding-top:60px;color:#aaa;text-align:center;}#logo{float:left;position:relative;margin:32px 0 0 0;font-size:40px;line-height:42px;font-weight:normal;word-spacing:-.25em;text-shadow:0 0 5px #f3f3f3;white-space:nowrap;}#logo a{color:#666;font-weight:100;}#logo a:hover,#logo a:active{text-decoration:none;}#sub-logo{color:#999;padding-left:10px;font-size:14px;word-spacing:0;white-space:nowrap;line-height:1;}@media(max-width:400px){#logo{font-size:28px;}#sub-logo{padding-left:5px;}}@media(max-width:315px){#logo{margin-top:14px;line-height:36px;}#sub-logo{display:block;padding-bottom:4px;line-height:20px;padding-left:0;}}#nav{position:relative;overflow:hidden;float:right;margin-top:50px;}#nav li{float:left;border-right:1px solid #ccc;padding:0 2px;}#nav li.last{border-right:0;padding-right:0;}#nav li a{display:inline-block;padding:0 3px;}.btn-navbar{display:none;float:right;padding:8px 10px;margin:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;background-color:#efefef;background-image:-moz-linear-gradient(top,#f9f9f9,#e0e0e0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f9f9),to(#e0e0e0));background-image:-webkit-linear-gradient(top,#f9f9f9,#e0e0e0);background-image:-o-linear-gradient(top,#f9f9f9,#e0e0e0);background-image:linear-gradient(to bottom,#f9f9f9,#e0e0e0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f9f9',endColorstr='#ffe0e0e0',GradientType=0);border-color:#f9f9f9 #f9f9f9 #e0e0e0;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);cursor:pointer;}.btn-navbar:hover,.btn-navbar:focus,.btn-navbar:active{background-color:#e0e0e0;}.btn-navbar:active{background-color:#c6c6c6;}.btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25);}.btn-navbar .icon-bar+.icon-bar{margin-top:3px;}@media(max-width:600px){#nav{float:none;clear:both;max-height:0;overflow:hidden;}body.show-nav #nav{max-height:600px;}#search-drop.show{height:0;}#search-drop.show>div{top:-60px;}#nav li{float:none;border:0;border-top:1px solid #ccc;}#nav li a{display:block;padding:10px 0;}.btn-navbar{display:block;float:right;margin-top:20px;}}.about-text h2,.about-text p{display:inline;font-size:14px;line-height:20px;}.post{position:relative;margin:0 0 20px;border-bottom:1px solid #ddd;padding:20px 0 35px;}.post .header{position:relative;padding-bottom:20px;overflow:hidden;zoom:1;}.post .date{position:relative;float:right;margin-left:15px;font-size:12px;color:#aaa;}body.post_detail .post .date{font-size:14px;line-height:25px;}.post .content{position:relative;zoom:1;}.post img.left{margin:0 15px 15px 0;}.post img.right{margin:0 0 15px 15px;}.post img{max-width:100%;}@media(max-width:400px){.post img.left,.post img.right{float:none;margin-left:0;margin-right:0;}}.other-posts{width:100%;overflow:hidden;}.post table{margin-bottom:20px;}.post td,.post th{padding-right:30px;}.pagination{overflow:hidden;zoom:1;}.widget{position:relative;margin:0 0 20px;}.widget .header{position:relative;padding-bottom:5px;border-bottom:1px solid #ccc;margin-bottom:12px;}.widget .content{position:relative;}.thumb-up,.thumb-dn{display:-moz-inline-box;display:inline-block;height:40px;width:40px;padding-right:10px;vertical-align:middle;background:url(../../img/thumb-up.png) no-repeat;}.thumb-dn{background-image:url(../../img/thumb-dn.png);}form{position:relative;display:block;}form .elt{margin-bottom:10px;}label{display:block;}input.text{display:table-cell;display:inline-block;position:relative;height:15px;line-height:15px;margin:6px 0;border:1px solid #bbb;padding:5px 7px 6px;vertical-align:middle;}button{display:-moz-inline-box;display:inline-block;position:relative;margin:6px 0;padding:0 12px;border:1px solid #bbb;height:26px;*height:28px;width:auto;overflow:visible;font-family:"Helvetica Neue",helvetica,arial,sans-serif;font-size:13px;line-height:26px;text-align:center;color:#111;text-decoration:none;white-space:nowrap;cursor:pointer;vertical-align:middle;background:#ddd;background:-moz-linear-gradient(center top,#fafafa 0,#ddd 100%) repeat-x 0 0;background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#fafafa),color-stop(100%,#ddd)) repeat-x 0 0;background:linear-gradient(top,#fafafa 0,#ddd 100%);-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;-khtml-box-sizing:content-box;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-khtml-appearance:none;-moz-appearance:none;}button::-moz-focus-inner{padding:0;border:0;}>button{padding-top:1px;height:25px;line-height:25px;}input.border-box,button.border-box{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;}input.border-box{height:28px;}button.border-box{height:28px;}textarea{font-size:14px;line-height:20px;height:60px;margin:4px 0;border:1px solid #bbb;padding:4px 7px;}.comments-form .elt input{width:250px;}.comments-form .elt textarea{height:120px;width:584px;}.comments-form .elt .label{display:block;overflow:hidden;zoom:1;color:#666;}.comments-form .elt label{display:inline;font-weight:bold;}.comments-form .elt .helptext{font-size:12px;}#disqus_thread{margin-top:40px;}#comments{padding-top:20px;margin-bottom:60px;}.comment{display:block;margin-bottom:20px;padding:10px 20px;width:auto;overflow:hidden;}.comment h5{padding-bottom:10px;}.comment p{font-size:12px;margin-bottom:20px;}.comment p code{font-size:12px;}.comment .date{margin-bottom:10px;font-size:12px;color:#666;}.odd{background-color:#f3f3f3;}.errorlist{font-size:12px;color:#c6401b;}a.bookmarklet,a.button{display:-moz-inline-box;display:inline-block;padding:1px 6px;height:18px;color:#fff;background:#32a0eb;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}a.button{background:#db5f14;}a.button:hover{background:#cc5814;}body.post_search h1{padding-right:10px;}#search-container{max-width:330px;}#search-container #search{float:left;width:80%;margin-right:1%;}#search-container button{float:left;width:19%;}.codehilite .hll{background-color:#ffc;}.codehilite .c{color:#bf5902;font-style:italic;}.codehilite .err{color:#a40000;border:1px solid #ef2929;}.codehilite .g{color:#000;}.codehilite .k{color:#204a87;font-weight:bold;}.codehilite .l{color:#000;}.codehilite .n{color:#000;}.codehilite .o{color:#000;}.codehilite .x{color:#000;}.codehilite .p{color:#000;}.codehilite .cm{color:#bf5902;font-style:italic;}.codehilite .cp{color:#bf5902;font-style:italic;}.codehilite .c1{color:#bf5902;font-style:italic;}.codehilite .cs{color:#bf5902;font-style:italic;}.codehilite .gd{color:#a40000;}.codehilite .ge{color:#000;font-style:italic;}.codehilite .gr{color:#ef2929;}.codehilite .gh{color:#000080;font-weight:bold;}.codehilite .gi{color:#00A000;}.codehilite .go{color:#000;font-style:italic;}.codehilite .gp{color:#bf5902;}.codehilite .gs{color:#000;font-weight:bold;}.codehilite .gu{color:#800080;font-weight:bold;}.codehilite .gt{color:#a40000;font-weight:bold;}.codehilite .kc{color:#204a87;font-weight:bold;}.codehilite .kd{color:#204a87;font-weight:bold;}.codehilite .kn{color:#204a87;font-weight:bold;}.codehilite .kp{color:#204a87;font-weight:bold;}.codehilite .kr{color:#204a87;font-weight:bold;}.codehilite .kt{color:#204a87;font-weight:bold;}.codehilite .ld{color:#000;}.codehilite .m{color:#000;}.codehilite .s{color:#109a06;}.codehilite .na{color:#c4a000;}.codehilite .nb{color:#204a87;}.codehilite .nc{color:#000;}.codehilite .no{color:#000;}.codehilite .nd{color:#003;font-weight:bold;}.codehilite .ni{color:#ce5c00;}.codehilite .ne{color:#c00;font-weight:bold;}.codehilite .nf{color:#000;}.codehilite .nl{color:#f57900;}.codehilite .nn{color:#000;}.codehilite .nx{color:#000;}.codehilite .py{color:#000;}.codehilite .nt{color:#204a87;font-weight:bold;}.codehilite .nv{color:#000;}.codehilite .ow{color:#204a87;font-weight:bold;}.codehilite .w{color:#f8f8f8;text-decoration:underline;}.codehilite .mf{color:#0000cf;font-weight:bold;}.codehilite .mh{color:#0000cf;font-weight:bold;}.codehilite .mi{color:#0000cf;}.codehilite .mo{color:#0000cf;font-weight:bold;}.codehilite .sb{color:#109a06;}.codehilite .sc{color:#109a06;}.codehilite .sd{color:#bf5902;font-style:italic;}.codehilite .s2{color:#109a06;}.codehilite .se{color:#109a06;}.codehilite .sh{color:#109a06;}.codehilite .si{color:#109a06;}.codehilite .sx{color:#109a06;}.codehilite .sr{color:#109a06;}.codehilite .s1{color:#109a06;}.codehilite .ss{color:#109a06;}.codehilite .bp{color:#3465a4;}.codehilite .vc{color:#000;}.codehilite .vg{color:#000;}.codehilite .vi{color:#000;}
.codehilite .il{color:#0000cf;font-weight:bold;}
</style>
<link rel="SHORTCUT ICON" href="/media/img/favicon.ico" />

<!-- start Mixpanel --><script type="text/javascript">(function(f,b){if(!b.__SV){var a,e,i,g;window.mixpanel=b;b._i=[];b.init=function(a,e,d){function f(b,h){var a=h.split(".");2==a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(Array.prototype.slice.call(arguments,0)))}}var c=b;"undefined"!==typeof d?c=b[d]=[]:d="mixpanel";c.people=c.people||[];c.toString=function(b){var a="mixpanel";"mixpanel"!==d&&(a+="."+d);b||(a+=" (stub)");return a};c.people.toString=function(){return c.toString(1)+".people (stub)"};i="disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" ");

for(g=0;g<i.length;g++)f(c,i[g]);b._i.push([a,e,d])};b.__SV=1.2;a=f.createElement("script");a.type="text/javascript";a.async=!0;a.src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js";e=f.getElementsByTagName("script")[0];e.parentNode.insertBefore(a,e)}})(document,window.mixpanel||[]);
mixpanel.init("ea3eaa7cb3103da36d6cba3105ce1722");</script><!-- end Mixpanel -->
</head>
<body class="blog tetris">
<div id="wrapper">
<div id="header"><s></s><div id="header-inner">
</div></div>
<div id="content"><div id="content-inner">

<div id="alpha">

<div id="game-wrap">
<div class="prose">
<h1>Tetris</h1>
<p>
A simple tetris implementation—using the HTML5 canvas element—that lets you choose from different
modes for selecting the next piece. You might have the most fun with “nice” and “evil”.
Also, “autopilot” can be fun to watch.
</p>
</div>
<div class="clr">
<canvas width="200" height="400" id="game" class="left">If you can read this, your browser doesn't support the canvas element. Please upgrade to a better browser.</canvas>
<canvas width="100" height="450" id="info" class="left"></canvas>
</div>
<p>
Move the shapes with the arrow keys. Rotate piece with the up key,
<strong>z</strong>, and <strong>x</strong>. Pause the game with <strong>p</strong>
and toggle autopilot mode with the back tick (the key that has <strong>~</strong> on it).
</p>
</div>


<!-- jquery.min.js -->

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="jquery-1.4.4.min.js"%3E%3C/script%3E'))</script>
<!-- Tetris.js -->
<script>
$.fn.safekeypress = function(func, cfg) {

    cfg = $.extend({

        stopKeys: {37:1, 38:1, 39:1, 40:1}
    }, cfg);

    function isStopKey(evt) {

        var isStop = (cfg.stopKeys[evt.keyCode] || (cfg.moreStopKeys && cfg.moreStopKeys[evt.keyCode]));
        if (isStop) evt.preventDefault();
        return isStop;
    }

    function getKey(evt) { return 'safekeypress.' + evt.keyCode; }


    function keypress(evt) {

        var key = getKey(evt),
            val = ($.data(this, key) || 0) + 1;
        $.data(this, key, val);
        if (val > 0) return func.call(this, evt);
        return isStopKey(evt);
    }

    function keydown(evt) {

        var key = getKey(evt);
        $.data(this, key, ($.data(this, key) || 0) - 1);
        return func.call(this, evt);
    }

    function keyup(evt) {

        $.data(this, getKey(evt), 0);
        return isStopKey(evt);
    }

    return $(this).keypress(keypress).keydown(keydown).keyup(keyup);

};


var getNiceShapes = function(shapeFactory, undefined) {

    /*
     * Things I need for this to work...
     *  - ability to test each shape with filled data
     *  - maybe give empty spots scores? and try to maximize the score?
     */

    var shapes = {},

        attr;

    for (attr in shapeFactory) {

        shapes[attr] = shapeFactory[attr]();
    }

    function scoreBlocks(possibles, blocks, x, y, filled, width, height) {

        var i, len=blocks.length, score=0, bottoms = {}, tx, ty, overlaps;

        // base score

        for (i=0; i<len; i+=2) {
            score += possibles[filled.asIndex(x + blocks[i], y + blocks[i+1])] || 0;
        }

        // overlap score -- //TODO - don't count overlaps if cleared?

        for (i=0; i<len; i+=2) {
            tx = blocks[i];
            ty = blocks[i+1];
            if (bottoms[tx] === undefined || bottoms[tx] < ty) {
                bottoms[tx] = ty;
            }
        }
        overlaps = 0;
        for (tx in bottoms) {
            tx = parseInt(tx);
            for (ty=bottoms[tx]+1, i=0; y+ty<height; ty++, i++) {
                if (!filled.check(x + tx, y + ty)) {
                    overlaps += i == 0 ? 2 : 1; //TODO-score better
                    //if (i == 0) overlaps += 1;
                    break;
                }
            }
        }

        score = score - overlaps;


        return score;

    }

    function resetShapes() {

        for (var attr in shapes) {
            shapes[attr].x = 0;
            shapes[attr].y = -1;
        }
    }

    //TODO -- evil mode needs to realize that overlap is bad...

    var func = function(filled, checkCollisions, width, height, mode, _one_shape) {
        if (!_one_shape) resetShapes();

        var possibles = new Array(width * height),

            evil = mode == 'evil',
            x, y, py,
            attr, shape, i, blocks, bounds,
            score, best_shape, best_score = (evil ? 1 : -1) * 999, best_orientation, best_x,
            best_score_for_shape, best_orientation_for_shape, best_x_for_shape;

        for (x=0; x<width; x++) {

            for (y=0; y<=height; y++) {
                if (y == height || filled.check(x, y)) {
                    for (py=y-4; py<y; py++) {
                        possibles[filled.asIndex(x, py)] = py; //TODO - figure out better scoring?
                    }
                    break;
                }
            }
        }

        // for each shape...

        var opts = _one_shape === undefined ? shapes : {cur: _one_shape}; //BOO
        for (attr in opts) { //TODO - check in random order to prevent later shapes from winning
            shape = opts[attr];
            best_score_for_shape = -999;

            // for each orientation...

            for (i=0; i<(shape.symmetrical ? 2 : 4); i++) { //TODO - only look at unique orientations
                blocks = shape.getBlocks(i);
                bounds = shape.getBounds(blocks);

                // try each possible position...

                for (x=-bounds.left; x<width - bounds.width; x++) {
                    for (y=-1; y<height - bounds.bottom; y++) {
                        if (checkCollisions(x, y + 1, blocks, true)) {
                            // collision
                            score = scoreBlocks(possibles, blocks, x, y, filled, width, height);
                            if (score > best_score_for_shape) {
                                best_score_for_shape = score;
                                best_orientation_for_shape = i;
                                best_x_for_shape = x;
                            }
                            break;
                        }
                    }
                }
            }

            if ((evil && best_score_for_shape < best_score) ||

                (!evil && best_score_for_shape > best_score)) {
                best_shape = shape;
                best_score = best_score_for_shape;
                best_orientation = best_orientation_for_shape;
                best_x = best_x_for_shape;
            }
        }

        best_shape.best_orientation = best_orientation;

        best_shape.best_x = best_x;

        return best_shape;

    };

    func.no_preview = true;

    return func;
};


var undefined;

if (1) {
//(function(window, document, undefined) {

    var canvas = document.getElementById('game'),

        ctx = canvas.getContext('2d'),
        info_canvas = document.getElementById('info'),
        info_ctx = info_canvas.getContext('2d'),
        WIDTH = 10,
        HEIGHT = 20,
        PIXEL_WIDTH = $(canvas).width(),
        PIXEL_HEIGHT = $(canvas).height(),
        block_size = Math.ceil(PIXEL_WIDTH / WIDTH),
        bevel_size = Math.floor(block_size / 10),
        border_width = 2;

    function randInt(a, b) { return a + Math.floor(Math.random() * (1 + b - a)); }

    function randSign() { return randInt(0, 1) * 2 - 1; }
    function randChoice(choices) { return choices[randInt(0, choices.length-1)]; }

    function drawBlock(x, y, color, _ctx) {

        // convert x and y to pixel
        _ctx = _ctx || ctx;
        x = x * block_size;
        y = y * block_size;
        _ctx.fillStyle = color;
        _ctx.globalAlpha = .5;
        _ctx.fillRect(x, y, block_size, block_size);
        _ctx.globalAlpha = .5;
        _ctx.fillRect(x + bevel_size, y + bevel_size, block_size - 2*bevel_size, block_size - 2*bevel_size);
        _ctx.globalAlpha = 1;
    }

    function Shape(orienations, color, symmetrical) {


        $.extend(this, {

            x: 0,
            y: 0,
            symmetrical: symmetrical,
            init: function() {
                $.extend(this, {
                    orientation: 0,
                    x: Math.floor(WIDTH / 2) - 1,
                    y: -1
                });
                return this;
            },
            color: color,
            blocksLen: orienations[0].length,
            orientations: orienations,
            orientation: 0, // 4 possible
            rotate: function(right) {
                var orientation = (this.orientation + (right ? 1 : -1) + 4) % 4;

                //TODO - when past limit - auto shift and remember that too!

                if (!checkCollisions(this.x, this.y, this.getBlocks(orientation)))
                    this.orientation = orientation;
            },
            moveRight: function() {
                if (!checkCollisions(this.x + 1, this.y, this.getBlocks()))
                    this.x++;
            },
            moveLeft: function() {
                if (!checkCollisions(this.x - 1, this.y, this.getBlocks()))
                    this.x--;
            },
            getBlocks: function(orientation) { // optional param
                return this.orientations[orientation !== undefined ? orientation : this.orientation];
            },
            draw: function(drop, _x, _y, _orientation, _ctx) {
                if (drop) this.y++;

                var blocks = this.getBlocks(_orientation),

                    x = _x === undefined ? this.x : _x,
                    y = _y === undefined ? this.y : _y,
                    i = 0;
                for (; i<this.blocksLen; i += 2) {
                    drawBlock(x + blocks[i], y + blocks[i+1], this.color, _ctx);
                }
            },
            getBounds: function(_blocks) { // _blocks can be an array of blocks, an orientation index, or undefined
                var blocks = $.isArray(_blocks) ? _blocks : this.getBlocks(_blocks),
                    i=0, len=blocks.length, minx=999, maxx=-999, miny=999, maxy=-999;
                for (; i<len; i+=2) {
                    if (blocks[i] < minx) minx = blocks[i];
                    if (blocks[i] > maxx) maxx = blocks[i];
                    if (blocks[i+1] < miny) miny = blocks[i+1];
                    if (blocks[i+1] > maxy) maxy = blocks[i+1];
                }
                return {
                    left: minx,
                    right: maxx,
                    top: miny,
                    bottom: maxy,
                    width: maxx - minx,
                    height: maxy - miny
                };
            }
        });

        return this.init();

    };

    var shapeFactory = {

        line: function() {
            /*
             *   X        X
             *   O  XOXX  O XOXX
             *   X        X
             *   X        X
             */
            var ver = [0, -1, 0, -2, 0, -3, 0, -4],
            hor = [-1, -2, 0, -2, 1, -2, 2, -2];
            return new Shape([ver, hor, ver, hor], '#f90', true);
        },
        square: function() {
            /*
             *  XX
             *  XX
             */
            var s = [0, 0, 1, 0, 0, -1, 1, -1];
            return new Shape([s, s, s, s], 'red', true);
        },
        arrow: function() {
            /*
             *    X   X       X
             *   XOX  OX XOX XO
             *        X   X   X
             */
            return new Shape([
                [0, -1, 1, -1, 2, -1, 1, -2],
                [1, -2, 1, -1, 1, 0, 2, -1],
                [0, -1, 1, -1, 2, -1, 1, 0],
                [0, -1, 1, -1, 1, -2, 1, 0]
            ], 'yellow');
        },
        rightHook: function() {
            /*
             *       XX   X X
             *   XOX  O XOX O
             *   X    X     XX
             */
            return new Shape([
                [0, 0, 0, -1, 1, -1, 2, -1],
                [0, -2, 1, 0, 1, -1, 1, -2],
                [0, -1, 1, -1, 2, -1, 2, -2],
                [0, -2, 0, -1, 0, 0, 1, 0]
            ], 'blue');
        },
        leftHook: function() {
            /*
             *        X X   XX
             *   XOX  O XOX O
             *     X XX     X
             */
            return new Shape([
                [2, 0, 0, -1, 1, -1, 2, -1],
                [0, 0, 1, 0, 1, -1, 1, -2],
                [0, -2, 0, -1, 1, -1, 2, -1],
                [0, 0, 0, -1, 0, -2, 1, -2]
            ], 'purple');
        },
        leftZag: function() {
            /*
             *        X
             *   XO  OX
             *    XX X
             */
            var ver = [0, 0, 0, -1, 1, -1, 1, -2],
                hor = [0, -1, 1, -1, 1, 0, 2, 0];
            return new Shape([hor, ver, hor, ver], 'gray', true);
        },
        rightZag: function() {
            /*
             *       X
             *    OX OX
             *   XX   X
             */
            var ver = [0, -2, 0, -1, 1, -1, 1, 0],
                hor = [0, 0, 1, 0, 1, -1, 2, -1];
            return new Shape([hor, ver, hor, ver], 'green', true);
        }

    };


    var shapeFuncs = [];

    $.each(shapeFactory, function(k,v) { shapeFuncs.push(v); });

    var filled = {

        data: new Array(WIDTH * HEIGHT),
        toClear: {},
        check: function(x, y) {
            return this.data[this.asIndex(x, y)];
        },
        add: function(x, y, color) {
            if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT)
                this.data[this.asIndex(x, y)] = color;
        },
        asIndex: function(x, y) {
            return x + y*WIDTH;
        },
        asX: function(index) {
            return index % WIDTH;
        },
        asY: function(index) {
            return Math.floor(index / WIDTH);
        },
        _popRow: function(row_to_pop) {
            for (var i=WIDTH*(row_to_pop+1) - 1; i>=0; i--) {
                this.data[i] = (i >= WIDTH ? this.data[i-WIDTH] : undefined);
            }
        },
        checkForClears: function() {
            var rows = [], i, len, count, mod;

            for (i=0, len=this.data.length; i<len; i++) {

                mod = this.asX(i);
                if (mod == 0) count = 0;
                if (this.data[i] && typeof this.data[i] == 'string') {
                    count += 1;
                }
                if (mod == WIDTH - 1 && count == WIDTH) rows.push(this.asY(i));
            }

            for (i=0, len=rows.length; i<len; i++) {

                this._popRow(rows[i]);
                board.lines++;
                if (board.lines % 10 == 0 && board.dropDelay > 1) board.dropDelay -= 2;
            }
        },
        draw: function() {
            for (var i=0, len=this.data.length, row, color; i<len; i++) {
                if (this.data[i] !== undefined) {
                    row = this.asY(i);
                    color = this.data[i];
                    drawBlock(this.asX(i), row, color);
                }
            }
        }
    };

    function checkCollisions(x, y, blocks, checkDownOnly) {

        // x & y should be aspirational values
        var i = 0, len = blocks.length, a, b;
        for (; i<len; i += 2) {
            a = x + blocks[i];
            b = y + blocks[i+1];

            if (b >= HEIGHT || filled.check(a, b)) {

                return true;
            } else if (!checkDownOnly && a < 0 || a >= WIDTH) {
                return true;
            }
        }
        return false;
    }

    var niceShapes = getNiceShapes(shapeFactory);


    var board = {

        animateDelay: 50,
        cur: null,

        lines: 0,


        dropCount: 0,

        dropDelay: 24, //5,

        init: function() {

            this.cur = this.nextShape();

            ctx.font = 'bold 30px/40px "lucida grande",helvetica,arial';

            ctx.fillStyle = '#333';
            ctx.fillText(' Click', 50, 120);
            ctx.fillText('to start', 50, 160);

            var start = [], colors = [], i, ilen, j, jlen, color;


            for (i in shapeFactory) {

                colors.push(shapeFactory[i]().color);
            }

            for (i=0, ilen=WIDTH; i<ilen; i++) {

                for (j=0, jlen=randChoice([randInt(0, 8), randInt(5, 9)]); j<jlen; j++) {
                    if (!color || !randInt(0, 3)) color = randChoice(colors);
                    start.push([i, HEIGHT - j, color]);
                }
            }

            for (i=0, ilen=start.length; i<ilen; i++)

                drawBlock.apply(drawBlock, start[i]);
        },
        nextShape: function(_set_next_only) {
            var next = this.next,
                func, shape, result;

            if (shapeFactory[info.mode])

                func = shapeFactory[info.mode];
            else if (info.mode == 'nice' || info.mode == 'evil')
                func = niceShapes;
            else
                func = randChoice(shapeFuncs);

            if (func.no_preview) {

                this.next = null;
                if (_set_next_only) return null;
                shape = func(filled, checkCollisions, WIDTH, HEIGHT, info.mode);
                if (!shape) throw new Error('No shape returned from shape function!', func);
                shape.init();
                result = shape;
            } else {
                shape = func(filled, checkCollisions, WIDTH, HEIGHT, info.mode);
                if (!shape) throw new Error('No shape returned from shape function!', func);
                shape.init();
                this.next = shape;
                if (_set_next_only) return null;
                result = next || this.nextShape();
            }

            if (window.autopilot) { //fun little hack...

                niceShapes(filled, checkCollisions, WIDTH, HEIGHT, 'nice', result);
                $.extend(result, {
                    orientation: result.best_orientation,
                    x: result.best_x
                });
            }

            return result;

        },
        animate: function() {
            var drop = false,
                gameOver = false;

            if (!this.paused) {

                this.dropCount++;
                if (this.dropCount >= this.dropDelay || window.autopilot) {
                    drop = true;
                    this.dropCount = 0;
                }

                // test for a collision

                if (drop) {
                    var cur = this.cur, x = cur.x, y = cur.y, blocks = cur.getBlocks();
                    if (checkCollisions(x, y+1, blocks, true)) {
                        drop = false;
                        for (var i=0; i<cur.blocksLen; i+=2) {
                            filled.add(x + blocks[i], y + blocks[i+1], cur.color);
                            if (y + blocks[i] < 0) {
                                gameOver = true;
                            }
                        }
                        filled.checkForClears();
                        this.cur = this.nextShape();
                    }
                }

                // draw it!

                ctx.clearRect(0, 0, PIXEL_WIDTH, PIXEL_HEIGHT);
                filled.draw();
                this.cur.draw(drop);
                info.draw();
            }

            if (!gameOver)

                window.setTimeout(function() { board.animate(); }, this.animateDelay);
        }
    };

    var info = {

        mode: null,
        modes: [
            'random',
            'nice',
            'evil'
        ],
        modesY: 170,
        autopilotY: null,
        draw: function() {
            info_ctx.clearRect(0, 0, info_canvas.width, info_canvas.height);

            if (board.next) {

                var bounds = board.next.getBounds(0), w = 5, h = 6;
                info_ctx.fillStyle = '#000';
                info_ctx.fillRect(0, 0, w*block_size, h*block_size);
                info_ctx.fillStyle = '#fff';
                info_ctx.fillRect(border_width, border_width, w*block_size - 2*border_width, h*block_size - 2*border_width);
                board.next.draw(
                    false,
                    (w-bounds.width)/2 - bounds.left - .5, //1 - bounds.left,
                    (h-bounds.height)/2 + bounds.height - bounds.bottom - .5,
                    0,
                    info_ctx
                );
            }

            info_ctx.font = 'bold 14px/20px "lucida grande",helvetica,arial';

            info_ctx.fillStyle = '#333';
            info_ctx.fillText('Lines: ' + board.lines, 0, 140);

            info_ctx.fillText('Shape Mode:', 0, this.modesY);

            for (var i=0, len=this.modes.length, selected, y; i<len; i++) {
                selected = this.mode == this.modes[i];
                y = this.modesY + (i+1)*20;
                this.radio(0, y, selected);
                info_ctx.fillStyle = selected ? '#930' : '#333';
                info_ctx.fillText(this.modes[i], 20, y);
            }

            if (this.autopilotY === null) this.autopilotY = y+30;


            this.checkBox(0, this.autopilotY, window.autopilot);

            info_ctx.fillStyle = window.autopilot ? '#930' : '#333';
            info_ctx.fillText('autopilot', 20, this.autopilotY);
        },
        init: function() {
            this.mode = this.modes[0];

            for (var attr in shapeFactory)

                this.modes.push(attr);

            $(window).trigger('hashchange'); // setup modes


            var self = this;

            $(info_canvas).click(function(evt) {
                evt.preventDefault();
                var offset = $(info_canvas).offset(),
                    x = evt.pageX - offset.left,
                    y = evt.pageY - offset.top,
                    mode;
                if (y > self.modesY) {
                    mode = self.modes[Math.floor((y - self.modesY) / 20)];
                    if (mode) {
                        window.location.hash = mode;
                        self.setMode(mode);
                    } else if (self.autopilotY - 20 <= y && y <= self.autopilotY) {
                        window.autopilot = !window.autopilot;
                    }
                }
            });
        },
        setMode: function(mode) {
            // title
            var titleDiv = ' - ',
                title = document.title.split(' - '),
                firstEnd = title[0].split(' ').pop(),
                newFirst = mode;
            newFirst = (newFirst.charAt(0).toUpperCase() +
                        newFirst.substring(1).replace(/([A-Z])/g, ' $1'));
            title[0] = newFirst += ' ' + firstEnd;
            $('#game-wrap').find('h1').text(title[0]);
            document.title = title.join(' - ');

            // set mode

            this.mode = mode;
            board.nextShape(true);
        },
        circle: function(x, y, r, color) {
            info_ctx.beginPath();
            if (color) info_ctx.fillStyle = color;
            info_ctx.arc(x, y, r, 0, 2 * Math.PI, true);
            info_ctx.closePath();
            info_ctx.fill();
        },
        radio: function(x, y, selected) {
            y -= 4;
            x += 8;
            this.circle(x, y, 6, '#333');
            this.circle(x, y, 5, '#fff');
            if (selected) this.circle(x, y, 4, '#333');
        },
        checkBox: function(x,  y, selected) {
            y -= 4;
            x += 8;
            info_ctx.fillStyle = '#333';
            info_ctx.fillRect(x - 6, y - 6, 12, 12);
            info_ctx.fillStyle = '#fff';
            info_ctx.fillRect(x - 5, y - 5, 10, 10);

            if (selected) {

                info_ctx.strokeStyle = '#333';
                info_ctx.beginPath();
                info_ctx.moveTo(x - 6, y - 6);
                info_ctx.lineTo(x + 6, y + 6);
                info_ctx.moveTo(x - 6, y + 6);
                info_ctx.lineTo(x + 6, y - 6);
                info_ctx.closePath();
                info_ctx.stroke();
            }
        }
    };


    //

    //
    //

    $(window).bind('hashchange', function(evt) {

        var hash = window.location.href.split('#')[1] || '',
            i = 0, len = info.modes.length;
        for (; i<len; i++) {
            if (info.modes[i] == hash) {
                if (info.mode != hash) {
                    info.setMode(hash);
                }
                break;
            }
        }
    });

    info.init();

    board.init();

    function startBoard(evt) {

        evt.preventDefault();
        board.started = true;
        board.animate();
        return false;
    }

    $(document).keyup(function(evt) {

        return (!board.started && (evt.keyCode == 13 || evt.keyCode == 32)) ? startBoard(evt) : true;
    });

    $(canvas).click(function(evt) {

        return (!board.started) ? startBoard(evt) : true;
    });

    $(document).keyup(function(evt) {

        if (evt.keyCode == 80) { /*p*/
            board.paused = !board.paused;
        } else if (evt.keyCode == 192) { /*`*/
            window.autopilot = !window.autopilot;
        }
    });

    $(document).safekeypress(function(evt) {

        var caught = false;
        if (board.cur) {
            caught = true;
            switch(evt.keyCode) {
              case 37: /*left*/ board.cur.moveLeft(); break;
              case 38: /*up*/ board.cur.rotate(true); break;
              case 39: /*right*/ board.cur.moveRight(); break;
              case 40: /*down*/ board.dropCount = board.dropDelay; break;
              case 88: /*x*/ board.cur.rotate(true); break;
              case 90: /*z*/ board.cur.rotate(false); break;
            default: caught = false;
            }
        }
        if (caught) evt.preventDefault();
        return !caught;
    });

}

//})(this, this.document);

</script>

<script>
var disqus_shortname = 'mrcoles'; // required: replace example with your forum shortname
var disqus_identifier = 'mrcoles_tetris_app';
//var disqus_url = 'http://mrcoles.com/tetris/';

/* * * DON'T EDIT BELOW THIS LINE * * */

(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
</div>
<script>
(function() {
var startTime = (new Date).getTime();
mixpanel.track('View Page', {
'Page title': document.title
});
mixpanel.track_links('.shop-ad a', 'Click Shop Ad', function() {
var isSideBar = (window.innerWidth > 850);
return {
'time on page': (new Date).getTime() - startTime,
'in side bar': isSideBar
};
});
})();
</script>
<!-- main.js -->
<script>
(function(d, w, undefined) {
    d.getElementById('nav-toggle').onclick = function() {
        var elt = d.body,
            r = /(^|\s+)show-nav(\s+|$)/;
        if (r.test(elt.className)) {
            elt.className = elt.className.replace(r, '');
        } else {
            elt.className += (elt.className ? ' ' : '') + 'show-nav';
        }
    };
})(document, this);
</script>
<script>
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4202460-2']); _gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'http://www.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

<script>(function(d,g) {

var s = d[g]('search-link');
if (s) {
s.onclick = function() {

var f = d[g]('search-drop'), n = f.className;

if (n=='show') {
f.className = '';
} else {
f.className = 'show';
f.getElementsByTagName('input')[0].focus();
}

return false;

}
}
})(document,'getElementById')</script>
<!-- cchd Sat, 4 Oct 2014 14:21:58 -0400 -->
</body>
</html>      

How To Make A Simple Snake Game:



<!DOCTYPE html>
<html>
<head>
<title>Space Shooter Demo</title>
<style>


</style>


<script>

$(document).ready(function(){
//Canvas stuff
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();

//Lets save the cell width in a variable for easy control
var cw = 10;
var d;
var food;
var score;

//Lets create the snake now
var snake_array; //an array of cells to make up the snake

function init()
{
d = "right"; //default direction
create_snake();
create_food(); //Now we can see the food particle
//finally lets display the score
score = 0;

//Lets move the snake now using a timer which will trigger the paint function
//every 60ms
if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
}
init();

function create_snake()
{
var length = 5; //Length of the snake
snake_array = []; //Empty array to start with
for(var i = length-1; i>=0; i--)
{
//This will create a horizontal snake starting from the top left
snake_array.push({x: i, y:0});
}
}

//Lets create the food now
function create_food()
{
food = {
x: Math.round(Math.random()*(w-cw)/cw), 
y: Math.round(Math.random()*(h-cw)/cw), 
};
//This will create a cell with x/y between 0-44
//Because there are 45(450/10) positions accross the rows and columns
}

//Lets paint the snake now
function paint()
{
//To avoid the snake trail we need to paint the BG on every frame
//Lets paint the canvas now
ctx.fillStyle = "lightgreen";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, w, h);

//The movement code for the snake to come here.
//The logic is simple
//Pop out the tail cell and place it infront of the head cell
var nx = snake_array[0].x;
var ny = snake_array[0].y;
//These were the position of the head cell.
//We will increment it to get the new head position
//Lets add proper direction based movement now
if(d == "right") nx++;
else if(d == "left") nx--;
else if(d == "up") ny--;
else if(d == "down") ny++;

//Lets add the game over clauses now
//This will restart the game if the snake hits the wall
//Lets add the code for body collision
//Now if the head of the snake bumps into its body, the game will restart
if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw || check_collision(nx, ny, snake_array))
{
//restart game
init();
//Lets organize the code a bit now.
return;
}

//Lets write the code to make the snake eat the food
//The logic is simple
//If the new head position matches with that of the food,
//Create a new head instead of moving the tail
if(nx == food.x && ny == food.y)
{
var tail = {x: nx, y: ny};
score++;
//Create new food
create_food();
}
else
{
var tail = snake_array.pop(); //pops out the last cell
tail.x = nx; tail.y = ny;
}
//The snake can now eat the food.

snake_array.unshift(tail); //puts back the tail as the first cell

for(var i = 0; i < snake_array.length; i++)
{
var c = snake_array[i];
//Lets paint 10px wide cells
paint_cell(c.x, c.y);
}

//Lets paint the food
paint_cell(food.x, food.y);
//Lets paint the score
var score_text = "Score: " + score;
ctx.fillText(score_text, 5, h-5);
}

//Lets first create a generic function to paint cells
function paint_cell(x, y)
{
ctx.fillStyle = "red";
ctx.fillRect(x*cw, y*cw, cw, cw);
ctx.strokeStyle = "white";
ctx.strokeRect(x*cw, y*cw, cw, cw);
}

function check_collision(x, y, array)
{
//This function will check if the provided x/y coordinates exist
//in an array of cells or not
for(var i = 0; i < array.length; i++)
{
if(array[i].x == x && array[i].y == y)
 return true;
}
return false;
}

//Lets add the keyboard controls now
$(document).keydown(function(e){
var key = e.which;
//We will add another clause to prevent reverse gear
if(key == "37" && d != "right") d = "left";
else if(key == "38" && d != "down") d = "up";
else if(key == "39" && d != "left") d = "right";
else if(key == "40" && d != "up") d = "down";
//The snake is now keyboard controllable
})
})

</script>
</head>
<body>
 <!-- Lets make a simple snake game -->
<canvas id="canvas" width="450" height="450"></canvas>

<!-- Jquery -->

<script src="jquery-1.10.2.js" type="text/javascript"></script>
</body>
</html>


How To Make A Simple Puzzle Game:

just change my picture from the code below e.g

(_img.src = "1.gif";) to (_img.src = "your folder/images/name.jpg";)



<!DOCTYPE html>
<html>
  
  <head>
    <title>Pujjle</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
      html, body {
        width: 100%;
        height: 100%;
        margin: 0px;
      }
      body {
        background-color: transparent;
        -webkit-transform: perspective(1400px) matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
        -webkit-transform-style: preserve-3d;
      }
    </style>
    <script>

const PUZZLE_DIFFICULTY = 4;

const PUZZLE_HOVER_TINT = '#009900';

var _stage;

var _canvas;

var _img;

var _pieces;
var _puzzleWidth;
var _puzzleHeight;
var _pieceWidth;
var _pieceHeight;
var _currentPiece;
var _currentDropPiece;

var _mouse;


function init(){

_img = new Image();
_img.addEventListener('load',onImage,false);
_img.src = "1.gif";
}
function onImage(e){
_pieceWidth = Math.floor(_img.width / PUZZLE_DIFFICULTY)
_pieceHeight = Math.floor(_img.height / PUZZLE_DIFFICULTY)
_puzzleWidth = _pieceWidth * PUZZLE_DIFFICULTY;
_puzzleHeight = _pieceHeight * PUZZLE_DIFFICULTY;
setCanvas();
initPuzzle();
}
function setCanvas(){
_canvas = document.getElementById('canvas');
_stage = _canvas.getContext('2d');
_canvas.width = _puzzleWidth;
_canvas.height = _puzzleHeight;
_canvas.style.border = "1px solid black";
}
function initPuzzle(){
_pieces = [];
_mouse = {x:0,y:0};
_currentPiece = null;
_currentDropPiece = null;
_stage.drawImage(_img, 0, 0, _puzzleWidth, _puzzleHeight, 0, 0, _puzzleWidth, _puzzleHeight);
createTitle("Click to Start Puzzle");
buildPieces();
}
function createTitle(msg){
_stage.fillStyle = "#000000";
_stage.globalAlpha = .4;
_stage.fillRect(100,_puzzleHeight - 40,_puzzleWidth - 200,40);
_stage.fillStyle = "#FFFFFF";
_stage.globalAlpha = 1;
_stage.textAlign = "center";
_stage.textBaseline = "middle";
_stage.font = "20px Arial";
_stage.fillText(msg,_puzzleWidth / 2,_puzzleHeight - 20);
}
function buildPieces(){
var i;
var piece;
var xPos = 0;
var yPos = 0;
for(i = 0;i < PUZZLE_DIFFICULTY * PUZZLE_DIFFICULTY;i++){
piece = {};
piece.sx = xPos;
piece.sy = yPos;
_pieces.push(piece);
xPos += _pieceWidth;
if(xPos >= _puzzleWidth){
xPos = 0;
yPos += _pieceHeight;
}
}
document.onmousedown = shufflePuzzle;
}
function shufflePuzzle(){
_pieces = shuffleArray(_pieces);
_stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
var i;
var piece;
var xPos = 0;
var yPos = 0;
for(i = 0;i < _pieces.length;i++){
piece = _pieces[i];
piece.xPos = xPos;
piece.yPos = yPos;
_stage.drawImage(_img, piece.sx, piece.sy, _pieceWidth, _pieceHeight, xPos, yPos, _pieceWidth, _pieceHeight);
_stage.strokeRect(xPos, yPos, _pieceWidth,_pieceHeight);
xPos += _pieceWidth;
if(xPos >= _puzzleWidth){
xPos = 0;
yPos += _pieceHeight;
}
}
document.onmousedown = onPuzzleClick;
}
function onPuzzleClick(e){
if(e.layerX || e.layerX == 0){
_mouse.x = e.layerX - _canvas.offsetLeft;
_mouse.y = e.layerY - _canvas.offsetTop;
}
else if(e.offsetX || e.offsetX == 0){
_mouse.x = e.offsetX - _canvas.offsetLeft;
_mouse.y = e.offsetY - _canvas.offsetTop;
}
_currentPiece = checkPieceClicked();
if(_currentPiece != null){
_stage.clearRect(_currentPiece.xPos,_currentPiece.yPos,_pieceWidth,_pieceHeight);
_stage.save();
_stage.globalAlpha = .9;
_stage.drawImage(_img, _currentPiece.sx, _currentPiece.sy, _pieceWidth, _pieceHeight, _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth, _pieceHeight);
_stage.restore();
document.onmousemove = updatePuzzle;
document.onmouseup = pieceDropped;
}
}
function checkPieceClicked(){
var i;
var piece;
for(i = 0;i < _pieces.length;i++){
piece = _pieces[i];
if(_mouse.x < piece.xPos || _mouse.x > (piece.xPos + _pieceWidth) || _mouse.y < piece.yPos || _mouse.y > (piece.yPos + _pieceHeight)){
//PIECE NOT HIT
}
else{
return piece;
}
}
return null;
}
function updatePuzzle(e){
_currentDropPiece = null;
if(e.layerX || e.layerX == 0){
_mouse.x = e.layerX - _canvas.offsetLeft;
_mouse.y = e.layerY - _canvas.offsetTop;
}
else if(e.offsetX || e.offsetX == 0){
_mouse.x = e.offsetX - _canvas.offsetLeft;
_mouse.y = e.offsetY - _canvas.offsetTop;
}
_stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
var i;
var piece;
for(i = 0;i < _pieces.length;i++){
piece = _pieces[i];
if(piece == _currentPiece){
continue;
}
_stage.drawImage(_img, piece.sx, piece.sy, _pieceWidth, _pieceHeight, piece.xPos, piece.yPos, _pieceWidth, _pieceHeight);
_stage.strokeRect(piece.xPos, piece.yPos, _pieceWidth,_pieceHeight);
if(_currentDropPiece == null){
if(_mouse.x < piece.xPos || _mouse.x > (piece.xPos + _pieceWidth) || _mouse.y < piece.yPos || _mouse.y > (piece.yPos + _pieceHeight)){
//NOT OVER
}
else{
_currentDropPiece = piece;
_stage.save();
_stage.globalAlpha = .4;
_stage.fillStyle = PUZZLE_HOVER_TINT;
_stage.fillRect(_currentDropPiece.xPos,_currentDropPiece.yPos,_pieceWidth, _pieceHeight);
_stage.restore();
}
}
}
_stage.save();
_stage.globalAlpha = .6;
_stage.drawImage(_img, _currentPiece.sx, _currentPiece.sy, _pieceWidth, _pieceHeight, _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth, _pieceHeight);
_stage.restore();
_stage.strokeRect( _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth,_pieceHeight);
}
function pieceDropped(e){
document.onmousemove = null;
document.onmouseup = null;
if(_currentDropPiece != null){
var tmp = {xPos:_currentPiece.xPos,yPos:_currentPiece.yPos};
_currentPiece.xPos = _currentDropPiece.xPos;
_currentPiece.yPos = _currentDropPiece.yPos;
_currentDropPiece.xPos = tmp.xPos;
_currentDropPiece.yPos = tmp.yPos;
}
resetPuzzleAndCheckWin();
}
function resetPuzzleAndCheckWin(){
_stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
var gameWin = true;
var i;
var piece;
for(i = 0;i < _pieces.length;i++){
piece = _pieces[i];
_stage.drawImage(_img, piece.sx, piece.sy, _pieceWidth, _pieceHeight, piece.xPos, piece.yPos, _pieceWidth, _pieceHeight);
_stage.strokeRect(piece.xPos, piece.yPos, _pieceWidth,_pieceHeight);
if(piece.xPos != piece.sx || piece.yPos != piece.sy){
gameWin = false;
}
}
if(gameWin){
setTimeout(gameOver,500);
}
}
function gameOver(){
document.onmousedown = null;
document.onmousemove = null;
document.onmouseup = null;
initPuzzle();
}
function shuffleArray(o){
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}

</script>

  </head>
  
 <body onload="init();">
<canvas id="canvas"></canvas>
</body>
</html>


 Ok boss, Please Try All Those Code Above.Thanks a lot for visiting me.To Go Home Page Click Home.              

Comments