simulate Crowds of people walking or not moving on the beach

To simulate crowds of people walking or not moving on the beach using Python 3, we can use the Pygame library to create a graphical user interface and simulate the movement of the people. Here’s an example code:

pythonCopy codeimport pygame
import random

# Initialize Pygame
pygame.init()

# Set the dimensions of the screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Crowds on the Beach")

# Set up the clock
clock = pygame.time.Clock()

# Define the colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# Set up the font
font = pygame.font.Font(None, 25)

# Set up the beach background
beach_image = pygame.image.load("beach.jpg")
beach_rect = beach_image.get_rect()

# Set up the people
people = []
for i in range(50):
    person = {}
    person["image"] = pygame.image.load("person.png")
    person["rect"] = person["image"].get_rect()
    person["rect"].x = random.randint(0, screen_width - person["rect"].width)
    person["rect"].y = random.randint(0, screen_height - person["rect"].height)
    person["direction"] = random.choice(["up", "down", "left", "right"])
    person["speed"] = random.randint(1, 3)
    people.append(person)

# Main game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Update the people's positions
    for person in people:
        if person["direction"] == "up":
            person["rect"].y -= person["speed"]
            if person["rect"].top < 0:
                person["direction"] = "down"
        elif person["direction"] == "down":
            person["rect"].y += person["speed"]
            if person["rect"].bottom > screen_height:
                person["direction"] = "up"
        elif person["direction"] == "left":
            person["rect"].x -= person["speed"]
            if person["rect"].left < 0:
                person["direction"] = "right"
        elif person["direction"] == "right":
            person["rect"].x += person["speed"]
            if person["rect"].right > screen_width:
                person["direction"] = "left"

    # Draw the background and the people
    screen.blit(beach_image, beach_rect)
    for person in people:
        screen.blit(person["image"], person["rect"])

    # Draw the text
    text = font.render("Press Q to quit", True, BLACK)
    screen.blit(text, (10, 10))

    # Update the screen
    pygame.display.flip()

    # Set the frame rate
    clock.tick(60)

# Quit Pygame
pygame.quit()

This code creates a window with a beach background and 50 people represented as images. The people move randomly in four directions, and bounce off the edges of the screen. The program uses the Pygame clock to set the frame rate to 60 frames per second, and handles events such as quitting the game.

Leave a Comment