breakout - i

a bouncy ball contained by four walls

by djwelsh

HTML

<script src="//cdn.jsdelivr.net/tinycolor/0.9.16/tinycolor-min.js"></script>
<div id="cont">
  <div id="game"></div>
</div>
<div id="debug"><button id="startstop">Start / Stop</button></div>

CSS

html, body {
  margin: 0px;
  padding: 0px;
}
#cont {
  position: absolute;
  margin: 0px;
  width: 100%;
  height: 100%;
  background-color: white;
}
  #game {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 500px;
    height: 400px;
    background-color: palegoldenrod;
  }
    #game-bg {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 100%;
      height: 100%;
    }
    #game-fg {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 100%;
      height: 100%;
    }
    
  #debug {
    position: fixed;
    bottom: 0px;
    left: 0px;
    right: 0px;
    height: 40px;
    background-color: #990000;
  }

JavaScript

var oO = {
  el : {
    game : null
  },
  canvas : {
    bg : null,
    fg : null
  },
  ctx : {
    bg : null,
    fg : null
  },
  
  data : {
    bg : {
      width : 0,
      height : 0
    },
    fg : {
      width : 0,
      height : 0
    }
  },
  
  components : {
    bg : {},
    fg : {
      ball : {
        hue : 0,
        dx : 2.35,//random value
        dy : 2.73,//random value
        x : 40,
        y : 40,
        r : 10
      }
    }
  },
  
  animation : {
    //Called when the user starts the animation
    start : function () {
      oO.animation.interval = setInterval(oO.animation.onInterval, oO.animation.timeGap);
    },
    //Called when the user stops the animation
    stop : function () {
      clearTimeout(oO.animation.interval);
      oO.animation.interval = null;
    },
    //Container for the setInterval
    interval : null,
    //How long is the interval (ms)?
    timeGap : 20,
    //The function to call every (timeGap) seconds
    onInterval : function () {
      oO.redraw();
    }
  },
  
  redraw : function () {
    
    if (oO.components.fg.ball.hue < 360) {
      oO.components.fg.ball.hue++;
    }
    else {
      oO.components.fg.ball.hue = 0;
    }
    oO.components.fg.ball.hue = oO.components.fg.ball.hue % 360;
    
    //Background (just a purple rectangle for now)
    oO.ctx.bg.fillStyle = (tinycolor('hsv(300, 100%, 15%)').toRgbString());
    //For demo purposes, our rectangle is the size of our canvas minus 10px on each side
    oO.ctx.bg.fillRect(10, 10, 480, 380);
    
    //Foreground (just the ball for now)
    
    //Current position of the ball
    var oldX = oO.components.fg.ball.x;
    var oldY = oO.components.fg.ball.y;
    
    //Position the ball would be in if we added the current dx and dy
    var newX = oldX + oO.components.fg.ball.dx;
    var newY = oldY + oO.components.fg.ball.dy;
      
    //Check if the ball is gonna be out of bounds...
    if ((newY > 390) || (newY < 10)) {
      //... and if so,...