2015/11/2 use Python to write a game. Get started with pygame (2): Events and display in the game, pythonpygame

Source: Internet
Author: User
Tags response code

2015/11/2 use Python to write a game. Get started with pygame (2): Events and display in the game, pythonpygame

Pygame is a relatively large library, so I cannot explain it with my weak strength. So I only want to talk about what I know, and the rest will be slowly searched for and understood.

-------------------------------

I use pygame with a clear goal to write my own game entertainment, so that I can relax in learning. It is a sense of accomplishment to run a small project, so all explanations should follow such simple steps.

 

First, let's understand the animation:

The above is a small game for children. We put several pictures of different attitudes on a rotating axis, and we can see a coherent flying animation when rotating the rotating axis, when we switch between several broken and static images at a high speed, the human eyes will think of them as continuous actions. This is the embodiment of the visual temporary effect. According to this principle, humans invented movies.

In 1824, Peter, a professor at the University of London. mark. in his research report, the phenomenon of vision persistence of mobile objects first proposes that optical signals are transmitted into the brain nerves when the human eyes observe the scenes, after a short period of time, after the effect of light, the visual image does not disappear immediately. This residual visual name is "post image ". In general, the vision will stay for about 0.1-0.4 seconds. Of course, this varies from person to person. At the beginning of the film industry, we thought that 24 frames (24 images in one second) would make everyone aware of exceptions and become real motion graphs. Of course, with the development of technology, the frame rate of a movie is higher than this value. In the gaming industry, we usually use 30 ~ The 40-frame image rate is because the game images are discrete and not continuous. Therefore, a higher frame rate is required to improve the experience. The higher the frame rate, the smoother the experience, however, the changes will not be obvious after more than 100 frames. The game process is actually an animation process. Unlike a pure animation, we have also added player feedback on the screen. That is, the event. Feedback is done by entering the device, such as the mouse, keyboard, and handle. Each device has feedback, such as moving the mouse, pressing the buttons, and releasing. These are all basic events in pygame and can be used directly. Next I will illustrate the basic animations and events through an example:
#-*-Coding: utf8-*-background_image_filename = 'sky.jpg 'mouse _ image_filename = 'cloud.png' # specify the image file name import pygame # import the pygame library from sys import exit # use an exit function to exit the program from the sys module pygame. init () # initialize pygame to prepare for using hardware screen = pygame. display. set_mode (600,450), 0, 32) # create a window pygame. display. set_caption ("Hello, World! ") # Set the window title background = pygame. image. load (background_image_filename ). convert () mouse_cursor = pygame. image. load (mouse_image_filename ). convert_alpha () # Load and convert the image while True: # main game loop for event in pygame. event. get (): if event. type = pygame. QUIT: # exit the pygame program after receiving the exit event. quit () exit () screen. bground (background, () # Add the background image x, y = pygame. mouse. get_pos () # obtain the mouse position x-= mouse_cursor.get_width ()/2 y-= mouse_cursor.get_height ()/2 # Calculate the screen position in the upper left corner of the cursor. BITs (mouse_cursor, (x, y) # Draw the cursor over pygame. display. update () # refresh the screen

The running result is as follows:

When the mouse moves in the screen, the cloud will also move, of course, this cloud is my temporary, it is really illegal .. This is skipped.

 

Let's take a look at

While True: # main game loop... screen. bground (background, (0, 0) # upload the background picture... screen. BITs (mouse_cursor, (x, y) # Draw the cursor over pygame. display. update () # refresh the screen

Omit unnecessary things. Read these sentences first. In the main loop, we execute the following three statements of code again and again. It is to first draw the background image, then spend the bidding image, and then refresh the screen. Every time the cursor changes, it draws different images each time, so it becomes an animation and can be displayed in real time, that is, the part I mentioned above.

 

What about events?

Read this Code:

For event in pygame. event. get (): if event. type = pygame. QUIT: # exit the program pygame. quit () exit () After receiving the exit event ()

This is an event response code. The pygame. event. get () method accepts events in all programs. When it is determined that the event is a QUIT event, the program is closed.

So what are the events?

Event Production path Parameters
QUIT The user presses the close button. None
ATIVEEVENT Pygame activated or hidden Gain, state
KEYDOWN Press the keyboard Unicode, key, mod
KEYUP Keyboard opened Key, mod
MOUSEMOTION Move the mouse Pos, rel, buttons
MOUSEBUTTONDOWN Press the mouse Pos, button
MOUSEBUTTONUP Move the mouse Pos, button
JOYAXISMOTION Game handle (Joystick or pad) mobile Joy, axis, value
JOYBALLMOTION Joy ball )? Mobile Joy, axis, value
JOYHATMOTION Game handle (Joystick )? Mobile Joy, axis, value
JOYBUTTONDOWN Game handle press Joy, button
JOYBUTTONUP Open the Game Controller Joy, button
VIDEORESIZE Pygame Window Scaling Size, w, h
VIDEOEXPOSE Is the Pygame window partially public (expose )? None
USEREVENT Triggered a user event. Code

 

There are many events here. Of course we don't need to back them up. Here is just a description. In the font module, I will write a program that will display all the events you get.

 

The above code is described in detail.

background_image_filename = 'sky.jpg'

This is a simple string value assignment statement, just to make it easier to understand the meaning of the name.

screen = pygame.display.set_mode((600, 450), 0, 32)

This sentence uses pygame. display. set_mode (640,450), 0, 32) is used to create a window. The first parameter is a tuples used to pass the window size. The second parameter is the window mode, by default, you can write 0. The third parameter is color depth. Generally, you can write 32.

Set_mode () returns a Surface object, which can be operated on later.

The second parameter is used as follows:

Flag Space Function
FULLSCREEN Create a full screen window
DOUBLEBUF Create a "double buffer" window. We recommend that you use it when using HWSURFACE or OPENGL.
HWSURFACE Create a hardware acceleration window, which must be used together with FULLSCREEN
OPENGL Create an OPENGL rendering window
RESIZABLE Create a window that can change the size
NOFRAME Create a window without Borders

You can use it to see the effect.

background = pygame.image.load(background_image_filename).convert()

Convert () can convert image data into Surface objects. This event should be performed after each image is loaded (in fact, it is too common, if you do not write pygame, it will also help you); convert_alpha retains the Alpha channel information (which can be simply understood as a transparent part), so that our cursor can be in an irregular shape.

BITs () is an important function. The first parameter is a Surface object, and the second parameter is the upper left corner. Draw the first object to the corresponding position.

However, it is useless to finish the painting. You must use update () to display the image after the painting on the screen. Otherwise, the screen is dark.

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.