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


Babel includes JSX processing.

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


Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.


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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.


                <!DOCTYPE html>
    <meta charset="UTF-8">
    <title>Effective JavaScript: Frogger</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/resources.js"></script>
    <script src="js/app.js"></script>
    <script src="js/engine.js"></script>



                body {
    text-align: center;



                /* Resources.js
 * This is simply an image loading utility. It eases the process of loading
 * image files so that they can be used within your game. It also includes
 * a simple "caching" layer so it will reuse cached images if you attempt
 * to load the same image multiple times.
(function() {
    var resourceCache = {};
    var loading = [];
    var readyCallbacks = [];

    /* This is the publicly accessible image loading function. It accepts
     * an array of strings pointing to image files or a string for a single
     * image. It will then call our private image loading function accordingly.
    function load(urlOrArr) {
        if(urlOrArr instanceof Array) {
            /* If the developer passed in an array of images
             * loop through each value and call our image
             * loader on that image file
            urlOrArr.forEach(function(url) {
        } else {
            /* The developer did not pass an array to this function,
             * assume the value is a string and call our image loader
             * directly.

    /* This is our private image loader function, it is
     * called by the public image loader function.
    function _load(url) {
        if(resourceCache[url]) {
            /* If this URL has been previously loaded it will exist within
             * our resourceCache array. Just return that image rather
             * re-loading the image.
            return resourceCache[url];
        } else {
            /* This URL has not been previously loaded and is not present
             * within our cache; we'll need to load this image.
            var img = new Image();
            img.onload = function() {
                /* Once our image has properly loaded, add it to our cache
                 * so that we can simply return this image if the developer
                 * attempts to load this file in the future.
                resourceCache[url] = img;

                /* Once the image is actually loaded and properly cached,
                 * call all of the onReady() callbacks we have defined.
                if(isReady()) {
                    readyCallbacks.forEach(function(func) { func(); });

            /* Set the initial cache value to false, this will change when
             * the image's onload event handler is called. Finally, point
             * the image's src attribute to the passed in URL.
            resourceCache[url] = false;
            img.src = url;

    /* This is used by developers to grab references to images they know
     * have been previously loaded. If an image is cached, this functions
     * the same as calling load() on that URL.
    function get(url) {
        return resourceCache[url];

    /* This function determines if all of the images that have been requested
     * for loading have in fact been properly loaded.
    function isReady() {
        var ready = true;
        for(var k in resourceCache) {
            if(resourceCache.hasOwnProperty(k) &&
               !resourceCache[k]) {
                ready = false;
        return ready;

    /* This function will add a function to the callback stack that is called
     * when all requested images are properly loaded.
    function onReady(func) {

    /* This object defines the publicly accessible functions available to
     * developers by creating a global Resources object.
    window.Resources = {
        load: load,
        get: get,
        onReady: onReady,
        isReady: isReady

//game engine javascript

var Engine = (function(global) {
    /* Predefine the variables we'll be using within this scope,
     * create the canvas element, grab the 2D context for that canvas
     * set the canvas elements height/width and add it to the DOM.
    var doc = global.document,
        win = global.window,
        canvas = doc.createElement('canvas'),
        ctx = canvas.getContext('2d'),

    canvas.width = 505;
    canvas.height = 606;

    /* This function serves as the kickoff point for the game loop itself
     * and handles properly calling the update and render methods.
    function main() {
        /* Get our time delta information which is required if your game
         * requires smooth animation. Because everyone's computer processes
         * instructions at different speeds we need a constant value that
         * would be the same for everyone (regardless of how fast their
         * computer is) - hurray time!
        var now =,
            dt = (now - lastTime) / 1000.0;

        /* Call our update/render functions, pass along the time delta to
         * our update function since it may be used for smooth animation.

        /* Set our lastTime variable which is used to determine the time delta
         * for the next time this function is called.
        lastTime = now;

        /* Use the browser's requestAnimationFrame function to call this
         * function again as soon as the browser is able to draw another frame.

    /* This function does some initial setup that should only occur once,
     * particularly setting the lastTime variable that is required for the
     * game loop.
    function init() {
        lastTime =;

    /* This function is called by main (our game loop) and itself calls all
     * of the functions which may need to update entity's data. Based on how
     * you implement your collision detection (when two entities occupy the
     * same space, for instance when your character should die), you may find
     * the need to add an additional function call here. For now, we've left
     * it commented out - you may or may not want to implement this
     * functionality this way (you could just implement collision detection
     * on the entities themselves within your app.js file).
    function update(dt) {
        // checkCollisions();

    /* This is called by the update function and loops through all of the
     * objects within your allEnemies array as defined in app.js and calls
     * their update() methods. It will then call the update function for your
     * player object. These update methods should focus purely on updating
     * the data/properties related to the object. Do your drawing in your
     * render methods.
    function updateEntities(dt) {
        allEnemies.forEach(function(enemy) {

    /* This function initially draws the "game level", it will then call
     * the renderEntities function. Remember, this function is called every
     * game tick (or loop of the game engine) because that's how games work -
     * they are flipbooks creating the illusion of animation but in reality
     * they are just drawing the entire screen over and over.
    function render() {
        /* This array holds the relative URL to the image used
         * for that particular row of the game level.
        var rowImages = [
                '',   // Top row is water
                '',   // Row 1 of 3 of stone
                '',   // Row 2 of 3 of stone
                '',   // Row 3 of 3 of stone
                '',   // Row 1 of 2 of grass
                ''    // Row 2 of 2 of grass
            numRows = 6,
            numCols = 5,
            row, col;

        // Before drawing, clear existing canvas

        /* Loop through the number of rows and columns we've defined above
         * and, using the rowImages array, draw the correct image for that
         * portion of the "grid"
        for (row = 0; row < numRows; row++) {
            for (col = 0; col < numCols; col++) {
                /* The drawImage function of the canvas' context element
                 * requires 3 parameters: the image to draw, the x coordinate
                 * to start drawing and the y coordinate to start drawing.
                 * We're using our Resources helpers to refer to our images
                 * so that we get the benefits of caching these images, since
                 * we're using them over and over.
                ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83);


    /* This function is called by the render function and is called on each game
     * tick. Its purpose is to then call the render functions you have defined
     * on your enemy and player entities within app.js
    function renderEntities() {
        /* Loop through all of the objects within the allEnemies array and call
         * the render function you have defined.
        allEnemies.forEach(function(enemy) {


    /* This function does nothing but it could have been a good place to
     * handle game reset states - maybe a new game menu or a game over screen
     * those sorts of things. It's only called once by the init() method.
    function reset() {
        // noop

    /* Go ahead and load all of the images we know we're going to need to
     * draw our game level. Then set init as the callback method, so that when
     * all of these images are properly loaded our game will start.

    /* Assign the canvas' context object to the global variable (the window
     * object when run in a browser) so that developers can use it more easily
     * from within their app.js files.
    global.ctx = ctx;

//above is game engine
//below is game logic

// Enemies our player must avoid
//initial setup of the Enemy constructor function and its object properties
var Enemy = function(x, y, speed) {
    this.sprite = '';
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.width = 97;
    this.height = 64;

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.
    this.x += this.speed * dt;

    //If the enemy runs off the screen, it resets it
    if (this.x > 600) {

    //Collision detection with the player.
    if ((Math.abs(this.x - player.x) < (this.width + player.width)/2) &&
    (Math.abs(this.y - player.y) < (this.height + player.height)/2)) {

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);

Enemy.prototype.reset = function() {

  //ensures that the enemy starts off the screen
  this.x = -98;
  //randomizes the position and speed of the enemy
  this.yArrayIndex = Math.floor(Math.random() * 3);
  //sets the array of possible vertical positions of the enemy
  this.enemyVerticalPositions = [62, 145, 228];
  //randomizes the vertical position of the enemy
  this.y = this.enemyVerticalPositions[this.yArrayIndex];
  //sets a random speed between 30 and 130 to ensure the enemy isn't too slow
  this.speed = Math.floor(Math.random() * 100 + 30)

var Player = function() {
    //sets the image of the player
    this.sprite = '';
    //sets the starting position of the player
    this.x = 201;
    this.y = 400;
    //defines the dimensions of the player
    this.width = 72;
    this.height = 75;

//necessary function for the game engine
Player.prototype.update = function(dt) {

//draw the player on the screen, required method for the game engine
Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);

Player.prototype.handleInput = function(key) {
  //defines the distances of each step
  this.verticalStep = 83;
  this.horizontalStep = 101;
  //utilizing a switch to define the function of each arrow key
  switch(key) {
    case 'left':
      if (this.x >= 0) {
        this.x -= this.horizontalStep;
    case 'right':
      if (this.x <= 402) {
        this.x += this.horizontalStep;
    case 'up':
      if (this.y == 68) {
      } else {
        this.y -= this.verticalStep;
    case 'down':
      if (this.y <= 399) {
        this.y += this.verticalStep;

//defines the reset position of the player
Player.prototype.reset = function() {
  this.x = 201;
  this.y = 400;

//defines the number of enemies present on the screen at any given time
var numberOfEnemies = 5;

//creates the enemy array
var allEnemies = [];

//initiating a new instance of an enemy and initializing the randomization of
//the speed and position of that enemy
for (var i = 0; i < numberOfEnemies; i++) {
  allEnemies[i] = new Enemy(0,0,0);

//initializes the player
var player = new Player();

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'