Make games with Python & pygame (2)

Source: Internet
Author: User

Continue with the previous one.

 

Simple Drawing Functions

Pygame provides several simple drawing functions, such as rectangle, circle, ellipse, line, and independent pixel.

The following program implements some simple drawing operations.

import pygame, sysfrom pygame.locals import *pygame.init()DISPLAYSURF = pygame.display.set_mode((500,400),0,32)BLACK = (0, 0 , 0)WHITE = (255, 255, 255)RED = (255, 0, 0)GREEN = (0, 255, 0)BLUE = (0, 0, 255)DISPLAYSURF.fill(WHITE)pygame.draw.polygon(DISPLAYSURF, GREEN, ((146,0),(291,106),(236,277),(56,277),(0,106)))pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120,60), 4)pygame.draw.line(DISPLAYSURF, BLUE, (20, 60), (60,20))pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120,120), 4)pygame.draw.circle(DISPLAYSURF,BLUE, (300,50), 20, 0)pygame.draw.ellipse(DISPLAYSURF,RED,(300,250,40,80),1)pygame.draw.rect(DISPLAYSURF,RED,(200,150,100,50))pixObj = pygame.PixelArray(DISPLAYSURF)pixObj[480][380] = BLACKpixObj[482][382] = BLACKpixObj[484][384] = BLACKpixObj[486][386] = BLACKpixObj[488][388] = BLACKdel pixObjwhile True:    for event in pygame.event.get():        if event.type == QUIT:            pygame.quit()            sys.exit()    pygame.display.update()

Effect after execution

There are more things about pygame.

Fill (color)Is a method of surface object. fill all the windows of the Surface object with a color, that is, the background color.

Pygame. Draw. polygon (surface, color, pointlist, width)Draw a polygon. The surface and color parameters indicate the object to be drawn and the color to use. The pointlist parameter is a tuple or list composed of multiple points, then, the polygon is connected from the first vertex to form a polygon. The width parameter is optional. If not, the polygon is colored by the color parameter, instead of filling, the width of the polygon contour is determined by the width parameter. Passing 0 to the width parameter is the same as without the width parameter.

Note that all the pygame. Draw drawing functions have a selection parameter width at the end. They work the same way as the width parameter in the pygame. Draw and polygon functions.

Pygame. Draw. Line (surface, color, start_point, end_point, width)
Draw line function

Pygame. Draw. Lines (surface, color, closed, pointlist, width)Draw multiple connected lines, from the start point to the end point, with pygame. draw. similar to polygon, the only difference is that if the closed parameter is set to false, the end is not connected to the start point. If the parameter is set to true, the end is connected to the start point.

Pygame. Draw. Circle (surface, color, center_point, radius, width)
Circle

Pygame. Draw. ellipse (surface, color, bounding_rectange, width)
Draw an ellipse

Pygame. Draw. rect (surface, color, rectangle_tuple, width)Draw a rectangle

Pygame, pixelarray object

Pygame does not have a single point function. The method is to create a pygame. pixelarray object and set an independent pixel. Creating a pixelarray object about surface locks the surface object. Once the surface object is locked, the drawing function can still be used, but images like PNG or JPG cannot be used on the Surface object. If you want to check whether a surface object is locked, you can call the get_locked () method of the Surface object. If it is locked, true is returned. Otherwise, false is returned.

The method to set these independent pixels is to use two index values for access, such as pixobj [480] [380] = black, in this way, the 480 and 380 of the X and Y coordinates are set to black.

To tell pygame that you have finished painting the independent pixel, You need to delete the pixarray object using a del statement. Deleting the pixarray object will unlock the 'surface object, so that you can continue to load images on it. If you forget to delete the image, the next time you want to load the image on the Surface object, an error will be reported.

Pygame. display. Update () function

After you complete all the drawing functions, you must call the pygame. display. Update () function to display the function on the monitor.

Note that the pygame. display. Update () function only displays the Display object (that is, the object returned by calling pygame. display. set_mode () on the screen. If you want images to be displayed on the screen, you must "bits" them (copy their meaning) to the Display object through the BITs () method.

Animation

It is actually very easy to make the image move from one place to another, that is, to clear the image where it was originally located and then load the image in another place, it looks like the image is moving. In computer opinion, it is actually a group of pixels moving. Is an example

The following is a sample code.

import pygame, sysfrom pygame.locals import *pygame.init()FPS = 30 # frames per second settingfpsClock = pygame.time.Clock()# set up the windowDISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)pygame.display.set_caption('Animation')WHITE = (255, 255, 255)catImg = pygame.image.load('cat.png')catx = 10caty = 10direction = 'right'while True: # the main game loop    DISPLAYSURF.fill(WHITE)    if direction == 'right':        catx += 5        if catx == 280:            direction = 'down'    elif direction == 'down':        caty += 5        if caty == 220:            direction = 'left'    elif direction == 'left':        catx -= 5        if catx == 10:            direction = 'up'    elif direction == 'up':        caty -= 5        if caty == 10:            direction = 'right'    DISPLAYSURF.blit(catImg, (catx, caty))    for event in pygame.event.get():        if event.type == QUIT:            pygame.quit()            sys.exit()    pygame.display.update()    fpsClock.tick(FPS)

In this example, the PDF of cat.png is provided. The downloaded file must be placed in a folder with the source file. The execution result is that a cat moves in a window. First right, then down, then left, then up, So loop.

Some new things appear in the above Code.

Frame Rate and pygame. Time. Clock object

Frame Rate and refresh rate indicate the number of images displayed in one second by the program, expressed by FPS and frame per second. (On other computer monitors, FPS has a common name: Hz. Many monitors have a frame rate of 60Hz, or 60 frames per second) A low frame rate may cause the game to appear to be jumping and jitters when it appears in some image games. If the program has too much code and often refreshes the screen, the FPS will decrease. However, the games in this book are simple enough to prevent problems even on some old computers.

The pygame. Time. Clock object can help us identify a maximum fixed FPS value that the program can run. The clock object inserts a small pause in the main loop of the game to ensure that our game programs do not run too fast. Without these pauses, our games will run as fast as computers. It is indeed too fast for gamers. Calling the clock object tick () method in the game loop ensures that our game runs at a definite speed no matter how fast the computer is. Create a clock object using the following statement:

Fpsclock = pygame. Time. Clock ()

The Tick method should be called at the end of the game loop, that is, after pygame. display. Update, the call statement is as follows:

Fpsclock. Tick (FPS)

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.