Adding the Frame

Now, let's enhance the appearance of our snake game. We will add a 75 pixel border around the game window and create a rectangle with a DARK_GREEN border to contain the game play area, to look like this. To add the border, we will define an offset value named "OFFSET" with a value of 75 pixels.

This offset value will determine the width of the border. Let's adjust the size of the game window to include the frame of 75 pixels on each side.

In this line of code we create the game window. The first two arguments in this call are the width and the height of the game window.

We need to increase that by 2OFFSET pixels. So we change this line of code like this: 2OFFSET + cell_size*number_of_cells

And 2OFFSET + cell_sizenumber_of_cells. We'll also create a DARK_GREEN rectangle in the game loop, with no fill and a stroke of

5 pixels to contain the play area. This will create a visually appealing frame around the game window, and help distinguish it from the rest of the screen . To draw the DARK_GREEN rectangle, we'll use the "pygame.draw.rect" function, which takes four arguments: the surface to draw on, the color of the rectangle, the position of the rectangle, and the border size of the rectangle.

pygame.draw.rect(surface, color, rectangle, border_size)

Let’s fill in all the things we know so far.

The surface is the display_surface so we enter the screen here, then the color is DARK_GREEN, and the border size is 5 pixels. Now, let’s think about the position and the size of the rectangle.

For the rectangle we want the coordinates of its top left corner, its width and its height. Since we want to have a frame of 75 pixels around the game window the rect will be drawn with the following coordinates: (OFFSET-5, OFFSET-5,

And width and height cell_sizenumber_of_cells + 10, cell_sizenumber_of_cells + 10).

We subtract 5 pixels from the x and y coordinate because the rectangle has a 5 pixel border.

That's why we add 10 pixels to the width and the height of it. So to draw the DARK_GREEN rectangle the code looks like this.

Now that we've added the frame, let's see how the game looks! Unfortunately, the positions of the snake and food are not calculated correctly due to the omission of the OFFSET. Let's fix it now. We need to make changes to the draw methods in both the Snake and Food classes.

In the Snake class, we simply add OFFSET to the x and y coordinates of the rectangle that we are drawing on the screen. OFFSET + here and here.

We do the same in the Food class in the draw method in the food rectangle.

OFFSET + here and here. We are just adding OFFSET to its x and y coordinates.

Let's try the game again. Excellent, everything is working as intended. Now, let's give the game a title, add a score, and sounds and we're done.