Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # this is just a script containing the basics for a life simulation with 3 competing lifeforms and food items...
- # for Edu purposes ;)
- # File : Three_lifeForms_and_food.py
- # Script by: MrLunk
- # https://github.com/mrlunk/
- """
- This script is a basic simulation of three competing life forms and food items using the Pygame library in Python. It simulates the interactions and behaviors of the life forms in a two-dimensional environment.
- """
- import pygame
- import random
- # Define some colors
- WHITE = (255, 255, 255)
- RED = (255, 0, 0)
- BLUE = (0, 0, 255)
- YELLOW = (255, 255, 0)
- GREEN = (0, 255, 0)
- # Set the width and height of the screen
- WIDTH = 1000
- HEIGHT = 1000
- # Define the life form class
- class LifeForm(pygame.sprite.Sprite):
- def __init__(self, color, x, y):
- super().__init__()
- self.color = color
- self.energy = 50
- self.speed = self.energy / 10
- self.image = pygame.Surface([20, 20])
- self.image.fill(self.color)
- self.rect = self.image.get_rect()
- self.rect.x = x
- self.rect.y = y
- def update(self, food_group, life_group):
- self.energy -= 1
- # Move towards food or other life forms of a different color
- targets = []
- for food in food_group:
- distance = ((food.rect.x - self.rect.x) ** 2 + (food.rect.y - self.rect.y) ** 2) ** 0.5
- if distance < 100:
- targets.append(food)
- for life in life_group:
- if life.color != self.color:
- distance = ((life.rect.x - self.rect.x) ** 2 + (life.rect.y - self.rect.y) ** 2) ** 0.5
- if distance < 100:
- targets.append(life)
- if len(targets) > 0:
- target = min(targets, key=lambda t: ((t.rect.x - self.rect.x) ** 2 + (t.rect.y - self.rect.y) ** 2) ** 0.5)
- dx = target.rect.x - self.rect.x
- dy = target.rect.y - self.rect.y
- distance = ((dx ** 2) + (dy ** 2)) ** 0.5
- if distance > 0:
- self.rect.x += int((dx / distance) * self.speed)
- self.rect.y += int((dy / distance) * self.speed)
- # If the life form is close enough to food, eat it
- if isinstance(target, Food) and distance < 20:
- self.energy += 10
- target.kill()
- # If the life form is close enough to a life form of a different color, fight it
- # READ !
- # ... ... ...
- # the FULL SCRIPT can be found on my GitHUB here: https://github.com/mrlunk/Fun-with-Python/tree/main/Life_Simulations
- # give us a STAR there if you like this basic educational script.
Advertisement
Advertisement