Snake game is one of the most popular game, since a long time when we used to have keypad phones.
The game is as easy to code as to play and in this article, we will develop snake game in python
We will use python to build the logic of the game and for the interface part, we will use tkinter because it is easy to use.
Project Prerequisites
The prerequisites are as follows: Basic concepts of Python, Tkinter
Creating Snake Game Program – main.py
As you can see in the above code we have created a snake class and there we have defined eight functions which are explained below:
1. __init__: This is the constructor function that calls initialSetup function and also it initializes the tkinter window.
2. initialSetup: This function creates all the variables like the snake, playground, score, and many more. We will use canvas for the playground area because canvas provides many inbuilt functions for creating shapes and it is recommended to use while developing games. Also, we will link the keys for snake movement by calling linkKeys function.
3. linkKeys: This function is responsible for changing the direction of the snake and for all four directions we have modified the coordinates accordingly.
4. Move_snake: This function is responsible for moving the snake body by moving its whole body by one block and deleting the last block.
5. food: This function generates a random x and y coordinate by calling random function to place the food at a random location on the playground and then it creates an oval shape denoting the fruit. And then it checks if the snake’s head overlaps with the food and if it does, it increases snake’s length by one and after that, it calls updateScore().
6. updateScore: It simply increases the score and then it displays the updated score.
7. check_snake_coords: This function checks if any coordinate of the snake lies outside the playground (i.e. less than 0 or greater than 500), and if it does, it will print “Game Over” on the playground and will set gameStatus to zero.
8. Manage: It is the most important function because it is responsible for calling food, move_snake, and check_snake_coords, the functions responsible for movement of the snake.
After definition of the Snake class, we have created its object ‘snakeobj’. And then we have an infinite while loop which updates snake and calls manage function after every 0.4 seconds.
Note: You can modify the sleeping time of the while loop to increase or decrease speed of the snake.
No comments:
Post a Comment