Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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="root"></div>
              
            
!

CSS

              
                body {
  margin: 0;
  padding: 0;
  font-family: 'Press Start 2P', sans-serif;
  background-color: black;
}

              
            
!

JS

              
                const routeReducers = reducers => (state, action) =>
  reducers[action.type] ? reducers[action.type](state, action) : state;

const TileType = {
  WALL: "WALL",
  PATH: "PATH",
  PLAYER: "PLAYER",
  ENEMY: "ENEMY",
  HEALTH: "HEALTH",
  WEAPON: "WEAPON"
};

const Weapon = {
  KNIFE: "KNIFE",
  DAGGER: "DAGGER",
  AXE: "AXE",
  SWORD: "SWORD",
  PIKE: "PIKE"
};

const Damage = {
  KNIFE: 20,
  DAGGER: 25,
  AXE: 30,
  SWORD: 35,
  PIKE: 50
};

const Move = {
  LEFT: "LEFT",
  RIGHT: "RIGHT",
  UP: "UP",
  DOWN: "DOWN"
};

const Direction = {
  37: Move.LEFT,
  38: Move.UP,
  39: Move.RIGHT,
  40: Move.DOWN
};

const getRandomMap = () =>
  fetch(
    "https://rogue-api.herokuapp.com/api/rogue?width=70&height=35"
  ).then(response => response.json().then(res => res.map));

const getEmptyRandomTile = board => {
  let row = Math.floor(Math.random() * (board.length - 2) + 1),
    col = Math.floor(Math.random() * (board[0].length - 2) + 1);
  return board[row][col].type === TileType.PATH
    ? { row, col }
    : getEmptyRandomTile(board);
};

const scatterGameObjects = (board, objects) => {
  let location;
  for (let i = 0; i < objects.length; i++) {
    location = getEmptyRandomTile(board);
    board[location.row][location.col] = objects[i];
  }
};

const nextPosition = (state, direction) => {
  const { row, col } = state.playerPosition;
  switch (direction) {
    case Move.LEFT:
      return { row, col: col - 1 };
    case Move.UP:
      return { row: row - 1, col };
    case Move.RIGHT:
      return { row, col: col + 1 };
    case Move.DOWN:
      return { row: row + 1, col };
    default:
      return state.playerPosition;
  }
};

const store = Redux.createStore(
  routeReducers({
    initialize: (state = {}, action) => {
      let gameMap = action.gameMap.map(row =>
        row.map(
          col => (col === 1 ? { type: TileType.WALL } : { type: TileType.PATH })
        )
      );
      const playerPosition = getEmptyRandomTile(gameMap);
      gameMap[playerPosition.row][playerPosition.col] = {
        type: TileType.PLAYER,
        level: 1,
        hp: 60,
        xp: 0,
        weapon: Weapon.KNIFE
      };
      const gameObjects = [
        {
          type: TileType.ENEMY,
          isBoss: true,
          hp: 100,
          weapon: Weapon.PIKE
        },
        {
          type: TileType.ENEMY,
          isBoss: false,
          hp: 80,
          weapon: Weapon.SWORD
        },
        {
          type: TileType.ENEMY,
          isBoss: false,
          hp: 60,
          weapon: Weapon.AXE
        },
        {
          type: TileType.ENEMY,
          isBoss: false,
          hp: 40,
          weapon: Weapon.DAGGER
        },
        {
          type: TileType.HEALTH,
          hp: 60
        },
        {
          type: TileType.HEALTH,
          hp: 80
        },
        {
          type: TileType.HEALTH,
          hp: 100
        },
        {
          type: TileType.WEAPON,
          weapon: Weapon.SWORD
        },
        {
          type: TileType.WEAPON,
          weapon: Weapon.DAGGER
        },
        {
          type: TileType.WEAPON,
          weapon: Weapon.AXE
        }
      ];
      scatterGameObjects(gameMap, gameObjects);
      return {
        gameMap: Immutable.fromJS(gameMap),
        playerPosition,
        gameState: "playing"
      };
    },
    move: (state = {}, action) => {
      const { row: or, col: oc } = state.playerPosition,
        op = state.gameMap.get(or).get(oc),
        { row: nr, col: nc } = nextPosition(state, action.direction),
        ot = state.gameMap.get(nr).get(nc);
      switch (ot.get("type")) {
        case TileType.WALL:
          return state;
        case TileType.PATH:
          return {
            ...state,
            gameMap: state.gameMap
              .update(or, row => row.set(oc, ot))
              .update(nr, row => row.set(nc, op)),
            playerPosition: { row: nr, col: nc }
          };
        case TileType.HEALTH:
          return {
            ...state,
            gameMap: state.gameMap
              .update(or, row =>
                row.set(oc, Immutable.Map({ type: TileType.PATH }))
              )
              .update(nr, row =>
                row.set(nc, op.update("hp", hp => hp + ot.get("hp")))
              ),
            playerPosition: { row: nr, col: nc }
          };
        case TileType.WEAPON:
          return {
            ...state,
            gameMap: state.gameMap
              .update(or, row =>
                row.set(oc, Immutable.Map({ type: TileType.PATH }))
              )
              .update(nr, row =>
                row.set(
                  nc,
                  op.update(
                    "weapon",
                    weapon =>
                      Damage[ot.get("weapon")] > Damage[weapon]
                        ? ot.get("weapon")
                        : weapon
                  )
                )
              ),
            playerPosition: { row: nr, col: nc }
          };
        case TileType.ENEMY:
          const ne = ot.update(
            "hp",
            hp => hp - Damage[op.get("weapon")] * op.get("level")
          ),
            ned = ne.get("hp") <= 0,
            nxp = ned ? op.get("xp") + 500 : op.get("xp"),
            nl = nxp >= 1000 ? op.get("level") + 1 : op.get("level"),
            np = op
              .update("hp", hp => hp - Damage[ot.get("weapon")])
              .set("xp", nxp % 1000)
              .set("level", nl);
          if (np.get("hp") <= 0) return { ...state, gameState: "lost" };
          if (ned && ne.get("isBoss")) return { ...state, gameState: "won" };
          if (ned) {
            return {
              ...state,
              gameMap: state.gameMap
                .update(or, row =>
                  row.set(oc, Immutable.Map({ type: TileType.PATH }))
                )
                .update(nr, row => row.set(nc, np)),
              playerPosition: { row: nr, col: nc }
            };
          }
          return {
            ...state,
            gameMap: state.gameMap
              .update(or, row => row.set(oc, np))
              .update(nr, row => row.set(nc, ne))
          };
        default:
          return state;
      }
    }
  })
);

const distance = ({ row: r1, col: c1 }, { row: r2, col: c2 }) => {
  return Math.sqrt((r1 - r2) ** 2 + (c1 - c2) ** 2);
};

const tileColor = tile => {
  switch (tile.type) {
    case TileType.WALL:
      return "#8D6E63";
    case TileType.PATH:
      return "white";
    case TileType.PLAYER:
      return "#01579B";
    case TileType.ENEMY:
      return tile.isBoss ? "#7B1FA2" : "#D32F2F";
    case TileType.HEALTH:
      return "#388E3C";
    case TileType.WEAPON:
      return "#FFEB3B";
    default:
      return "#8D6E63";
  }
};

const Header = () => {
  const headerStyle = {
    paddingTop: "30px",
    fontSize: '22px',
    color: '#FF5722',
    fontWeight: 'bold'
  };
  const subHeaderStyle = {
    fontSize: '15px',
    color: '#FFFF00',
    paddingBottom: '20px'
  }
  return (
    <div>
    <div style={headerStyle}>React Roguelike Dungeon Crawler Game</div>;
      <div style={subHeaderStyle}>Play with arrow keys (Click anywhere to start)</div>
    </div>
    )
};

const Gauge = ({ type, value }) => {
  const gaugeStyle = {
    display: "inline-block",
    margin: "0 10px",
    color: '#FF8A65'
  };
  return <div style={gaugeStyle}>{type}: {value}</div>;
};

const Notify = ({ gameState }) => {
  const notifyStyle = {
    color: 'white'
  };
  const gameStateStyle = {
    color: gameState === 'won' ? 'green' : 'red'
  };
  return (
    <div style={notifyStyle}>
      <div>You have <span style={gameStateStyle}>{gameState}</span> the Game.</div>
      <br/>
      <div>Press <span style={{color: 'yellow'}}>Spacebar</span> to restart.</div>
    </div>
  );
};

const Cell = ({ tile, location, playerLocation }) => {
  const cellStyle = {
    height: "12px",
    width: "12px",
    display: "inline-block",
    backgroundColor: distance(location, playerLocation) >= 5
      ? "black"
      : tileColor(tile),
    border: tile.type === TileType.WALL ? '1px dashed #4E342E': '1px solid transparent',
    boxSizing: 'border-box'
  };
  return <div style={cellStyle} />;
};

const Row = ({ row, rowIndex, playerLocation }) => {
  const rowStyle = {
    height: "12px"
  };
  return (
    <div style={rowStyle}>
      {row.map((cell, index) =>
        <Cell
          tile={cell}
          key={index}
          location={{ row: rowIndex, col: index }}
          playerLocation={playerLocation}
        />
      )}
    </div>
  );
};

const Map = ({ gameMap, playerLocation }) => {
  return (
    <div style={{marginTop: '20px'}}>
      {gameMap.map((row, index) =>
        <Row
          row={row}
          key={index}
          rowIndex={index}
          playerLocation={playerLocation}
        />
      )}
    </div>
  );
};

const Game = ({ state }) => {
  const gameMap = state.gameMap.toJS(),
    player = gameMap[state.playerPosition.row][state.playerPosition.col];
  const gameStyle = {
    textAlign: 'center'
  }
  return (
    <div style={gameStyle}>
      <Header />
      {state.gameState === "playing"
        ? [
            <Gauge type="Health" value={player.hp} />,
            <Gauge type="Weapon" value={player.weapon.toLowerCase()} />,
            <Gauge type="Attack" value={Damage[player.weapon]} />,
            <Gauge type="XP" value={player.xp} />,
            <Gauge type="Level" value={player.level} />,
            <Map gameMap={gameMap} playerLocation={state.playerPosition} />
          ]
        : <Notify gameState={state.gameState} />}
    </div>
  );
};

const initialize = () =>
  getRandomMap().then(gameMap =>
    store.dispatch({ type: "initialize", gameMap })
  );

window.addEventListener("keydown", event => {
  if (
    event.which >= 37 &&
    event.which <= 40 &&
    store.getState().gameState === "playing"
  )
    store.dispatch({ type: "move", direction: Direction[event.which] });
  else if (event.which === 32 && store.getState().gameState !== "playing")
    initialize();
});

const render = () =>
  ReactDOM.render(
    <Game state={store.getState()} />,
    document.getElementById("root")
  );
store.subscribe(() => render());
initialize();

              
            
!
999px

Console