Have Fun with Coding! – Lab 6 Help

Lab 6 – Lifeline

Back to Lab

<!DOCTYPE html>
<html>
<body style="text-align: center; font-family:Arial">

<h1>
  My Snake Game
</h1>

<canvas id="gameCanvas" width="400" height="400"></canvas>

<h2 id="scoreBoard">
  Score = 0
</h2>

  Start Game by moving snake using Arrow Keys.
  <br>
  ! ! ! Be careful not to hit the wall ! ! !

<script>
// 1. Variables
var snakeX = 200; 
var snakeY = 200;
var ratX = 300;
var ratY = 300;
var msg = "Press any arrow key to start!";
var msgPrevScore = "Your Score was X";
var moveX = 0; 
var moveY = 0;
var loopid = null;
var frameInterval = 200;
var score = 0;

// 2. On Load
window.onload=function() {
  // Define Canvas
  canvas = document.getElementById("gameCanvas");
  ctx = canvas.getContext("2d");
  
  // Add Keypress Listener
  document.addEventListener("keydown", keyPress);

  // Start Game
  startGame();
}

// 3. Start Game
function startGame(){
  loopid = setInterval(frame,frameInterval);
}

// 4. Frame
function frame() {
  ////////////
  // Change //
  ////////////

  snakeX = snakeX + moveX;
  snakeY = snakeY + moveY;

  // Snake caught rat?
  checkCaughtRat();

  ////////////
  // Render //
  ////////////

  // Clear
  drawRect(0, 0, canvas.width, canvas.height, "black")
  
  // Draw
  drawRect(snakeX, snakeY, 18, 18, "lime")
  drawRect(ratX, ratY, 18, 18, "red")
}

// 5. Draw Text
function drawText(text, x, y){
  ctx.fillStyle = "white";
  ctx.font = "20px Arial";
  ctx.fillText(text, x, y);
}

// 6. Draw Rect
function drawRect(x, y, width, height, colour){
  ctx.fillStyle = colour;
  ctx.fillRect(x, y, width, height);
}

// 7. Draw Snake

// 8. Draw Rat

// 9. Get Random
function getRandom(num){
  // Returns a random integer from 0 to num*20
  return (Math.floor(Math.random() * num) * 20);
}

// 10. Move Rat
function moveRat(){
  ratX=getRandom(20);
  ratY=getRandom(20);
}

// 11. Check Hit Border

// 12. Check Caught Rat
function checkCaughtRat(){

  if(ratX==snakeX && ratY==snakeY) {

    // Add to Score & Display score
    score++;
    document.getElementById("scoreBoard").innerHTML = "Score : " + score;
    
    // Move rat
    moveRat();
  }
}

// 13. Lose

// 14. Key Press
function keyPress(evt) {
  switch(evt.keyCode) {
    case 37:
      // Left
      moveX = -20;
      moveY = 0;
      break;
    case 39:
      // Right
      moveX = 20;
      moveY = 0;
      break;
    case 38:
      // Up
      moveX = 0;
      moveY = -20;
      break;
    case 40:
      // Down
      moveX = 0;
      moveY = 20;
      break;
  }
}

// 15. Sound Function

// 16. Change Speed 

// 17. Check Bit Self (Challenge)

</script>

</body>
</html>