Coding is Fun!

Lab 9 – Lifeline

Back to Lab

<!DOCTYPE html>
<html lang="en">
<body>

<canvas id="gameCanvas" width="600" height="300" style="border-style: solid; border-width: 2px; border-color: black;"></canvas>

<p>
  <button id="startBtn" onclick="start()">Start</button>
</p>

<h1>
  My First Game
</h1>

<script>

// 1. Variables
var loopid;
var timer;
var timeout = 600;
var mouse_X, mouse_Y;
var fly_X, fly_Y;
var flyTimer;
var flyTimeout = 15;

// 2. Frame
function frame(){
  update();
  render();
}

// 3. Update 
function update(){
  //increase timer every frame
  timer = timer + 1;
  
  //random fly position
  if (flyTimer >= flyTimeout) 
  {
     //reset random fly position
     fly_X = getRandomInt(600);
     fly_Y = getRandomInt(300);
     //reset flyTimer
     flyTimer = 0;
   }else{
     //increase flyTimer every frame
     flyTimer = flyTimer + 1;
   }

}

// 4. Render
function render(){
  // clear the canvas
  drawFilledRect(0, 0, 600, 300, "white");
  // display Time Bar
  drawTimeBar(timer);
  // display Swatter
  drawSwatter(mouse_X, mouse_Y);
  // display fly
  drawFly(fly_X , fly_Y);
}

// 5. Start
function start(){
  // where to draw
  canvas = document.getElementById("gameCanvas");
  ctx = canvas.getContext('2d');

  //reset
  timer = 0;
  flyTimer = 0;

  // add mouse listeners
  canvas.addEventListener("mousemove", onMouseMove, false);

  // Run fame every 50 ms
  loopid = setInterval(frame,50);
}

// 6. Stop 

// 7. Mouse Move
function onMouseMove(e) {
  mouse_X = e.clientX; 
  mouse_Y = e.clientY; 
}

// 8. Mouse Click

// 9. Filled Rectangle
function drawFilledRect(x, y, width, height, color){
  ctx.fillStyle = color;
  ctx.fillRect(x, y, width, height);
}

// 10. Empty Rectangle
function drawEmptyRect(x, y, width, height, color){
  ctx.strokeStyle = color;
  ctx.strokeRect(x, y, width, height);
}

// 11. Filled Circle
function drawFilledCircle(x, y, radius, startAngle, endAngle, CounterClockwise, color){
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(x, y, radius, startAngle, endAngle, CounterClockwise);
  ctx.closePath();
  ctx.fill();
}

// 12. Draw Text
function drawText(text,x,y){
  ctx.fillStyle = "black";
  ctx.font = "30px fantasy";
  ctx.fillText(text, x, y);
}

// 13. Draw Fly
function drawFly(x, y){
  drawFilledCircle(x, y, 8, 0, 2 * Math.PI, false, "black")
  drawFilledCircle(x-10, y-10, 10, 0, 2 * Math.PI, false, "gray");
  drawFilledCircle(x+10, y-10, 10, 0, 2 * Math.PI, false, "gray");
}

// 14. Draw Swatter
function drawSwatter(x, y){
  drawEmptyRect(x, y, 20, 20, "black");
  drawEmptyRect(x-20, y, 20, 20, "black");
  drawEmptyRect(x, y-20, 20, 20, "black");
  drawEmptyRect(x-20, y-20, 20, 20, "black");
  drawFilledRect(x - 5, y + 23, 10, 15, "gray");
}

// 15. Draw Time Bar
function drawTimeBar(t){
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, t, 10);
}

// 16. Random Number
function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

</script>

</body>
</html>