The use and advancement of pygame

Posted by expert_21 on Fri, 12 Jun 2020 12:30:57 +0200

Use of pygame

Pygame is a cross platform Python module designed for video games, including images and sounds. Based on SDL, real-time video game development is allowed without being bound by low-level languages (such as machine language and assembly language).

Minimum game development framework

import pygame,sys#Import pygame module
pygame.init()##Initialization, which is equivalent to telling the system that I want to develop a game
##Game window size, parameter is a tuple
windows=pygame.display.set_mode((600,400))
##Set captions
pygame.display.set_caption("Yang Guoping's games")
##Background color fill
windows.fill((255,255,255))##Parameter is a triple
pygame.display.flip()##Refresh page for the first time
##pygame.display.update() refresh after first time
while True:
    for event in pygame.event.get():##Listening events
        if event.type==pygame.QUIT:
            sys.exit()

Load picture & show picture

import pygame,sys
pygame.init()
##Game window size
windows=pygame.display.set_mode((600,400))
##subtitle
pygame.display.set_caption("Yang Guoping's games")
##Background color fill
windows.fill((255,255,255))
##-------Game start page static effect
##1. Load the picture (just put it in memory)
image1=pygame.image.load("java3.jpg")
##Zoom and rotate (the image loaded into memory is processed on the shape)
##This method cannot be scaled
new1=pygame.transform.scale(image1,(200,150))
##Scaling and angle rotation (the image loaded into memory is processed on the shape)
##The second parameter is the angle, and the third is the percentage of the original image
new2=pygame.transform.rotozoom(image1,45,0.7)
##2. Render the picture (this is to get the picture on the page (windows))
windows.blit(new1,(0,0))##Every time this method is called, a graph is rendered
windows.blit(new2,(200,0))
##Operation picture
w,h=image1.get_size()##Get the width and height of the picture
##3. Refresh the display page
pygame.display.flip()##Refresh page for the first time
##pygame.display.update() refresh after first time
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()

display graphics

import pygame,sys
pygame.init()
##Game window size
windows=pygame.display.set_mode((600,400))
pygame.display.set_caption("Yang Guoping's games")
windows.fill((255,255,255))
##pygame.draw It's like a paintbrush
##Draw a line (where, color, start, end, pixel)
pygame.draw.line(windows,(255,0,0),(50,100),(100,400),2)
##Draw line (where, color, smoothness, point set, pixel)
pygame.draw.lines(windows,(0,255,0),True,[(10,300),(100,160),(500,100),(150,400)],2)
##If you don't write the last parameter of circle drawing, it defaults to 0, filling, the third parameter is the center of circle, and the fourth parameter is the radius
pygame.draw.circle(windows,(10,50,150),(100,100),100,1)
##Draw a rectangle (the fourth parameter is the coordinates of the top left corner vertex and the width and height of the rectangle)
pygame.draw.rect(windows,(255,200,100),(100,100,100,200),1)
##Ellipse (tangent of rectangle, so the parameter is the same as rectangle)
pygame.draw.ellipse(windows,(255,0,100),(100,100,100,200),1)
##Arc, the fourth parameter is the start radian, the fifth parameter is the end radian
pygame.draw.arc(windows,(0,0,0),(100,100,100,200),0,3.1415926/3,3)
#3. Refresh the display page
pygame.display.flip()##Refresh page for the first time
##pygame.display.update() refresh after first time
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()

display text

import pygame,sys
pygame.init()
##Game window size
windows=pygame.display.set_mode((600,400))
pygame.display.set_caption("Yang Guoping's games")
windows.fill((255,255,255))
##1. Get the font object (equivalent to a brush)
font=pygame.font.Font("C:\\Windows\\Fonts\\FZSTK.TTF",30)
##2. Get text object
##The third parameter is font color, and the fourth parameter is font background
text=font.render("Hello game",True,(255,0,0),(255,255,0))
##Rendering, this is the same as image rendering
windows.blit(text,(0,0))
##Operation text
w,h=text.get_size()
windows.blit(text,(600-w,400-h))
##Zoom and rotate as picture
new1=pygame.transform.scale(text,(200,100))
new2=pygame.transform.rotozoom(text,45,0.5)
windows.blit(new1,(300,100))
windows.blit(new2,(100,200))
##3. Refresh the display page
pygame.display.flip()##Refresh page for the first time
##pygame.display.update() refresh after first time
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()

Animation principle

Animation is a frame of pictures connected, each frame of the picture difference is very small, the human eye is a coherent effect.

import pygame,sys
pygame.init()
WIN_WIDTH=600
WIN_HIGH=400
# #Game window size
windows=pygame.display.set_mode((WIN_WIDTH,WIN_HIGH))
pygame.display.set_caption("Yang Guoping 's Games")
windows.fill((255,255,255))
# #1. Load picture
# image1 = pygame.image.load("java3.jpg")
y = 100
r = 30
pygame.draw.circle(windows,(255,0,0),(150,y),r,1)
# windows.blit(image1,(0,0))
#3. Refresh the display page
pygame.display.flip()##Refresh page for the first time
##pygame.display.update() refresh after first time
num=0
d=0
y_speed=1
while True:
    num=num+1
    if num%1000==0:##Slow down refresh
        pygame.draw.circle(windows,(255,255,255),(150,y),r,1)##Cover the previous frame with a circle with a white border
        y=y+y_speed##Control movement
        if y>=WIN_HIGH-r:##The speed is the opposite when touching the lower border
           y_speed=y_speed*(-1)
        if y<=r:##It's the opposite when it comes to the top border
            y_speed = y_speed * (-1)
        # r=r+1##Control zoom
        pygame.draw.circle(windows, (255, 0, 0), (150, y), r, 1)
        ##Rotate animation
        # windows.fill((255, 255, 255))
        # d+=1
        # new_image=pygame.transform.rotozoom(image1,d,1)
        # windows.blit(new_image,(0,0))
        pygame.display.update()##Refresh page after first time
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()

event detection

I have done two cases, one is to monitor the keyboard event to output the value of the key, the other is to monitor the mouse movement event to draw a circle with random color.

import pygame,sys
from random import  randint
pygame.init()
WIN_WIDTH=600
WIN_HIGH=400
# #Game window size
windows=pygame.display.set_mode((WIN_WIDTH,WIN_HIGH))
pygame.display.set_caption("Yang Guoping's games")
windows.fill((255,255,255))
##1. Get font object
font=pygame.font.Font("C:\\Windows\\Fonts\\FZSTK.TTF",30)
pygame.display.flip()
x=0
while True:
    for event in pygame.event.get():
        # if event.type==pygame.MOUSEBUTTONDOWN:
        #     a = randint(0, 255)
        #     b = randint(0, 255)
        #     c=randint(0,255)
        #     x,y=event.pos
        #     pygame.draw.circle(windows,(a,b,c),(x,y),20,1)
        #     pygame.display.update()
        if event.type==pygame.MOUSEMOTION:##Monitor mouse movement
            a = randint(0, 255)##Triples generating random colors
            b = randint(0, 255)
            c=randint(0,255)
            x,y=event.pos##Get coordinates of mouse movement
            pygame.draw.circle(windows,(a,b,c),(x,y),20,0)##Draw a circle on the acquired coordinates
            pygame.display.update()
        if event.type==pygame.KEYDOWN:
            ##2. Get text object
            text = font.render(chr(event.key), True, (255, 0, 0), (255, 255, 0))  ##The third parameter is font color, and the fourth parameter is font background
            ##Rendering
            windows.blit(text, (x, 0))
            x+=30
            pygame.display.update()
        if event.type==pygame.QUIT:
            sys.exit()

Button click

My case is to click OK and cancel in the specified range, the button will have different color changes!

import pygame,sys
pygame.init()
##Game window size
WIDTH=400
HIGH=600
windows=pygame.display.set_mode((WIDTH,HIGH))
pygame.display.set_caption("Yang Guoping's games")
##Background color fill
windows.fill((255,255,255))
pygame.display.flip()
font=pygame.font.Font("C:\\Windows\\Fonts\\FZSTK.TTF",30)
##Draw the first OK button, draw OK on the rectangle
bx1,by1,bw,bh=30,100,100,50
pygame.draw.rect(windows,(255,0,0),(bx1,by1,bw,bh))
text1=font.render("determine",True,(255,255,255))
tw1,th1=text1.get_size()
tx1=bx1+bw/2-tw1/2
ty1=by1+bh/2-th1/2
windows.blit(text1,(tx1,ty1))
##Draw the second button
bx2,by2=30,200
pygame.draw.rect(windows,(0,255,0),(bx2,by2,bw,bh))
text2=font.render("cancel",True,(255,255,255))
tw2,th2=text1.get_size()
tx2=bx2+bw/2-tw2/2
ty2=by2+bh/2-th2/2
windows.blit(text2,(tx2,ty2))
pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()
        if event.type==pygame.MOUSEBUTTONDOWN:##Monitor Click
            mx,my=event.pos
            if bx1 <= mx <=bx1 + bw and by1 <= my <= by1 + bh:##Determine the location of the click
                pygame.draw.rect(windows,(200,200,200),(bx1,by1,bw,bh))##Redraw a gray background
                text1=font.render("determine",True,(255,255,255))##Write on a gray background
                windows.blit(text1,(tx1,ty1))
                pygame.display.update()
            if bx2 <= mx <=bx2 + bw and by2 <= my <= by2 + bh:
                pygame.draw.rect(windows,(200,200,200),(bx2,by2,bw,bh))
                text2=font.render("cancel",True,(255,255,255))
                windows.blit(text2,(tx2,ty2))
                pygame.display.update()
        if event.type==pygame.MOUSEBUTTONUP:##Monitor loose mouse
            mx, my = event.pos
            if bx1 <= mx <= bx1 + bw and by1 <= my <= by1 + bh:##Judge the scope of mouse delivery
                pygame.draw.rect(windows, (255, 0, 0), (bx1, by1, bw, bh))##Change back to the original color
                text1 = font.render("determine", True, (255, 255, 255))##Write the original words again
                windows.blit(text1, (tx1, ty1))
                pygame.display.update()
            if bx2 <= mx <= bx2 + bw and by2 <= my <= by2 + bh:
                pygame.draw.rect(windows, (0, 255, 0), (bx2, by2, bw, bh))
                text2 = font.render("cancel", True, (255, 255, 255))
                windows.blit(text2, (tx2, ty2))
                pygame.display.update()


Click the button and the background will turn gray. Once released, it will change back to the original color!!

Hold on

This case is to monitor the keyboard wsad, that is, the up and down left and right buttons in the game, and then the arrow of the game interface will change. If you hold down the mouse, it will always move in that direction!!

import pygame,sys
pygame.init()
##Game window size
WIDTH=800
HIGH=1200
windows=pygame.display.set_mode((WIDTH,HIGH))
pygame.display.set_caption("Yang Guoping's games")
##Background color fill
windows.fill((255,255,255))
pygame.display.flip()
##First, add the up, down, left and right arrow pictures to the memory
upimg=pygame.image.load("upper.png")
downimg=pygame.image.load("lower.png")
leftimg=pygame.image.load("Left.png")
rightimg=pygame.image.load("right.png")
##Initialize to up arrow, and initialize coordinates
defaultDirect=upimg
xInit,yInit=200,400
windows.blit(defaultDirect,(xInit,yInit))
pygame.display.flip()
is_move=False#Move or not
x_speed=0
y_speed=0
while True:
    if is_move:
        windows.fill((255,255,255))
        xInit+=x_speed
        yInit+=y_speed
        windows.blit(defaultDirect, (xInit, yInit))
        pygame.display.update()
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()
        if event.type==pygame.KEYDOWN:
           ch = chr(event.key)
           if ch == 'w':##Monitor whether the key is wsad, if so, change it to move, modify the corresponding picture, and then change x_ speed,y_ The value of speed, and the program returns to if is_move, the contents are executed all the time, and the graph is rendered to windows all the time. Because the horizontal and vertical coordinates are changing, the position will go according to the key direction.
               is_move = True
               defaultDirect = upimg
               x_speed = 0
               y_speed = -1
           if ch == 's':
               is_move = True
               defaultDirect = downimg
               x_speed = 0
               y_speed = 1
           if ch == 'a':
               is_move = True
               defaultDirect = leftimg
               x_speed = -1
               y_speed = 0
           if ch == 'd':
               is_move = True
               defaultDirect = rightimg
               x_speed = 1
               y_speed = 0
        if event.type==pygame.KEYUP:
            is_move = False

[note] since the animation effect cannot be completely represented by the screenshot, please run the code to check the effect. For the picture, please find me!!

Topics: Windows Python Assembly Language