pygame

To test the pygame functions, open your text editor, create a file called sample.py, and save this file in your work folder. Once you have created this file, you are ready to start learning pygame. To use pygame, we will import the pygame module in the first line of our sample.py file:

import pygame

Initializing pygame

Next, we need to take a look at the methods that we need in order to start our instance of pygame. To start pygame, we need to initialize an instance of all the pygame modules. We do this by calling the init() function:

pygame.init()

A pygame game loop is the same as the game loops that we used in previous projects. In this chapter, it will be a while loop that uses while True in order to indicate that the game loop should repeat itself over and over again until it is stopped:

Initializing pygame

Setting up the game screen – size

Once we have pygame set up and initialized, we will want to know how to make a basic background screen. First, you will learn how to set the size of our screen. Then, you will learn to set the background color. pygame has modules to do both, as well as more advanced things, with the background.

For the tasks in this section, we will use the pygame.display and pygame.Surface modules. Our first task is to set the display size. For this task, we will create a screen_width and screen_height variable, and use the pygame.display.set_mode() function. Write these three lines of code under pygame.init():

  screen_width = 400
  screen_height = 600
  pygame.display.set_mode((screen_width, screen_height))

This is the most basic way to set a display and pygame will be able to choose the number of colors that are best for our system if we just use this basic setup.

Note

Explore advanced background setting options at https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode.

Compare your code with the code in the screenshot:

Setting up the game screen – size

Setting up the game screen – color

First, we will create code so we can use colors throughout our game. In computer programming, colors are represented by numbers. Every color is made up of three numbers. Each number represents the saturation of red, green, and blue, in that order. You can use numbers between 0 and 255. When all numbers are 0, game_screen will be black. When all the choices are 255 (255, 255, 255), game_screen will be white, (255, 0, 0) for red, (0, 255, 0) for green, and (0, 0, 255) for blue.

Rather than using numbers repeatedly in our code, we will make a global variable for each color and use the name of the color instead. Let's add a list of global variables to our code, starting from line five of our sample.py file:

  black = (0, 0, 0)
  white = (255, 255, 255)
  red = (255, 0, 0)
  green = (0, 255, 0)
  blue = (0, 0, 255)

For our next task, we will set our game surface color. In order to set the color, we use the fill() function. There are a few ways in which we can set the color of the background. We will make the game_screen = pygame.display.set_mode((screen_width, screen_height)) variable. Then, we will use the variable with the fill() function to set the screen color. Add the game_screen variable to the code in line 14 of the sample.py file:

game_screen = pygame.display.set_mode((screen_width, screen_height))

Then, add the code to fill the screen color in line 15:

game_screen.fill(black)
Setting up the game screen – color

Making stationary objects

Now you will learn how to set stationary (still) items on the canvas. This is often called drawing the objects. To know where to put the objects, we need to know about grids and coordinates. If you have used grids such as an x axis and a y axis in math class, it will be helpful as we will use the same. We will use the x and y coordinates to set the location of each object on our grid.

In math class, the (0,0) coordinates are usually at the center of the grid. In pygame, the (0,0) coordinates are at the top-left hand corner of the screen. As you move from left to right along the x axis, the numbers become larger. So, for our screen that is (400, 600), our x axis starts at 0 on the left and goes all the way up to 400, which is our maximum screen width.

As you move from the top-left of the screen to the bottom-left of the screen along the y axis, the numbers increase. So, our y axis starts at 0 on the top, and as we go to the bottom of our screen, it goes to 600, which is our maximum screen height.

Making stationary objects

We need to know this to understand where objects will go when we draw them on the screen. In order to draw a circle in the center of the screen, for example, the center of the circle would need to fall at (200, 300). The code to draw this circle would be as follows:

pygame.draw.circle(Surface, color, pos, radius)

You can see that there are many arguments that we need to define; let's have a look at each:

  • Surface would be game_screen, which identifies where to draw the circle.
  • For color, we can use one of the global variables that we made for each color. In this case, we can use green.
  • The pos argument means the position where the center of the circle will be located. Since it is (x, y), it will be two numbers in parentheses.
  • The radius argument tells the computer the distance between the center and the edge of the circle and it is used to determine the size.

Now that you know what each argument does, let's add a circle in line 18 of the sample.py file:

pygame.draw.circle(game_screen, red, (250, 300), 20)

So, our preceding code will draw a red circle in the center of the main screen, which is 40 pixels wide (20 pixels from the center of the circle to the outside), with a border, which is 2 pixels wide. Then, the screen will update to show the circle.

We can draw a great number of shapes and objects using pygame, which is very suitable for making games of all kinds. We can draw rectangles, polygons, circles, and ellipses, as well as line segments of varying thicknesses and colors. The following is a screenshot of a simple circle drawn from the code we wrote. You will be able to run it as soon as we write the while loop:

Making stationary objects

while loop – viewing the screen

It would be great if we could see the shapes that we are drawing, so let's add some code that allows us to view our screen. We will make a while loop, and place all of the actions, such as drawing and making the screen, inside of the while loop. First, take a look at the screenshot of the while loop so that you can see what the finished product looks like:

while loop – viewing the screen

You will notice that we have created a while True loop in line 17. This uses the True Boolean to keep all of the actions going while the loop is running. Add the while loop to line 17 of the sample.py file:

while True:

Beneath the while loop, you have already written the code to draw the circle. Indent it four spaces. On line 19, we will add the pygame.display.update() function:

pygame.display.update()

Now that the while loop is written, you should be able to run your code and see your first visual screen! To test your code, open your terminal/command prompt, and then run your code with the following command:

python sample.py

Making more shapes

Now that you know how to draw a circle, you are prepared to make other shapes. We will review the code for some basic shapes. You can add the code for different shapes to your while loop and make some great Python art to share with others.

Rectangle

To draw a rectangle, the basic function is pygame.draw.rect(Surface, color (x, y, width, height)). The Surface argument is game_screen; the color can be set to anything you like. The x and y variables will determine the placement of the top-left corner of the rectangle. The width and height determine the size of the rectangle in pixels. To add a rectangle to your code, copy this line into your sample.py file on line 18:

pygame.draw.rect(game_screen, blue, (20, 20, 50, 80))

Place the code before the pygame.display.update() code. The pygame.display.update() function should be the last line of code in your file for this exercise.

Ellipse

We can draw an ellipse by using the pygame.draw.ellipse(Surface, color, (x, y, width, height)) function. You will notice that the ellipse function accepts the same arguments as the rectangle function, except the ellipse will draw a circle within the rectangle instead of filling up the whole rectangle. If you want to add an ellipse to your code, copy the following line into line 19:

pygame.draw.ellipse(game_screen, white, (300, 200, 40, 80))

Save and try running your code to see the red circle, blue rectangle, and white ellipse in the black background:

python sample.py

If you have written your code without error, you should expect to see something like this:

Ellipse

Experimenting with shapes

Now that you know how to make a circle, rectangle, and ellipse, you can start experimenting with each of the arguments. Changing the radius, width, or height of a shape will change the size. Changing the x axis, y axis, or both will change the location of the shape on the screen. Here are some experiments to try:

  • Change the radius of the circle
  • Change the x and y coordinates of each shape
  • Change the width and height of the rectangle and ellipse
  • Change the color of each shape

More advanced shapes

There are some more advanced shapes that you can create with pygame, including polygons with as many sides as you like. You can explore the different functions in the pygame.draw module by visiting the pygame docs.

Note

To know more about shapes in pygame, visit https://www.pygame.org/docs/ref/draw.html.

Making moving objects

Now, video games worth playing have moving objects. Moving objects have a lot more problems to solve than stationary objects. Here are some questions to ask about moving objects:

  • Where do you want the object to originate on the screen?
  • How does the object move?
  • How does the object know how fast to move?
  • How does the object respond when it hits another object (collides)?
  • How does the object respond when it hits the edge of the screen?
  • How does the object know when to stop moving?

We create a moving object the same way that we create a stationary one—draw it on the screen.

Moving objects with the keyboard

Let's suppose that we want to move our red circle around the screen. Something we need to consider is that the objects do not actually move. Rather, the objects appear to move. This is how you get an object to move:

  • Draw an object
  • Get the user's input from pressed keys
  • Redraw the object based on user actions using pygame.display.update()

The pygame.key module contains methods to work with the keyboard. During the game loop, we need to know whether the user is pressing a key to move the blue rectangle. To figure out whether the user is pressing a key to move the rectangle, we would use this line of code, for example:

pygame.key.get_pressed()

Now, if we want to control how the computer takes the input when a user presses a key, we can use this line of code:

pygame.key.set_repeat()

This line tells the computer what to do when someone holds the key or presses it repeatedly, which happens a lot in games. We would use these key functions to set up some if/else logic about how our blue rectangles move when certain keys are pressed. You will see this logic in the next chapter.

Now, there are a lot of keys on the keyboard. Before going on to the next chapter, it is a good idea to review the documentation for pygame and learn how to select your keys. For example, if you want to use the down arrow key, you would use [pygame.K_DOWN] to identify that key, and then use other code to take a look at what happens if the down key is being pressed.

Note

The documentation for keys can be found at

https://www.pygame.org/docs/ref/key.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset