How does C++ realize the ultra-simple gluttonous Snake game?
Editor to share with you how C++ to achieve the ultra-simple gluttonous Snake game, I hope you will learn something after reading this article, let's discuss it together!
Design ideas
It is recommended to copy the code and run it again before you look at the train of thought!
It is easy to understand. Please read it carefully.
It is worth noting that the code I gave did not add a wall, if necessary, add it yourself.
There is no difficult design, ditto.
Map size (the wall is designed here, not implemented in the code)
Set a shaping array map with a size of 1600, corresponding to a map size of 1600, and initialize the array so that all values in the array are 0 and 0 represents open space.
By setting the width of the window to 80, the character corresponding to each map [I] occupies two positions when printing, we can achieve the effect of line wrapping for every 40 map [I] printed.
So the length and width of the map is 40x40.
two。 Wall body
The wall is in the outermost periphery of the map, which means that when the I in map [I] is the boundary of the map, it corresponds to the wall. If sentence is used to judge the value of I, and the wall can be printed in accordance with the conditions located at the boundary.
We know from the size of the map that when 0) break; / * eats food, snake body + 1, and generates new food * / if in the open space (map [heady * 40 + headx]
< 0) { len++; for (i = rand() % 1600; map[i] || !(map[i] = -1); i = rand() % 1600); } } /*是空地则蛇身值整体减1,蛇尾由1减为0变成空地*/ else for (i = 0; i < 1600; i++) { if (map[i] >0) map [I]-= 1;} system ("cls"); / * New snakehead assignment, traversing map, value greater than 0 is snake body, equal to 0 is open space, less than 0 is food * / for (map [heady * 40 + headx] = len, I = 0; I
< 1600; i++) { if (map[i] == len) { printf("%2d", map[i]); continue; } if (map[i] >0) printf ("% 2d", map [I]); if (map [I] = = 0) printf ("% 2d", map [I]); if (map [I] = =-1) printf ("% 2d", map [I]); / / print} Sleep (100);} effect
If you read the code carefully, it is easy to replace the number with the symbol you want (if it is a character with a space).
If you want the game to cycle, it's easy to do it.
After reading this article, I believe you have a certain understanding of "how C++ realizes the ultra-simple gluttonous Snake game". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!