xxxxxxxxxx
85
// Generated using ChatGPT with the following query:
// ---
// Draw a Christmas tree in code using P5.js, with animated randomly colored blinking lights and animated snowflakes falling.
// ---
let snowflakes = []; // An array to store the snowflakes
function setup() {
createCanvas(400, 400);
frameRate(30); // Set the frame rate to 30 fps
for (let i = 0; i < 100; i++) {
snowflakes.push(new Snowflake()); // Initialize each snowflake
}
}
function draw() {
background(255);
// Draw the trunk of the tree
fill(120, 80, 0);
rect(195, 280, 10, 120);
// Draw the branches of the tree
fill(0, 120, 0);
triangle(100, 280, 200, 100, 300, 280);
triangle(120, 200, 200, 120, 280, 200);
triangle(140, 160, 200, 140, 260, 160);
triangle(160, 120, 200, 160, 240, 120);
triangle(180, 100, 200, 180, 220, 100);
// Draw the lights on the tree
strokeWeight(5); // Set the stroke weight to 5 pixels
for (let i = 0; i < 10; i++) {
// Calculate the x and y coordinates of the light
let x = map(i, 0, 9, 100, 300);
let y = map(i, 0, 9, 100, 280);
// Generate a random color for the light
let r = random(255);
let g = random(255);
let b = random(255);
stroke(r, g, b); // Set the stroke color to the random color
// Draw a line to represent the light
if (frameCount % 20 > 10) { // Blink the light every 20 frames
line(x, y, x, y + 20);
}
}
// Update and draw the snowflakes
for (let i = 0; i < snowflakes.length; i++) {
snowflakes[i].update();
snowflakes[i].draw();
}
}
// A class to represent a snowflake
class Snowflake {
constructor() {
// Initialize the snowflake with random values
this.x = random(width);
this.y = random(-100, -10);
this.speed = random(1, 5);
this.size = random(4, 8);
}
update() {
// Update the snowflake's position
this.y += this.speed;
this.x += random(-1, 1);
// If the snowflake goes off the bottom of the screen, reset its position
if (this.y > height) {
this.y = random(-100, -10);
this.x = random(width);
}
}
draw() {
// Draw the snowflake as a small white circle
fill(255);
ellipse(this.x, this.y, this.size);
}
}