欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python编程从入门到实践练习(雨滴)

程序员文章站 2022-04-14 08:53:33
雨滴:寻找一幅雨滴图像,并创建一系列整齐排列的雨滴。让这些雨滴往下落,直到到达屏幕后消失。 先说今天的问题: 1.在更改函数形参时,调用的时候也要修改,否则会出现attributeerror 值得注...

雨滴:寻找一幅雨滴图像,并创建一系列整齐排列的雨滴。让这些雨滴往下落,直到到达屏幕后消失。

先说今天的问题:

1.在更改函数形参时,调用的时候也要修改,否则会出现attributeerror

值得注意的是:每当添加进新的代码,要检查函数传递的参数是否对应一致,函数本身与调用它的时候都要检查

2.愚蠢的错误:把创建整齐雨滴的函数写到循环体中去了,结果一直出现重叠,达不到预期效果,搞了半天眼睛快瞎了才发现,唉!

 

主程序 display

import pygame


from settings import settings

from rain import rain

import func as f

from pygame.sprite import group#####

def display():
	"""主函数----显示雨滴效果"""
	pygame.init()
	settings = settings()
	screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))
	pygame.display.set_caption('raining')
	rains = group()####
	f.create_rains(settings, screen, rains)#####
	while true:
		f.check_events()
		screen.fill(settings.bg_color)
		f.change_direction(settings, rains)
		rains.draw(screen)
		pygame.display.flip()

display()

函数模块func

import pygame

import sys

from rain import rain


def check_events():
	"""按键检查"""
	for event in pygame.event.get():
			if event.type == pygame.quit:
				sys.exit()

def get_col_numbers(settings, rain):#对于每一行来说,变化的是x坐标,列在变化
	"""一行可以存放的雨滴数"""
	col_numbers = int(settings.screen_width / (2 * rain.rect.width))
	return col_numbers

def get_row_numbers(settings, rain):
	"""可存放雨滴的行数"""
	row_numbers = int(settings.screen_height / (1 * rain.rect.height))
	return row_numbers

def create_rain(settings, screen, rains, col_number, row_number):
	rain = rain(settings, screen)
	rain_width = rain.rect.width
	rain.x = rain_width + 2 * rain_width * col_number
	rain.rect.x = rain.x#rect存放整数
	rain.rect.y = rain.rect.y + 2 * rain.rect.height * row_number
	rains.add(rain)

def create_rains(settings, screen, rains):
	rain = rain(settings, screen)#这句是要写的,不写的话get_col_numbers()中的rain将出现nameerror
	col_numbers = get_col_numbers(settings, rain)
	row_numbers = get_row_numbers(settings, rain)
	for row_number in range(row_numbers):
		for col_number in range(col_numbers):
			create_rain(settings, screen, rains, col_number, row_number)

def change_direction(settings, rains):
	for rain in rains.sprites():
		rain.rect.y += settings.drop_speed

		

		

rain类:

import pygame

from pygame.sprite import sprite

class rain(sprite):
	"""雨滴"""
	def __init__(self, settings, screen):
		super().__init__()
		self.screen = screen
		self.settings = settings
		self.image = pygame.image.load('rain.bmp')
		self.rect = self.image.get_rect()
		
		self.y = float(self.rect.y)
		
	def blitme(self):
		self.screen.blit(self.image, self.rect)
	
def check_edges(self):
		"""如果雨滴位于屏幕边缘就返回true"""
		if self.rect.top >= self.screen.rect.bottom:
			return true

settings类:

class settings():
	"""设置所有设置的类"""
	def __init__(self):
		self.screen_width = 1200
		self.screen_height = 600
		self.bg_color = (255, 255, 255)
		self.drop_speed = 1

效果图:

初始:

Python编程从入门到实践练习(雨滴)

下落:

Python编程从入门到实践练习(雨滴)