<! Doctype HTML>
<HTML>
<Body>
<Canvas id = "mycanvas" width = "240" Height = "240" style = "border: 1px solid # d3d3d3;"> your browser does not support the HTML5 canvas tag. </canvas>
<SCRIPT>
VaR CTX = Document. getelementbyid ("mycanvas"). getcontext ("2D"), // returns a two-dimensional painting Environment
R = [{X: 10, Y: 9}, {X: 10, Y: 8}], // starting from the snake location
CO = 40,
E = NULL;
CTX. shadowblur = 40, // shadow level
CTX. shadowcolor = "red ";
Setinterval (function (){
If (check (R [0], 0) | r [0]. x <0 | r [0]. x> = 24 | r [0]. Y <0 | r [0]. y> = 24) return;
E! = NULL & (CO = 40 & R [0]. X = E. X & R [0]. Y + 1 = E. y) | (CO = 38 & R [0]. X = E. X & R [0]. y-1 = E. y) | (CO = 37 & R [0]. x-1 = E. X & R [0]. y = E. y) | (CO = 39 & R [0]. X + 1 = E. X & R [0]. y = E. Y ))? (R. unshift (E), E = NULL, R. unshift (R. Pop (): (R. unshift (R. Pop ()));
(CO = 40 | Co = 38 )? (R [0]. x = R [1]. X, R [0]. Y = R [1]. Y + (CO = 40? 1:-1): (R [0]. x = R [1]. x + (CO = 39? 1:-1), R [0]. Y = R [1]. y );
CTX. clearrect (0, 0,240,240); // Delete the rectangular area of the canvas.
If (e) CTX. fillrect (E. x * 10, E. y * 10, 10); // fill the rectangle
For (VAR I = 0; I <R. length; I ++) CTX. fillrect (R [I]. x * 10, R [I]. y * 10, 10, 10 );
While (E = NULL | check (e ))
E = {y: (math. Random () * 24 >>> 0), X: (math. Random () * 24 >>> 0 )};
If (check (R [0], 0) | r [0]. x <0 | r [0]. x> = 24 | r [0]. Y <0 | r [0]. y> = 24)
Alert ("game over \ Nyou get [" + (R. Length-2) + "]");
},100 );
Document. onkeyup = function (event ){
CO = event. keycode> = 37 & event. keycode <= 40 & (math. Abs (event. keycode-Co )! = 2 )? Event. keycode: CO;
};
// Determine whether to hit yourself
Function check (E, j ){
For (VAR I = 0; I <R. length; I ++)
If (J! = I & R [I]. x = E. X & R [I]. Y = E. Y)
Return true;
Return false;
}
</SCRIPT>
</Body>
</Html>
Address: http://blog.csdn.net/lufy_legend/article/details/8233520
Take a closer lookCode, FoundAlgorithmIt's not complicated. If you think about it again, you can also write a Russian square... O (partition _ partition) o ha!