int maxBalls = 50; // Total number of balls to drop int numRows = 10; // Number of peg rows int numBins = numRows + 1; // Number of bins at the bottom ArrayList balls; Peg[] pegs; int[] bins; int ballCount = 0; // Track how many balls have been dropped void setup() { size(600, 700); balls = new ArrayList<>(); pegs = new Peg[numRows * (numRows + 1) / 2]; bins = new int[numBins]; int pegIndex = 0; for (int row = 0; row < numRows; row++) { for (int col = 0; col <= row; col++) { float x = width / 2 + (col - row / 2.0) * 50; float y = 100 + row * 50; pegs[pegIndex++] = new Peg(x, y); } } } void draw() { background(220); // Draw pegs for (Peg p : pegs) { p.display(); } // Update and display balls for (int i = balls.size() - 1; i >= 0; i--) { Ball b = balls.get(i); b.update(); b.display(); if (b.stopped) { balls.remove(i); bins[b.bin]++; } } // Continuously drop balls until reaching 2000 if (ballCount < maxBalls) { balls.add(new Ball(width / 2, 50)); ballCount++; } // Draw bins drawBins(); // Display message when simulation stops if (ballCount >= maxBalls && balls.isEmpty()) { fill(0); textSize(24); textAlign(CENTER); text("Simulation Complete", width / 2, height / 2); } } void drawBins() { int binWidth = width / numBins; for (int i = 0; i < numBins; i++) { fill(100, 100, 255); rect(i * binWidth, height - bins[i] * 5, binWidth - 2, bins[i] * 5); } } // Ball class with proper bouncing class Ball { float x, y, speedY = 0, gravity = 0.5; boolean stopped = false; int bin; float speedX = 0; Ball(float x, float y) { this.x = x; this.y = y; } void update() { if (stopped) return; speedY += gravity; y += speedY; // Check collision with pegs and bounce for (Peg p : pegs) { if (dist(x, y, p.x, p.y) < 10) { speedX = random(1) > 0.5 ? 2 : -2; // Random left or right bounce speedY *= 0.9; // Slight energy loss on collision y += 5; // Avoid getting stuck } } x += speedX; // Move horizontally based on bounce // Stop at the bottom and assign bin if (y > height - 20) { bin = int(map(x, 0, width, 0, numBins)); bin = constrain(bin, 0, numBins - 1); stopped = true; } } void display() { fill(255, 0, 0); noStroke(); ellipse(x, y, 10, 10); } } // Peg class class Peg { float x, y; Peg(float x, float y) { this.x = x; this.y = y; } void display() { fill(0); ellipse(x, y, 8, 8); } }