In order to make everyone right python Have an interest in , It's boring not to let everyone learn programming , So today Lao yuan prepared a little game for everyone to play , If you like, you can follow me to type the code . So, no more nonsense, let's just start ！
We choose a good development tool Python edition ：3.6.4, Related template selection pygame Templates , As well as some Python Built in modules . The environment construction is also very simple , Just install Python And add to environment variable ,pip Install the required relevant templates .
Principle introduction ：
I don't need to introduce more about the rules of the snake game . Writing a snake game is actually very simple . First , Let's start the game ：
Then define a greedy snake ：
among headcoord Used to record the location of the snake head , and tailcoords Is a two-dimensional array , Used to record the position of all snakes . In limine , Greedy snakes grow into 3, And the location is randomly generated . The user controls the action of greedy snake through up, down, left and right buttons ：
It should be noted that , Greedy snakes cannot 180° Big turn , Can only 90° Round the corner
then , We need to randomly generate a food , And it is necessary to ensure that the position of the food is not the same as that of the greedy snake ：
When updating the snake , If it eats food , Then the length of the snake increases by one , Otherwise, simply act in a given direction without changing the length of the snake ：
meanwhile , When greedy snakes eat food , Need to regenerate a new food ：
Last , When a greedy snake touches a wall or a snake's head touches a snake's body , Game over
And display the game interface ：
Finally, look at the result chart ：
If you understand, you can follow and try , After finishing , It's also good to send a circle of friends and have a cup . No, little buddy, don't worry , Follow the agency step by step , Still game implementation . If you have any questions, leave a message in the comment area , Or someone who wants this game can confide in me , I'll reply when I see , Last favorite friends , A little zanga collection , While facilitating learning , If you don't understand, you can ask me at any time .