JS code: Game object, food, snake, game control ideas as follows (full code download in Https://github.com/774044859yf/ObjectSnakeGame)
var Snake = {
asnake: [],//Add an array of snakes size : 20,//snake sizes, a size top for each body : 200,//initial position left : 400,//initial position speed: 250,//initial velocity level: 1,//Initial game class len: 3, //Snake length default of 3 units direction ' left ',//direction by default () {//Create initial Snake }, () {//move Traversing the body div of the snake sets the position equal to the previous position snake.check ();//When moving, check to see if it hits the wall or itself .
Snake.eat ();//check to see if food is eaten at time of movement}, () {//check the position of the snake's head (dead food)
}, () {//Snake eating growth method
}, () {//eating method
if () {//eat something
Snake.grow ()
}
} };
Since the food is called repeatedly, the class is built and new is done every time the food is created.
Add the method of the class to the prototype object of the class
Food () {}food. prototype () {//Initialize the location of food }; Food. prototype () {//create randomly generated food };
Create game controls on demand
= { inter' Inter ', () {//to initialize the game food () according to your own needs ; Food.default (); //Generate targeted food Snake. Create (); //Spawn snake }, () {//Snake starts to move the game. = SetInterval (snake. Move,snake. speed/snake. level); }, () { clearinterval (game. Inter) }};
Call the game to initialize the Games. Init ();
Beginner JS have any mistake please forgive me, you are welcome to point out the mistake and make suggestions, thank you ~
JavaScript object-oriented idea Snake game