Project 3: pygame game

Table of contents

pygame module

introduce

Function

Install

How to program a game

composition

Draw graphics using the pygame module

 Load images in the game window

Display text in the game window

Perform various operations in the game window (i.e. human-computer interaction)

Game 1: Xuerongrong

Game 2: Collision Detection

Summarize:

Commonly used submodules of pygame

pygame module

introduce

        ​ ​ Python Pygame is a software package specifically designed for the development and design of 2D electronic games. It supports operating systems such as Windows, Linux, and Mac OS, and has good cross-platform capabilities. Pygame was developed by Pete Shinners in 2000 and is a free and open source software package.        

        Pygame is developed on the basis of SDL (Simple DirectMedia Layer, a multimedia development library written in C language). It provides many operating modules, such as image module (image), sound module (mixer), input/output (mouse, Keyboard, display) module, etc.

Function

        Draw graphics

        display image        

        Animation effects        

        Interact with peripherals such as keyboard, mouse, game controller, etc.        

        Play sound        

        Impact checking

Install

        1. Open cmd

        2. pip install pygame

How to program a game

composition

1. Initial settings

        First you need to import the module, create the game screen, and then initialize some important variables

2. Game loop (meaning the game officially starts)

        When playing our game, various events in the game may be triggered, such as mouse events, keyboard key events, camera events, etc. Therefore, the game program needs to continuously monitor the player's operations in a loop. Only when the user clicks the "Close" button of the game When, monitoring will end. If you want to achieve the purpose of "loop monitoring", you need to set up a game loop (Game Loop), also called the main loop of the game, so as to ensure the human-computer interaction experience.

 3. Exit the program

        When the user wants to stop the program, use a method to end the program

Draw graphics using the pygame module

Code example:

Initial setup: This is the first part of the code in the entire program. Its function is to automatically detect whether the Pygame software package is available normally, and to check whether there are problems with the computer's hardware calling interface and basic functions, such as audio, optical drives, sound card drivers and other devices. At the same time, it will complete the initialization operations of all modules in Pygame, such as display (display module), font (font module), mixer (sound control module), cursors (cursor control module), etc.

import pygame
pygame.init()    #初始化pygame

screen=pygame.display.setmode((800,600)) #创建一个显示窗口
pygame.display.set_caption("pygame绘制图形") #设置窗口标题

Game loop: means the game officially starts

1. You need to set up a Game Loop (Game Loop), also called the main loop of the game.

2. Players may move and click the mouse, press skill keys on the keyboard, or slide the phone screen. These operations are for human-computer interaction between the player and the program. These operations that interact with the game program are called Event. The game program needs to traverse all the player's operations. Different operations will cause different changes in the game state, and the display on the screen needs to be refreshed in time to create a dynamic picture effect of the game. The loop ends when the user clicks the game's "Close" button.

while True:
    for event in pygame.event.get():   #监听事件(遍历)
        if event.type==pygame.QUIT:  #退出事件
            break
    pygame.draw.circle(screen,(255,0,0),(200,300),20) #绘制图形
    pygame.display.update() #更新屏幕

exit the program:

When the loop ends, the game chooses to exit

pygame.quit()

Rendering:

 Load image in game window

        In the game, most of the game elements that can be seen are images. Image files are initially saved on disk. If they need to be used, they need to be loaded into memory in the first step.

        To see the content of an image on the screen, you need to follow three steps:

        ​ ​ 1. Use pygame.image.load() to load image data

        ​ ​ 2. Use the game screen object and call the blit method to draw the image to the specified position

        ​ ​ 3. Call the pygame.display.update() method to update the display of the entire screen

Code example:

import pygame    #导入模块

pygame.init()    #pygame模块初始化
#创建一个窗口screen,大小为600*400
screen=pygame.display.set_mode([600,400])
back=pygame.image.load('bj.jpg') #加载背景图像
screen.blit(back,[0,0]) #将背景图画在窗口的[0,0]位置处
img=pygame.image.load('rr.jpg') #加载雪容融图像
screen.blit(img,[100,50])#将雪容融画在窗口的[100,50]位置处
pygame.display.update()    #窗口刷新

Rendering:

Use circulation to make the snow melt:

Code example:

import pygame    #导入模块

pygame.init()    #pygame模块初始化
#创建一个窗口screen,大小为600*400
screen=pygame.display.set_mode([600,400])
back=pygame.image.load('bj.jpg') #加载背景图像
screen.blit(back,[0,0]) #将背景图画在窗口的[0,0]位置处
img=pygame.image.load('rr.jpg') #加载雪容融图像
screen.blit(img,[100,50])#将雪容融画在窗口的[100,50]位置处
pygame.display.update()    #窗口刷新

#在上一代码基础上新增以下代码
for i in range(1,5):
    screen.blit(img,[100+i*30,50+i*30]) #不断更改显示位置
    pygame.display.update() #更新屏幕
    pygame.time.delay(800)  #设置两次显示雪容融之间的延时

Effect: Xuerongrong appears five times, which does not fit the movement situation.

Modification: Moving Xuerongrong requires completing two steps:

① Erase or cover the original image ② Draw the image in a new position

Code example:

import pygame    #导入模块

pygame.init()    #pygame模块初始化
#创建一个窗口screen,大小为600*400
screen=pygame.display.set_mode([600,400])
back=pygame.image.load('bj.jpg') #加载背景图像
screen.blit(back,[0,0]) #将背景图画在窗口的[0,0]位置处
img=pygame.image.load('rr.jpg') #加载雪容融图像
screen.blit(img,[100,50])#将雪容融画在窗口的[100,50]位置处
pygame.display.update()    #窗口刷新
for i in range(1,5):
    screen.blit(back,[0,0]) #用背景图覆盖原来的雪容融
    screen.blit(img,[100+i*30,50+i*30]) #画出雪容融新的位置
    pygame.display.update() #更新屏幕
    pygame.time.delay(800)  #设置两次显示雪容融之间的延时

Display text in the game window

Code example:

import pygame    #导入模块

pygame.init()    #pygame模块初始化
#创建一个窗口screen,大小为600*400
screen=pygame.display.set_mode([600,400])
back=pygame.image.load('bj.jpg') #加载背景图像
screen.blit(back,[0,0]) #将背景图画在窗口的[0,0]位置处
img=pygame.image.load('rr.jpg') #加载雪容融图像
screen.blit(img,[100,50])#将雪容融画在窗口的[100,50]位置处
pygame.display.update()    #窗口刷新

for i in range(1,5):
    screen.blit(back,[0,0]) #覆盖底图

    textfont=pygame.font.SysFont('Arial',30) #创建文本对象,Arial,大小30
    text="北京"
    t=textfont.render(text,True,(255,0,0)) #生成平滑的红色字符串
    screen.blit(t,[50,50]) #在窗口显示

    screen.blit(img,[100+i*30,50+i*30]) #不断更改显示位置
    pygame.display.update() #更新屏幕
    pygame.time.delay(800)  #设置显示之间的延时

Function introduction:

render (text content, whether to anti-alias, font color, font background color)

running result:

Perform various operations in the game window (i.e. human-computer interaction)

Pygame will accept various operations (i.e. events) generated by users. Event is one of the important modules of Pygame. It is the core of building the entire game program, such as mouse clicks, keyboard taps, game window movement, window resizing, triggering specific plots, exiting the game, etc., these can Think of it as an "event".

Loop through events and change game state:

for event in pygame.event.get(): #侦听并获取事件列表
        if event.type==pygame.QUIT: #接收到退出事件后退出程序
            sys.exit()

Some of the events are as follows:

Game 1: Xuerongrong

Game function: Click on the snow to melt and display the score

Code example:

import pygame    #导入模块
import sys
import random
pygame.init()    #pygame模块初始化
score=0 #变量初始化
mousex=0
mousey=0
#创建一个窗口screen,大小为600*400
screen=pygame.display.set_mode([600,400])
back=pygame.image.load('bj.jpg') #加载背景图像
img=pygame.image.load('rr.png') #加载雪容融图像

while True:
    screen.blit(back,[0,0]) #覆盖底图
    textfont=pygame.font.SysFont('SimHei',30) #创建文本对象,Arial,大小30
    t=textfont.render('2022北京冬奥助力值'+str(score),True,(255,0,0)) #生成平滑的红色字符串
    screen.blit(t,[150,50]) #在窗口显示
    x=random.randint(0,400)#随机生成福字水平方向坐标
    y=random.randint(0,300)
    screen.blit(img,[x,y])#不断更改显示位置
    pygame.display.update() #更新屏幕
    pygame.time.delay(800)  #设置显示之间的延时
    for event in pygame.event.get(): #侦听并获取事件列表
        if event.type==pygame.QUIT: #接收到退出事件后退出程序
            sys.exit()
        if event.type==pygame.MOUSEBUTTONDOWN: #侦听到鼠标点击事件
            mousex,mousey=pygame.mouse.get_pos() #获取鼠标按下的坐标
            #判断鼠标是否击中福字,本例福字宽为100,高为100
    if mousex in range(x,x+100) and mousey in range(y,y+100): 
        score=score+5 #加分

Game 2: Collision Detection

Game features: Keyboard control movement

Game screenshots:

Use the x coordinate to determine whether you have reached the end point

Code example:

if x<=0:
        textfont=pygame.font.SysFont('SimHei',30) #创建文本对象,使用系统自带字体,大小30
        t=textfont.render("YOU WIN!",True,(255,0,0)) #生成平滑的红色字符串
        screen.blit(t,[150,150]) #在窗口显示
        pygame.display.update() #更新屏幕
        pygame.time.delay(800)

Complete code:

import pygame    #导入模块
import sys

pygame.init()    #pygame模块初始化
#创建一个窗口screen,大小为500*300
screen=pygame.display.set_mode([500,300])
back=pygame.image.load('xd.jpg') #加载背景图像
screen.blit(back,[0,0]) #将背景图画在窗口的[0,0]位置处
img=pygame.image.load('xb.png') #加载人物图像
x=450
screen.blit(img,[x,200])#将人物画在窗口的[450,200]位置处
pygame.display.update()    #窗口刷新

while True:
    if x<=0:
        textfont=pygame.font.SysFont('SimHei',30) #创建文本对象,使用系统自带字体,大小30
        t=textfont.render("YOU WIN!",True,(255,0,0)) #生成平滑的红色字符串
        screen.blit(t,[150,150]) #在窗口显示
        pygame.display.update() #更新屏幕
        pygame.time.delay(800)
    else:
        for event in pygame.event.get(): #侦听并获取事件列表
            if event.type==pygame.QUIT: #接收到退出事件后退出程序
                sys.exit()
            if event.type==pygame.KEYDOWN:#键盘是否按下
                if event.key==pygame.K_LEFT:#按下左箭头键
                    x=x-2
                elif event.key==pygame.K_RIGHT:#按下右箭头键
                    x=x+2
    screen.blit(back,[0,0]) #覆盖底图
    screen.blit(img,[x,200])#不断更改显示位置
    textfont2=pygame.font.SysFont('SimHei',30) #创建文本对象,使用系统自带字体,大小30
    t2=textfont2.render("全民上冰雪",True,(255,0,0)) #生成平滑的红色字符串
    screen.blit(t2,[150,50]) #在窗口显示
    textfont3=pygame.font.SysFont('SimHei',20) #创建文本对象,使用系统自带字体,大小30
    t3=textfont3.render("加油!你距离终点还有"+str(x)+"米",True,(0,0,0)) #生成平滑红色字符串
    screen.blit(t3,[100,100]) #在窗口显示
    pygame.display.update() #更新屏幕
    pygame.time.delay(10)  #设置显示之间的延时

Summarize:

pygame is a module specially used to develop games, which can include images, sounds, etc.

Commonly used submodules of pygame

pygame.display accesses the display device

pygame.event manages events

pygame.font uses fonts

pygame.image loads and stores images

Guess you like

Origin blog.csdn.net/qq_28782419/article/details/127762482