Lab 4 – 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 = 20; //to change later
var moveY = 0;
var loopid = null;
var frameInterval = 200;
// 2. On Load
window.onload=function() {
// Define Canvas
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
// Start Game
startGame();
}
// 3. Start Game
function startGame(){
loopid = setInterval(frame,frameInterval);
}
// 4. Frame
function frame() {
////////////
// Change //
////////////
snakeX = snakeX + moveX;
snakeY = snakeY + moveY;
////////////
// 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
// 10. Move Rat
// 11. Check Hit Border
// 12. Check Caught Rat
// 13. Lose
// 14. Key Press
// 15. Sound Function
// 16. Change Speed
// 17. Check Bit Self (Challenge)
</script>
</body>
</html>
Like this:
Like Loading...