Python Tutorial Part Four: Approaching Coding

by Simon Bluck

Sometimes, you’re not sure what you’re going to write, where it’s going. You just have an idea for a program and you’re not sure where to start. So, what do you do? Sketch out what you are thinking about, write it down. Now, is there some part of what you want to do that you could make a start on? Throw some code together to implement some small part? Well, that’s a start. Perhaps it’s something that might have general usage, so you could write it as a separate module.

Say you want to write a chess program. It splits into different parts: the board (visual); the user interface; web features; moving the chess pieces; the core chess-playing algorithm; a database of standard chess moves (especially openings); move recording and replaying. These are in fact each pretty much independent and you could have a go at each one separately. Though, it would be nifty to get the visual board up and running first, and the chess pieces moving, so you can use that to see the results of your other efforts. And you may well want to research what other people have done in this area too. Much that you learn and achieve may be reuseable for other projects. Perhaps you write a general move (change) recorder and replayer that you can polish to be reusable across other games and similar.

Coding style

Depends on the size of the program/module, intended audience, enthusiasm etc.

  • If you’re just quickly trying something out then style isn’t overly important.

  • If you’re coding upwards of 50 lines then you’re best laying it out nicely and using comments.

  • If you’re coding upwards of 500 lines then that’s quite an investment of effort and it’s best to get it nicely maintainable at least by you. If it’s intended for a wider audience then put more effort into it. and if it’s being published then get it reviewed.

There should be a similar approach to testing: from no testing to a full regression test suite.

Documentation

Publishing also requires ensuring you don’t infringe on other people’s rights.

For best understanding, bear in mind who else may be reading the code. Don’t be too clever with complicated parts of the language and don’t try and do too much in one statement. Lay the code out so it looks neat and tidy.

Structuring a large program well can be difficult: what to split into separate programs, separate modules, and separate functions/classes.

Often, you end up with a structure that doesn’t feel like the best, and it would be a lot of effort to restructure. It’s a common problem. Perhaps the only sure thing I can say is that if you’ve got a GUI aspect to your program then try and keep that separate: program the non-GUI part with functions/methods that can be called by the GUI part.

Example from the pygame library

So, if we’ve got to this point in the course then there may just be time to have a look at some examples using the pygame library. On raspbian, you’ll find them here:

/usr/lib/python3/dist-packages/pygame/examples

Note that the readme page states that the pygame examples programs are in the public domain, so it’s OK to use them here.

A slightly modified version of moveit.py

#!/usr/bin/env python

"""
This is the full and final example from the Pygame Tutorial,
"How Do I Make It Move". It creates 10 objects and animates
them on the screen.

Note it's a bit scant on error checking, but it's easy to read. :]
Fortunately, this is python, and we needn't wrestle with a pile of
error codes.

Modified SDB  Jan 2016 to move at a fixed rate.
"""


#### import everything
import os, pygame
from pygame.locals import *

main_dir = os.path.split(os.path.abspath(__file__))[0]

#### our game object class
class GameObject:
    def __init__(self, image, height, speed):
        self.speed = speed
        self.image = image
        self.pos = image.get_rect().move(0, height)
    def move(self):
        self.pos = self.pos.move(self.speed, 0)
        if self.pos.right > 600:
            self.pos.left = 0


####quick function to load an image
def load_image(name):
    path = os.path.join(main_dir, 'data', name)
    return pygame.image.load(path).convert()



####here's the full code
def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480))

    player = load_image('player1.gif')
    background = load_image('liquid.bmp')

    # scale the background image so that it fills the window and
    #   successfully overwrites the old sprite position.
    background = pygame.transform.scale2x(background)
    background = pygame.transform.scale2x(background)

    screen.blit(background, (0, 0))

    objects = []
    for x in range(10):
        o = GameObject(player, x*40, x)
        objects.append(o)

    clock = pygame.time.Clock()
    while 1:
        for event in pygame.event.get():
            if event.type in (QUIT, KEYDOWN):
                pygame.quit()
                return

        for o in objects:
            screen.blit(background, o.pos, o.pos)
        for o in objects:
            o.move()
            screen.blit(o.image, o.pos)

        pygame.display.update()
        clock.tick(40)



if __name__ == '__main__': main()


Next -> Part Five: Syntax and Constructs