I watched a few episodes of Canvas videos on MOOC before, and I always wanted to practice writing something. I feel that Snake is relatively simple. When I was in college, I also wrote a character version of C language. Unexpectedly, I still encountered many problems.
The final effect is as follows (if the picture is too large, it will take too long. The software for recording gif has a time limit...)
Start by defining the game area. There are only two elements on the screen of Snake: snake body and apple, and both of them can be composed of square grids. Add gaps between squares. Why add gaps? You can imagine that when you successfully fill all the grids, if there are no gaps, it will be a big solid square... You have no idea what the snake body looks like.
Draw a picture.
The coordinates of the upper left corner of the grid are (0, 0), the abscissa increases to the right, and the ordinate increases downward. This direction is the same as Canvas.
Every time we draw a grid, we have to start from the upper left corner. We always know that the coordinates of the upper left corner of Canvas are (0, 0). Assuming that the side length of the grid is GRID_WIDTH and the width of the gap is GAP_WIDTH, we can get the (i, j)th The coordinates of the upper left corner of the grid (i*(GRID_WIDTH+GAP_WIDTH)+GAP_WIDTH, j*(GRID_WIDTH+GAP_WIDTH)+GAP_WIDTH) .
Assume that the snake body is composed of three blue grids. We can't just draw three grids, but also two purple gaps. Otherwise, as mentioned before, you will not know what the snake body looks like. As shown in the picture below, although it can be played without drawing gaps, the experience will definitely be different.
Draw gaps between adjacent grids without drawing gaps
Now we can try drawing a snake. The snake body is actually a collection of grids. Each grid is represented by an array containing two position information. The entire snake can be represented by a two-dimensional array.
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <title>blog_snack</title> <style> #canvas { background-color: #000; } </style></ head><body> <canvas id=canvas></canvas> <script> const GRID_WIDTH = 10; // The side length of the grid const GAP_WIDTH = 2; // The side length of the gap const ROW = 10; // How many rows of grids are there in total & how many grids are there in each row let canvas = document.getElementById('canvas'); canvas.height = GRID_WIDTH * ROW + GAP_WIDTH * ( ROW + 1); canvas.width = GRID_WIDTH * ROW + GAP_WIDTH * (ROW + 1); let ctx = canvas.getContext('2d'); let snack = [ [2, 3], [2, 4], [2, 5], [3, 5], [4, 5], [4, 4], [5, 4], [5, 5] ]; // Initialize one