Getting Started with Python Game Programming

The articles "Introduction to Python Game Programming"
are responsible for sorting out the knowledge points, precautions and attempts to implement after-school exercises in this book.
And analyze and annotate the final examples given in each chapter.

Getting to know pygame: pie games The
pygame game library makes it possible to draw graphics, get user input, perform animations
, and use timers to keep the game running at a steady frame rate.
Use the pygame library;
print text in a certain font;
use loops to repeat actions;
draw circles, rectangles, lines, and floorplans;
create pie games;

where to get the pygame library: http://www.pygame.org/download.shtml
I am now The environment used in the Python2.7 and pygame1.9
books is Python3.2 and pygame1.9.
Now the pip tool is not installed in the Python3 environment, which causes the environment to be inconsistent

. The initialization of the pygame library:
    import pygame
    from pygame.locals import *
    pygame.init()

creates a screen of size (600,500)
    screen=pygame.display.set_mode((600,500))
    screen is also assigned as <Surface(600x500x32 SW)>
    This is a useful value, so it is stored in the screen variable.

print text
    1. Create a font object
    myfont=pygame.font.Font(None,60)
    None: use the default font
    60: font size
    2. Create a plane that can be drawn with screen.blit()
    textimage=myfont.render("Hello Python" ,True,(255,255,255))
    render requires three parameters, the string to be displayed, whether antialiasing True/False, color
    3, handing the textimage to screen.blit() for drawing
    screen.blit(textimage,(100,100) )
    screen.blit() requires two parameters, the drawn object and its (top left vertex) coordinates

background fill
    screen.fill((0,0,0))
    screen.fill() needs to give the background color

to refresh the display
    screen. display.update()
    is generally used in conjunction with a

while loop .
    Through the while loop, event processing and continuous screen refresh can be performed
    while True:
        for event in pygame.event.get():
            if event.type in (QUIT,KEYDOWN):
                sys.exit()
        screen.display.update()

draw a circle
    pygame.draw.circle(screen,color,position,radius,width)
    color (0,0,0) given color
    radius circle radius
    position (0,0 ) ) Given the coordinates of the center of the circle     , width, and the
    width of the line     , draw

a rectangle     . (screen,color,(0,0),(100,100),width) (0,0)(100,100) is responsible for drawing an arc     at the two endpoints of a given line segment     start_angle=math.radians(0)     end_angle=math.radians( 90)     position=x-radius,y-radius,radius*2,radius*2     #x,y represents the coordinates of the center of the circle where the arc is located, and radius represents the radius












    pygame.draw.arc(screen,color,position,start_angle,end_angle,width)
    The starting angle of start_angle points to the radius on the right side, and it starts to rotate counterclockwise from 0 to 360.
    End_angle end angle

    


Two examples worth learning
1. Draw a moving rectangle
#!/usr/bin/python

import sys
import random
from random import randint
import pygame
from pygame import *
pygame.init()

screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Drawing Rectangles")
pos_x=300
pos_y=250
vel_x=2
vel_y=1
color=100,100,100            
while True:
    for event in pygame.event.get():
        if event.type in (QUIT,KEYDOWN):
            sys.exit()

    screen.fill(( 0,0,200))
    
    pos_x +=vel_x
    pos_y +=vel_y
    if pos_x>500 or pos_x<0:
        vel_x=-vel_x
        rand1=randint(0,255)
        rand2=randint(0,255)
        rand3=randint(0,255)
        color=rand1,rand2,rand3
    if pos_y>400 or pos_y<0:
        vel_y=-vel_y
        rand1=randint(0,255)
        rand2=randint(0,255)
        rand3=randint(0,255)
        color=rand1,rand2,rand3
    width=0
    pos=pos_x,pos_y,100,100
    pygame.draw.rect(screen,color,pos,width)

    pygame.display.update()


2、pie游戏
#!/usr/bin/python

#init
import sys
import math
import pygame
from pygame.locals import *
pygame.init()

screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("The Pie Game-Press 1,2,3,4")
myfont=pygame.font.Font(None,60)

color=200,80,60
width=4
x=300
y=250
radius=200
position=x-radius,y-radius,radius*2,radius*2

piece1=False
piece2=False
piece3=False
piece4=False

while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            sys.exit()
        elif event.type==KEYUP:
            if event.key==pygame.K_ESCAPE:
                sys.exit()
            elif event.key==pygame.K_1:
                piece1=True
            elif event.key==pygame.K_2:
                piece2=True
            elif event.key==pygame.K_3:
                piece3=True
            elif event.key==pygame.K_4:
                piece4=True

    screen.fill((0,0,200))

    #draw the four numbers
    textimage1=myfont.render("1",True,color)
    screen.blit(textimage1,(x+radius/2-20,y-radius/2))    
    textimage2=myfont.render("2",True,color)
    screen.blit(textimage2,(x-radius/2,y-radius/2))
    textimage3=myfont.render("3",True,color)
    screen.blit(textimage3,(x-radius/2,y+radius/2-20))
    textimage4=myfont.render("4",True,color)
    screen.blit(textimage4,(x+radius/2-20,y+radius/2-20))

    #draw arc,line
    if piece1:
        start_angle=math.radians(0)
        end_angle=math.radians(90)
        pygame.draw.arc(screen,color,position,start_angle,end_angle,width)
        pygame.draw.line(screen,color,(x,y),(x+radius,y),width)
        pygame.draw.line(screen,color,(x,y),(x,y-radius),width)

    if piece2:    
        start_angle=math.radians(90)
        end_angle=math.radians(180)
        pygame.draw.arc(screen,color,position,start_angle,end_angle,width)
        pygame.draw.line(screen,color,(x,y),(x,y-radius),width)
        pygame.draw.line(screen,color,(x,y),(x-radius,y),width)

    if piece3:
        start_angle=math.radians(180)
        end_angle=math.radians(270)
        pygame.draw.arc(screen,color,position,start_angle,end_angle,width)
        pygame.draw.line(screen,color,(x,y),(x-radius,y),width)
        pygame.draw.line(screen,color,(x,y),(x,y+radius),width)

    if piece4:
        start_angle=math.radians(270)
        end_angle=math.radians(360)
        pygame.draw.arc(screen,color,position,start_angle,end_angle,width)
        pygame.draw.line(screen,color,(x,y),(x,y+radius),width)
        pygame.draw.line(screen,color,(x,y),(x+radius,y),width)
        
    #if success,display green
    if piece1 and piece2 and piece3 and piece4:
        color=0,255,0

    pygame.display.update()


Challenge
1. Draw an ellipse
#!/usr/bin/python

import sys
import pygame
from pygame.locals import *
pygame.init()

screen=pygame.display.set_mode((600,500))
pygame.display .set_caption("Drawing Ellipse")

while True:
        for event in pygame.event.get():
                if event.type in (QUIT,KEYDOWN):
                        sys.exit()

        screen.fill((0,255,0))

        color= 255,0,255
        position=100,100,400,300
        width=8
        pygame.draw.ellipse(screen,color,position,width)

        pygame.display.update()
This topic is to let you know about the use of the pygame.draw.ellipse() function.
This function is very similar to the pygame.draw.rect() function.

2. Draw 1000 lines randomly
#!/usr/bin/python
import random
from random import randint
import sys
import pygame
from pygame import *
pygame.init()

screen=pygame.display.set_mode((800,600))
pygame.display .set_caption("Drawing Line")

screen.fill((0,80,0))
color=100,255,200
width=2
for i in range(1,1001):
        pygame.draw.line(screen,color,(randint(0,800 ),randint(0,600)),(randint(0,800),randint(0,600)),width)

while True:
        for event in pygame.event.get():
                if event.type in (QUIT,KEYDOWN):
                        sys.exit ()



        pygame.display.update()

Through this topic, I understand that if drawing graphics and refreshing the display are in the loop, the while True loop will
draw the .
Call the randint() function in the pygame module.
While drawing the graph outside the while True loop, the graph remains unchanged after the drawing is completed. Refresh shows a graph that has been
drawn .

3. Modify the rectangle program so that the rectangle touches the screen border, and the rectangle will change color

#!/usr/bin/python

import sys
import random
from random import randint
import pygame
from pygame import *
pygame.init()

screen=pygame.display .set_mode((600,500))
pygame.display.set_caption("Drawing Rectangles")
pos_x=300
pos_y=250
vel_x=2
vel_y=1
rand1=randint(0,255)
rand2=randint(0,255)
rand3=randint(0,255)
color= rand1,rand2,rand3            
while True:
    for event in pygame.event.get():
        if event.type in (QUIT,KEYDOWN):
            sys.exit()

    screen.fill((0,0,200))
    
    pos_x +=vel_x
    pos_y +=vel_y
    if pos_x>500 or pos_x<0:
        vel_x=-vel_x
        rand1=randint(0,255)
        rand2=randint(0,255)
        rand3=randint(0,255)
        color=rand1,rand2,rand3
    if pos_y>400 or pos_y<0:
        vel_y=-vel_y
        rand1=randint(0,255)
        rand2=randint(0,255)
        rand3=randint(0,255)
        color=rand1,rand2,rand3
    width=0
    pos=pos_x,pos_y,100,100
    pygame.draw.rect(screen,color,pos,width)

    pygame.display.update()

The random module is required here. Every time the screen boundary is hit, not only the direction of movement of the rectangle is changed, but also the color of the rectangle is changed using a random number.
You can also set the color to a fixed value first, which can save three lines of code.


Variables that are used for the first time in the lower-level (more nested) code block are still valid in the top-level code block.
The above problems belong to the scope of variables. It means that my understanding of this aspect is not clear enough.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325728368&siteId=291194637