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.

            
              .level-editor
  .tool-panel
    .controls
      %h2 Map file
      %button.save-map Save
      %form
        %input.load-map{ type: 'file'} Load
    .map-size
      %h2 Map size
      %form
        %label{ for: 'width' } Width
        %input{ name: 'width', type: 'number' }
        %label{ for: 'height' } Height
        %input{ name: 'height', type: 'number' }
    .tile-set
      %h2 Tiles
      .tiles
  .canvas
    %h2 Map Editor
    .canvas-wrapper
      .map-container
        .map
            
          
!
            
              $tileWidth: 64px;
$tileHeight: 64px;
$isoTileWidth: 90px;

.level-editor {
  height: 100%;
  
  h2 {
    margin-bottom: 12px;
    
    font-size: 18px;
    font-weight: 200;
    
    color: #DDD;
  }
}

// Editor layout
.level-editor {
  display: flex;
  
  .tool-panel {
  }
  .canvas {
    flex: 1;
  }
}

.tool-panel {
  position: relative;
  padding: 12px;
  width: $isoTileWidth + (2* 12);
  height: 100%;
  
  overflow-x: hidden;
  overflow-y: auto;
  
  pointer-events: auto;
  
  background: #333;
}

.map-size {
  margin-bottom: 24px;
  
  input,
  label,
  form {
    display: block;
    margin: 0 auto;
    max-width: 100%;
  }
  
  label {
    margin-bottom: 6px;
    color: #555;
  }
  
  input {
    padding: 6px;
    border: 1px solid #444;
    color: #555;
    background: #333;
    
    .no-touch &:hover {
      color: #999;
      border-color: #666;
    }
    
    &:focus,
    &:focus:hover {
      color: #EEE;
      border-color: #EEE;
    }
  }
  
  input + label {
    margin-top: 12px;
  }
}

.tile-set {
  margin-bottom: 12px;
  
  .tile-brush {
    margin: 0 auto;
    width: $isoTileWidth;
    height: $tileHeight;
    cursor: pointer;
    
    &:after {
      content: ' ';
      display: block;
      margin: 0 auto;
      width: $tileWidth;
      height: $tileHeight;
      
      transition: all 0.25s ease-in-out;
      transform: rotateX(60deg) rotateZ(45deg);
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.4);
      background: #F0F;
    }
    
    &.selected:after {
      border: 4px solid rgba(255, 255, 255, 0.8);
    }
      
    &.dirt:after {
      background: #9C8164;
    }

    &.field:after {
      background: #BDB76B;
    }

    &.grass:after {
      background: #228B22;
    }

    &.sea:after {
      background: #008B8B;
    }

    &.wall:after {
      background: #444;
    }
    
    &:active,
    .no-touch &:hover {
      &:after {
        transform: translateY(-6px) rotateX(60deg) rotateZ(45deg);
        box-shadow: 12px 12px 12px rgba(0, 0, 0, 0.4);
      }
    }
  }
}

.controls {
  margin-bottom: 24px;
  .save {
    display: block;
    width: 100%;
  }
}

.canvas {
  position: relative;
  overflow: auto;
  height: 100%;
  
  &:after {
    content: ' ';
    display: block;
    clear: both;
  }
}

// --- Map styles
.map-container {
  position: absolute;
  top: 50%;
  left: 50%;
  
  float: left;
  
  perspective: 1000px;
  transform: translate(-50%, -50%) rotateX(60deg) rotateZ(45deg);
  transform-style: preserve-3d;
  
  box-shadow: 12px 12px 12px rgba(0, 0, 0, 0.24);
  
  background: #242424;
}

.map {
  float: left;
}

.tile {
  float: left;
  pointer-events: auto;
  
  width: $tileWidth;
  height: $tileHeight;
  
  border: 1px solid #333;
  
  cursor: pointer;
    
  &.dirt {
    background: #9C8164;
  }
  
  &.field {
    background: #BDB76B;
  }
  
  &.grass {
    background: #228B22;
  }
  
  &.sea {
    background: #008B8B;
  }
  
  &.wall {
    background: #444;
  }
  
  &:after {
    content: ' ';
    display: block;
    width: 100%;
    height: 100%;
    
    transition: box-shadow 0.250s ease-in,
      background 0.250s ease-in;
    
    box-shadow: 6px 6px 6px rgba(0, 0, 0, 0);
    background: rgba(255, 255, 255, 0);
  }
  
  &:active,
  .no-touch &:hover {
    transition: background 0.250s ease-in;
    background: rgba(255, 255, 255, 0.2);
    
    &:after {
      transform: translate(-6px, -6px);
      box-shadow: 6px 6px 6px rgba(0, 0, 0, 0.24);
      // TODO This should be the selected brush
      background: rgba(255, 255, 255, 0.8);
    }
  }
}
 

// --- Global styles
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  outline: none;
  box-shadow: none;
}

html,
body {
  height: 100%;
}

body {
  // FIXME This is a workaround for webkit/blink not correctly handling
  // pointer events on 3d transformed containers
  // Don't forget to reset on each element that needs to be clickable!
  pointer-events: none;
  background: #222;
}
            
          
!
            
              'use strict';

// --- Map ---------------------------------------------------------------------------
// TODO Expose options
// options
// - map as two-dimensional array
// - map container name
// - tile sizes
function Map(options) {
  var self = this;
  
  this.container;
  this.options = options || {};
  
  this.tileWidth = this.options.tileWidth || 64;
  this.tileHeight = this.options.tileHeight || 64;
  
  this.mapData = this.options.mapData || [];
  // Collision map 0 is unpassable, 1 normal, everything above is preferred
  this.collisionMap = [];
  
  // Expects a two-dimensional array
  this.renderMap = function(map) {
    this.mapData = map;
    
    this.container.css({
        'width': this.mapData[0].length * this.tileWidth,
        'height': this.mapData.length * this.tileHeight
      });
    
    // Clear current map
    this.container.empty();
    
    // Render map
    for(var i = 0, yLen = map.length; i < yLen; i++) {
      this.collisionMap.push([]);
      for(var j = 0, xLen = map[i].length; j < xLen; j++) {
        var tileClass = '';

        switch(map[i][j]) {
          case 'd':
            tileClass = 'dirt';
            this.collisionMap[i].push(2);
            break;
          case 'f':
            tileClass = 'field';
            this.collisionMap[i].push(1);
            break;
          case 'g':
            tileClass = 'grass';
            this.collisionMap[i].push(1);
            break;
          case 's':
            tileClass = 'sea';
            this.collisionMap[i].push(0);
            break;
          case 'w':
            tileClass = 'wall';
            this.collisionMap[i].push(0);
            break;
        }
        this.container.append($('<div></div>', { class: 'tile ' + tileClass}));
      }
    }
  };
  
  this.init = function() {
    var mapContainerName = this.options.container || '.map';
    this.container = $(mapContainerName);
    // FIXME Check if container exists
    this.renderMap(this.mapData);
  };
  
  // --- Constructor
  this.init();

  return this;
}

// --- Map Tile ------------------------------------------------
function MapTile(options) {
  // TODO Maybe store info in tile itself instead of CSS file?
  // Name of CSS class
  this.className = options.className || '';
  // Should be one character
  this.id = options.id || '';
  // 0 is unpassable, higher values allow faster movement
  this.terrainModifier = options.terrainModifier || 2;
  
  return this;
}

// --- Map Editor ----------------------------------------------
// TODO Create JSON tile brush import
// TODO Create JSON map export
// TODO Create JSON map import
function MapEditor() {
  var self = this;
  
  this.map;
  this.mapWidth = 4;
  this.mapHeight = 4;
  
  this.selectedBrush = '';
  this.tiles = {};
  
  this._init = function() {
    
    this._initMap();
    this._initTileBrushes();
    this._initMapSize();
    this._initSave();
    this._initLoad();
    
  };
  
  // --- Initializes tile brushes and sets up event listeners
  this._initTileBrushes = function() {
    
    this._createTiles();
    
    this._addTilesToTileSet();
  };
  
  // --- Creates and adds tiles
  this._createTiles = function() {
    var tile;
    
    // TODO Load tile brushes from file instead of creating them here
    tile = new MapTile({
      id: 'd',
      className: 'dirt',
      terrainModifier: 1
    });
    this.tiles[tile.id] = tile;
    
    tile = new MapTile({
      id: 'f',
      className: 'field'
    });
    this.tiles[tile.id] = tile;
    
    tile = new MapTile({
      id: 'g',
      className: 'grass'
    });
    this.tiles[tile.id] = tile;
    
    tile = new MapTile({
      id: 'w',
      className: 'wall',
      terrainModifier: 0
    });
    this.tiles[tile.id] = tile;
    
    tile = new MapTile({
      id: 's',
      className: 'sea',
      terrainModifier: 0
    });
    this.tiles[tile.id] = tile;
  };
  
  // --- Adds the tiles to the control panel
  this._addTilesToTileSet = function() {
    var firstBrush = true;
    // Add brushes to control-panel
    for(var tileKey in this.tiles) {
      var tile = this.tiles[tileKey];
      var tileId = tileKey;
      
      $('.tile-set .tiles')
        .append(
          $('<div></div>', {
            class: 'tile-brush ' + tile.className
          })
            // Add listeners to tile brushes
            .click({ tileId: tileId }, function(e){
              self.selectedBrush = e.data.tileId;
              $('.tile-brush').removeClass('selected');
              $(this).addClass('selected');
            }))
      // Select first brush
        .find('.tile-brush').eq(0).addClass('selected');
      if(firstBrush) {
        this.selectedBrush = tileId;
        firstBrush = false;
      }
    }
  };
  
  // --- Initializes empty map and sets up event listeners for painting
  this._initMap = function() {
    // Create empty map of default size and init Map object with that
    var map = [];
    for(var i = 0; i < this.mapHeight; i++) {
      map.push([]);
      for(var j = 0; j < this.mapWidth; j++) {
        map[i].push(0);
      }
    }
    this.map = new Map({ mapData: map });
    
    // Add listener to paint with tile brush
    this.map.container.on('click touchstart', '.tile', function(e) {
      var pos = $(this).index();
      var gridWidth = self.map.mapData[0].length;
      var x = pos % gridWidth;
      var y = (pos - x) / gridWidth;
      
      self._paint(x, y, $(this));
    });
  };
  
  this._initMapSize = function() {
    var heightInput = $('input[name="height"]');
    heightInput.val(this.mapHeight);
    heightInput.change(function(){
      var newHeight = $(this).val();
      var currentHeight = self.map.mapData.length;
      
      if(newHeight <= 0) {
        self.mapHeight = newHeight = 1;
        $(this).val(self.mapHeight);
      } else if(newHeight > 96) {
        self.mapHeight = newHeight = 96;
        $(this).val(self.mapHeight);
      } else {
        self.mapHeight = newHeight;
      }
      
      if(newHeight < currentHeight) {
        self.map.mapData.length = newHeight;
      } else {
        var currentWidth = self.map.mapData[0].length;
        for(var i = currentHeight; i < newHeight; i++) {
          self.map.mapData.push([]);
          for(var j = 0; j < currentWidth; j++) {
            self.map.mapData[i].push(0);
          }
        }
      }
      self.map.renderMap(self.map.mapData);
    });
    
    var widthInput = $('input[name="width"]');
    widthInput.val(this.mapWidth);
    widthInput.change(function(){
      var newWidth = $(this).val();
      var currentWidth = self.map.mapData[0].length;
      var currentHeight = self.map.mapData.length;
      
      if(newWidth <= 0) {
        self.mapWidth = newWidth = 1;
        $(this).val(self.mapWidth);
      } else if(newWidth > 96) {
        self.mapWidth = newWidth = 96;
        $(this).val(self.mapWidth);
      } else {
        self.mapWidth = newWidth;
      }
      
      if(newWidth < currentWidth) {
        for(var i = 0; i < currentHeight; i++) {
          self.map.mapData[i].length = newWidth;
        }
      } else {
        for(var i = 0; i < currentHeight; i++) {
          for(var j = currentWidth; j < newWidth; j++) {
            self.map.mapData[i].push(0);
          }
        }
      }
      self.map.renderMap(self.map.mapData);
    });
  };
  
  this._initSave = function() {
    $('.save-map').click(function(){ self._save(); });
  };
  
  // --- Saves mapData as JSON file
  this._save = function() {
    var saveFile = { map: this.map.mapData };
    var saveString = 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(saveFile, null, 2));
    var saveLink = document.createElement('a');
    saveLink.setAttribute('href', saveString);
    saveLink.setAttribute('download', 'map.json');
    saveLink.click();
  };
  
  // --- Try to load map via file input and HTML5 file API
  this._initLoad = function() {
     if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
       console.log('The File APIs are not fully supported in this browser.');
       return;
     }   

    $('.load-map').change(function() {
      var file = $(this)[0].files[0];
      var fileReader = new FileReader();
      fileReader.onload = function(data) {
        self._load(fileReader.result);
      };
      fileReader.readAsText(file);
    });
  };
  
  // --- Load mapData from JSON encoded string
  this._load = function(saveFile) {
    var data = JSON.parse(saveFile);
    this.map.mapData = data.map;
    this.map.renderMap(this.map.mapData);
  };
  
  // --- Paints given coordinates with currently selected brush
  this._paint = function(x, y, element) {
    var tile = this.tiles[this.selectedBrush];
    // Change map data
    // TODO Decouple
    this.map.mapData[y][x] = tile.id;
    
    // Apply to element
    // TODO use variables for all class names
    element.attr('class', 'tile ' + tile.className);
  };
  
  
  // --- Implicit Constructor
  this._init();
  
  return this;
}

// --- Start loop ----------------------------------------------
$(document).ready(function(){
  var mapEditor = new MapEditor();
});
            
          
!
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.

Console