Python Pygame and pythonpygame

Source: Internet
Author: User

Python Pygame and pythonpygame

1. Experiment Introduction

1.1 experiment content

In this lesson, we will explain the common objects and operations of Pygame, including graphics, animations, text, and audio, to ensure that you have a basic understanding of Pygame, at the same time, make preparations for subsequent courses.

1.2 experiment knowledge points

  1. Pygame graphics
  2. Pygame Animation
  3. Pygame text
  4. Pygame audio
  5. Pygame event

1.3 experiment environment

  1. Python 2.7.6
  2. Xfce Terminal

1.4 suitable audience

This course is generally difficult and belongs to the preliminary level. It is suitable for users with basic Python knowledge and is familiar with basic Python knowledge to deepen and consolidate.

1.5 get code

The Code and related resource files used in this experiment can be downloaded to the experiment building environment using the following commands for reference and comparison.

$ wget http://labfile.oss.aliyuncs.com/courses/940/foundation.zip

Decompress the package to/home/shiyanlou/foundation:

$ unzip foundation.zip

2. Development Preparation

This course mainly uses the Pygame module for development. First, we need to open the Xfce terminal and use the pip command to install Pygame.

$ sudo pip install pygame

After the installation is complete, enter the Python interactive interface and enter the following command to check whether the installation is successful.

import pygame

If no exception exists, the installation is successful.

Iii. Experiment steps

3.1 HelloWorld

First, start our first HelloWorld program:

#-*-Coding: UTF-8-*-# helloworld. py # import required modules import pygame, sys # import all pygames. variables in locals (such as the upper-case QUIT variable below) from pygame. locals import * # initialize pygamepygame. init () # Set the window size, in pixel screen = pygame. display. set_mode (500,400) # Set the window title pygame. display. set_caption ('Hello World') # main program loop while True: # Get the event in pygame. event. get (): # determine whether the event is an exit event if event. type = QUIT: # exit pygame. quit () # exit the system sys. exit () # Draw the Screen Content pygame. display. update ()

As follows:

 

The Running Method of the above program is explained here

A game loop (also known as the main loop) Does the following three things:

  1. Event handling
  2. Update game status
  3. Draw game status to screen

 

3.2 drawing

The coordinate origin (0, 0) of Pygame is located in the upper left corner, the X axis is left to right, and the Y axis is from top to bottom, in pixels.

The following describes common methods:

Pygame. draw. line (Surface, color, start_pos, end_pos, width) This method is used to draw a line segment

Pygame. draw. aaline (Surface, color, start_pos, end_pos, blend) This method is used to draw a line that is anti-sawtooth.

Pygame. draw. lines (Surface, color, closed, pointlist, width) This method is used to draw a line

Pygame. draw. rect (Surface, color, Rect) This method is used to draw a rectangle

Pygame. draw. rect (Surface, color, Rect, width) This method is used to draw a Rectangular Box

Pygame. draw. ellipse (Surface, color, Rect) This method is used to draw an elliptic

Pygame. draw. ellipse (Surface, color, Rect, width) This method is used to draw an elliptical box

Pygame. draw. polygon (Surface, color, pointlist, width) This method is used to draw a polygon

Pygame. draw. arc (Surface, color, Rect, start_angle, stop_angle, width) This method is used to draw an arc

Pygame. draw. circle (Surface, color, Rect, radius) This method is used to draw a circle

The following is the sample code:

#-*-Coding: UTF-8-*-# drawing. py # import the required modules import pygame and sysfrom pygame. locals import * from math import pi # initialize pygamepygame. init () # Set the window size, in pixel screen = pygame. display. set_mode (400,300) # Set the window title pygame. display. set_caption ('Drawing ') # define the color BLACK = (0, 0, 0) WHITE = (255,255,255) RED = (255, 0, 0) GREEN = (0,255, 0) BLUE = (0, 0,255) # Set the background color screen. fill (WHITE) # draw a line pygame. draw. line (screen, GREEN, [0, 0], [50, 30], 5) # draw a line pygame with anti-aliasing. draw. aaline (screen, GREEN, [0, 50], [50, 80], True) # draw a line pygame. draw. lines (screen, BLACK, False, [[0, 80], [50, 90], [200, 80], [220, 30], 5) # Draw a hollow rectangle pygame. draw. rect (screen, BLACK, [75, 10, 50, 20], 2) # Draw a rectangle pygame. draw. rect (screen, BLACK, [150, 10, 50, 20]) # Draw a hollow elliptical pygame. draw. ellipse (screen, RED, [225, 10, 50, 20], 2) # draw an elliptical pygame. draw. ellipse (screen, RED, [300, 10, 50, 20]) # Draw a polygon pygame. draw. polygon (screen, BLACK, [[100,100], [0,200], [200,200], 5) # Draw Multiple Arc pygame. draw. arc (screen, BLACK, [210, 75,150,125], 0, pi/2, 2) pygame. draw. arc (screen, GREEN, [210, 75,150,125], pi/2, pi, 2) pygame. draw. arc (screen, BLUE, [210, 75,150,125], pi, 3 * pi/2, 2) pygame. draw. arc (screen, RED, [210, 75,150,125], 3 * pi/2, 2 * pi, 2) # Draw a circle pygame. draw. circle (screen, BLUE, [60,250], 40) # main loop of the program while True: # obtain the event in pygame. event. get (): # determine whether the event is an exit event if event. type = QUIT: # exit pygame. quit () # exit the system sys. exit () # Draw the Screen Content pygame. display. update ()

As follows:

 

3.3 animation implementation

Due to the special physiological structure of human eyes, when the Frame Rate of the image is higher than 24, it is regarded as coherent. This phenomenon is called Vision temporarily.

Frame rate is a measure of the number of display Frames. The so-called measurement unit is the number of display Frames per Second (Frames per Second, FPS)

In general, 30fps is acceptable, but improving the performance to 60fps can significantly improve the interaction and authenticity. However, generally, a higher smoothness is not obvious if the performance exceeds 75fps.

Add the offset on the basis of our original coordinate system, re-draw, and draw one by one in sequence to get the expected object moving effect.

Pygame:

Pygame. image. load (filename) loads an image

Pygame. Surface. Bags (source, dest, area = None, special_flags = 0) Draw the image to the corresponding coordinates of the screen (the next two parameters are default and can be left blank)

Pygame. time. Clock () Get the Clock of pygame

Pygame. time. Clock. tick (FPS) sets the time interval of the pygame Clock.

The following is the sample code:

#-*-Coding: UTF-8-*-# animation. py # import the required modules import pygame and sysfrom pygame. locals import * # initialize pygamepygame. init () # Set the frame rate (the number of screen refreshes per second) FPS = 30 # Get the pygame clock fpsClock = pygame. time. clock () # Set the window size screen = pygame. display. set_mode (500,400), 0, 32) # Set the title pygame. display. set_caption ('animation ') # define the color WHITE = (255,255,255) # load an image (for the image used, refer to code 1.5) img = pygame. image. load ('resources/shiyanlou. PNG ') # initialize the image position imgx = 10 imgy = 10 # initialize the direction of movement of the image direction = 'right' # main program loop while True: # re-draw the background white screen every time. fill (WHITE) # determine the direction of movement, and add or subtract the corresponding coordinates if direction = 'right': imgx + = 5 if imgx = 380: direction = 'low' elif direction = 'low': imgy + = 5 if imgy = 300: direction = 'left' elif direction = 'left ': imgx-= 5 if imgx = 10: direction = 'up' elif ction = 'up': imgy-= 5 if imgy = 10: direction = 'right' # This method will be used to draw an image to the corresponding coordinate screen. BITs (img, (imgx, imgy) for event in pygame. event. get (): if event. type = QUIT: pygame. quit () sys. exit () # refresh the screen pygame. display. update () # set the time interval fpsClock for the pygame clock. tick (FPS)

As follows:

 

3.4 draw text

If you want to draw text to the screen, Pygame provides a convenient way to use the. ttf font file, so that we can easily draw the text on the screen.

Here I use ARBERKLEY. ttf as the font. For more information about how to obtain the font file, see Code 1.5.

Mainly used methods:

Pygame. font. Font (filename, size)

Filename: the file name of the font file;

Size: the height of the font, in pixels;

Pygame. font. Font. render (text, antialias, color, background = None)

Text: the text to be displayed;

Antialias;

Color: font color;

Background: Specifies the background color (optional );

. Get_rect ()

Obtains the rect of an object to facilitate the setting of its coordinate position.

The following is the sample code:

#-*-Coding: UTF-8-*-# font. py # import the required modules import pygame and sysfrom pygame. locals import * # initialize pygamepygame. init () # Set the window size, in pixel screen = pygame. display. set_mode (500,400) # Set the title of the window pygame. display. set_caption ('font') # define the color WHITE = (255,255,255) GREEN = (0,255, 0) BLUE = (0, 0,128) # obtain the Font object fontObj = pygame through the Font file. font. font ('resources/ARBERKLEY. ttf', 50) # configure textSurfaceObj = fontObj. render ('pygame', True, BLUE, GREEN) # obtain the recttextRectObj = textSurfaceObj of the object to be displayed. get_rect () # sets the coordinate textRectObj of the displayed object. center = (250,200) # Set the background screen. fill (WHITE) # Draw the font screen. BITs (textSurfaceObj, textRectObj) # The main program loop while True: # Get the event in pygame. event. get (): # determine whether the event is an exit event if event. type = QUIT: # exit pygame. quit () # exit the system sys. exit () # Draw the Screen Content pygame. display. update ()

As follows:

 

3.5 play audio

There are two methods for playing audio in Pygame: one for playing special effects and the other for playing background music:

Pygame. mixer. Sound (filename)

This method returns a Sound object and calls its. play () method to play a short audio file (for example, a player is hurt or a gold coin is collected );

Pygame. mixer. music. load (filename)

This method is used to load background music. Then, you can call pygame. mixer. music. play () to play background music (Pygame can only load one background music at the same time)

The following is the sample code:

#-*-Coding: UTF-8-*-# audio. py # import the required modules import pygame and sysfrom pygame. locals import * # initialize pygamepygame. init () # Set the window size, in pixel screen = pygame. display. set_mode (500,400) # Set the title of the window pygame. display. set_caption ('audio') # defines the color WHITE = (255,255,255) # sets the background screen. fill (WHITE) # Load and play a special audio file (for the audio file used, refer to code 1.5) sound = pygame. mixer. sound ('resources/bounce.ogg ') sound. play () # load the background music file pygame. mixer. music. load ('resources/bgmusicloud ') # play background music. The first parameter is the number of playback times (-1 indicates an infinite loop ), the second parameter sets the playing Start Point (unit: seconds) for pygame. mixer. music. play (-1, 0.0) # main program loop while True: # Get event in pygame. event. get (): # determine whether the event is an exit event if event. type = QUIT: # Stop playing background music pygame. mixer. music. stop () # exit pygame. quit () # exit the system sys. exit () # Draw the Screen Content pygame. display. update ()

Note: Because audio cannot be played in the Lab Building for the time being, the above Code may not work normally in the lab building environment. You can try it on your computer.

3.6 events

The following table lists common events in Pygame:

Event Production path Parameters
QUIT The user presses the close button. None
ACTIVEEVENT 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
VIDEORESIZE Pygame Window Scaling Size, w, h

The following is the sample code:

#-*-Coding: UTF-8-*-# event. py # import the required modules import pygame and sysfrom pygame. locals import * # definition color WHITE = (255,255,255) # initialize pygamepygame. init () # Set the window size, in pixel screen = pygame. display. set_mode (500,400), 0, 32) # Set the title of the window pygame. display. set_caption ('event') # sets the background screen. fill (WHITE) # main program loop while True: # Get event in pygame. event. get (): # determine whether the event is an exit event if event. type = QUIT: # exit pygame. quit () # exit the system sys. exit () # obtain the current cursor position if event. type = MOUSEMOTION: print (event. pos) # obtain the place where the mouse is pressed if event. type = MOUSEBUTTONDOWN: print ("press the mouse:", event. pos) # obtain the position where the mouse is lifted if event. type = MOUSEBUTTONUP: print ("move the mouse up:", event. pos) # obtain the if event of the keyboard press. type = KEYDOWN: if (event. key = K_UP or event. key = K_w): print ("On") if (event. key = K_DOWN or event. key = K_s): print ("bottom") if (event. key = K_LEFT or event. key = K_a): print ("Left") if (event. key = K_RIGHT or event. key = K_d): print ("right") # Press Esc on the keyboard to exit if (event. key = K_ESCAPE): # exit pygame. quit () # exit the system sys. exit () # Draw the Screen Content pygame. display. update ()

As follows:

 

Iv. Experiment Summary

In this course, we mainly explain some common objects and operations of Pygame. These are the knowledge points we need in subsequent courses. I hope you can master these contents well. For more information, see the link to the Pygame official documentation below.

V. Reference Links

Pygame official documentation

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.