Pygame 4: Breakout – Step 3

Pygame Tutorial 4 – Breakout: Step 3
Written by Collin Green — Version 1.0.0 — 2010-12-31

Goal:

In step 2 we created a semi-playable version of breakout; we could break the blocks but there was only one level and no way to win or lose. Next tutorial we will add the rest of the gameplay, but in this one we are going to make a level editor so we can create levels very quickly and easily. At the end you should be able to crank out new levels in a couple second each.

The Plan

To create the level editor we are going to copy over a bunch of code from the game and modify it. We want the editor to have exactly the same setup as the main board, so we will set up the background the same way. Our goal is to have an easy interface to create a bunch of blocks and then export them into a file we can easily parse in the next step of the tutorial. I decided we will do this by creating a full ‘level’ of Blocks and adjusting the Block class to represent both a blank space and an unbreakable block in addition to the 5 block levels we already have. Now we just figure out what Block the user clicks on and increment/decrement its level accordingly. Then when the user decides to save, we will take our level of Blocks and save off a file containing all their levels.

The Setup

The very first thing to do is start a new file. This is a separate program so we want it in its own file. At the top of the file put the usual import code.

11
12
13
14
15
16
17
18
try:
    import sys, os
    import pygame
    from pygame.locals import *
 
except ImportError, err:
    print "%s Failed to Load Module: %s" % (__file__, err)
    sys.exit(1)

The Pieces

Now we need to copy over some of the pieces we used in the real game. We could have imported the classes from the game file and modified them, but the changes are pretty severe and I felt like it was more clear to just rewrite everything here.

The first thing we have is our Block class. It is fairly similar to the game one, except we made some changes. We removed the hit function since we don’t need it and added up and down functions to adjust the block level. We also added the resetImage function which just reloads the correct image for the Block when we change its level.

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Block(pygame.sprite.Sprite):
    """A block sprite. Has a level and a position."""
    def __init__(self, xy, images, level=1):
        pygame.sprite.Sprite.__init__(self)
 
        # save images and level
        self.images = images
        self.level = level
 
        # create initial rect
        self.rect = pygame.Rect(xy[0]-25, xy[1]-10, 50, 20) # left, top, width, height
 
        # set image and rect so we can be rendered
        self.resetImage()
 
    def up(self):
        self.level += 1
        self.resetImage()
 
    def down(self):
        self.level -= 1
        self.resetImage()
 
    def resetImage(self):
        if self.level in self.images:
            self.image = self.images[self.level]
            xy = self.rect.center               # save previous position
            self.rect = self.image.get_rect()   # reset rect in case shape changes
            self.rect.center = xy               # reset block to old position

BlockFactory

Next we copy over the BlockFactory. This is nearly the same except we remove the getSolidBlock function and add the gray block image to the regular image list we pass to new Blocks. That way we don’t have to do anything different when we want to create a solid block – it is just another level as far as our Block class is concerned.

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class BlockFactory(object):
    """Using this class to return blocks with a copy of the images
        already loaded. No sense in re-loaded all the images for
        every block every time one is created."""
 
    def __init__(self):
        # load all our block images
        self.images = {
            1: pygame.image.load(os.path.join('images','block_blue.png')),
            2: pygame.image.load(os.path.join('images','block_green.png')),
            3: pygame.image.load(os.path.join('images','block_red.png')),
            4: pygame.image.load(os.path.join('images','block_orange.png')),
            5: pygame.image.load(os.path.join('images','block_purple.png')),
            6: pygame.image.load(os.path.join('images','block_gray.png'))
        }
 
    def getBlock(self, xy, level=1):
        return Block(xy, self.images, level)

Button Sprite

Since the rest of the editor is all mouse clicks, I wanted a button the user could click to save the level instead of having to go to the keyboard and hitting ctrl-s, so here is an extremely simple button class. It is just a sprite that uses the font class to generate an
image and uses that for rendering. It isn’t pretty, but we could easily make it a little nicer looking if we wanted to with a little draw code instead of just filling the background.

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class Button(pygame.sprite.Sprite):
    """An extremely simple button sprite."""
    def __init__(self, xy, text):
        pygame.sprite.Sprite.__init__(self)
        self.xy = xy
        self.font = pygame.font.Font(None, 25)  # load the default font, size 25
        self.color = (0, 0, 0)         # our font color in rgb
        self.text = text
        self.generateImage() # generate the image
 
    def generateImage(self):
        # draw text with a solid background - about as simple as we can get
        self.image = self.font.render(self.text, True, self.color, (200,200,200))
        self.rect = self.image.get_rect()
        self.rect.center = self.xy

Text Sprite

This one is very very similar to the button sprite above, but for clarity I decided they could be two different classes. This one stores and renders some text the same way, but has another method for changing the text. I also hardcoded the colors into these classes because I’m lazy — If you wanted to merge them you would just need to make some options for setting the font color and filling the background.

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class TextSprite(pygame.sprite.Sprite):
    """An extremely simple text sprite."""
 
    def __init__(self, xy, text=''):
        pygame.sprite.Sprite.__init__(self)
        self.xy = xy    # save xy -- will center our rect on it when we change the text
        self.font = pygame.font.Font(None, 25)  # load the default font, size 25
        self.color = (255, 165, 0)         # our font color in rgb
        self.text = text
        self.generateImage() # generate the image
 
    def setText(self, text):
        self.text = text
        self.generateImage()
 
    def generateImage(self):
        """Updates the text. Renders a new image and re-centers at the initial coordinates."""
        self.image = self.font.render(self.text, True, self.color)
        self.rect = self.image.get_rect()
        self.rect.center = self.xy

LevelBuilder

Next we have our LevelBuilder class. This is the same as the Game class in the previous tutorials, and you’ll see that their __init__ and run methods are very similar. Things to notice in the __init__ — we are now also listening for mouse click events, we create our save button and feedback text sprites, and we have a function resetLevel that we call to get it set up and ready for the user.

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
class LevelBuilder(object):
    """Our level builder object! Initializes everything."""
 
    def __init__(self):
        """Initializes pygame and sets up our pygame window
        and other pygame tools."""
 
        # load and set up pygame
        pygame.init()
 
        # create our window
        self.window = pygame.display.set_mode((520, 600))
 
        # clock for ticking
        self.clock = pygame.time.Clock()
 
        # set the window title
        pygame.display.set_caption("Pygame Tutorial 4 - Breakout")
 
        # tell pygame to only pay attention to certain events
        # we want to know if the user hits the X on the window, and we
        # want keys so we can close the window with the esc key
        pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP, MOUSEBUTTONDOWN])
 
        # make background
        self.background = pygame.image.load(os.path.join('images','background.jpg'))
        # blit the background onto the window
        self.window.blit(self.background, (0,0))
        # flip the display so the background is on there
        pygame.display.flip()
 
        # create sprite group for blocks
        self.blocks = pygame.sprite.RenderUpdates()
 
        # create sprite group for everything else
        self.sprites = pygame.sprite.RenderUpdates()
 
        # create our blockfactory object
        self.blockfactory = BlockFactory()
 
        # create a blank level
        self.resetLevel()
 
        # Save button sprite
        self.savebutton = Button((260,450), 'Save')
        self.sprites.add(self.savebutton)
 
        # feedback sprite
        self.feedback = TextSprite((260, 550),  '')
        self.sprites.add(self.feedback)

LevelBuilder.run

The run method is almost exactly the same except each frame we also call self.drawGrid which draws grid lines to show where the user can click. I put this method after we draw the blocks, which makes the lines overlap them a bit, but doing it before the clear was causing some flickering I didn’t like. Try both ways and see what I mean.

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    def run(self):
        """Runs the game. Contains the game loop that computes and renders
        each frame."""
 
        print 'Starting Event Loop'
 
        running = True
        # run until something tells us to stop
        while running:
 
            # tick pygame clock
            # you can limit the fps by passing the desired frames per seccond to tick()
            self.clock.tick(60)
 
            # handle pygame events -- if user closes game, stop running
            running = self.handleEvents()
 
            # update the title bar with our frames per second
            pygame.display.set_caption('Pygame Tutorial 4 - Breakout   %d fps' % self.clock.get_fps())
 
            # render blocks
            self.blocks.clear(self.window, self.background)
            dirty = self.blocks.draw(self.window)
 
            # render everything else
            self.sprites.clear(self.window, self.background)
            dirty += self.sprites.draw(self.window)
 
            # draw a grid on our background
            self.drawGrid()
 
            # blit the dirty areas of the screen
            pygame.display.update(dirty)                        # updates just the 'dirty' areas
 
        print 'Quitting. Thanks for playing'

LevelBuilder.resetLevel

Here is the resetLevel method we called in the __init__. The first line empties our block render group so we don’t leave any Blocks in there rendering when they were supposed to be removed. The rest creates an empty 2D array then fills it with Blocks of level 0.

197
198
199
200
201
202
203
204
205
206
207
208
209
    def resetLevel(self):
        # empty our sprite group
        self.blocks.empty()
 
        # create our level object -- 2D array of blocks with level 0
        self.level = []
        for y in range(5):
            row = []
            for x in range(10):
                pos = (35+(x*50), 20+(y*20))    # calculate the position for the block
                block = self.blockfactory.getBlock(pos, 0)  # create the block
                row.append(block)               # add the block to the row
            self.level.append(row)              # add the row to the array

LevelBuilder.drawGrid

Next is the drawGrid class we call each frame to, you guessed it, draw the grid. It uses the pygame.draw functions to put white lines around all the places we can put a block. Looking back now, I think a better way to write this would have been to just create another block image that was just an outline and pass that to new Blocks as their level 0 image. Oh well – take this as an example of how there are lots of ways to solve the same problem.

211
212
213
214
215
216
217
218
219
220
221
    def drawGrid(self):
        # draw lines on the background where blocks can go
        linecolor = (255,255,255)
        for col in range(11):   # 11 so we get both sides of all the columns
            # surface, color, start, end
            pygame.draw.line(self.window, linecolor, (10+(col*50),10), ((10+col*50),110))
 
            for row in range(6):    # 6 so we get both sides of all the rows
                pygame.draw.line(self.window, linecolor, (10, 10+(row*20)), (510, 10+(row*20)))
        # render the display
        pygame.display.flip()

LevelBuilder.handleEvents

This one is pretty similar to the game handleEvents method. We check if the user presses escape to end or control-s to save and we send any mouse clicks to the mouseDown method for processing.

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    def handleEvents(self):
        """Poll for PyGame events and behave accordingly. Return false to stop
        the event loop and end the level builder."""
 
        # poll for pygame events
        for event in pygame.event.get():
            if event.type == QUIT:
                return False
 
            # handle user input
            elif event.type == KEYDOWN:
 
                # if the user presses escape, quit the event loop.
                if event.key == K_ESCAPE:
                    return False
 
                # ctrl-s saves the level
                elif event.key == K_s and event.mod & KMOD_CTRL:
                    self.save()
 
            # handle mouse clicks in self.mouseDown
            elif event.type == MOUSEBUTTONDOWN:
                self.mouseDown(event.pos, event.button)
 
        return True

LevelBuilder.mouseDown

This is the bulk of the level editor functionality. First, we check if the user clicked the save button and call the save function. Next, we filter out any clicks that aren’t in our level area because we don’t care about those. Then we figure out what Block the click was over and call Block.up for left clicks and Block.down for right clicks. We also have some code to remove Blocks with level 0 from the render group. Note: we wouldn’t need this extra code if we had gone with the alternative transparent level 0 image discussed above.

249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    def mouseDown(self, position, button):
        """Handles all the mouse clicks. We want left clicks
        to add to a block or create one and right clicks to take away."""
        posx, posy = position
 
        # check if the save button was clicked
        if self.savebutton.rect.collidepoint( position):
            self.save()
            return
 
        # otherwise, only care about clicks in the level area
        if posx < 10 or posx >= 510 or posy < 0 or posy >= 110:
            return
 
        # convert mouse position to block coordinate
        x = int((posx-10) / 50)     # subtract 10 for the wall and divide by block width
        y = int((posy-10) / 20)     # subtract 10 for the wall and divide by block height
 
        # get the block we are on
        block = self.level[y][x]    # notice y then x because our level is rows then cols
 
        # Left click
        if button == 1:
            # if the block in this space is level 0, increment and add for render
            if block.level == 0:
 
                # increment block level
                block.up()
 
                # add to rendering group so it gets displayed
                self.blocks.add(block)
 
            # on a block with level less than 6
            elif block.level < 6:
                # increment block level
                block.up()
 
            # on a block with level > 6
            else:
                # loop back to an empty block
                block.level = 0
 
                # remove from rendering group
                self.blocks.remove(block)
 
        # right click
        elif button == 3:
            # if the block in this space is greater than 1
            if block.level > 1:
                # decrement block level
                block.down()
 
            # on a block with level < 1
            else:
                # change back to an empty block
                block.level = 0
 
                # remove from rendering group
                self.blocks.remove(block)

LevelBuilder.save

The last thing we need to do in the LevelBuilder class is the save method. We first generate the ‘next’ level name by starting at level1.level and incrementing the number until there is not already a file with that name. Then we create the file and write the level of each block in each row, separated by spaces. Finally, we call resetLevel to clear out all the Blocks and give the user a clean slate to work from.

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    def save(self):
        self.feedback.setText('Saving...')
 
        # generate unique level name
        count = 1
        name = 'level%d.level'%count
        while os.path.isfile( os.path.join('levels', name) ):
            count += 1
            name = 'level%d.level'%count
 
        # create file
        f = open(os.path.join('levels',name), 'w')
 
        # generate contents from self.level
        for row in self.level:
            for col in row:
                f.write('%d ' % col.level)    # write block level
            f.write('\n')   # write new line
 
        # close file handle
        f.close()
 
        # show level name in feedback
        self.feedback.setText('Saved level to levels/%s' % name)
        print 'Saved levels/%s' % name
 
        # reset level
        self.resetLevel()

The End

The very last thing is the couple lines of code at the end to create the LevelBuilder object and run it when the script is run.

339
340
341
if __name__ == '__main__':
    lb = LevelBuilder()
    lb.run()

Result and Download

Now we have a fully functional level builder! Use left and right clicks to add/subtract block levels and hit save to save. Couldn’t be more simple.

A level editor for our Breakout tutorial

A level editor for our Breakout tutorial

Tutorial Download:
Pygame Tutorial 4 - Breakout (223)