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.

            
              <body>
  <div class="container">
    <div id="app">
      <div id="space">
        <div class="score">
          <p>Score: <span id="score">0</span></p>
        </div>
        <div class="start">
          <p>CLICK TO START</p>
        </div>
        <img class="space" />
        <img class="ship" id="ship" src="https://pahosler.com/images/rocket.png" />
        <div class="explode"></div>
      </div>
    </div>
  </div>
</body>
            
          
!
            
              /* :root {
  top,left,margin,padding: 0;
}
 */
.container {
/*   position: relative;
  top: 100px;
  left: 10px; */
/*   display: flex;
  justify-content: center;
  align-self: center; */
}

body {
  background-color: #212121;
}

#space {
  position: relative;
  margin: auto;
/*   left: 10px; */
  top: 100px;
  height: 400px;
  width: 600px;
  overflow: hidden;
  border: 5px solid #fff;
}
.score {
  position: absolute;
  top: -20px;
  left: 15px;
  color: #fff;
  z-index: 5;
}
.score p {
  font-size: 1.5em;
}
.start {
  position: absolute;
  display: visible;
  color: rgb(255,0,0);
  -moz-animation: startFlash 2s ease infinite alternate;
  -webkit-animation: startFlash 2s ease infinite alternate;
  animation: startFlash 2s ease infinite alternate;
  z-index: 5;
  width: 50%;
  margin: 25% 25%;
}
.start .hidden {
  display: none;
}
.start p {
  text-align: center;
  font-size: 2em;
}

.gameover {
  
}
.space {
  position: relative;
  left: 0;
  top: 0;
  width: 600px;
  height: 400px;
  background: url(https://raw.githubusercontent.com/pahosler/rocket-rock-dodger/master/images/space1.jpg);
  /*background-size: cover;*/
/*   background: url(https://source.unsplash.com/random/100x200); */
  background-size: cover;
  -moz-animation: -moz-backgroundScroll 25s linear infinite;
  -webkit-animation: backgroundScroll 25s linear infinite;
  animation: backgroundScroll 25s linear infinite;
}

.ship {
  position: absolute;
/*   border: 1px solid white; */
  z-index: 5;
}

/* .rock {
  background: url(https://pahosler.com/images/rock.png);
  height: 60px;
  width: 60px;
  position: absolute;
  -webkit-animation: rockScroll 4s linear infinite;
  animation: rockScroll 4s linear infinite;
}
 */
.explode {
  display: none;
  position: absolute; 
  top: 30px;
  left: 150px;
  height: 130px;
  width: 160px;
  background: url(https://raw.githubusercontent.com/pahosler/rocket-rock-dodger/master/images/explode-color-300px.png);
  background-size: cover;
  transform-origin: center center;
  -webkit-animation: boom .5s ease-in-out alternate infinite ;
  -moz-animation: boom .5s ease-in-out alternate infinite ;
  z-index: 6;
  animation: boom .5s ease-in-out alternate infinite ;
  z-index: 6;
}

@-webkit-keyframes boom {
  from {
    transform: scale(0,0);
  }
  to {
    transform: scale(2,1.5)
  }
}

@-webkit-keyframes rockSpin {
  from {
    transform: rotate(360deg);
  }
  to {
    transform: rotate(0deg);
  }
}

@-moz-keyframes rockSpin {
  from {
    -moz-transform: rotate(360deg);
  }
  to {
    -moz-transform: rotate(0deg);
  }
}

@-webkit-keyframes backgroundScroll {
  from {
    background-position: 0 0;
  }
  to {
    background-position: -601px 0;
  }
}

@-moz-keyframes backgroundScroll {
  from {
    background-position: 0px 0px, 0px 0px;
  }
  to {
    background-position: -601px 0px, 0px 0px;
  }
}

@-webkit-keyframes startFlash {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@-moz-keyframes startFlash {
  from {
    -moz-opacity: 0;
  }
  to {
    -moz-opacity: 1;
  }
}

@keyframes backgroundScroll {
  from {
    background-position: 0 0;
  }
  to {
    background-position: -601px 0;
  }
}

@keyframes boom {
  from {
    transform: scale(0,0);
  }
  to {
    transform: scale(2,1.5)
  }
}
@keyframes rockSpin {
  from {
    transform: rotate(360deg);
  }
  to {
    transform: rotate(0deg);
  }
}

@keyframes startFlash {
  from {
    opacity: .2;
  }
  to {
    opacity: 1;
  }
}

@-moz-media only screen and (max-width: 1000px) {
  #space {
    top:0;
    left:0;
  }
}

@media only screen and (max-width: 1000px) {
  #space {
    top:0;
    left:0;
  }
}
            
          
!
            
              // const KEY_UP = 38;
// const KEY_DOWN = 40;
// const KEY_SPACE = 32;
const MakeTimer = function() {
  let t = {
    start: function(duration, func, callback) {
      this.func = func;
      this.duration = duration;
      this.callback = callback;
      this.timer = setInterval(function() {
        func();
        if (typeof callback === "function") {
          callback();
        }
      }, duration);
    },
    stop: function() {
      clearInterval(this.timer);
      return;
    }
  };
  return {
    start: t.start,
    stop: t.stop
  };
};

const Rock = function(id) {
  this.rockImg = "https://pahosler.com/images/rock.png";
  
  // rock height/width and animation
  this.rockStyle = {
    "background-image": `url(${this.rockImg})`,
    position: "absolute",
    height: "52px",
    width: "54px",
    "-moz-animation": "rockSpin 4s linear infinite",
    animation: "rockSpin 4s linear infinite",
    // color: "rgba(0,0,0,0)",
    "z-index": "5"
  };
  
  // ??? what was this for :O
  this.divStyle = {
    position: "absolute",
    height: "50px",
    width: "50px",
    // color: "rgba(0,0,0,0)"
  };
  // without it there are no rocks, why???
  
  this.id = id; // the rocks id
  this.timer = new MakeTimer(); // a rock timer Vroooommmm
  // we display a rock with this
  this.div = $(`<div id=${id}><div id=spin${id}></div></div>`);
  // start rock off right side of play field
  this.rockX = 650; 
  // these are the Y positions we choose at random
  this.rockY = [30, 80, 130, 180, 230, 280, 330,30, 80, 130, 180, 230, 280, 330,30, 80, 130, 180, 230, 280, 330][Math.floor(Math.random() *21)]
  // our rocks random speed, some numbers get picked more often 
  // we don't want too many really fast or really slow rocks
  // 3 is good, 2 is average
  this.rockDX = [1, 1,2,2,2,2,2, 2, 2, 2, 2, 2, 2, 4, 3,3,3,3, 3, 3, 3][Math.floor(Math.random() * 21)];
};

const app = {
  init: function() {
    this.state();
    this.cacheDom();
    this.bindEvents();
    $ship.css({ left: "150px", top: "70px" });
  },
  state: function() {
    // poor man's game physics
    mouseTimer = new MakeTimer(); // gravity.... sort of
    launch = new MakeTimer(); // rock lobster... errr... launcher
    // this is ships starting place
    shipY = 70;
    shipX = 150;
    // some events that happen
    mouseDown = false;
    start = false;
    gameover = false;
    collision = false;
    dead = false;
    score = 0;
    // look ma no rocks!
    rock = [
      {
        id: null
      }
    ];
    // no rock timers yet either
    rockTimer = [];
  },
  createRock: function(id) {
    // a new rock is born, ahhhhh
    // and it's id is array.length
    // we should change it to an object
    // instead of having an array that grows forever
    // even though it's hard to get past even 100 rocks
    this.ROCK = new Rock(id);
    // push the new rock onto the "stack"
    rock.push(this.ROCK);
    // add the rock to the dom and give it some style too
    $space.append(rock[id].div);
    $(`#${id}`).css(rock[id].divStyle);
    // don't forget to make it spin!
    $(`#spin${id}`).css(rock[id].rockStyle);
    
    // be really mean, every third rock aims at the ships current position!
    if (id % 2 === 0) {
      rock[id].rockY = shipY;
    }
    
    // the rocks css is added
    $(`#${id}`).css({ top: rock[id].rockY, left: rock[id].rockX });
    // rock! start your engine
    rock[id].timer.start(
      10,
      function() {
        return this.moveRock(id);
      }.bind(this)
    );
  },
  collision: function(id) {
    // did a rock hit your crapy ship?
    if (
      rock[id] !== null &&
      rock[id].rockX <= shipX + 80 &&
      rock[id].rockX >= shipX &&
      rock[id].rockY + 35 >= shipY &&
      rock[id].rockY <= shipY + 45
    ) {
      return true;
    }
  },
  moveRock: function(id) {
    rock[id].rockX -= rock[id].rockDX;
    if (rock[id].rockX > -60) {
      $(`#${id}`).css({ top: rock[id].rockY, left: rock[id].rockX });
    } else {
      rock[id].timer.stop();
      $(`#${id}`).remove();
      rock[id] = null;
      // console.log(rock)
      ++score; 
      $score.text(`${score}`);
    }
    if (this.collision(id)) {
      dead = true;
      this.stopRocks();
      this.exit();
    }
  },
  stopRocks: function() {
    launch.stop();
    for (let id = 1; id < rock.length; ++id) {
      if (rock[id] !== null) {
        rock[id].timer.stop();
        $(`#${id}`).remove();
      }
    }
  },
  cacheDom: function() {
    $el = $("#app");
    $space = $el.find("#space");
    $rock = $el.find("#rock");
    $ship = $el.find("#ship");
    $score = $el.find("#score");
    // $start = $el.find(".start");
  },
  bindEvents: function() {
    $space.on(
      "mousedown touchstart",
      function(e) {
        if (!start) {
          start = true;
          $(".start").toggle();
          $score.text(score);
          launch.start(
            700,
            function() {
              // create rocks at end of array
              this.createRock(rock.length);
            }.bind(this)
          );
          this.gameLoop();
        }
        if (shipY === 345) {
          shipY = 344;
        }
        mouseDown = true;
        mouseTimer.stop();
        if (!dead) {
          mouseTimer.start(10, this.shipUp.bind(this));
        }
      }.bind(this)
    );

    $space.on(
      "mouseup touchend",
      function() {
        mouseDown = false;
        mouseTimer.stop();
        if (!dead && start) {
          mouseTimer.start(10, this.shipDown.bind(this));
        }
      }.bind(this)
    );
  },
  shipUp: function() {
    shipY -= 3;
    if (shipY <= 0) {
      shipY = 0;
    }
    $ship.css({ position: "absolute", top: shipY });
    this.gameLoop();
  },
  shipDown: function() {
    shipY += 3;
    if (shipY >= 345) {
      shipY = 345;
    }
    $ship.css({ position: "absolute", top: shipY });
    this.gameLoop();
  },
  gameLoop: function() {
    if (!mouseDown && shipY === 0) {
      shipY = 1;
    }
    if (mouseDown && shipY === 345) {
      shipY = 344;
    }
  },
  exit: function() {
    launch.stop();
    mouseTimer.stop();
    start = false;
    rock = [];
    score = 0;
    $(".start").toggle();
    this.init();
  }
};
app.init();

            
          
!
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