How to write a greedy snake with JavaScript

Source: Internet
Author: User
Tags event listener setinterval

I used to use C language, with the help of curses library to achieve the Linux terminal under the Snake game.

This javascript version of the greedy snake is http://www.veryhuo.com/game/tanchishe.html learning notes, the principle of implementation and C version of the Basic.

The most important thing here is to use the two-dimensional array of gridelems to represent the 20*20 lattice (actually the TD element of HTML), through the Gridelems[x][y].classname control of the TD elements of the CSS. Furthermore, the judgment in the snake movement.

--------------------

1. How to express a snake

Use a two-dimensional array to store snake points (x,y), and Mark these points (x,y) as "cover", which is used to check if the snake head hits the body of the snake later.

Initialize snake
function initsnake () {
	var pointer = randompointer (len-1, len-1, WIDTH/2);
	for (var i = 0; i < len; i++) {
		var x = pointer[0]-I,
			y = pointer[1];
		Snake.push ([x,y]);
		Gridelems[x][y].classname = "Cover"; Mark Snake Body
	}
}

2. Use JS to draw a lattice

Create the TABLE->TR->TD with the Document.createelent () method, and append the Document.appendchild () method to the element with the id "snakewrap":

Initialize grid 
function Initgrid () {
	var body = document.getelementsbytagname (' body ') [0];
	var table = document.createelement ("table"),
		tbody = document.createelement ("tbody") for
	(var j = 0; J < HEIGHT ; J + +) {  
		var col = document.createelement ("tr");  
		for (var i = 0; i < WIDTH; i++) {  
			var row = document.createelement ("TD");
			GRIDELEMS[I][J] = col.appendchild (row);  It is important here to represent TD through a two-dimensional array of elements, through classname control of the TD's color
		}
		tbody.appendchild (col);  
	}
	Table.appendchild (tbody);
	document.getElementById ("Snakewrap"). appendchild (table);

Partial CSS files:

TD {
	width:20px;
	height:20px;
	Background: #f4f4f4/* TD background Color*/
}

/*snake body color*/
. Cover {	background: #39c;}
/*food color*/
. Food {background: #093}


3. Random coordinates for food generation

function Randompointer (startx,starty,endx,endy) {
	startx = StartX | | 0;
	Starty = Starty | | 0;
	EndX = EndX | | WIDTH;
	EndY = EndY | | HEIGHT;
	
	var p = [],
	x = Math.floor (Math.random () * (ENDX-STARTX)) + startx,
	y = Math.floor (Math.random () * (Endy-starty) ) + Starty;
	
	if (X,y) has an object, regenerate the coordinate
	if (Carrier[x][y]) {return
		randompointer (Startx,starty,endx,endy);
	}
	
	P[0] = x;
	P[1] = y;
	return p;
}

Add a new food:

AddObject ("food")
function AddObject (name) {
	var p = randompointer ();//get random position
	var x = p[0];
  var y = p[1];
	Gridelems[x][y].classname = name;

4. The direction key presses the action event to listen:

Allow the upper left 4 buttons to change the direction of Snake movement, note that if the opposite direction, not effective.

For each keystroke on the keyboard, there is a key cord, my blog recording the JavaScript key cord, you can see:

Left Arrow 37
Up ARROW 38
Right Arrow 39
Down ARROW 40

Keyboard Event Listener
function attachevents (e) {
	e = e | | | event;
	Directkey = Math.Abs (e.keycode-directkey)!= 2 && e.keycode > && e.keycode < 41? E.keycode:directkey; return
	false;
}

5. The core of the greedy snake--judgment

Each judgment (that is, the judge () function uses the SetInterval () method every time the--> is run), the snake "Head" node is saved and then judged

1 To determine the direction, according to the direction of the "head" of the coordinates (due to the setinterval () method, the system will run every millisecond judge () function, to ensure that the user presses the direction key can be the table direction)

2 to determine whether the "head" hit the wall, or encounter snake body (that is, gridelems[headx][heady].classname = = "Cover"), if encountered, the game is over.

3 Judge the "head" current position is not food (that is, gridelems[headx][heady].classname = = "Food"), if the head element of the carrier is not food, then let snake tail pop out; Then let the current position carry information Gridelems[headx][heady].classname = False

4 adds an element--> to the beginning of the array to achieve the " visually " snake movement (or eating food body growth)


function Step () {//Snake the "head" position of the HEADX var = snake[0][0], heady = snake[0][1];  Switch (directkey) {case 37:HEADX = 1; break,//left case 38:heady-= 1; break;//up Case 39:HEADX + + 1; break Right case 40:heady + 1; Break  Down}//Encounter boundary (block), or head touch Body (cover), then end game if (HEADX >= WIDTH | | HEADX < 0 | | Heady >= HEIGHT | | Heady < 0 || Gridelems[headx][heady].classname = = "Block" | |
		
		Gridelems[headx][heady].classname = = "Cover") {$ ("say"). innertext = "Game over."
		$ ("Start"). RemoveAttribute ("Disabled");
		
		$ ("Start"). Style.color = "#000";
		
		Window.clearinterval (Snaketimer);
	Return
	var lastx = snake[snake.length-1][0], lasty = snake[snake.length-1][1]; If the carrier of the head element is not food, let the snake's tail pop out if (gridelems[headx][heady].classname!= "food") {Gridelems[lastx][lasty].
		ClassName = "";
	Snake.pop ();
		else {gridelems[lastx][lasty].classname = "";
	AddObject ("Food"); ///Add an element--> to the beginning of the array to achieve the effect of "visually" snake movement (or eating body growth) SNAke.unshift ([Headx,heady]);
	
	Gridelems[headx][heady].classname = "Cover";
len = snake.length; }


SetInterval () function (makes the above judge () function run once every 300ms):

function Run_run_run () {
	if (snaketimer) {
		window.clearinterval (snaketimer);
	}
	Snaketimer = Window.setinterval ("Judge ()", Math.floor);
}

6.onload Operation

The OnLoad event occurs immediately after the page or image has finished loading:

Window.onload = function () {
	initgrid (); 
	Document.onkeydown = attachevents; Listens for KeyDown event
	$ ("Start"). onclick = function (e) {
		len = 3;//snake initial length
		Directkey =;//right
		snake = new Array ();
		Initsnake (); 
		AddObject ("food");
		Run_run_run ();
		
		Let the Start button fail
		$ ("Start"). setattribute ("Disabled", true);
		$ ("Start"). Style.color = "#aaa";
	}
}

7. For reference:Http://www.veryhuo.com/game/tanchishe.html

8. Play: My simple and stupid snake game

Effect Graph (CSS I borrowed from the next very hot 2048):


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.