Snake Game Python Code

Active1 year, 9 months ago
Python$begingroup$

I'm working for a month or so on a Snake game in Python. It's working well (I got some good help on it already), but since I'm a beginner in pygame, I would like some feedback from better programmers than me. Anything that improves performance, readability and/organization is welcomed.

Snake in 35 lines. Samuel Backman. A snake game in 35 lines of code. I wrote it only to check how many lines i needed to write a snake game. 2019 Light Bright. This is a simple GUI Based game written for the beginners. Snake Game in Python project with source code is free to download. Use for education purpose only! For the project demo, have a look at the image slider below.

Keep in mind that the sounds are in a separate folder so this code will not work on your computer unless you have the files. I just want a code review.

Jamal
32k12 gold badges123 silver badges231 bronze badges
MateusMateus
Python$endgroup$Game

1 Answer

$begingroup$

Thank you for sharing. Much of this looks nice, and the code is understandable. Your identifiers are well chosen.

Please run flake8. It will ask you to add a few blank lines, that sort of thing. Also, PEP-008 asks that one-line docstrings end with a '.' period.

Keeping variables out of global scope is good. But 'main() is the new global' is an odd style. Consider moving at least some def's to top level, or creating a SnakeGame class.

You have a lot of magic numbers. Some are mostly OK, like pre_init(44100, -16, 1, 512). But things like grid resolution of 10 pixels, and grid size, really need to be constants, like GRID_WIDTH = 72 or GRID_SIZE = (72, 46). Refactor this. Refactor it now.

There is maybe an opportunity to introduce a Display class that knows the 'secret' of grid resolution being 10px. So much of the game would manipulate food + snake in game space coordinates less than GRID_SIZE, and would ask Display to plot points in the much larger screen space. With that in hand, imagine adding one blue pill (food) and one red pill to the board. Eating blue causes Display to flip mirror image around X axis, and red, around Y axis. The rest of your game wouldn't know or care about the visual effect.

This is perfectly nice: bugs = pygame.init(). But consider re-phrasing it as pass, fail = pygame.init(), as bugs[1] is slightly obscure (I had to consult the docs).

DRY: don't repeat yourself. Consider writing a helper function for game_sound(), to factor out the common expressions.

Referring to sys.argv[0] in game_sound is an anti-pattern. Parse it out early and store it in a named variable.

Your comments are weirdly specific, e.g. on you_lose(). Please don't say in comments what the code already says clearly. At some point you'll make it 42px Arial font, and then either you'll remember to update the comment, or you'll have a comment that lies. Put generalities into English language comments, and put specifics into the code.

The same literal text is repeated several times. You should add a manifest constant like FONT = 'times new roman'.

Things like pause_position.midtop and score_position.midtop could use an expression like GRID_WIDTH * 0.5.

It appears food_spawn is misnamed, and should be food_spawned. Spawning more food when it is False is surprising. Perhaps a name like out_of_food would be clearer.

You defined food_position to be a list, [x, y]. Please make it a tuple, (x, y). Lists are variable length, unlike tuples. (At some point you may support a list of multiple food locations, and the spawn check would test if its length is zero.)

modeling direction

I recommend you parse key_{up,right,down,left} into dx and dy values drawn from {-1, 0, 1}. And model current direction in the same way. This would reduce 'going backwards?' to two tests. And if you store direction as an index 0..3 into this:

then 'going backwards?' is just a test of (direction + 2) % 4. (That's plus len(delta)/2, mod len(delta).)

Advancing the snake is merely adding (dx, dy) to snake_position.

detecting collision

This seems more expensive than necessary:

Consider maintaining a set alongside snake_body. (This is an opportunity to define a Snake class.) When pixel is added to head of snake_body, add it to the set as well (constant time, independent of snake length.) When pixel is removed from tail, remove it from set. Now instead of linear scan you can do a single set membership query.

Of course, there is already a data structure that can be queried in constant (less than linear) time. The screen. Ask the display if we're moving onto a snake-colored pixel when detecting collision.

J_HJ_H
$endgroup$

Snake Game Python Code Turtle

Not the answer you're looking for? Browse other questions tagged pythonperformancepython-3.xpygamesnake-game or ask your own question.

Project: Snake Game in Python with source code

– To download Snake Game project for free (scroll down)

About Project

Snake Game project is written in Python. The project file contains Assets, python scripts (main.py, food.py, block.py, world.py) with text files. The gameplay Graphics is simple, good enough and the controls are simple for the users. Talking about the gameplay, it’s a common game for all. All the playing methods are too simple like the original all you have to do is just move around in order to eat things. Here, the user has to control the snake using A, S, D, W keys and the snake expands after eating things. After a certain score, the borders will appear in the game. The player loses whenever the snake runs into a border or itself/its own tail. A simple GUI is provided for the easy gameplay. The gameplay design is so simple that user won’t find it difficult to use and navigate.

Snake Game Python Worm

In order to run the project, you must have installed Python, Pygame on your PC. This is a simple GUI Based game written for the beginners. Snake Game in Python project with source code is free to download. Use for education purpose only! For the project demo, have a look at the image slider below.

DOWNLOAD SNAKE GAME IN PYTHON WITH SOURCE CODE: CLICK THE BUTTON BELOW

You May Also Like

Catch The Fruit In Python With Source Code

Project: Catch The Fruit In Python -to download catch the fruit in python project for free(Scroll Down) Catch…

Snake Game Python Code Microbit

Simple Airline Booking System In PYTHON With Source Code

Project: Simple Airline Booking System in Python with source code About Project This simple airline booking system project…

Game of Crowns Game In PYTHON With Source Code

Project: Game of Crowns Game in Python with source code About Project Game of Crowns Game project is…

Simple Employee Record System In PYTHON With Source Code

Snake Game

Project: Simple Employee Record System in Python with source code About Project This simple employee record system project…

Simple Customer Feedback System In PYTHON With Source Code

Python 2.7 Snake Game Code

Project: Simple Customer Feedback System in Python with source code About Project This simple customer feedback system project…