Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <header>
  <div>
    <h1>bouncing balls</h1>
  </div>
  <div>
    Ball Count: <br><span  class="balls-remaining">0</span>
  </div>
  <div>
    # of Balls:
    <select>
      <option value="10">10</option>
      <option value="20">20</option>
      <option value="30" selected>30</option>
      <option value="40">40</option>
      <option value="50">50</option>
    </select>
  </div>
  <div>
    <button id="start">Start</button>
  </div>

</header>

<canvas></canvas>
              
            
!

CSS

              
                html,
body {
  margin: 0;
}

html {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  height: 100%;
}

body {
  overflow: hidden;
  height: inherit;
  background-color: black;
}

header {
  height: 3em;
  background-color: brown;
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  color: #fff;
  text-align: center;
  gap: 5px;
  align-items: stretch;
  justify-items: stretch;
}

h1 {
  margin: 0;
  font-size: 2rem;
  color: white;
}

select, button {
  width: 100%;
}

#start {
  height: 100%;
}
              
            
!

JS

              
                // setup header
const header = document.querySelector("header");
const numBalls = document.querySelector("select");
const btnStart = document.querySelector("#start");
const ballsRemaining = document.querySelector('.balls-remaining');

btnStart.addEventListener("click", function () {
  start();
});

// setup canvas
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

const width = (canvas.width = window.innerWidth);
const height = (canvas.height = window.innerHeight - header.offsetHeight);

// setup play bits
let balls = [];
let evilCircle;
let ballCount = 0;
let requestId;

// function to generate random number
function random(min, max) {
  const num = Math.floor(Math.random() * (max - min + 1)) + min;
  return num;
}

// function to start game
function start() {
  cancelAnimationFrame(requestId);
  ballCount = 0;
  updateBallsRemaining();
  makeBalls(Number(numBalls.value), 20);
  makeEvilCircle();
  updateBallsRemaining();
  loop();
}

// function to loop game
function loop() {
  ctx.fillStyle = "rgba(0,0,0,0.25)";
  ctx.fillRect(0, 0, width, height);

  for (let i = 0; i < balls.length; i++) {
    if (balls[i].exists) {
      balls[i].draw();
      balls[i].update();
      balls[i].collisionDetect();
    }
  }

  evilCircle.draw();
  evilCircle.checkBounds();
  evilCircle.collisionDetect();

  requestId = requestAnimationFrame(loop);
}

// function to create balls
function makeBalls(numBalls, ballSize) {
  balls.length = 0; // Clear existing balls array

  while (balls.length < numBalls) {
    let size = random(ballSize / 2, ballSize);
    let color = `rgb(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)})`;
    let ball = new Ball(
      // ball position always drawn at least one ball width away from the edge of the canvas, to avoid drawing errors
      random(0 + size, width - size),
      random(0 + size, height - size),
      random(-7, 7),
      random(-7, 7),
      true,
      color,
      size
    );

    balls.push(ball);
    ballCount++;
    updateBallsRemaining();
  }
}

// function to create evil circle
function makeEvilCircle() {
  evilCircle = new EvilCircle(width / 2, 50);
  evilCircle.setControls();
}

// function update balls remaining
function updateBallsRemaining() {
  ballsRemaining.textContent = ballCount;
}

class Shape {
  constructor(x, y, velX, velY, exists) {
    this.x = x;
    this.y = y;
    this.velX = velX;
    this.velY = velY;
    this.exists = exists;
  }
}

class Ball extends Shape {
  constructor(x, y, velX, velY, exists, color, size) {
    super(x, y, velX, velY, exists);
    this.color = color;
    this.size = size;
  }

  draw() {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
  }

  update() {
    if (this.x + this.size >= width) {
      this.velX = -this.velX;
    }

    if (this.x - this.size <= 0) {
      this.velX = -this.velX;
    }

    if (this.y + this.size >= height) {
      this.velY = -this.velY;
    }

    if (this.y - this.size <= 0) {
      this.velY = -this.velY;
    }

    this.x += this.velX;
    this.y += this.velY;
  }

  collisionDetect() {
    for (let j = 0; j < balls.length; j++) {
      if (!(this === balls[j]) && balls[j].exists) {
        const dx = this.x - balls[j].x;
        const dy = this.y - balls[j].y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < this.size + balls[j].size) {
          balls[j].color = this.color =
            "rgb(" +
            random(0, 255) +
            "," +
            random(0, 255) +
            "," +
            random(0, 255) +
            ")";
        }
      }
    }
  }
}

class EvilCircle extends Shape {
  constructor(x, y) {
    super(x, y, 20, 20, true);
    this.color = "white";
    this.size = 10;
  }

  draw() {
    ctx.beginPath();
    ctx.lineWidth = 3;
    ctx.strokeStyle = this.color;
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.stroke();
  }

  checkBounds() {
    if (this.x + this.size >= width) {
      this.x -= this.size;
    }

    if (this.x - this.size <= 0) {
      this.x += this.size;
    }

    if (this.y + this.size >= height) {
      this.y -= this.size;
    }

    if (this.y - this.size <= 0) {
      this.y += this.size;
    }
  }

  setControls() {
    let _this = this;
    window.onkeydown = function (e) {
      if (e.key === "a") {
        _this.x -= _this.velX;
      } else if (e.key === "d") {
        _this.x += _this.velX;
      } else if (e.key === "w") {
        _this.y -= _this.velY;
      } else if (e.key === "s") {
        _this.y += _this.velY;
      }
    };
  }

  collisionDetect() {
    for (let j = 0; j < balls.length; j++) {
      if (balls[j].exists) {
        const dx = this.x - balls[j].x;
        const dy = this.y - balls[j].y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < this.size + balls[j].size) {
          balls[j].exists = false;
          ballCount--;
          updateBallsRemaining();
        }
      }
    }
  }
}

// Can't work out how to stop from speeding up when re-run
// Don't know answer to, can you tell us why we've had to set let _this = this; in the position it is in? It is something to do with function scope.

              
            
!
999px

Console