Design idea:

  1. Each part of the snake body should have its own direction of movement, each part of the snake body is an object, and the whole snake has a way to become a body initially, and a way to get food to grow the body. Ball is the Snake body constructor, Snake is the whole Snake constructor
  2. When the snake and the food are separated, the food is handled by the food itself, not by the snake. When the code is not separated, the callback is used
  3. When the snake changes direction, it will generate an inflection point, and each snake body needs to store these inflection points in the array. The attributes of an inflection point include position coordinates and velocity vector (including direction in velocity).
  4. Snake food can use the singleton idea, generate N divs as food at one time, then the food is eaten, trigger the callback, which food is eaten, the new generation, the emergence of the generation here does not delete or increase the div, but secretly change the location of the div, can also change the size at the same time
  5. Reviewing the design, the control of the snake is to control the snake head, so it is impossible to give each snake a timer, so the whole snake a timer, polling the snake body move method in the snake move, because each snake body has the current speed vector, and inflection point information, can process the position of the snake body at the next moment
  6. Whether the food is eaten or not is caused by the actions of the snake. Only the center position of the snake head (i.e. the first Ball representing the snake body) and the center position of the food are detected to be less than a certain value
  7. Snake has room to move. In New Snake, pass the parent div, div set to relative position
  8. Since you have chosen to separate the food from the Snake, you should pass in an instance of the food when new Snake is created

Github address: github.com/HYjey/tanch…