Code Comments Tutorial: Snakey

Welcome to the Code Comments Tutorial for Snakey, a Nibbles clone. Code Comments is a series of simple games with detailed comments in the source code, so you can see how the game works.

The text in between the triple-double-quotes are comments (technically they are multi-line strings, but Python uses them for multi-line comments). The Python interpreter ignores any text in between them, so we can add any comments about the source code without affecting the program. In general for Code Comments, the comments will describe the lines of code above the comment. It helps to view this file either on the Code Comments site or with a text editor that does "syntax highlighting", so that the comments appear in a separate color and are easier to distinguish from the code.

This Code Comments assumes you know some basic Python programming. If you are a beginner and would like to learn computer programming, there is a free book online called "Invent Your Own Computer Games with Python" at http://inventwithpython.com

The Code Comments programs make references to sections of this book throughout the program. This Code Comments can also teach you how to use the Pygame library to make your own games with graphics, animation, and sound. You can download Pygame from http://pygame.org and view its documentation.

You can make some easy modifications to the game by changing the all-caps constant variables (such as WINDOWWIDTH, FPS, CELLSIZE, etc.) This code uses global variables instead of object oriented programming in order to make it simple to understand.

Snakey source code with comments.

Snakey source code without comments.

Snakey .exe executable Windows binary (no need to download Python & Pygame)

Also, someone has written a nice version of this game in C++ with SDL (which is the library that Pygame wraps) here: https://github.com/0x20/Snake

How To Play Snakey:

You are the green snake on the screen. Use the arrow keys or the WASD keys to move the snake around and eat the red apples that are on the screen. Each time you eat an apply, your snake grows in length. Do not run into either the edges or yourself.

3 thoughts on “Code Comments Tutorial: Snakey

  1. Nice concept, well done! But, man, those huge, endless lines... I suggest you word wrap to 72 characters according to PEP 8, and maybe even put online a syntax-colored version (or link to pastebin.com).

  2. There's a typo in snakey_plain.py. Line #66:

    rotatedRect.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)

    should be:

    rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)

    EDIT: Thanks for the typo! I've corrected the code now. -Al

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>