css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              	<canvas id="canvas" width="480" height="320"></canvas>
	<div class="image">
		<img id="cookie" src="https://drive.google.com/uc?export=view&id=1O4X8znsfSZsYkgkJImYsgtRrvilXTZPn" height="50px" width="50px"/>
	</div>
	<div class="image">
		<img id="pizza" src="https://drive.google.com/uc?export=view?&id=1j0HHQ1JQm-j15Y8Bx7qT5wntLPm-MW44" height="50px" width="50px" />
	</div>








            
          
!
            
              canvas { 
			background: #fff; 
			display: block; 
			margin: 0 auto; 
			border: 4px solid #0095DD;
			margin-top: 100px;
		}

.image {
			display: none;
		}
            
          
!
            
              	
// Get elements from document	
	let canvas = document.getElementById("canvas");
	let cookie = document.getElementById("cookie");
	let pizza = document.getElementById("pizza");
	let ctx = canvas.getContext("2d");

// Initialise variables
	let wide = canvas.width;
	let high = canvas.height;

// Initialise icon size and speeds
	let iconDx = 2;
	let iconDy = 2;
	let iconX = wide/2;
	let iconY = high/2;
	let iconWidth = 50;
	let iconHeight = 50;
	let attackerX = 40;
	let attackerY = 40;
	let attackerDx = 9;
	let attackerDy = 9;

// Initialise key presses
	let rightPressed = false;
	let leftPressed = false;
	let upPressed = false;
	let downPressed = false;

// Manage lives
	let lives = 3;
	let hit = false;
	let lastHit = false;

// Draw starting screen with instructions
	window.onload = function() {
		ctx.drawImage(cookie, wide/2-50, 40, 100, 100);
	    ctx.font = "20px Arial";
	    ctx.fillStyle = "#056c9f";
	    ctx.textAlign= "center";
	    ctx.fillText("Move cookie monster to avoid the pizza", wide/2, high/2);
	    ctx.fillText("Press spacebar to start the game", wide/2, high/2+30);
	}

// Draw icons
	function drawIcon() {
		ctx.drawImage(cookie, iconX, iconY, 50, 50);
	}

	function drawAttacker() {
		ctx.drawImage(pizza, attackerX, attackerY, 50, 50);
	}

// Make icon flash red when it's hit
	function drawHit() {
		ctx.beginPath();
		ctx.arc(iconX+25, iconY+25, 30, 0, Math.PI*2); //left top width height
		ctx.fillStyle = 'red';
		ctx.fill();
		ctx.closePath();
	}

// Use arrow keys to move icon around the canvas	
	function keyDownHandler(e) {
		if(e.keyCode == 39) {
	        rightPressed = true;
	    }
	    else if(e.keyCode == 37) {
	        leftPressed = true;
	    }
    	else if(e.keyCode == 38) {
            upPressed = true;
        }
        else if(e.keyCode == 40) {
            downPressed = true;
        }
	}

	function keyUpHandler(e) {
		if(e.keyCode == 39) {
	        rightPressed = false;
	    }
	    else if(e.keyCode == 37) {
	        leftPressed = false;
	    }
	    else if(e.keyCode == 38) {
	        upPressed = false;
	    }
	    else if(e.keyCode == 40) {
	        downPressed = false;
	    }
	}	
	
	document.addEventListener("keydown", keyDownHandler);
	document.addEventListener("keyup", keyUpHandler);	

// Draw the number of lives left in the top corner of the screen
	function drawLives() {
	    ctx.font = "16px Arial";
	    ctx.fillStyle = "#0095DD";
	    ctx.fillText("Lives: "+lives, wide-65, 20);
	}

// Detect whether the icons are in the same space, and therefore a hit should be registered
	function collide() {
		if ((attackerX+25 > iconX && attackerX+25 < iconX+50) && (attackerY+25 > iconY && attackerY+25 < iconY+50)) {
			hit = true;
		} else {
			hit = false;
		}
	}
	
// Controlling animation function
	function draw() {
	  	ctx.clearRect(0, 0, wide, high);
	  	drawAttacker();
	  	collide();

// Let the icon move so long as it's within the canvas boundaries. 		
		if (rightPressed == true && iconX <= wide-50) {
			iconX += iconDx;
		} else if (leftPressed == true && iconX >= 0) {
			iconX -= iconDx;
		} else if (upPressed == true && iconY >= 0) {
			iconY -= iconDy;
		} else if (downPressed == true && iconY <= high-50) {
			iconY += iconDy;
		}

// If the attacker is outside the canvas boundaries, reverse direction
		if (attackerX <= 0 || attackerX >= wide-40) {
			attackerDx = -attackerDx;
		}

		if (attackerY <= 0 || attackerY >= high-40) {
			attackerDy = -attackerDy;
		}

// Keep the attacker constantly moving
		attackerX += attackerDx;
		attackerY += attackerDy;

// If the icons are in the same space, give the icon a red flash
		if (hit == true) {
			drawHit();

// Only decrement lives once for each hit, rather than for each pixel movement within the same hit
			if (lastHit != hit) {
				lives -= 1;
			}
		}			
		lastHit = hit;
	  	drawIcon();
	  	drawLives();

// Continue game until lives are at zero
	    if (lives == 0) {
		    ctx.font = "20px Arial";
		    ctx.fillStyle = "#000";
		    ctx.textAlign = "center";
		    ctx.fillText("GAME OVER!", wide/2, high/2);
		} else {
			requestAnimationFrame(draw);
		}
	}

// Spacebar handler to start game
	function startGame(e) {
		if (e.keyCode == 32) {
			draw();
		}
	}

	document.addEventListener("keydown", startGame);
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console