Pen Settings

HTML

CSS

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

JavaScript

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

Packages

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.

Behavior

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.

HTML

              
                <h1>Zombies Love a Good Wall</h1>

<div id="game"></div>

<p>Made possible by artwork from:</p>

<ul>
  <li><a href="https://opengameart.org/users/segel">Segel</a></li>
  <li><a href="https://opengameart.org/users/spriteattack">SpriteAttack</a></li>
  <li><a href="https://opengameart.org/users/not-in-use-no-more">not in use no more</a></li>
</ul>
              
            
!

CSS

              
                body {
  margin: 0;
  font-family: sans-serif;
  background-color: #222;
  color: #04ff99;
}

#game {
  margin: 0 auto;
  margin-bottom: 3em;
  width: 800px;
  border: 2px solid #000;
  box-shadow: 0 2px 10px rgba(#000, 0.8);
  
  canvas {
    display: block;
  }
}

h1 {
  font-family: 'Impact', sans-serif;
  text-align: center;
  text-shadow: 0 2px 8px rgba(#000, 0.8);
}

p, ul {
  margin: 0 auto;
  margin-top: 1em;
  width: 800px;
}

a {
  color: skyblue;
}
              
            
!

JS

              
                // PIXI variables ============================
const loader = PIXI.Loader.shared;
const ticker = PIXI.Ticker.shared;

// Create the app ============================

const app = new PIXI.Application({ width: 800, height: 500 });
document.querySelector('#game').appendChild(app.view);
app.stage.interactive = true;
app.stage.on('pointermove', onPointerMove);

// Game variables ===========================

let level = 0;
const bulletSpeed = 25;
let gunAngleSpeed = 0;
let ammo = 6;
let hp = 10;
let isGameOver = false;
let gunIsLoading = false;
let gunLoadingProgress = 0;
const gunLoadingSpeed = 1.5;
const zombieLimit = 550;

const fireZoneGeo = {
  x: app.view.width * 0.8,
  y: 0,
  width: app.view.width * 0.2,
  height: app.view.height
}

// Set up all the objects ======================

const bg = PIXI.Sprite.from('https://assets.codepen.io/40070/bg-2.png?format=auto');
bg.interactive = true;
bg.width = app.view.width;
bg.height = app.view.height;
bg.on('pointerdown', onFireZonePointerDown);
app.stage.addChild(bg);

const bulletTexture = PIXI.Texture.from('https://assets.codepen.io/40070/bullet-1.png');
const bulletsContainer = new PIXI.Container();
bulletsContainer.x = 0;
bulletsContainer.y = 0;
bulletsContainer.width = app.view.width;
bulletsContainer.height = app.view.height;
app.stage.addChild(bulletsContainer);

const gun = PIXI.Sprite.from('https://assets.codepen.io/40070/revolver-1.png');
gun.scale.set(0.2);
gun.anchor.set(0.5);

const flash = new PIXI.Graphics();
flash.beginFill(0xFFF3D9);
flash.drawPolygon(
  59.7054443, 53.3786565,
  29.9492187, 0.172324725,
  40.404541, 44.6617565,
  10.2475586, 36.5434795,
  40.404541, 64.9344565,
  0.192993164, 98.5111363,
  40.404541, 83.9981565,
  40.404541, 121.098249,
  59.7054443, 74.4730565
);
flash.scale.set(2);
flash.x = -200 - flash.width;
flash.y = -90 - flash.height/2;
flash.alpha = 0;
gun.addChild(flash);

// Gun loader progress ============

const gunLoadingBar = new PIXI.Graphics();
app.stage.addChild(gunLoadingBar);

// Text ===========================

const style = new PIXI.TextStyle({
  fontFamily: 'Impact',
  fontSize: 36,
  fontWeight: 'bold',
  fill: ['#ffffff', '#00ff99'], // gradient
  stroke: '#4a1850',
  strokeThickness: 5,
  dropShadow: true,
  dropShadowColor: '#000000',
  dropShadowBlur: 4,
  dropShadowAngle: Math.PI / 6,
  dropShadowDistance: 6,
  wordWrap: true,
  wordWrapWidth: 440,
  lineJoin: 'round',
});

const rightAligned = style.clone();
rightAligned.align = 'right';

const redText = rightAligned.clone();
redText.fill = ['#cc0000', '#770000'];
redText.stroke = '#330000';

const startBtn = new PIXI.Text('START LEVEL 1', style);
startBtn.anchor.set(0.5);
startBtn.x = app.view.width/2;
startBtn.y = app.view.height/2;
startBtn.interactive = true;
startBtn.buttonMode = true;
startBtn.on('pointerup', onClickOfStart);
app.stage.addChild(startBtn);

const ammoDisplay = new PIXI.Text(ammo.toString(), rightAligned);
ammoDisplay.x = app.view.width - ammoDisplay.width - 10;
ammoDisplay.y = 10;
app.stage.addChild(ammoDisplay);

const hpDisplay = new PIXI.Text(hp.toString(), redText);
hpDisplay.x = app.view.width - hpDisplay.width - 10;
hpDisplay.y = app.view.height - hpDisplay.height - 10;
app.stage.addChild(hpDisplay);

// zombies =====================================

let zombieSheet = null;
loader.add('zombies', 'https://assets.codepen.io/40070/zombie03Half.json').load(() => {
  zombieSheet = loader.resources['zombies'];
});
const zombies = new PIXI.Container();
zombies.sortableChildren = true;
app.stage.addChild(zombies);

// game loop ======================================

ticker.add(gameLoop);

function gameLoop(dt) {  
  // animate bullets
  bulletsContainer.children.forEach(bullet => {
    bullet.x -= dt * bulletSpeed;
    
    if (bullet.x < -20) {
      bullet.destroy();
    } else {
      // detect zombie hit
      zombies.children.forEach(zombie => {
        if (isZombieHit(zombie, bullet)) {
          bullet.destroy();
          zombie.lives -= 1;
          
          if (zombie.lives === 0) {
            killZombie(zombie);
            
            if (isLevelComplete()) {
              nextLevel();
            }
            
            return;
          }
          
          zombie.tint = 0xff0000;
        }
      });
    }
  });
  
  zombies.children.forEach(zombie => {
    // animate zombie walking
    zombie.x = clamp(zombie.x + zombie.walkingSpeed * dt, -200, zombieLimit);
    
    // animate zombie hits
    const rgb = hexToRgb(zombie.tint);
    rgb[1] = Math.floor(clamp(rgb[1] + 10 * dt, 0, 255));
    rgb[2] = Math.floor(clamp(rgb[2] + 10 * dt, 0, 255));
    zombie.tint = rgbToHex(rgb);
    
    // animate zombie rage
    if (zombie.lives === 1) {
      zombie.x = clamp(zombie.x + zombie.walkingSpeed * dt, -200, zombieLimit);
      zombie.animationSpeed = 0.2;
      zombie.tint = 0xff0000;
    }
    
    // zombie reached firing zone
    if (zombie.x >= zombieLimit) {
      zombieAttack(zombie);
    }
  });
  
  // animate gun "recoil"
  if (!gunIsLoading) {
    gun.angle = gunAngleSpeed * dt;
    gunAngleSpeed = clamp(gunAngleSpeed - 0.5, 0, 10);
  }
  
  // animate gun flash
  flash.alpha = clamp(0, 1, flash.alpha - 0.1);

  // check for game over
  if (hp === 0) {
    gameOver();
  }
}

// Levels ============================

function startGame() {
  app.stage.addChild(gun);
  
  // run the first level
  runLevel();
}

function runLevel() {
  const numOfZombies = (level + 1) * 3;
  let delay = 0;
  
  for (let i = 0; i < numOfZombies; i++) {
    delay += clamp((Math.random() * 3000) - level * 200, 500, 3000)
    setTimeout(() => {
      const zombie = addZombie();
      zombie.walkingSpeed += zombie.walkingSpeed * level * 0.05;
    }, delay);
  }
}

// Game Functions ====================

function nextLevel() {
  level++;
  startBtn.visible = true;
  startBtn.text = `START LEVEL ${level+1}`;
}

function addZombie() {
  const zombie = PIXI.AnimatedSprite.fromImages(zombieSheet.data.animations['__Zombie01_Walk']);
  zombie.scale.set(0.25);
  zombie.x = 0 - zombie.width/2;
  zombie.y = clamp(
    Math.floor(Math.random() * app.view.height),
    zombie.height,
    app.view.height
  );
  zombie.animationSpeed = 0.1;
  zombie.play();
  zombie.isDead = false;
  zombie.lives = 3;
  zombie.walkingSpeed = clamp(Math.random(), 0.25, 0.65);
  zombies.addChild(zombie);
  
  // set zombie z-indexes
  zombies.children.forEach(z => {
    z.zIndex = z.y;
  });
  
  return zombie;
}

function zombieAttack(zombie) {
  if (zombie.isAttacking) {
    return;
  }
  
  zombie.isAttacking = true;
  zombie.walkingSpeed = 0;
  zombie.textures = zombieSheet.data.animations['__Zombie01_Attack'].map(
    url => zombieSheet.textures[url]
  );
  zombie.gotoAndPlay(0);
  zombie.onLoop = () => {
    hp = clamp(hp - 1, 0, 10);
    hpDisplay.text = hp.toString();
    hpDisplay.x = app.view.width - hpDisplay.width - 10;
  };
}

function isZombieHit(zombie, bullet) {
  if (bullet._destroyed || zombie.isDead) {
    return false;
  }

  const bx = bullet.x;
  const by = bullet.y;
  const offset = 20;
  // based on bottom center anchor point
  const left = zombie.x - zombie.width/2 + offset;
  const right = zombie.x + zombie.width/2 - offset;
  const top = zombie.y - zombie.height + offset;
  const bottom = zombie.y - offset;

  return bx > left && bx < right && by > top && by < bottom;
}

function killZombie(zombie) {
  zombie.isDead = true;
  zombie.walkingSpeed = 0;
  zombie.loop = false;
  zombie.textures = zombieSheet.data.animations['__Zombie01_Dead'].map(
    url => zombieSheet.textures[url]
  );
  zombie.animationSpeed *= 2;
  zombie.gotoAndPlay(0);
  zombie.onComplete = () => {
    let elapsed = 0;
    const fadeZombie = dt => {
      // one second-ish delay
      elapsed += dt;
      if (elapsed < 100) {
        return;
      }
      zombie.alpha = clamp(zombie.alpha - 0.01, 0, 1);
      if (zombie.alpha === 0) {
        zombie.destroy();
        ticker.remove(fadeZombie);
      }
    };
    ticker.add(fadeZombie);
  }
}

function loadGun() {
  if (gunIsLoading) {
    return;
  }
  
  gunIsLoading = true;
  gun.angle = -45;
  
  const loading = dt => {
    gunLoadingProgress += gunLoadingSpeed * dt;
    const width = clamp(gunLoadingProgress * 8, 0, 800);
    
    gunLoadingBar.clear();
    gunLoadingBar.beginFill(0x04ff99);
    gunLoadingBar.drawRect(0, 0, width, 10);
    
    if (gunLoadingProgress > 100) {
      ticker.remove(loading);
      gunLoadingProgress = 0;
      gun.angle = 0;
      ammo = 6;
      ammoDisplay.text = ammo.toString();
      gunLoadingBar.clear();
      gunIsLoading = false;
    }
  }
  
  ticker.add(loading);
}

function isLevelComplete() {
  return zombies.children.filter(z => !z.isDead).length === 0;
}

function gameOver() {
  if (isGameOver) {
    return;
  }
  
  isGameOver = true;
  
  const gameOverScreen = new PIXI.Container();
  gameOverScreen.x = 0;
  gameOverScreen.y = 0;
  gameOverScreen.width = app.view.width;
  gameOverScreen.height = app.view.height;
  gameOverScreen.alpha = 0;
  app.stage.addChild(gameOverScreen);
  
  const overlay = new PIXI.Graphics();
  overlay.beginFill(0xcc0000, 0.5);
  overlay.drawRect(0, 0, app.view.width, app.view.height);
  gameOverScreen.addChild(overlay);
  
  const gameOverText = new PIXI.Text('GAME OVER', style);
  gameOverText.x = app.view.width/2 - gameOverText.width/2;
  gameOverText.y = app.view.height/2 - gameOverText.height/2;
  gameOverScreen.addChild(gameOverText);
  
  // fade in
  const gameOverScreenFade = dt => {
    gameOverScreen.alpha = clamp(gameOverScreen.alpha + 0.01 * dt, 0, 1);
    if (gameOverScreen.alpha === 1) {
      ticker.remove(gameOverScreenFade);
    }
  };
  
  ticker.add(gameOverScreenFade);
}

// event handlers =========================

function onClickOfStart() {
  startBtn.visible = false;
  
  if (level === 0) {
    startGame();
    return;
  }
  
  // if (!levels[level]) {
  //   startBtn.text = "ACTUALLY THAT'S IT…";
  //   startBtn.interactive = false;
  //   startBtn.buttonMode = false;
  //   startBtn.visible = true;
  //   return;
  // }
  
  runLevel();
}

function onFireZonePointerDown(event) {
  if (isGameOver || event.data.global.x < 600) {
    return;
  }
  
  if (!ammo) {
    loadGun();
    return;
  }
  
  ammo--;
  ammoDisplay.text = ammo >= 0 ? `${ammo}` : '?';
  
  const xOffset = gun.width/2;
  const yOffset = gun.height/2;
  const x = event.data.global.x - xOffset;
  const y = event.data.global.y - yOffset + 5;
  const bulletSprite = new PIXI.Sprite(bulletTexture);
  bulletSprite.x = x;
  bulletSprite.y = y;
  bulletSprite.scale.set(0.25);
  bulletsContainer.addChild(bulletSprite);
  gunAngleSpeed = 8;
  flash.alpha = 1;
}

function onPointerMove(event) {
  const x = event.data.global.x;
  const y = event.data.global.y;
  gun.x = clamp(x, fireZoneGeo.x, fireZoneGeo.x + fireZoneGeo.width);
  gun.y = clamp(y, fireZoneGeo.y, fireZoneGeo.y + fireZoneGeo.height);
}

// Utils ===========================

function clamp(val, min, max) {
  return Math.min(Math.max(val, min), max);
};

function hexToRgb(hex) {
  const hexString = hex.toString(16);
  const r = parseInt(hexString.substring(0, 2), 16);
  const g = parseInt(hexString.substring(2, 4), 16);
  const b = parseInt(hexString.substring(4, 6), 16);
  return [r, g, b];
}

function rgbToHex(rgb) {
  const hexString = rgb.reduce((acc, val) => {
    let str = val.toString(16);
    str = str.length === 1 ? '0' + str : str;
    return acc + str;
  }, '0x');
  return parseInt(hexString, 16);
}

              
            
!
999px

Console