Installation and use of pygame

Introduction to pygame

pygame is a free and open source cross-platform python multimedia library, mainly used for game development. pygame was born in 2000. In the field of python 2D game development, pygame is the most classic game library

pygame installation

1. Before installation, first use pycharm to create a project with a virtual environment, complete the settings as shown in the figure below and click Create.
1-1
2. Click Python Packages, search for pygame in the search box and click the installation package to install
insert image description here
3. Verify, if you want to verify whether you have installed pygame, you can enter pip list in the terminal to get the feedback as follows:
insert image description here
or enter in the terminal Run the following command to verify:

python -m pygame.examples.aliens

Feedback is as follows:
insert image description here

The first pygame program (framework)

First create a new folder of type py. The operation is as follows: Click File>New>Python file, enter the file name and press Enter.
insert image description here
insert image description here
insert image description here
Secondly, we should start writing the code. First, we should know which modules our program uses, and then import the module. Import the module in python. The keyword used is import so there are the following two lines of code:

#引入相关模块也可以这样写import pygame,sys
import pygame
import sys

The relevant module has a function that we need to give the user a direct access, that is to say, give the user an entry to start the program, what is that? That's right, it is the main function, and the corresponding expansion generates the following code:

import pygame,sys
if __name__ == '__main__':
#该print语句仅仅是为了程序不报错无实际意义
    print("Hello")

First of all, when we use the pygame module, we must align and initialize. The initialization method is very simple, that is, calling pygame.init() (pygame.init and pygame.quit() respectively correspond to the initialization and de-initialization processes. Both must appear at the same time. ). Then we think about what games we usually play? When there is a demand for a window that displays various screens, we should think about how to realize it. At this time, we will notice pygame.display.set_mode(), which receives a two-tuple representing width and height. Expand the code after the relevant code is implemented:

import pygame,sys
if __name__=='__main__':
	pygame.init()
	pygame.display.set_mode((400,300))
	pygame.quit()

At this point, users can try to run it. After running, they find that the window disappears immediately after being displayed for a while. The effect picture is as follows:
Please add a picture description
So how to make it display for a long time? A loop statement is used here. There are two types of loops in python, one is the for loop and the other is the while loop. Here's a small example of both:

#for循环案例
for a in [1,2,3]:
    for b in ['a','b']:
        print(a,b)

The output is as follows:
insert image description here

#while循环案例
a=0
while a<5:
    a=a+1
    print(a)

The output results are as follows:
insert image description here
If the condition behind while is always true, the while will loop forever unless a break or corresponding event is encountered to end the loop. Then let's think about the timing of pygame.quit(). It should work when we click the cross on the upper right corner. After it works, it should follow the sys.exit() function to exit the console so that the program does not report an error. Then we should How do you know if the user clicked the × in the upper right corner? Here we use pygame.event. Through the get method, we can know what the user has done on the window, and then use the if statement to determine whether its type is the same as the constant in pygame and call the method according to the user's action. The code for this step is expanded as follows:

import pygame,sys
if __name__=='__main__':
	pygame.init()
	pygame.display.set_mode((400,300))
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()
    #该代码为刷新界面之用会在之后进行讲解
    pygame.display.update()

Then we make some small adjustments to the code, write the content in main into a function and call the function in the main function, and the transformation result is as follows:

# 引入相关模块
import pygame,sys
# 函数声明与定义
def main():
    # 初始化
    pygame.init()
    # 设置窗口大小
    pygame.display.set_mode((400, 300))
    # 主循环
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 用户点击叉号结束
                pygame.quit()
                sys.exit()
        # 刷新窗口页面
        pygame.display.update()


if __name__=='__main__':
    # 调用函数
	main()

Pay extra attention to indentation when converting

Guess you like

Origin blog.csdn.net/weixin_51371629/article/details/125114256
Recommended