Created
April 1, 2020 23:37
-
-
Save jegor377/8b17d890816873672ecceae23086fea5 to your computer and use it in GitHub Desktop.
Little script for procedural generating parallax background sprite. I use it for generating a lot of little stars. You can adjust size of the image, amount of stars, star sample sprite, deviation in size (don't set 100%).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
from random import randint | |
import math | |
def distance(a, b): | |
return math.sqrt(math.pow(b[0] - a[0], 2) + math.pow(b[1] - a[0], 2)) | |
def is_near_other_star(star, stars, min_dist): | |
for _star in stars: | |
if distance(_star, star) <= min_dist: | |
return True | |
return False | |
def create_star(star_size, img_size): | |
return (randint(star_size[0] / 2, img_size[0] - star_size[0] / 2), randint(star_size[1] / 2, img_size[1] - star_size[1] / 2)) | |
def deviate_size(original_size, deviation): | |
bonus_size = float(randint(0, deviation)) / 100 * randint(-1, 1) | |
x = original_size[0] + (original_size[0] * bonus_size) | |
y = original_size[1] + (original_size[1] * bonus_size) | |
return (int(x), int(y)) | |
if __name__ == '__main__': | |
created_stars = [] | |
img = Image.open(input('File name: ')) | |
size = tuple([int(x) for x in input('WxH: ').split('x')]) | |
amount = int(input('Amount of stars: ')) | |
min_distance = int(input('Minimum distance: ')) | |
deviation = int(input('Size deviation (in %): ')) | |
for i in range(amount): | |
new_star = create_star(img.size, size) | |
while is_near_other_star(new_star, created_stars, min_distance): | |
new_star = create_star(img.size, size) | |
created_stars.append( | |
new_star | |
) | |
bg = Image.new('RGBA', size, (0, 0, 0, 0)) | |
for star in created_stars: | |
bg.paste(img.resize(deviate_size(img.size, deviation)), star) | |
bg.save('result.png', quality=95) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment