Introduction to the pygame module of Python learning and making code rain

foreword

Friends who know something about Python games know that in 2D game production, a module pygame is often used, which can help us realize many convenient functions, such as drawing windows, feedback keyboard and mouse information, playing audio files, Rendering picture text and other functions.

Today we implement a simple example of code rain through the pygame module. By the way, we will explain some simple functional code examples in the sub-modules. I hope it will be helpful to the friends who see it.

The complete code is at the end of the article, please read it patiently! ! !

insert image description here

Explanation of some functions of the pygame module

Pygame (Python Game) is a cross-platform multimedia library mainly used for developing games, audio and graphics applications. The following introduces some commonly used Pygame submodules and how to use them.

1、pygame.display

This module is used to manage the display of the game window. You can use it to create game windows, set window sizes, refresh the screen, and more.

import pygame  
pygame.init()  
  
# 创建游戏窗口  
screen = pygame.display.set_mode((800, 600))  
pygame.display.set_caption("My Game")  
  
while True:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            pygame.quit()  
            exit()  
    # 在屏幕上绘制图形  
    pygame.display.update()

2、pygame.event

This module is used to handle events, such as keyboard, mouse, game controller and other events. You can use it to check if a key is pressed, the mouse is moved, etc.

import pygame  
pygame.init()  
  
# 创建游戏窗口  
screen = pygame.display.set_mode((800, 600))  
pygame.display.set_caption("My Game")  
  
while True:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            pygame.quit()  
            exit()  
        elif event.type == pygame.KEYDOWN:  
            if event.key == pygame.K_ESCAPE:  
                pygame.quit()  
                exit()  
    # 在屏幕上绘制图形  
    pygame.display.update()

3、pygame.locals

This module contains various constants, such as keycodes for keys, keycodes for mouse buttons, etc. It can be used to obtain various constants.

import pygame  
pygame.init()  
  
# 创建游戏窗口  
screen = pygame.display.set_mode((800, 600))  
pygame.display.set_caption("My Game")  
  
while True:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            pygame.quit()  
            exit()  
        elif event.type == pygame.KEYDOWN:  
            if event.key == pygame.K_ESCAPE:  
                pygame.quit()  
                exit()  
    # 在屏幕上绘制图形并设置字体样式和颜色  
    pygame.draw.line(screen, (255, 0, 0), (100, 100), (300, 100), 5)  
    font = pygame.font.Font(None, 36)  
    text = font.render("Hello, World!", True, (255, 255, 255))  
    screen.blit(text, (100, 50))  
    pygame.display.update()

4、pygame.time

This module is used to manage the timing and frame rate of the game. You can use it to get the current time, delays, timers, etc.

import pygame  
pygame.init()  
  
# 创建游戏窗口  
screen = pygame.display.set_mode((800, 600))  
pygame.display.set_caption("My Game")  
  
clock = pygame.time.Clock()  
running = True  
  
while running:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            running = False  
        elif event.type == pygame.KEYDOWN:  
            if event.key == pygame.K_ESCAPE:  
                running = False  
    # 在屏幕上绘制图形并设置字体样式和颜色  
    pygame.draw.line(screen, (255, 0, 0), (100, 100), (300, 100), 5)  
    font = pygame.font.Font(None, 36)  
    text = font.render("Hello, World!", True, (255, 255, 255))  
    screen.blit(text, (100, 50))  
    # 控制游戏帧率  
    clock.tick(60)  
    pygame.display.update()

5、pygame.mixer

This module is used to play audio files, such as music, sound effects, etc. It can be used to play various audio files.

import pygame  
pygame.init()  
  
# 创建游戏窗口  
screen = pygame.display.set_mode((800, 600))  
pygame.display.set_caption("My Game")  
  
# 加载音频文件  
pygame.mixer.music.load("audio.mp3")  
pygame.mixer.music.play()  
  
# 在屏幕上绘制图形并设置字体样式和颜色  
pygame.draw.line(screen, (255, 0, 0), (100, 100), (300, 100), 5)  
font = pygame.font.Font(None, 36)  
text = font.render("Hello, World!", True, (255, 255, 255))  
screen.blit(text, (100, 50))  
  
# 控制游戏帧率  
clock = pygame.time.Clock()  
while pygame.mixer.music.get_busy():  
    clock.tick(60)  
    pygame.display.update()

6. 30 lines of code to solve the code rain

Simple design:

1. Black background, random font color, random characters ----- pygame and random

2. drop, display, refresh

import sys
import random
import pygame
from pygame.locals import *


# 屏幕大小
WIDTH = 800
HEIGHT = 600
# 下落速度范围
SPEED = [15, 30]
# 字母大小范围
SIZE = [5, 30]
# CODE长度范围
LEN = [1, 8]


# 随机生成一个颜色
def randomColor():
	return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


# 随机生成一个速度
def randomSpeed():
	return random.randint(SPEED[0], SPEED[1])


# 随机生成一个大小
def randomSize():
	return random.randint(SIZE[0], SIZE[1])


# 随机生成一个长度
def randomLen():
	return random.randint(LEN[0], LEN[1])


# 随机生成一个位置
def randomPos():
	return (random.randint(0, WIDTH), -20)


# 随机生成一个字符串
def randomCode():
	return random.choice('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890')


# 定义代码精灵类
class Code(pygame.sprite.Sprite):
	def __init__(self):
		pygame.sprite.Sprite.__init__(self)
		self.font = pygame.font.Font('./font.ttf', randomSize())	# 随机字体大小
		self.speed = randomSpeed()			# 随机速度
		self.code = self.getCode()			# 随机长度
		self.image = self.font.render(self.code, True, randomColor())	# 使用已有的文本创建一个位图image,返回值为一个image  随机颜色
		self.image = pygame.transform.rotate(self.image, random.randint(87, 93))	# 讲图像随机旋转角度
		self.rect = self.image.get_rect()
		self.rect.topleft = randomPos()		# 随机位置

	def getCode(self):
		length = randomLen()
		code = ''
		for i in range(length):
			code += randomCode()
		return code
	def update(self):
		self.rect = self.rect.move(0, self.speed)
		if self.rect.top > HEIGHT:
			self.kill()


pygame.init()			# 初始函数,使用pygame的第一步
screen = pygame.display.set_mode((WIDTH, HEIGHT))	#生成主屏幕screen;第一个参数是屏幕大小
pygame.display.set_caption('逃逸的卡路里')	# 窗口命名

clock = pygame.time.Clock()					# 初始化一个clock对象
codesGroup = pygame.sprite.Group()			# 精灵组,一个简单的实体容器
while True:
	clock.tick(24)							# 控制游戏绘制的最大帧率为30
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			sys.exit(0)
	# screen.fill((1, 1, 1))					# 填充
	screen.fill((0, 0, 0))						# 填充背景颜色

	codeobject = Code()
	codesGroup.add(codeobject)				# 添加精灵对象
	codesGroup.update()
	codesGroup.draw(screen)
	pygame.display.update()

Code rain effect diagram display

insert image description here

Summarize

Pygame (Python Game) is a Python module for developing games. It provides functions such as processing game windows, audio, event processing, and graphics rendering. It can be used to develop 2D games and graphical interface applications.
The above are some common sub-modules and usage methods of Pygame. Using these modules can help developers more conveniently carry out tasks such as game development and graphical interface development.

Guess you like

Origin blog.csdn.net/u014740628/article/details/130865461