Introduction to Pygame-python Game Programming (0)

Source: Internet
Author: User
Tags color representation

Introduction

The blog just opened, want to take the recent study of things to record down, is a kind of notes. Recently I'm going to start learning python, because I feel python is a very interesting language, long ago to learn (lazy), it is very powerful, you can use it for scientific operations, or digital image processing, or task automation, you can also build dynamic website, A lot of it sounds like an interesting implementation. You can also find more information about Python, which is not mentioned here.

Speaking of starting to learn a new programming language, many children's shoes may immediately think, "Ah, brother to buy a book to chew!" ", the result bought this tome, all is the boring grammar knowledge, looked behind forgets the front, the thing doubles the power half. Remember a friend told me before, want to learn a new technology, from a project to start, this sentence is still worth thinking about! ( ' @@facesymbol@@´ ') so! It's in the chase! We might as well be a little game, familiar with the syntax of Python, but also not afraid to stuffy to their own ~

Python's library is a very important part of Python, and we can use these libraries to implement a number of functions. Our goal is to achieve a small game through Pygame! What exactly does it do? I've got the direction! is to do a PC-side aircraft war ~ because this game mode is simple, functional clear, simple interface, very well in line with our expected goals. But I'd like to reiterate here that this idea is not what I came up with, but I found it on GitHub, with the address: pyshootgame (the resources used are also here!). )。

As a final note, this series of posts uses Python 3.3.5 + pygame 1.9.2a0. About Python 2.x and 3.x versions I don't compare, semantic understanding is good. Remember that Python should correspond to the corresponding Pygame version.

Positive Start ~1. Preparatory workinstallation of 1.1 Pygame

first python you have to have it, pygame the simplest way of course is to download it from the official website (attached: www.pygame.org/download.shtml). But now the problem has come, the official online version of the Pygame as if only for Python 2.5/2.6/2.7/3.1/3.2, if your Python version is greater than 3.2 what to do? A big brother on stack Overflow said "The main Pygame page seems to be rarely updated." The crowd seemed to understand something, and then the eldest brother smiled, "download it here (attached: bitbucket.org/ Pygame/pygame/downloads) ". The version here seems to have been updated more diligently than the official website (just ...). Like). The version number is written very clearly, picking is good ~

Finally, we will confirm whether the installation is correct.

Import Pygame Print (pygame.ver)1.9.2a0

  If there is no error, it should be installed ~

If the error does not find the module, it is probably the issue of the installation version.

 not being found.

1.2 path to Pygame document

  Pygame documents are still very complete, when we encounter usage problems, first look at the document, a lot of problems will be solved.

Pygame documentation:% your Python installation path%/python/lib/site-packages/pygame/docs/index.html

(different versions of Python and Pygame document location may not be the same, I just posted their own path, everyone reference, the library installed in their own Python installation path under the search is it; if you feel trouble, there are online documents, attached: www.pygame.org/docs/)

Which modules are in the Pygame, which are also given in docs:

Module Brief introduction
Pygame. Bufferproxy An array protocol view of surface pixels
Pygame.cdrom How to access and control the CD audio devices.
Pygame. Color Color representation.
Pygame.cursors Loading and compiling cursor images.
Pygame.display Configure the display surface.
Pygame.draw Drawing simple shapes like lines and ellipses to surfaces.
Pygame.event Manage the incoming events from various input devices and the windowing platform.
Pygame.examples Various programs demonstrating the use of individual pyame modules.
Pygame.font Loading and rendering Truetype fonts.
Pygame.freetype Enhanced Pygame module for loading and rendering font faces.
Pygame.gfxdraw Anti-aliasing draw functions.
Pygame.image Loading, saving, and transferring of surfaces.
Pygame.joystick Manage the joystick devices.
Pygame.key Manage the keyboard device.
Pygame.locals Pygame constants.
Pygame.mixer Load and Play sounds
Pygame.mouse Manage the mouse device and display.
Pygame.movie Video playback from MPEG movies.
Pygame.mixer.music Play streaming music tracks.
Pygame. Overlay Access Advanced video Overlays.
Pygame Top level functions to manage Pygame.
Pygame. PixelArray Manipulate image pixel data.
Pygame. Rect Flexible container for a rectangle.
Pygame.scrap Native Clipboard access.
Pygame.sndarray Manipulate Sound sample data.
Pygame.sprite Higher level objects to represent game images.
Pygame. Surface Objects for images and the screen.
Pygame.surfarray Manipulate image pixel data.
Pygame.tests Test Pygame.
Pygame.time Manage timing and framerate.
Pygame.transform Resize and move images.

  The introduction is very intuitive, there is not much to explain. The module provides a relatively straightforward operation (just relative), like pasting an image, but also provides a high level of abstraction of the operation, like a sprite module (sprite). Anyway, we have a general understanding of what to use, and then to seriously learn the relevant things.

2. Our first task--add the background of the game2.1 We have to have a window before we load the background. Let's do it ~
1 ImportPygame#Import Pygame Library2  fromPygame.localsImport*#import some constants in the Pygame library3  fromSysImportExit#Import the Exit function in the SYS library4 5 # define the resolution of the window6Screen_width = 4807Screen_height = 6408   9 #Initializing the gameTenPygame.init ()#Initialize Pygame OneScreen = Pygame.display.set_mode ([Screen_width, Screen_height])#Initializes a window for display APygame.display.set_caption ('This is my first pygame-program')#Set Window caption -  - #Event Loop (main loop) the  whileTrue: -      -     #Handling Game Exit -     #looping from a message queue +      forEventinchpygame.event.get (): -         ifEvent.type = =Pygame. QUIT: + pygame.quit () AExit ()

Program Run Result:

  Though it was dark and not likely to do anything, it was the first step.

2.2 The next step is to highlight several parts of the program:

line 2: The pygame.locals module contains a number of constants that pygame need to use, such as the flags for set_mode inside the window, the type of message event, and so on. In addition, if the program wants to use Pygame constants inside the Pygame.locals module, it can only use "from pygame.locals import *".

Line 3: One embodiment of Python simplicity is the ability to import what functionality you need to use. Here we need to use the Exit function to close the window and import it from the SYS library.

Line 5: The resolution of the background image is actually 480*800, but my computer screen resolution is only 1280*800, so I temporarily changed it to "short".

Line :pygame.init () will initialize all imported Pygame modules. However, when an error occurs in a module, the function does not throw an exception, and, relatively, init () returns a tuple, including the number of modules successfully initialized and the number of modules that have failed. In this example, the information returned by the output init () can be seen,

>>> ================================ RESTART ================================>>> (6, 0)

If you want to, you can also manually initialize the module by hand, so that you can catch the thrown exception.

Line one :the Set_mode () function creates a display panel (surface) that has three parameters, the first is the resolution of the surface, the size of the window, which is entered as a tuple (width, height), If not entered or set to (0, 0), the system will set the resolution of the surface to the current screen resolution (Pygame uses SDL version 1.2.10 or above), the second is the flag bit (flags), That is, the display mode of the selected surface, see the following list:

# Pygame. Fullscreen    Create a fullscreen display#pygame. Doublebuf     recommended for hwsurface or OPENGL#pygame. Hwsurface     hardware accelerated, only in fullscreen#pygame. OpenGL        Create an OpenGL renderable display#pygame. Resizable     display window should be sizeable#pygame. Noframe       Display window would have no border or controls

The third parameter is bit depth (depth), which is how many bits are used to represent the color, and the document recommends that you do not need to set this parameter and the system chooses the optimal value.

Line : in our main program, we need an event loop (loop) to constantly detect the user's actions during the interaction. The Pygame.event.get () method can get a list of all events from the event queue, we use a loop to constantly detect each event, and once we find the Quit event, we exit the game close window. There is also a point worth thinking about, if we do not set the exit operation, our black window will become what? As a result, when we click on the Red Fork in the upper right corner of the window, the program can still detect the Quit event, but the window is not closed because we do not have the relevant action set for it.

2.3 Formally loaded in the background

  With the above knowledge, we have a general understanding of the framework of the program, then into the topic! Load Background Image ~

Note that we can add a few statements to the ~ (?? Omega??)

ImportPygame#Import Pygame Library fromPygame.localsImport*#import some constants in the Pygame library fromSysImportExit#Import the Exit function in the SYS library#define the resolution of the windowScreen_width = 480Screen_height= 640#Initializing the gamePygame.init ()#Initialize PygameScreen = Pygame.display.set_mode ([Screen_width, Screen_height])#Initializing WindowsPygame.display.set_caption ('This is my first pygame-program')#Set Window caption#Loading Background mapBackground = Pygame.image.load ('Resources/image/background.png')#New#Event Loop (main loop) whileTrue:#Draw BackgroundScreen.blit (background, (0, 0))#New    #Update ScreenPygame.display.update ()#New        #Handling Game Exit    #looping from a message queue     forEventinchpygame.event.get ():ifEvent.type = =Pygame. QUIT:pygame.quit () exit ()

We added 3 statements to the original program. The first sentence is to load the background image, the resources folder with your py file to put together oh; the second sentence is used to draw the image, Surface.blit () is a very common function, the first parameter is the image resource, the second parameter determines the location of the image placement (upper left corner of the coordinates) The third statement is to update the screen, that is, to draw a good background to the "brush" up. To say more about Pygame.display.flip () and Pygame.display.update (), the document says that update is more like Flip's optimized version, the main difference being that flip is the overall screen refresh (entire), Update is a local refresh (portion). Finally, consider a question, what if we move the next two new statements to the while loop? There will be no noticeable effect in this demo, but when we add other image elements to the screen later, the background image is gone when we perform the update operation.

There is a blogger's intention to pygame the module introduction translated a bit, attached address: eyehere.net/2011/python-pygame-novice-professional-1/

Summary: The first time to write Bo, feel good Tired (/tдt)/

Introduction to Pygame-python Game Programming (0)

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.