[Unity] unity中对象池的使用

#1024程序员节|用代码,改变世界#

前言

Pygame是被设计用来写游戏的python模块集合,Pygame是在优秀的SDL库之上开发的功能性包。使用python可以导入pygame来开发具有全部特性的游戏和多媒体软件,Pygame是极度轻便的并且可以运行在几乎所有的平台和操作系统上。Pygame包已经被下载过成千上万次,并且也被访问过成千上万次。
Pygame是免费的,发行遵守GPL,你可以利用它开发开源的、免费的、免费软件、共享件、还有商业软件等等。
截止到 2020 年 10 月 28 日,Pygame 已经诞生 20 周年。Pygame 是 Pete Shinners 在 SDL(Simple DirectMedia Layer,一套开源的跨平台多媒体开发库,使用 C语言编写,它提供了多种控制图像、声音、输入/输出的函数,Pygame 可以看做是对 SDL 的封装,在 SDL 库基础上提供了各种 Python 的 API接口。目前 SDL 主要用于多媒体领域,比如开发游戏、模拟器、媒体播放器等。)基础上开发而来,其目的是取代 PySDL。
Python 作为一门解释型语言并不适合开发大型的 3D 游戏,但 Python 通过对其他语言的接口封装,使自身具备了开发大型 3D 游戏的能力,例如 Panda3D 的底层是用 C++ 语言编写的。但在网上看有人分析,panda3D用起来也不太爽,正从之转用unity3d;一些较为知名的 3D 游戏,比如魔兽世界、文明帝国4等游戏都是使用 Python 语言开发的,而国内较为知名的“阴阳师”手游,也是由 Python 语言开发而成。准备花些时间把pygame整理下,再去了解其它游戏知识。

知识点

1、python知识点

1.1 RGB 颜色表示

在pygame中,颜色也是采用RGB方式来设定,这种颜色由红色,绿色,蓝色组成,其中每个值的取值范围都为0~255.颜色值(255,0,0)表示红色,(0,255,0)表示绿色,(0,0,255)表示蓝色。从(0,0,0)到(255,255,255)一共有16,777,216种不同的颜色,下表简单列出一些常用的颜色
白色:rgb(255,255,255)
黑色:rgb(0,0,0)
红色:rgb(255,0,0)
绿色:rgb(0,255,0)
蓝色:rgb(0,0,255)
青色:rgb(0,255,255)
紫色:rgb(255,0,255)
在这里插入图片描述

1.2 类

定义按钮类,界面相关无素,为以后做简单小游戏作准备

class Button(object):
	def __init__(self, text, color, x=None, y=None, **kwargs):
		self.surface = font.render(text, True, color)
		self.WIDTH = self.surface.get_width()
		self.HEIGHT = self.surface.get_height()
		if 'centered_x' in kwargs and kwargs['centered_x']:
			self.x = display_width // 2 - self.WIDTH // 2
		else:
			self.x = x
		if 'centered_y' in kwargs and kwargs['cenntered_y']:
			self.y = display_height // 2 - self.HEIGHT // 2
		else:
			self.y = y

	def display(self):
		screen.blit(self.surface, (self.x, self.y))

	def check_click(self, position):
		x_match = position[0] > self.x and position[0] < self.x + self.WIDTH
		y_match = position[1] > self.y and position[1] < self.y + self.HEIGHT
		if x_match and y_match:
			return True
		else:
			return False```

### 2、pygame知识点
#### 2.1 安装 导入
关于PyGame的安装,如同python的第三方包一样,利用pip进行安装最为方便快捷:
pip install pygame
在安装完成后,在idle中或是ipython等交互命令窗口利用以下代码可验证是成功:
import pygame
#### 2.2 游戏初始化
![在这里插入图片描述](https://img-blog.csdnimg.cn/73d8c5fe11c54e20a93e31e5b393ae85.png)

```python
# _*_ coding: UTF-8 _*_
# 开发团队: 信息化未来
# 开发人员: Administrator
# 开发时间:2022/10/21 16:52
# 文件名称: pg初始2.py
# 开发工具: PyCharm
import pygame

# 初始化操作
pygame.init()
# 创建游戏窗口
# set_mode(大小),创建一个窗口,宽400像素、高600像素,需要传入一个元组。这个函数会返回一个pygame中的Surface对象(这里就是屏幕),
# 这个Surface对象是pygame中的一个非常重要的对象
window = pygame.display.set_mode((400, 600))
# 设置游戏名
pygame.display.set_caption('pygame游戏的初始化')
# 设置背景颜色
window.fill((255, 255, 255))
pygame.display.flip()
# 让游戏保持一直运行的状态
# 游戏循环(检测事件)
while True:
    # 检测事件(比如鼠标,键盘的点击检测)
    # 固定写法,event,get可以一次获取多个事件,所以要循环遍历
    for event in pygame.event.get():
        # 判断是否退出(点×)
        if event.type == pygame.QUIT:
            # 退出函数
            exit()

2.3 pygame.display.update()

pygame.display.update()就是用来刷新屏幕的,它会将屏幕清空,变成初始的样子。因为你游戏中可以不止一个人物在动,所以当所有事件响应完毕、计算出新的位置之后,会将屏幕刷新,然后在新的位置上重新绘制所有人物(或者模型),就仿佛人物在移动一样。另外,这个游戏默认应该是不退出的,也就是要不停的循环事件、并响应,所以我们外面要有一个while True:
flip()功能将整个显示表面更新到屏幕。
更常见的是,使用update()函数代替flip()函数,因为它只更新屏幕的某些部分,而不是整个区域,从而节省内存。让我们将update()函数添加到*.py文件的底部

2.4 加载图片

pygame.image.load表示加载一个图片,支持多种格式,然后返回一个Surface对象

import pygame
import time

def main():
    #1. 创建窗口
    screen = pygame.display.set_mode((370,598),0,32)
    #2. 创建一个背景图片
    background = pygame.image.load("images/bg1.jpg")
    while True:
        screen.blit(background, (50,0))
        pygame.display.update()
        time.sleep(0.01)
        for event in pygame.event.get():
            # 判断是否退出(点×)
            if event.type == pygame.QUIT:
                # 退出函数
                exit()

if __name__ == "__main__":
    main()

2.5 鼠标 键盘

pygame.event.get()
对于游戏来讲,事件是一个非常重要的概念,pygame需要接收事件并且进行响应。而对于pygame来讲,用户的键盘输入、鼠标移动、点击以及窗体的移动等等都是事件,pygame会把所有的事件都放在一个队列里面。通过pygame.event.get()即可拿到存放所有事件的队列,每一个事件在pygame中都是一个Event对象。
pygame.event.get()获取用户对窗口的所有响应。这里要注意,由于用户在同一时间有可能会对窗体进行多种操作,所以pygame.event.get()将返回一个列表,该列表中每一个元素均为pygame.event.Event类型,当然,如果用户不曾操作窗体,该列表将为空。
在这里插入图片描述

# _*_ coding: UTF-8 _*_
# 开发团队: 信息化未来
# 开发人员: Administrator
# 开发时间:2022/10/22 21:09
# 文件名称: pgbutton.py
# 开发工具: PyCharm

import pygame


class Button(object):
	def __init__(self, text, color, x=None, y=None, **kwargs):
		self.surface = font.render(text, True, color)

		self.WIDTH = self.surface.get_width()
		self.HEIGHT = self.surface.get_height()

		if 'centered_x' in kwargs and kwargs['centered_x']:
			self.x = display_width // 2 - self.WIDTH // 2
		else:
			self.x = x

		if 'centered_y' in kwargs and kwargs['cenntered_y']:
			self.y = display_height // 2 - self.HEIGHT // 2
		else:
			self.y = y

	def display(self):
		screen.blit(self.surface, (self.x, self.y))

	def check_click(self, position):
		x_match = position[0] > self.x and position[0] < self.x + self.WIDTH
		y_match = position[1] > self.y and position[1] < self.y + self.HEIGHT

		if x_match and y_match:
			return True
		else:
			return False


def starting_screen():
	screen.blit(bg, (0, 0))

	game_title = font.render('英语大战', True, WHITE)

	screen.blit(game_title, (display_width // 2 - game_title.get_width() // 2, 150))

	play_button = Button('开始', RED, None, 350, centered_x=True)
	exit_button = Button('关闭', WHITE, None, 400, centered_x=True)

	while True:

		if play_button.check_click(pygame.mouse.get_pos()):
			play_button = Button('开始', RED, None, 350, centered_x=True)
		else:
			play_button = Button('开始', WHITE, None, 350, centered_x=True)

		if exit_button.check_click(pygame.mouse.get_pos()):
			exit_button = Button('关闭', RED, None, 400, centered_x=True)
		else:
			exit_button = Button('关闭', WHITE, None, 400, centered_x=True)

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				raise SystemExit
		if pygame.mouse.get_pressed()[0]:
			if play_button.check_click(pygame.mouse.get_pos()):
				bfunc()
				print('开始')
				break
			if exit_button.check_click(pygame.mouse.get_pos()):
				print('结束')
				break
		play_button.display()
		exit_button.display()
		pygame.display.update()


display_width = 400
display_height = 600

WHITE = (255, 255, 255)
RED = (255, 0, 0)
bg_location = 'images\\bg2.jpg'

pygame.init()
screen = pygame.display.set_mode((display_width, display_height))
bg = pygame.image.load(bg_location)
font = pygame.font.Font('fonts\\simhei.ttf', 30)

def bfunc():
	print('按钮事件')


starting_screen()

2.6 颜色

pygame.color
Parameters(参数):
r (int)–红色值,取值范围为0 ~ 255(含255)
g (int)–绿色取值范围为0 ~ 255(含255)
b (int)–蓝色值,取值范围为0 ~ 255
a (int)–(可选)alpha值的取值范围为0 ~ 255(含255),默认为255
pygame.Color.r
获取或设置“颜色”的红色值。
pygame.Color.g
获取或设置Color的绿色值。
pygame.Color.b
获取或设置颜色的蓝色值。
pygame.Color.a
获取或设置颜色的alpha值

2.7 中文字体

font = pygame.font.Font(‘fonts\simhei.ttf’, 30)

2.8 音效

按钮加上音效

扫描二维码关注公众号,回复: 14579197 查看本文章
# _*_ coding: UTF-8 _*_
# 开发团队: 信息化未来
# 开发人员: Administrator
# 开发时间:2022/10/22 21:09
# 文件名称: pgbutton.py
# 开发工具: PyCharm

import pygame


class Button(object):
	def __init__(self, text, color, x=None, y=None, **kwargs):
		self.surface = font.render(text, True, color)

		self.WIDTH = self.surface.get_width()
		self.HEIGHT = self.surface.get_height()

		if 'centered_x' in kwargs and kwargs['centered_x']:
			self.x = display_width // 2 - self.WIDTH // 2
		else:
			self.x = x

		if 'centered_y' in kwargs and kwargs['cenntered_y']:
			self.y = display_height // 2 - self.HEIGHT // 2
		else:
			self.y = y

	def display(self):
		screen.blit(self.surface, (self.x, self.y))

	def check_click(self, position):
		x_match = position[0] > self.x and position[0] < self.x + self.WIDTH
		y_match = position[1] > self.y and position[1] < self.y + self.HEIGHT

		if x_match and y_match:
			return True
		else:
			return False


def starting_screen():
	screen.blit(bg, (0, 0))

	game_title = font.render('英语大战', True, WHITE)

	screen.blit(game_title, (display_width // 2 - game_title.get_width() // 2, 150))

	play_button = Button('开始', RED, None, 350, centered_x=True)
	exit_button = Button('关闭', WHITE, None, 400, centered_x=True)

	while True:

		if play_button.check_click(pygame.mouse.get_pos()):
			play_button = Button('开始', RED, None, 350, centered_x=True)
			pygame.mixer.Sound.play(sheji)
		else:
			play_button = Button('开始', WHITE, None, 350, centered_x=True)

		if exit_button.check_click(pygame.mouse.get_pos()):
			exit_button = Button('关闭', RED, None, 400, centered_x=True)
		else:
			exit_button = Button('关闭', WHITE, None, 400, centered_x=True)
			# pygame.mixer.Sound.play(yx)

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				raise SystemExit
		if pygame.mouse.get_pressed()[0]:
			if play_button.check_click(pygame.mouse.get_pos()):
				bfunc()
				print('开始')
				pygame.mixer.Sound.play(yx)
				# break
			if exit_button.check_click(pygame.mouse.get_pos()):
				print('结束')
				break
		play_button.display()
		exit_button.display()
		pygame.display.update()


display_width = 400
display_height = 600

WHITE = (255, 255, 255)
RED = (255, 0, 0)
bg_location = 'images\\bg2.jpg'

pygame.init()
pygame.mixer.init()
yx = pygame.mixer.Sound('sounds\\boom.wav')
sheji = pygame.mixer.Sound('sounds\\biu.wav')
screen = pygame.display.set_mode((display_width, display_height))
bg = pygame.image.load(bg_location)
font = pygame.font.Font('fonts\\simhei.ttf', 30)

def bfunc():
	print('按钮事件')


starting_screen()

总结

通过此次的《pygame基础的学习》对pygame的相关知识有了进一步的了解,对游戏进一步开发也有了比以前更深刻的认识。

源码获取

关注博主后,私聊博主免费获取
需要技术指导,育娃新思考,企业软件合作等更多服务请联系博主

今天是以此模板持续更新此育儿专栏的第 8 /50次。
可以关注我,点赞我、评论我、收藏我啦。

猜你喜欢

转载自blog.csdn.net/m0_51776409/article/details/124905816