pygame学习--精灵组、碰撞检测、精灵更新
- 一.效果
- 二.代码
通过pygame库,模拟种群的分化
1.X从左往右移动,表示年龄的增加;Y坐标表示阶层
2.随着X坐标不断增大,圆逐渐增大,颜色也加深
3.精灵越多,碰撞后死亡的概率越大,诞生新精灵的概率越小
4.每个精灵都有随机的运动速度及Y坐标的移动方向
5.发生碰撞且诞生新精灵时,继承当前坐标的Y值
一.效果
- 初始状态
- 迭代一段时间后
二.代码
import pygame
import numpy as np
import random
min_sprite_radius=5
max_sprite_radius=15
max_width=max_sprite_radius*100
max_height=min_sprite_radius*100
max_sprites=5000
class Life(pygame.sprite.Sprite):
def __init__(self,y=None):
super().__init__()
self.image = pygame.Surface((min_sprite_radius, min_sprite_radius),pygame.SRCALPHA)
self.rect = self.image.get_rect()
self.rect.centerx = np.random.randint(0,max_width)
if y:
self.rect.centery = y
else:
self.rect.centery = np.random.randint(0,max_height)
def update(self):
dir = np.random.randint(-1*min_sprite_radius,min_sprite_radius)
speed = np.random.randint(1,min_sprite_radius)
self.rect.centerx += speed
self.rect.centery += dir
ratio=self.rect.centerx/max_width
color_depth=ratio*255
radius =ratio*(max_sprite_radius-min_sprite_radius)+min_sprite_radius
self.image = pygame.transform.scale(self.image, (radius , radius ))
pygame.draw.circle(self.image, (color_depth, 128, 128), (radius //2, radius //2), (radius //2)-1)
random.seed(2)
np.random.seed(2)
pygame.init()
screen = pygame.display.set_mode((max_width,max_height))
pygame.display.update()
clock = pygame.time.Clock()
fps=30
sprite_group = pygame.sprite.Group(*[Life() for _ in range(max_sprites//10)])
while True:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("退出...")
pygame.quit()
exit()
screen.fill((31, 31, 31))
sprite_group.update()
# 判断是否超出边界
for group_a_sprite in sprite_group.sprites():
bkill=False
if group_a_sprite.rect.centerx>=max_width:
bkill=True
if group_a_sprite.rect.centery>=max_height or group_a_sprite.rect.centery<0:
bkill=True
if bkill:
group_a_sprite.kill()
# 碰撞检测
add_yoffsets=[]
total_sprites=len(sprite_group)
for group_a_sprite in sprite_group.sprites():
collision = pygame.sprite.spritecollide(group_a_sprite, sprite_group, False)
for j in collision:
if id(group_a_sprite)==id(j):
continue
else:
kill_prob=total_sprites/max_sprites
remain_prob=1.0-kill_prob
state=random.choices([0,1,2],[kill_prob,remain_prob/2,remain_prob/2],k=1)[0]
if state==0:
group_a_sprite.kill()
if state==1:
add_yoffsets.append(group_a_sprite.rect.centery)
if state==2:
pass
# 生成新精灵
if total_sprites<max_sprites:
for y in add_yoffsets:
sprite_group.add(Life(y))
sprite_group.draw(screen)
myString=f"count:{total_sprites}"
font = pygame.font.SysFont("Times New Roman", 48)
text = font.render(myString, True, (255,255,255))
screen.blit(text, (10,10))
pygame.display.update()
pygame.quit()