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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                <div id="body" class="container-fluid">
</div>
              
            
!

CSS

              
                .base
  display: inline-block
  width: 25px
  height: 25px
  background: white
  
.darkness
  @extend .base
  background: black
.wall
  @extend .base
  background: grey
  
.player
  @extend .base
  background: #0099CC
  
.item 
  @extend .base
  background: #ffbb33
  
.health
  @extend .base
  background: #00C851
  
.enemy00
  @extend .base
  background: #ff4444
  
.enemy10
  @extend .base
  background: #ff4444
  
.enemy20
  @extend .base
  background: #ff4444
  
.enemy30
  @extend .base
  background: #ff4444
  
.enemy40
  @extend .base
  background: #ff4444
  
.enemy50
  @extend .base
  background: #ff4444
  
.enemy60
  @extend .base
  background: #ff4444
  
.enemy70
  @extend .base
  background: #ff4444
  
.enemy80
  @extend .base
  background: #ff4444
  
.enemy90
  @extend .base
  background: #ff4444
  
  
.exit
  @extend .base
  background: #9933CC
  
.boss
  @extend .base
  background: #CC0000

body
  background: black
  
#display
  text-align: center
  color: white
              
            
!

JS

              
                //from npm: https://www.npmjs.com/package/random-dungeon-generator
const NewDungeon = function NewDungeon({width = 50, height = 50, minRoomSize = 5, maxRoomSize = 20}) {

  const VERTICAL = 'vertical';
  const HORIZONTAL = 'horizontal';

  const Dungeon = {

      init(width, height, minRoomSize, maxRoomSize) {
        // Create an empty 2D array width x height
        this.minRoomSize = 5;
        this.maxRoomSize = 20;
        this.counter = 1;
        this.tree = {
          level: Array.apply(null, {length: height}).map(() => Array.apply(null, {length: width})),
        }
        this.split(this.tree);
        this.connectRooms(this.tree);
      },


      setMinRoomSize(num) {
        if (num > this.maxRoomSize) {
          throw "Minimum room size cannot be larger than the maximum room size of " + this.maxRoomSize;
          return;
        }
        this.minRoomSize = num;
      },


      setMaxRoomSize(num) {
        if (num < this.minRoomSize) {
          throw "Maximum room size cannot be smaller than the minumum room size of " + this.minRoomSize;
          return;
        }
        this.minRoomSize = num;
      },


      /**
       * Given a 2d array (node.level), this function will split the room into two separate arrays
       * and store then in node.lNode.level and node.rNode.level. The split is random (vertical or horizontal)
       * and can be anywhere along the axis as long as it doesn't result in making the room smaller
       * than this.min.
       * 
       * @param {object} node 
       */
      split(node) {

        if (node.level.length > this.maxRoomSize || node.level[0].length > this.maxRoomSize) {
          // If this condition is true, then we need to split again

          const splitDirection = randomDirection(this.getSplitOptions(node.level.length, node.level[0].length));
          const indexToSplit = this.getIndexToSplit(splitDirection, node.level[0].length, node.level.length);

          let lNode = node.leftNode = {};
          let rNode = node.rightNode = {};
          node.splitDirection = splitDirection;
          node.splitIndex = indexToSplit;

          /**
           * Split the rooms either vertically or horizontally and store the
           * new array in the left node and right nodes
           */
          if (splitDirection === 'vertical') {
            lNode.level = node.level.map(row => row.slice(0, indexToSplit));
            rNode.level = node.level.map(row => row.slice(indexToSplit, row.length));
          } else {
            lNode.level = node.level.slice(0, indexToSplit);
            rNode.level = node.level.slice(indexToSplit, node.level.length);
          }

          /**
           * Recursive call to split the rooms again if needed
           */
          this.split(lNode);
          this.split(rNode);

        } else {
          /**
           * If we reach this point, then we can guarantee that the room does not have any children nodes.
           * I.e. it's the smallest leaf node
           * counter is used so we can visually see the different rooms when the room is rendered
           */
          this.counter += 1;
          node.level = node.level.map(row => row.map(() => this.counter));
          node.level = AddRoomBoundaries(node.level);
        }
        
      },

      /**
       * returns an array with the values VERTICAL if a vertical split is an option, and
       * HORIZONTAL is a horizontal split is an option, or an empy array neither are options.
       * Whether or not it is an option is based on if the size of the room is greater than
       * the maximum allowed room size.
       * 
       * @param {number} verticalLength 
       * @param {number} horizontalLength 
       * @returns {array}
       */
      getSplitOptions(verticalLength, horizontalLength) {
        let directionOptions = [];
        if (verticalLength > this.maxRoomSize) {
          directionOptions.push(HORIZONTAL);
        }
        if (horizontalLength > this.maxRoomSize) {
          directionOptions.push(VERTICAL);
        }
        return directionOptions;
      },


      /**
       * Returns a random number along the vertical or horizontal axis
       * 
       * @param {any} verticalLength 
       * @param {any} horizontalLength 
       * @returns {number}
       */
      getIndexToSplit(splitDirection, horizontalLength, verticalLength) {
        const min = this.minRoomSize;
        const max = splitDirection === VERTICAL ? horizontalLength - min : verticalLength - min;
        return randomIndexBetweenValues(min, max);
      },


      /**
       * 
       * 
       * @param {any} node 
       * @returns 
       */
      connectRooms(node) {
        /**
         * First, recursively loop through all the rooms so we're starting at the
         * lowest nodes in the tree that have child nodes, and we work our way back up.
         */
        if (node.leftNode) {
          this.connectRooms(node.leftNode);
        } else {
          return;
        }

        if (node.rightNode) {
          this.connectRooms(node.rightNode);
        } else {
          return;
        }

        const lNode = node.leftNode.level;
        const rNode = node.rightNode.level;


        /**
         * Since this function is called after all the rooms have been created, we know that all
         * the rooms already have boundaries. We just need to remove the wall at a random
         * intersecting point.
         */
        if (node.splitDirection === VERTICAL) {
          /**
           *  For vertical cut, the corridor will be horizontal. So somewhere along the 0 -> firstRoom.length axis
           * Don't put the corridor on the outer most index values (0 and length - 1) because
           * that can allow the corridor to be on the map boundary
           */ 
          const vIndex = randomIndexBetweenValues(1, lNode.length - 2);
          node.corridorIndex = vIndex;
          lNode[vIndex][lNode[0].length - 1] = 0;
          lNode[vIndex][lNode[0].length - 2] = 0;
          rNode[vIndex][0] = 0;
          rNode[vIndex][1] = 0;
        } else {
        // For horizontal cut, the corridor will be vertical. So somewhere along the firstRoom[row[0]] -> firstRoom[row.length] axis
          const hIndex = randomIndexBetweenValues(1, lNode[0].length - 2);
          node.corridorIndex = hIndex;
          lNode[lNode.length - 1][hIndex] = 0;
          lNode[lNode.length - 2][hIndex] = 0;
          rNode[0][hIndex] = 0;
          rNode[1][hIndex] = 0;
        }

        /**
         * Combine the child left node and right node rooms back together, and
         * save the result in the current level node.
         */
        node.level = [];
        if (node.splitDirection === VERTICAL) {

          node.level = lNode.reduce((obj, val, index) => {
            let temp = [];
            temp.push(...lNode[index]);
            temp.push(...rNode[index]);
            obj.push(temp);
              return obj;
          }, []);
          
        } else {

          // If we get to this point, then the slice was horizontal
          node.level.push(...lNode);
          node.level.push(...rNode);
        
        }
      }
  };


  /**
   * 50% chance of returning a 0
   * 50% chance of returning a 1
   * 
   * @returns {number} 0 or 1
   */
  function fiftyfifty() {
    return randomIndexBetweenValues(0, 1);
  }


  /**
   * Return a random direction of vertical or horizontal
   * 
   * @returns {string} 'vertical' or 'horizontal'
   */
  function randomDirection(directionOptions = [VERTICAL, HORIZONTAL]) {
    if (directionOptions.length === 0) {
      return '';
    }

    const numOptions = directionOptions.length - 1;
    return directionOptions[randomIndexBetweenValues(0, numOptions)];
  }


  /**
   * Returns a random number between min and max
   * 
   * @param {number} min minimum random number to return
   * @param {number} max maximum random number to return
   * @returns {number}
   */
  function randomIndexBetweenValues(min, max) {
    return Math.floor((Math.random() * (max - min + 1)) + min);
  }

    
  /**
   * Add blocking tiles around the parameter of the 2d array
   * 
   * @param {array} array 2d array representing a room
   */
  function AddRoomBoundaries(array) {
    const height = array.length - 1;
    const width = array[0].length - 1;
    array = array.map((row, rIndex) => {
      return row.map((col, cIndex) => {
        if (rIndex === 0 || rIndex === height || cIndex === 0 || cIndex === width) {
          return 1;
        }
        return col;
      });
    });
    return array;
  }
  const dungeon = Object.create(Dungeon);
  dungeon.init(width, height, minRoomSize, maxRoomSize);
  return dungeon.tree.level;
} 

class Room extends React.Component {
  render () {
    var rows = this.props.data.map((x, xi) => {
      var column = x.map((y,yi) =>{
        if(y!==1){
          if(this.props.playerPos[0] === xi && this.props.playerPos[1] === yi) {
            y = 'player'
          }
          if(typeof y === 'number') {
            return <a className='base'></a>
          }else{
            return <a className={y}></a>
          }
        }else{
          return <a className='wall'></a>
        }
      })
      return <div>{column}</div>
    })
    return <div>{rows}</div>
  }
}
class Display extends React.Component {
  render () {
    var attack = (this.props.player.item + this.props.player.lvl) * 10
    return (
      <div id="display">
        <h2>
          Player = health: {this.props.player.health}, attack: {attack - 10} - {attack + 10}, item: {this.props.items[this.props.player.item]}, lvl: {this.props.player.lvl}, exp: {this.props.player.exp}
        </h2>
        <h3>
          Dungeon Level = {this.props.dungeonLvl + 1} 
        </h3>
      </div>
    )
  }
}
class ToggleShadow extends React.Component {
  render () {
    return <button onClick={this.props.onClick} class="btn btn-primary">I hereby agree I suck</button>
  }
}
class Message extends React.Component {
  render () {
    return <h1>{this.props.data[1]}</h1>
  }
}
class Complete extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      playerPos: [],
      items:['Fist','Baseball Bat','Kitchen Knife','Fireman Axe','Desert Eagle',"Reaper's Scythe"],
      shadow: true,
      dungeonLvl: 0,
      player: {health: 100, item: 0, lvl: 1, exp: 0},
      dungeon: NewDungeon({width : 50, height : 50, minRoomSize : 5, maxRoomSize : 20}),
      alive: [true,]
    };
  }
  componentWillMount () {
    this.processDungeon(this.state.dungeon)
    window.addEventListener('keydown', this.handleKeyDown.bind(this));
  }
  componentWillUnmount () {
    window.removeEventListener('keydown', this.handleKeyDown.bind(this));
  }
  processDungeon (dungeon) {
    var newDungeon = dungeon
    var obj = {
      'player': 1,
      'item': 1,
      'health': 5,
      'enemy00': 5
    }
    this.state.dungeonLvl === 4 ? obj.boss = 1 : obj.exit = 1
    Object.keys(obj).forEach(val => {
      for(let x=0; x<obj[val]; x++) {
        var xPos = Math.floor(Math.random() * 50)
        var yPos = Math.floor(Math.random() * 50)
        while(typeof newDungeon[xPos][yPos] === 'Number' || newDungeon[xPos][yPos] === 1){
          xPos = Math.floor(Math.random() * 50)
          yPos = Math.floor(Math.random() * 50)
        }
        if(val === 'player'){
          this.setState({playerPos: [xPos, yPos]})
          //console.log(this.state.playerPos)
        }else{
          newDungeon[xPos][yPos] = val
        }
      }
    })
    //console.log(newDungeon)
    this.setState({dungeon: newDungeon})
  }
  handleKeyDown (e) {
    var key = e.key;
    switch (key) {
      case 'a':
      case 'ArrowLeft':
        key = [0,-1]
        break;
      case 's':
      case 'ArrowDown':
        key = [1,0]
        break;
      case 'w':
      case 'ArrowUp':
        key = [-1,0]
        break;
      case 'd':
      case 'ArrowRight':
        key = [0,1]
        break;
    }
    let playerPos = this.state.playerPos
    let neighbor = [playerPos[0] + key[0], playerPos[1] + key[1]]
    let neighborType = this.state.dungeon[playerPos[0] + key[0]][playerPos[1] + key[1]]
    if(typeof neighborType === 'number'){
      if(neighborType !== 1){
        this.setState({playerPos: neighbor})
      }
    }else{
      if(neighborType === 'health') {
        this.setState((prevState, props) => {
          let modPlayer = prevState.player
          modPlayer.health += 60
          let modDungeon = prevState.dungeon
          modDungeon[neighbor[0]][neighbor[1]] = 2
          return {playerPos: neighbor, player: modPlayer, dungeon: modDungeon}
        })
      }else if(neighborType === 'boss') {
        this.setState((prevState, props) => {
          if(prevState.player.item + prevState.player.lvl == 12 || prevState.player.item + prevState.player.lvl == 11){
            return {alive: [false, 'You Win']}
          }else{
            return {alive: [false, 'You Died']}
          }
        })
      }else if(neighborType === 'item') {
        this.setState((prevState, props) => {
          let modPlayer = prevState.player
          modPlayer.item += 1
          let modDungeon = prevState.dungeon
          modDungeon[neighbor[0]][neighbor[1]] = 2
          return {playerPos: neighbor, dungeon: modDungeon, player: modPlayer}
        })
      }else if(neighborType === 'exit') {
        this.setState((prevState, props) => {
          return {dungeon: NewDungeon({width : 50, height : 50, minRoomSize : 5, maxRoomSize : 20}),dungeonLvl: prevState.dungeonLvl + 1}
        })
        this.processDungeon(this.state.dungeon)
      }else {
        this.setState((prevState, props) => {
          let modDungeon = prevState.dungeon
          let enemyHp = modDungeon[neighbor[0]][neighbor[1]][5]
          let modPlayer = prevState.player
          let playerAttack = (modPlayer.item + modPlayer.lvl) * 10 + ((Math.floor(Math.random() * 3) -1) * 10)
          modPlayer.health -= (((prevState.dungeonLvl + 1) * 10) + ((Math.floor(Math.random() * 3) -1) * 10))
          if(modPlayer.health <= 0) {
            return {alive: [false, 'died fighting']}
          }else{
          if((parseInt(enemyHp) * 10) + playerAttack >= 100) {
            modDungeon[neighbor[0]][neighbor[1]] = 2
            modPlayer.exp += 20
          }else{
            modDungeon[neighbor[0]][neighbor[1]] = 'enemy' + ((parseInt(enemyHp) * 10) + playerAttack)
            console.log(modDungeon[neighbor[0]][neighbor[1]])
            neighbor = prevState.playerPos
          }
          if(modPlayer.exp === 100) {
            modPlayer.exp = 0
            modPlayer.lvl = prevState.player.lvl + 1
          }
          return {player: modPlayer, dungeon: modDungeon, playerPos: neighbor}
          }
        })
      }
    }
  }
  
  toggleShadow() {
    if(this.state.shadow===true){
      this.setState({shadow: false})
    }else{
      this.setState({shadow: true})
    }
  }
  render () {
    if(this.state.alive[0] === true) {
    var modDungeon = this.state.dungeon
    if(this.state.shadow === true){
      modDungeon = modDungeon.map((row, xPos) => {
        var newRow = row.map((item, yPos) => {
          var xDif = this.state.playerPos[0] - xPos
          var yDif = this.state.playerPos[1] - yPos
          if(xDif === 1 || xDif === 0 || xDif === -1){
            if(yDif === 1 || yDif === 0 || yDif === -1) {
              return item
            }else{
              return 'darkness'
            }
          }else{
            return 'darkness'
          }
        })
        return newRow
      })
    }
    
    return (
      <div>
        <Display dungeonLvl={this.state.dungeonLvl} player={this.state.player} items={this.state.items}/>
        <ToggleShadow onClick={this.toggleShadow.bind(this)}/>
        <Room data={modDungeon} playerPos={this.state.playerPos}/>
      </div>
    )
    }else {
      return <Message data={this.state.alive} />
    }
  }
}
ReactDOM.render(<Complete />, document.getElementById('body'))
              
            
!
999px

Console