How to make Snake Game using jQuery

Well while checking the simplicity of jQuery , tried making snake game which is quite popular on mobiles or cellphones. Since I made it quickly and might miss some shorthand or small syntax. Please make me correct if I have made any mistake in the code. So lets start will simple thing , the html.

Why not to check the DEMO before moving on.

I scored 900 points as my highest score. Post in your highest score and I will try to beat that. 🙂

HTML

1
2
3
4
<body>
    <div id="scoreBoard">Your Score : 0</div>
    <div class="gameOver" style="display:none">Oops! Game Over</div>
 </body>

jQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
	<script type="text/javascript">
		var direction = 'right', speed = 100, ticker = null, fruitCell = [], score = 0, size = 50;
		var snakeCells = [
			[ 10, 14 ],
			[ 10, 13 ],
			[ 10, 12 ],
			[ 10, 11 ],
			[ 10, 10 ],
			[ 10, 9 ],
			[ 10, 8 ],
			[ 10, 7 ]
		];
		var snakeHead = [ 10, 14 ];
 
		function renderSnake (){
			$('td').removeClass('snakeCell snakeHead');
			for (var cell in snakeCells ){
				$('tr').eq( snakeCells[cell][0] ).find('td').eq(snakeCells[cell][1]).addClass('snakeCell');
			}
			$('tr').eq( snakeHead[0] ).find('td').eq(snakeHead[1]).addClass('snakeHead');
		}
 
		function getFruitCell() {
			fruitCell = [ getRandomNumber( $( 'tr' ).length ), getRandomNumber( $( 'tr:eq(0)>td' ).length ) ];
		}
 
		function gameOver() {
			$('div.gameOver').show('fast', function() {
				$( this ).animate({top:250}, 'slow');
			});
			clearInterval( ticker );
		}
 
		function updateSnakeCell(){
			var snakeNewHead = [];
			switch(direction){
				case 'right':
					snakeNewHead = [ snakeHead[0], snakeHead[1]+1 ];
					break;
				case 'left':
					snakeNewHead = [ snakeHead[0], snakeHead[1]-1 ];
					break;
				case 'up':
					snakeNewHead = [ snakeHead[0]-1, snakeHead[1] ];
					break;
				case 'down':
					snakeNewHead = [ snakeHead[0]+1, snakeHead[1] ];
					break;
			}
			var newCell = {length:0}
			if( snakeNewHead[0] < 0 || snakeNewHead[1] < 0 ) {
				gameOver();
				return;
			} else if( snakeNewHead[0] >= size || snakeNewHead[1] >= size ) {
				gameOver();
				return;
			}
			var newCell = $('tr').eq( snakeNewHead[0] ).find('td').eq(snakeNewHead[1]);
			if( newCell.length == 0 ) {
				gameOver();
			} else {
				if ( newCell.hasClass('snakeCell') ) {
					gameOver();
				} else {
					if( newCell.hasClass( 'fruitCell' ) ) {
						snakeCells.push( [] );
						getFruitCell();
						renderFruitCell();
						score += 100;
						$( '#scoreBoard' ).html( 'Your Score : ' + score );
						speed = speed - 10 > 5 ? speed - 10 : speed;
						clearInterval( ticker );
						startGame();
					}
					for( var i = ( snakeCells.length - 1 ); i > 0 ; i-- ) {
						snakeCells[ i ] = snakeCells[ i - 1 ];
					}
					snakeCells[ 0 ] = snakeHead = snakeNewHead;
					renderSnake();
				}
			}
		}
 
		function getRandomNumber( limit ) {
			return parseInt( Math.random() * limit % limit );
		}
 
		function getNewDirection( keyCode ) {
			var codes = {
				37 : 'left',
				38 : 'up',
				39 : 'right',
				40 : 'down'
			};
 
			if( typeof codes[ keyCode ] != 'undefined' ) {
				var newDirection = codes[ keyCode ], changeDirection = true;
				switch( direction ) {
					case 'up' :
						changeDirection = newDirection != 'down';
						break;
					case 'down' :
						changeDirection = newDirection != 'up';
						break;
					case 'right' :
						changeDirection = newDirection != 'left';
						break;
					case 'left' :
						changeDirection = newDirection != 'right';
						break;
				}
				direction = changeDirection ? newDirection : direction;
			}
		}
 
		function renderBoard() {
			var rowhtml = '';
			for( var i = 0; i < size; i++ ) {
				rowhtml +='<td cellpadding="0" cellspacing="0"></td>'
			}
			html = [];
			for( var i = 0; i < size; i++ ) {
				html.push( '<tr cellpadding="0" cellspacing="0">' + rowhtml + '</tr>' );
			}
			$( document.body ).append( '<table>' + html.join( '\n' ) + '</table>' );
			getFruitCell();
		}
 
		function renderFruitCell() {
			$( 'td' ).removeClass( 'fruitCell' );
			$('tr').eq( fruitCell[0] ).find('td').eq(fruitCell[1]).addClass( 'fruitCell' );
		}
 
		function startGame() {
			ticker = setInterval( updateSnakeCell, speed );
		}
 
		$( document ).ready(function(){
			renderBoard();
			renderFruitCell();
			$( document ).bind('keydown', function( e ) {
				getNewDirection( e.keyCode );
			});
			startGame();
		});
	</script>

CSS

1
2
3
4
5
6
7
8
9
10
*{margin:0;padding:0;font-family:trebuchet ms;}
body{width:900px;position:realtive;margin:0 auto;}
		table{margin:0 auto 10px auto;border:1px solid #ccc;box-shadow:3px 3px 10px #999;}
		td{width:6px;height:6px;border:1px solid #fff;cellpadding:0;cellspacing:0;}
		td.snakeCell{background:#000;-moz-border-radius:5px;border:1px solid #000;box-shadow:1px 1px 1px #aaa;}
		td.snakeHead{background:red;-moz-border-radius:5px;border:1px solid red;}	
		td.fruitCell{background:green;-moz-border-radius:5px;border:1px solid green;box-shadow:1px 1px 1px #aaa;}
 
		#scoreBoard{text-shadow:2px 2px 1px #fff;box-shadow:0 -3px 5px #aaa;width:482px;margin:50px auto 0 auto;border:1px solid #ccc;background:#eee;font-weight:bold;padding:10px;}
		.gameOver{font-weight:bold;text-shadow:2px 2px 1px #fff;position:absolute;top:0;left:550px;background:#eee;color:red;width:70px;border:50px solid #eee;text-align:center;-moz-border-radius:90px;-webkit-border-radius:90px;border-radius:90px;box-shadow:3px 3px 10px #999;}

Here is the DEMO.

That’s all folks! Updations and errors are welcome.

Recently Published

»

8 Ways the Right Ecommerce Platform Makes Your Business Perform Better

Starting your own ecommerce store is an exciting experience, but ...

»

The SSL certificates and why are they essential for sites

What are SSL and its purpose? SSL is a modern technology that is ...

»

Entering Into M-Commerce as a Small Business

According to a December 2016 Business Insider article, the U.S. ...

»

How to Convert More Traffic Quickly and Easily

If you’ve got a blog that gets plenty of traffic but ...

»

Strengthen Workplace Productivity with Live Chat Software

Live chat has become an important part of every company’s customer ...

»

How More Powerful Smartphones Are Making Websites Load Faster

Smartphone speeds keep accelerating. Last October, Qualcomm joined ...

»

The Most Effective Method To Present A Logo Plan

The Most well-known creators’ battles are and how they are ...

»

Sure Guide for Improving Your WP Site Accessibility

This article compiles some best practices to optimize a WP site ...

»

9 Social Media and Marketing Tools Recommended for a Business

A business is set up to have a profit by delivering a product or a ...