The goal would be to create a simple game that does the following:
- At the start of the game, there is a blue-colored cell in the middle of the canvas.
- On every left-click, the cell increases in size.
- If an arrow key is pressed, the cell changes color and moves to that direction.
- If the enter key is pressed, the game is reset.
Though it's just a really simple game, I find this a challenge. *I'm the Tech Noob after all. ;)
I've shared the codes below. Hopefully this helps beginners like myself. ;)
index.html
<!DOCTYPE html> <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> </head> <body> <canvas id="canvas" width="450" height="450"></canvas> <script src="cell.js" type="text/javascript"></script> </body> </html>
cell.js
$(document).ready(function(){ // canvas stuff var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var w = canvas.width; var h = canvas.height; var locX; // location in X var locY; // location in Y var pxX; // pixel size in X var pxY; // pixel size in Y var cellColor; var BGColor; var strokeColor; function init() { // set default color BGColor = "white"; cellColor = "blue"; strokeColor = "black"; // set default pixel size pxX = 10; pxY = 10; // set default location (center of canvas) locX = (w - pxX) / 2; locY = (h - pxY) / 2; paint(); } init(); function paint() { // paint background ctx.fillStyle = BGColor; ctx.fillRect(0, 0, w, h); ctx.strokeStyle = strokeColor; ctx.strokeRect(0, 0, w, h); // paint cell ctx.fillStyle = cellColor; ctx.fillRect(locX, locY, pxX, pxY); ctx.strokeStyle = strokeColor; ctx.strokeRect(locX, locY, pxX, pxY); } $(document).click(function() { // add one pixel for x and y on every click pxX++; pxY++; paint(); }) $(document).keydown(function(e) { var key = e.which; if(key == "37") // left { locX--; cellColor = "red"; } else if(key == "38") // up { locY--; cellColor = "blue"; } else if(key == "39") // right { locX++; cellColor = "yellow"; } else if(key == "40") // down { locY++; cellColor = "green"; } else if(key == "13") // enter init(); paint(); }) })
No comments:
Post a Comment