Python: pygame game programming journey 7 (pygame basics 1)

Source: Internet
Author: User

Similar to Python's built-in modules such as random, math, and time, the Pygame framework also has many modules to provide functions such as drawing, playing sound, and processing mouse input.

This chapter describes the basic modules and functions provided by Pygame, and assumes that the reader has basic python programming knowledge, read "Ivent Your Own Computer Games With Python.

 


GUI and CLI

 


Use the print () and input () functions provided by Python to operate the text. Your program can display the text on the display and allow the user to input the text from the keyboard, this type of program has a command line interface (CLI), but it cannot display images, colors, or use the mouse, this type of program only through the input () the function receives keyboard input and responds to the input only after the user presses the Enter key. Therefore, it is not suitable for the development of real-time action games.

Pygame provides the graphicaluser interface (GUI) program function to replace the text-based CLI program. GUI programs can display windows with images and colors.

 


HelloWorld program of Pygame version

 


We will use Pygame to compile a window program that displays "Hello World". The source code is as follows:


[Python]
Import pygame, sys
From pygame. locals import *
 
Pygame. init ()
DISPLAYSURF = pygame. display. set_mode (400,300 ))
Pygame. display. set_caption ('Hello World! ')
While True: # main game loop
For event in pygame. event. get ():
If event. type = QUIT:
Pygame. quit ()
Sys. exit ()
Pygame. display. update ()
Import pygame, sys
From pygame. locals import *

Pygame. init ()
DISPLAYSURF = pygame. display. set_mode (400,300 ))
Pygame. display. set_caption ('Hello World! ')
While True: # main game loop
For event in pygame. event. get ():
If event. type = QUIT:
Pygame. quit ()
Sys. exit ()
Pygame. display. update ()


Run the program, as shown in the following empty window:

 


Yes, you have just created the most boring game in the World. It only displays "Hello World" in the title of the window, but creating a window is the first step of the graphic interface game, when you click Close in the upper-right corner of the window, the program exits and the window disappears.

If you call the print () function to display text in the window, it will not work, because print () is a function of the CLI program, and the input function is the same. Pygame uses other functions to provide input and output, which will be described later in this chapter. Let's first explain the meaning of each line of the "Hello World" program.

 

Create a Pygame Program

 


The first line in this program is essential for almost all pygame programs.


[Python]
Import pygame, sys
Import pygame, sys

This line uses the import Statement to import the pygame and sys modules to be used in the program. The pygame module provides functions such as graphics and sound.

Note: When you import the pygame module, you will import all sub-modules of pygame by default, such as pygame. images, pygame. mixer. music, so there is no need to import them again.


[Python]
From pygame. locals import *
From pygame. locals import *

Line 2nd is also an import statement, but it does not use the import modulename format, but uses the from modulename import * format. Generally, if you want to call a function in a module, you must use modulename. functionname () format. However, using the frommodulename improt * format directly uses the function name without the module name prefix (just like a Python built-in function ).

We imported pygame. locals because it contains many constants provided by Pygame. From... The import * Format removes the need to add the pyame. locals prefix before the constant name.


[Python]
Pygame. init ()
Pygame. init ()

Line 3 calls pygame. init () function, which must be called after the pygame module is imported and before any function provided by Pygame is used, to use the pygame function, you must call it at the beginning. If you encounter an error like pygame. error: font not initialized, check whether you forget to call pygame. init () in front of the program ().


[Python]
DISPLAYSURF = pygame. display. set_mode (400,300 ))
DISPLAYSURF = pygame. display. set_mode (400,300 ))

Line 3 calls pygame. display. set_mode () function, which returns a pygame of the current window. surface object (the Surface object will be described later in this chapter). Note that you input a tuple with two integer values to the function. This tuple notifies set_mode () function the width and height of the current window (in pixels), (400,300) will create a window with a width of 400 pixels and a height of 300 pixels.

Remember to pass a variable with two integer tuples to the set_mode () function, instead of two independent numbers. The correct call method is pygame. display. set_mode (400,300 )). For example, pygame. display. set_mode (400,300) will generate an error such as TypeError: argument 1 must be 2-item sequence, not int.

The returned pygame. Surface is saved in the DISPLAYSURF variable.


[Python]
Pygame. display. set_caption ('Hello World! ')
Pygame. display. set_caption ('Hello World! ')

Line 3 calls pygame. display. set_caption () to set the text on the title bar.

 


Game loop and game status

 

[Python]
While True: # main game loop
For event in pygame. event. get ():
While True: # main game loop
For event in pygame. event. get ():

Row 7th is A while LOOP statement with the condition True, which indicates an infinite loop, exit the loop only by using the break statement in the while loop (re-starting the execution from the next row of while) or by using sys. exit () function (it will end the entire program ).

All the games in this book have a while True loop, and note the words "main game loop. A game loop mainly performs the following three tasks:

1. Process events

2. Update game status

3. Drawing on the screen

The game status can be understood as a set of values of all variables in the program. In some games, the game status includes variables that store the health and location of characters, these values can be displayed in the form of scores on the screen. If a person is hurt, the health value will be reduced. We call these values a game status change.

This is also true for saving games. In most games, pausing means that the status change of the game is stopped.

The game status usually changes with the occurrence of events, such as mouse clicks, keyboard input, or time loss. The game loop is executed multiple times in one second to check whether new events are generated, the game status is updated based on events, which are usually called event processing.

 

 

 

 

 


Pygame. event. Event object

 


The user may perform some operations from time to time, such as pressing the button and moving the mouse in the window. In this case, a pygame. event. event object is generated. This object is defined in pygame. in the event module, you can use pygame. event. get () function to capture these events, which returns a pygame. event. list of Event objects. This list contains all events after the pygame. event. Event function is called.


[Python]
While True: # main game loop
For event in pygame. event. get ():
While True: # main game loop
For event in pygame. event. get ():

The fifth line is pygame. event. the events captured by get () are retrieved one by one and assigned to the event variables. For example, if you click the mouse and press the button, the event is returned first, and then the event is returned. If no event is generated, pygame. event. get returns an empty list.

 

QUIT events and pygame. quit () Functions

 


[Python]
If event. type = QUIT:
Pygame. quit ()
Sys. exit ()
If event. type = QUIT:
Pygame. quit ()
Sys. exit ()

The Event object has some member variables (or attributes) that indicate the Event. Row 9th checks if the Event object type is QUIT. Remember, we use from pygame. locals improt * format, which can be replaced by QUIT. locals. QUIT.

If the event type is exit, pygame is called. quit () and sys. exit () function, pygame. quit () and pygame. init () is opposite. It will deregister the pygame Library and the program should call sys. call pygame before exit. quit ().

We didn't use the if statement to process other events, such as mouse clicks and buttons. Although these events will be generated, the program will not process them.


[Python]
Pygame. display. update ()
Pygame. display. update ()

Line 3 calls pygame. display. update () function to draw by pygame. display. the Surface object returned by the set_mode () function. If the Surface object does not change, pygame is called each time. dispaly. A blank image will be drawn on the screen during update.

After explaining the entire program, the program did nothing except to display a blank window on the screen. Next we will learn how to display interesting things in the window. Before that, you need to understand pixels, Surface objects, Color objects, and Rect objects to use pygame's plotting functions.

 

Note: The book Making Games with Python & Pygame, Which is recently planned to be translated by Sweigart, will be published based on the progress. You can find the original book at http://inventwithpython.com.

 


From Socrates Column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.