Informatics 9. Билингвальный учебник | страница 33



If you run the code above, a 600x400 pixel window will appear and close immediately.

Why does the window close immediately?

Because the program ends after the execution of these expressions. Neither init () nor set_mode () suggest cyclic event. That’s why you need to create a loop, causing the program to hang. And now, create a loop:


Example 1

run = True

while run:

for event in pygame.event.get(): # User did something

if event.type == pygame.QUIT: # If user clicked close

run = False # Close clicked so exit this loop


To set the title of the window (which is shown in the title bar) use the following line of code:


pygame.display.set_caption(“Title”)

Ending the Program

Right now, clicking the “close” button of a window while running this Pygame program in IDLE will still cause the program to crash. The problem is, even though the loop has exited, the program hasn’t told the computer to close the window. By calling the command below, the program will close any open windows and exit as desired.


pygame.quit() # Uninitialize all pygame modules

Practice 2

1. Create a simple PyGame window(495x120 pixels).

2. Set title “Cool game in PyGame“.


Literacy

1. What is the PyGame library?

2. What functions does PyGame provide?

3. What can you get if you use it?


Terminology

library - кітапхана - библиотека

package - пакет - пакет

collide – соқтығысу - сталкиваться

import – импорттау - импортировать

surface – беті - поверхность

initialize – инициализациялау - инициализировать

event – жағдай - событие


4.2 BACKGROUND IMAGE IN PYGAME

You will:

Set a background image.


What makes you want to play a 2d game?

How to create background

First of all, you need to add variables that define colors that you use in program. Colors are defined in a list of three colors: red, green, and blue.

As you remember, lists in Python are surrounded by either square brackets or parentheses. Individual numbers in the list are separated by commas. Below is an example that creates variables and sets them equal to lists of three numbers. These lists will be used later to specify colors.


# Define some colors

BLACK = ( 0, 0, 0)

WHITE = ( 255, 255, 255)

GREEN = ( 0, 255, 0)

RED = ( 255, 0, 0)

BLUE = ( 0, 0, 255)


Clearing the Screen

The following code clears whatever might be in the window with a white background. Remember that the variable WHITE was defined earlier as a list of 3 RGB values.


# Clear the screen and set the screen background