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.

            
              <div id="react-container"></div>
            
          
!
            
              $cellW: 10px;
$cellH: $cellW;
$tableW: 640px;

#map-container {
  //line-height: 0px;
  //background-color: black;
  //border: 5px solid Silver;
  //border-radius: 10px;
}

.border {
  border: 1px solid black;
}

.vcenter {
  //display: flex;
  //flex-direction: column;
  //justify-content: center;
}

.legend-button {
  display: inline-block;
}

#status-bar {
  width: $tableW;
  margin: auto;
}

.cell {
  display: block;
  width: $cellW;
  height: $cellH;
  padding: 0px;
  margin: 0px;
  &.wall {
    background-color: DimGrey;
  }
  &.floor {
    background-color: Linen;
  }
  &.player {
    background-color: GoldenRod;
  }
  &.potion {
    background-color: Aquamarine;
  }
  &.weapon {
    background-color: Indigo;
  }
  &.monster {
    background-color: FireBrick;
  }
  &.fog {
    background-color: LightGrey;
  }
  &.fog-wall {
    background-color: mix(DimGrey,black);
  }
  &.fog-floor {
    background-color: mix(Linen,black);
  }
  &.unknown {
    background-color: black;
  }
  &.boss {
    background-color: OrangeRed;
  }
}

.hidden {
  visibility: hidden;
}

.map-col {
  display: inline-block;
  line-height: 0px;
  margin: 0px;
  padding: 0px;
  width: $cellW;
}

#rogue-game {
  text-align: center;
  width: 80%;
  margin: auto;
}
            
          
!
            
              /* stuff to fiddle with */
const mapW = 64,
      mapH = 36;

const potionHP = 20;
const baseAttack = 10;

var legend = [
  {name:'Wall',     desc:'An impassable wall.'},
  {name:'Floor',    desc:'This floor was made for walking!'},
  {name:'Player',   desc:'That\'s you!'},
  {name:'Potion',   desc:'The only way to get health. '+potionHP+'HP per potion.'},
  {name:'Weapon',   desc:'Upgrade your weapon to increase your ATK. Player ATK = (10 + weapon ATK) x LVL'},
  {name:'Monster',  desc:'Kill these to get XP!'},
  {name:'Boss',     desc:'Kill the boss to win the game. Be careful - he\'s pretty strong!'},
   ];
/* ~~~~~~~~~~~~~~~~~~~~ */

var keys = {w:87,s:83,a:65,d:68};

var Button = ReactBootstrap.Button,
    Modal  = ReactBootstrap.Modal,
    Grid   = ReactBootstrap.Grid,
    Row    = ReactBootstrap.Row,
    Col    = ReactBootstrap.Col,
    Table  = ReactBootstrap.Table;

function Cell(tile){
  this.tile = tile;
  this.entity = null;
  this.visible = false;
  this.seen = false;
  this.passable = function(){
    if (this.entity){
      return (this.tile.passable && this.entity.passable);
    }
    return (this.tile.passable);
  }
}

function Entity(settings){
  if (!(settings instanceof Object)){
    console.log('error');
    console.log(settings);
    return;
  }
  this.tooltip = function(){
    return this.name;
  };
  
  var k = Object.keys(settings);
  for (var i=0; i<k.length; i++){
    this[k[i]] = settings[k[i]];
  }
}

var tiles = {
  floor: {v:0, type:'floor', passable: true},
  wall: {v:1, type:'wall', passable: false}
};

var weapons = [{
  name: 'Dagger',
  atk: 1
}, {
  name: 'Shortsword',
  atk: 5
}, {
  name: 'Longsword',
  atk: 10
}, {
  name: 'Halberd',
  atk: 15
}, {
  name: 'Battle axe',
  atk: 20
}, {
  name: 'Death\'s scythe',
  atk: 200
}, ];

var monsters = [
  [{lv: 0, name: 'THE BOSS - Beelzebub',  hp: 300,  atk: 50,  xp: 5000 }],
  [{lv: 1, name: 'imp',  hp: 25, atk: 10, xp: 25},
   {lv: 1, name: 'thief',hp: 30, atk: 12, xp: 30},
   {lv: 1, name: 'punk', hp: 40, atk: 15, xp: 40},
   {lv: 1, name: 'rat',  hp: 15, atk: 10, xp: 20}],
  [{lv: 2, name: 'wolf', hp: 50, atk: 20, xp: 50}]
];

function Monster(level){
  var m = new Entity(monsters[level][randx(0,monsters[level].length)]);
  m.type = 'monster';
  m.passable = false;
  m.dead = false;
  m.tooltip = function(){
    return this.name + " (XP: "+this.xp+" HP: " + this.hp+")";
  }
  return m;
}

function Boss(){
  var m = new Monster(0);
  m.type = 'boss';
  return m;
}

function Potion(){
  return new Entity({type: 'potion', name: 'potion', passable: true});
}

function Weapon(){
  var w = new Entity(weapons[randx(0,weapons.length)]);
  w.type = 'weapon';
  w.passable = true;
  w.tooltip = function(){
    return this.name + " (Base ATK: " + this.atk + ")";
  }
  return w;
}

function Player() {
  return new Entity({
  x: 0,
  y: 0,
  hp: 100,
  lv: 1,
  xp: 50,
  atk: 0,
  dead: false,
  type: 'player',
  name: 'player',
  tooltip: function(){
    return this.name;
  },
  weapon: weapons[0],
  calcAtk: function() {
    this.atk = (baseAttack + this.weapon.atk) * this.lv;
  },
  getWeapon: function(newWeapon) {
    if (newWeapon.atk > this.weapon.atk){
      this.weapon = newWeapon;
      this.calcAtk();
    }
  },
  drinkPotion: function() {
    this.hp += potionHP;
  },
  getXP: function(xp){
    this.xp -= xp;
    if (this.xp <= 0){
      var leftover = 0-this.xp;
      this.levelup();
      this.getXP(leftover);
    }
  },
  levelup: function(){
    this.lv++;
    this.xp = this.lv * 50;
    this.calcAtk();
  },
  fightMonster: function(cell){
    var m = cell.entity;
    // attack first;
    m.hp -= (this.atk + rand(-5,5));
    // if enemy lives, hurt player
    if (m.hp > 0){
      this.hp -= (m.atk + rand(-5,5));
      // if player dies, set 'dead' to true
      if (this.hp <= 0){
        this.dead = true;
      }
    } else {
      // if enemy dies, get xp and remove it
      this.getXP(m.xp);
      cell.entity.dead = true;
      cell.entity = null;
    }
  }});
}

function Dungeon(width,height){
  var self = this;
  this.map = [];
  for (var x = 0; x < width; x++) {
    this.map[x] = [];
    for (var y = 0; y < height; y++) {
      this.map[x][y] = null;
    }
  }
  this.digger = new ROT.Map.Digger(width,height,{corridorLength: [1,3], timeLimit: 50});
  this.spaces = [];
  this.digger.create(function (x,y,v){
    if (v == tiles.wall.v){
      self.map[x][y] = new Cell(tiles.wall);
    } else {
      self.map[x][y] = new Cell(tiles.floor);
      self.spaces.push({x:x,y:y});
    }
  });
  this.lightPasses = function(x,y){
    if (self.map[x] && self.map[x][y]){
      return self.map[x][y].tile == tiles.floor;
    }
    return false;
  };
  this.fov = new ROT.FOV.PreciseShadowcasting(this.lightPasses);
  this.doFOV = function(px,py,fog){
    // remember to setState after!
    var self = this;
    if (fog){
      for (var x=0; x<this.map.length; x++){
        for (var y=0; y<this.map[x].length; y++){
          this.map[x][y].visible = false;
        }
      }
    }
    this.fov.compute(px, py, 10, function(x, y, r, visibility) {
      self.map[x][y].visible = true;
      self.map[x][y].seen = true;
    });
  };
  this.placeRand = function(ent){
    var spot = this.spaces.splice(randx(0,this.spaces.length),1)[0];
    this.map[spot.x][spot.y].entity = ent;
    return spot;
  };
}

var RogueGame = React.createClass({
  getInitialState: function() {
    var dungeon = new Dungeon(mapW,mapH);
    
    // place player
    var player = new Player();
    player.calcAtk();
    var spot = dungeon.placeRand(player);
    
    player.x = spot.x;
    player.y = spot.y;
    
    
    // place potions
    var count = rand(3,10);
    for (var i=0; i<count; i++){
      dungeon.placeRand(new Potion());
    }
    
    // place weapons
    var count = rand(2,5);
    for (var i=0; i<count; i++){
      dungeon.placeRand(new Weapon());
    }
    
    // place monsters
    var count = rand(7,15);
    for (var i=0; i<count; i++){
      dungeon.placeRand(new Monster(1));
    }
    
    // place boss
    var boss = new Boss();
    dungeon.placeRand(boss);
    
    // FOV
    dungeon.doFOV(player.x,player.y,true);
    
    // return initial state
    return ({
      dungeon: dungeon,
      player: player,
      boss: boss,
      gameOver: false,
      settings: {fog:true}
    });
  },
  resetGame: function(){
    this.setState(this.getInitialState());
  },
  checkEndGame: function(){
    if (this.state.player.dead){
      alert('Oh no! You have died. Enter a new dungeon and try again!');
      this.resetGame();
    } else if (this.state.boss.dead && !this.state.gameOver){
      alert('Congratulations! You have beaten the boss and won the game. You are still free to continue exploring the dungeon. Click the "reset" button to start a new game.');
      this.setState({gameOver: true});
    }
  },
  movePlayer: function(dir){
    var m = this.state.dungeon.map;
    var p = this.state.player;
    var x = p.x,
        y = p.y;
    switch (dir){
      case 'up':
        y--;
        break;
      case 'down':
        y++;
        break;
      case 'left':
        x--;
        break;
      case 'right':
        x++;
        break;
    }
    m[p.x][p.y].entity = null;
    if (m[x][y]){
      if (m[x][y].entity){
        switch (m[x][y].entity.type){
          case 'potion':
            p.drinkPotion();
            break;
          case 'weapon':
            p.getWeapon(m[x][y].entity);
            break;
          case 'boss':
          case 'monster':
            p.fightMonster(m[x][y]);
            break;
        }
      }
      
      if (m[x][y].passable()){
        p.x = x;
        p.y = y;
      }
      
    }
    m[p.x][p.y].entity = p;
    this.state.dungeon.doFOV(p.x,p.y,this.state.settings.fog);
    this.setState({dungeon:this.state.dungeon, player:p});
    this.checkEndGame();
  },
  keypressed: function(event){
    //console.log(event.keyCode);
    switch(event.keyCode){
      case keys.w:
        this.movePlayer('up');
        break;
      case keys.s:
        this.movePlayer('down');
        break;
      case keys.a:
        this.movePlayer('left');
        break;
      case keys.d:
        this.movePlayer('right');
        break;
    }
  },
  componentWillMount: function(){
    //this.doFOV();
  },
  componentDidMount: function() {
    $(document.body).on('keydown', this.keypressed);
  },
  render: function() {
    return (
      <div id="rogue-game" >
        <h1 className="text-primary text-center">React.js Rogue-Like Game</h1>
        <StatusBar player={this.state.player} resetGame={this.resetGame}/>
        <MapView map={this.state.dungeon.map} player={this.state.player} />
      </div>
    )
  }
});

var MapView = React.createClass({
  render: function() {
    var self = this;
    return (
      <div id="map-container">
        {
          this.props.map.map(function (col){
            return (
            <div className="map-col">
              {
                col.map(function (cell){
                  
                  return (
                    <CellView cell={cell} />
                  );
                })
              }
            </div>
            );
          })
        }
      </div>
    );
  }
});

var CellView = React.createClass({
  render: function(){
    var c = this.props.cell;
    var view = '';
    if (c.visible){
      if (c.entity){
        view = c.entity.type;
      } else {
        view = c.tile.type;
      }
    } else if (c.seen){
      view = 'fog-'+c.tile.type;
    } else {
      view = 'unknown';
    }
    if (c.visible && c.entity){
      return (
        <div className={"cell "+view} title={c.entity.tooltip()}></div>
      );
    } else {
      return (
        <div className={"cell "+view}></div>
      );
    }    
  }
});

var StatusBar = React.createClass({
  render: function(){
    var p = this.props.player;
    return (
      <div id="status-bar">
        
        <Legend />
        <Button
          bsStyle="danger"
          bsSize="small"
          onClick={this.props.resetGame}
        >
          Reset
        </Button>
        <h5>WASD to move/attack. Mouseover objects for more info.</h5>
        
        <Table bordered condensed>
          <thead>
            <tr>
              <th className="text-center">HP</th>
              <th className="text-center">LVL</th>
              <th className="text-center">XP to LVL-UP</th>
              <th className="text-center">Weapon</th>
              <th className="text-center">ATK</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{p.hp}</td>
              <td>{p.lv}</td>
              <td>{p.xp}</td>
              <td>{p.weapon.name}</td>
              <td>{p.atk}</td>
            </tr>
          </tbody>
        </Table>
      </div>
    )
  }
});

var Legend = React.createClass({

  getInitialState() {
    return { showModal: false };
  },

  close() {
    this.setState({ showModal: false });
  },

  open() {
    this.setState({ showModal: true });
  },

  render() {
    var styles = {
      border:'1px solid black',
      position: 'absolute',
      top: '50%',
      'margin-top': '-5px'
    };
    return (
      <div className="legend-button">
        <Button
          bsStyle="primary"
          bsSize="small"
          onClick={this.open}
        >
          Legend
        </Button>

        <Modal show={this.state.showModal} onHide={this.close}>
          <Modal.Header closeButton>
            <Modal.Title>Legend</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Table striped bordered condensed hover>
              <thead>
                <tr>
                  <th>Icon</th>
                  <th>Name</th>
                  <th>Description</th>
                </tr>
              </thead>
              <tbody>
            {
              legend.map(function (item){
                return (
                  <tr>
                    <td className="vcenter">
                      <div className={"border cell "+item.name.toLowerCase()}  ></div>
                    </td>
                    <td >{item.name}</td>                    
                    <td >{item.desc}</td>
                  </tr>
                );
              })
            }
              </tbody>
            </Table>
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.close}>Close</Button>
          </Modal.Footer>
        </Modal>
      </div>
    );
  }
});

function snapshot(m) {
  var ans = "";
  for (var x = 0; x < m.length; x++) {
    for (var y = 0; y < m.length; y++) {
      ans += m[x][y];
    }
    ans += "\n";
  }
  console.log(ans);
}

function rand(from, to){ //inclusive
  return Math.floor(Math.random()*(to-from+1) + from);
}
function randx(from, to){ //exclusive
  return Math.floor(Math.random()*(to-from) + from);
}

ReactDOM.render(<RogueGame/>, document.getElementById('react-container'));
            
          
!
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