Effect demonstration:Home page for free source code
Code directory:
Main code implementation:
Part code:
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <meta http-equiv=" x-UA-compatible "content="ie=edge"> <title>Document</title> <style> canvas { border: 1px solid #000000; } </style> </head> <body> <canvas width="980" height="600" id="canvas"></canvas> <script> // initialize var foods = new Array(); Var gameover = false; Var gridWidth = 10; Var canvas = document.getelementById ("canvas"); var ctx = canvas.getContext("2d"); // Build canvas // food timer, Snake timer, scene, Snake object var food_interval, snake_interval, Farm, Snake; Function node(x, y, w) {var self = this; self.x = x; self.y = y; self.w = w; Self.foodinit = function() {ctx.fillstyle = "#FF0000"; ctx.fillRect(self.x, self.y, self.w, self.w); Self.snakeinit = function() {ctx.fillstyle = "#000000"; ctx.strokeStyle = "#FFFFFF"; ctx.fillRect(x, y, w, w); ctx.strokeRect(x, y, w, w); } self.equals = function(node) {if (self.x == node.x && self.y == node.y) {return true; } else { return false; Self. clear = function() {ctx.fillstyle = "#E8FFFF"; self.clear = function() {ctx.fillstyle = "#E8FFFF"; ctx.strokeStyle = "#E8FFFF"; ctx.fillRect(x, y, w, w); ctx.strokeRect(x, y, w, w); Function farm() {var self = this; ctx.fillStyle = "#E8FFFF"; // The scene color ctx.fillrect (0, 0, canvas.width, canvas.height); Self.addfood = function() {if (gameover) {return gameover (); Var x = parseInt(canvas.width/gridWidth * math.random ()) * gridWidth; var y = parseInt(canvas.height / gridWidth * Math.random()) * gridWidth; Var food = new node(x, y, gridWidth); FoodInit (); foodInit(); foodInit(); // Append to array foods.push(food); Function snake(x, y, len, speed) {var self = this; self.init = function() { self.len = len; Self.nodes = new Array(); // Snake body array self.dir = "R"; Self. Speed = speed; Var nx = x, ny = y; var nx = x, ny = y; For (var I = 0; i < len; Var tmpNode = new node(nx, ny, gridWidth); // Store the snake body self.nodes[I] = tmpNode; Tmpnode.snakeinit (); nx -= gridWidth; Snake_interval = setInterval(self.move, self.speed); Document.onkeydown = function(e) {var code = e.keycode; Self. odir = self.dir; WASD case 65: self.dir = "L"; break; case 87: self.dir = "U"; break; case 68: self.dir = "R"; break; case 83: self.dir = "D"; break; case 37: self.dir = "L"; break; case 38: self.dir = "U"; break; case 39: self.dir = "R"; break; case 40: self.dir = "D"; break; }}}Copy the code
Clocked articles updated 40/100 days