preface

Implementing it in Python is a good example of code rain. Let’s have a good time

Code effect display

The development tools

Python version: 3.6.4

Related modules:

Pygame module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required related modules.

Introduction of the principle

Code rain is actually quite simple to implement, first define a code Sprite class, which is used to generate random letter fragments, note that each update Sprite should let it fall a certain distance and “kill” the Sprite when it falls off-screen:

# Define code sprites
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())
		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()
Copy the code

The main loop then generates the letter fragments (i.e. instantiates the sprites) and updates them (i.e. drops the letter fragments) :

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Code Rain-ilove-python')
clock = pygame.time.Clock()
codesGroup = pygame.sprite.Group()
while True:
	clock.tick(24)
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			sys.exit(0)
	screen.fill((1.1.1))
	codeobject = Code()
	codesGroup.add(codeobject)
	codesGroup.update()
	codesGroup.draw(screen)
	pygame.display.update()
Copy the code

That’s all, full source code see personal profile for relevant files.