pygame is a python module designed to develop games, in fact, to be frank, and time, os, sys are the same thing. Today started to learn pygame, download address:. Just download it and install it, I used the spe editor in my pygame studies and it felt pretty good.
1. pygame window
Before pygame draws a graphic, you first need to create a window, it is very simple to say, please see the following code, how about it, is not very simple.
import pygame #No need to comment this one, huh?
() #Module initialization, any pygame program needs to run this line
screencaption=.set_caption('hello world')#Define the title of the window as'hello world'
screen=.set_mode([640,480]) #define the window size as 640*480
([255,255,255])#Fill window with white color
2、Window exit
pygame has an event loop that constantly checks what the user is doing. The common code for how to break the loop down in the event loop (the insertion sign on the right in the window formed by pygame doesn't work until it is defined) is as follows:
while True:
for event in ():
if ==:
()
3. colors in pygame
In the statement ([255,255,255]), it has been seen that pygame uses the RGB system. Pure green uses [0,255,0], pure blue uses [0,0,255], and pure red uses [255,0,0]. If RGB notation is not used, pygame also provides a list of named colors that can also be used directly. There are over 600 defined color sentences, and you can view the exact names in the file. To use the named list, first import THECOLORS at the top of the program.
from import THECOLORS
Then use one of the named colors:
(screen,THECOLORS["red"],[100,100],30,0)
4. Round
() is used to draw a circle, specifically including five parameters: (1) the surface of the circle, in this case with screen to create a window, so it is drawn on the surface of the screen. (2) with what color to draw, such as with red [255,0,0]. (3) At what position to draw, [top,left]. (4) The diameter. (5) Line width, where 0 means complete fill.
(screen,[255,0,0],[100,100],30,0)
5. Rectangle
() is used to create a rectangle. Rect(left,top,width,height) is used to define the position and width and height, the specific code is as follows:
(screen,[255,0,0],[250,150,300,200],0)
It is also possible to use the following definition method
rect_list=[250,150,300,200]
(screen,[255,0,0],rect_list,0)
or
my_rect=(250,150,300,200)
(screen,[255,0,0],my_rect,0)
6. Examples
Use random module to randomly generate the size and position to draw on the surface, the specific code is as follows:
import pygame,sys
import time
import random
()
screencaption=.set_caption('hello world')
screen=.set_mode([640,480])
([255,255,255])
for i in range(10):
zhijing=(0,100)
width=(0,255)
height=(0,100)
top=(0,400)
left=(0,500)
(screen,[0,0,0],[top,left],zhijing,1)
(screen,[255,0,0],[left,top,width,height],3)
()
while True:
for event in ():
if ==:
()
Rendering: