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

CSS

              
                $background-color: #F0ECCE
$text-color: #222
$wall-color: lighten($text-color, 20)
$floor-color: darken($background-color, 15)
$player-color: blue
$healing-item-color: green
$story-item-color: purple
$weapon-color: orange
$enemy-color: red
$seen-opacity: .15
$health-bar-color: $wall-color
$health-bar-low-color: #c11
$cell-width: 15px
$cell-height: 15px
$title-font: 'Indie Flower', cursive
$body-font: 'serif'

body
  background-color: $background-color
  color: $text-color
  font-family: $body-font
  
h1
  font-family: $title-font
  font-size: 2.5em
  margin-bottom: .2em
  
.full-screen
  position: absolute
  left: 0
  top: 0
  z-index: 10
  height: 100%
  width: 100%
  
.bigger
  font-size: 2em
  
.hidden
  display: none
  
.clickable
  cursor: pointer
  
.centered
  text-align: center
  
div#restart
  position: fixed
  font-size: 1.5em
  text-align: center
  bottom: .3em
  right: .3em
  padding: .12em .3em
  border: .2em solid $wall-color
  border-radius: .3em
  background-color: black
  color: #aaa
  opacity: .5
  cursor: pointer

div#restart.emphasized
  font-family: sans-serif
  display: block
  font-size: 2em
  top: 4em
  bottom: auto
  left: 1em
  right: 1em
  opacity: .8
  z-index: 10
  
div#restart:hover
  opacity: 1
  background-color: #333
  color: #ddd
  

    
div.messages
  margin: .4em auto .1em auto
  max-width: 768px
    
@media screen and (min-width: 1024px) 
  div.player-space
    position: absolute
    top: 0
    left: 50%
    width: 45%
  div.messages
    position: absolute
    top: 0
    right: 50%
    width: 45%

  
div.grid-wrapper
  display: inline-block
  
table
  border-collapse: collapse
  margin: auto
  
tbody, tr, td
  border: none
  margin: 0px
  padding: 0px
  
td
  width: $cell-width
  height: $cell-height
  background-color: $floor-color

td.seen
  opacity: $seen-opacity

td.unseen
  border-radius: 0px
  background-color: $background-color

td.visible
  opacity: 1
  
td.wall
  background-color: $wall-color
  border-radius: 0px
  
td.healing-item, td.story-item, td.weapon, td.enemy, td.player
  border-radius: 6px
  position: relative
  
td.healing-item::after, td.story-item::after, td.weapon::after, td.enemy::after, td.player::after
  width: $cell-width + 1
  height: $cell-width + 1
  content: " "
  background-color: $floor-color
  top: 0
  left: 0
  position: absolute
  z-index: -1
  

td.healing-item.healing-item-1
  background-color: $healing-item-color
td.healing-item.healing-item-2
  background-color: lighten($healing-item-color, 5)
td.healing-item.healing-item-3
  background-color: lighten($healing-item-color, 10)
td.healing-item.healing-item-4
  background-color: lighten($healing-item-color, 15)
td.healing-item.healing-item-5
  background-color: lighten($healing-item-color, 20)
td.healing-item.healing-item-6
  background-color: lighten($healing-item-color, 25)
td.healing-item.healing-item-7
  background-color: lighten($healing-item-color, 30)
td.healing-item.healing-item-8
  background-color: lighten($healing-item-color, 35)
  
td.story-item.story-item-1
  background-color: $story-item-color
td.story-item.story-item-2
  background-color: lighten($story-item-color, 5)
td.story-item.story-item-3
  background-color: lighten($story-item-color, 10)
td.story-item.story-item-4
  background-color: lighten($story-item-color, 15)
td.story-item.story-item-5
  background-color: lighten($story-item-color, 20)
td.story-item.story-item-6
  background-color: lighten($story-item-color, 25)
td.story-item.story-item-7
  background-color: lighten($story-item-color, 30)
td.story-item.story-item-8
  background-color: lighten($story-item-color, 35)

td.weapon.weapon-1
  background-color: $weapon-color
td.weapon.weapon-2
  background-color: darken($weapon-color, 5)
td.weapon.weapon-3
  background-color: darken($weapon-color, 10)
td.weapon.weapon-4
  background-color: darken($weapon-color, 15)
td.weapon.weapon-5
  background-color: darken($weapon-color, 20)
td.weapon.weapon-6
  background-color: darken($weapon-color, 25)
td.weapon.weapon-7
  background-color: darken($weapon-color, 30)
td.weapon.weapon-8
  background-color: darken($weapon-color, 35)

td.enemy.enemy-0  
  background-color: $enemy-color
td.enemy.enemy-1
  background-color: darken($enemy-color, 10)
td.enemy.enemy-2
  background-color: darken($enemy-color, 20)
td.enemy.enemy-3
  background-color: darken($enemy-color, 30)
td.enemy.enemy-4
  background-color: darken($enemy-color, 40)
td.enemy.enemy-5
  background-color: darken($enemy-color, 50)
td.enemy.enemy-6
  background-color: darken($enemy-color, 60)
td.enemy.enemy-7
  background-color: darken($enemy-color, 70)

td.player
  background-color: $player-color
  
div.health-bar-wrapper
  position: relative
  margin: .15em
  
div.health-bar
  height: 6px
  background-color: $health-bar-color

div.health-bar-low
  height: 6px
  background-color: $health-bar-low-color
  position: absolute
  top: 0
  opacity: 0
  
div.inventory-list
  color: lighten($weapon-color, 80%)
  margin: .2em
  
span.weapon
  cursor: pointer
  background-color: darken($weapon-color, 30%)
  padding: .1em .3em
  opacity: .6

span.weapon:hover
  background-color: darken($weapon-color, 10%)
  
span.equipped
  font-weight: bold
  border-width: .15em
  opacity: 1
    
ul
  margin: auto
  padding-left: 0
  
li
  list-style: none
  margin-bottom: .6em
              
            
!

JS

              
                (function() {
  
  //////// Game Properties
  
  var sharedProps = {
    origin: {x: 4, y: 4},
    distancePerLevel: 20,
  };
  
  var screenProps = {
    origin: sharedProps.origin,
    width: 25,
    height: 25,
    playerEdgePad: 8
  };
  
  var messageProps = {
    initialMessages: ['Click to begin', 'in a dream'],
    triggeredMessages: [{
      name: 'click',
      firstTimeMessage: 'Use the arrow keys to move.'
    },{
      name: 'move',
      firstTimeMessage: 'That\'s it. I\'m the blue dot.'
    },{
      name: 'see enemy',
      firstTimeMessage: 'The red thing is a bad memory.  I\'m facing it mortal combat style - we strike at one-another until one of us goes down.  I\'m not going down.'
    },{
      name: 'see healing item',
      firstTimeMessage: 'That green thing looks like a good memory.'
    },{
      name: 'see story item',
      firstTimeMessage: 'That purple thing is why I\'m here, I think.'
    },{
      name: 'see weapon',
      firstTimeMessage: 'The yellow thing should make me stronger here.'
    },{
      name: 'attack',
      firstTimeMessage: 'Keep moving towards it to take it out!'
    },{
      name: 'enemy destroyed',
      firstTimeMessage: 'That wasn\'t as hard as I thought, but I\'d better check my stamina in that bar on top.'
    },{
      name: 'away from origin',
      firstTimeMessage: 'I\'m getting pretty far from where I started.  I should have some boosted stamina and something to help me before I get too far.' 
    },{
      name: 'further away from origin',
      firstTimeMessage: 'I\'m really going far.  I better be prepared for tougher challenges.'
    },{
      name: 'see boss',
      firstTimeMessage: 'It\'s her.  I...don\'t even know what to do.  The way I left her....'
    },{
      name: 'death',
      firstTimeMessage: 'I can\'t take this any more.  What a nightmare.  I\'ll try again the next time I dream.'
    },{
      name: 'win',
      firstTimeMessage: 'That\'s it.  It\'s over.  I\'m...free.'
    }],
    levelMessages: [
      'I should probably have felt bad about that.',
      'Oh, I\'ve totally got this.',
      'Fuck that guy.  He was a dick.',
      'This is going very well.  I feel powerful!',
      'Bring it on.  I\'ll take it all on!',
      'Come get some, demons!  Taste my badassary!!',
      'That\'s it.  I\'ve conquered my fears.'
    ],
    messagesShown: 10 
  };
  
  var worldProps = {
    origin: sharedProps.origin,
    roomAvgWidth: 8,
    roomAvgHeight: 8,
    roomMaxVariance: 5,
    roomCount: 30,
    worldWidth: 78,
    worldHeight: 78,
    wallWidth: 2
  };
  
  var playerProps = {
    origin: sharedProps.origin,
    distancePerLevel: sharedProps.distancePerLevel,
    vision: 10,
    xRayVision: false,
    baseLevel: 0,
    baseAttack: .6,
    baseDamage: 1,
    damageVariance: .5,
    attackVariance: 0,
    baseHP: 15,
    baseXP: 0,
    HPWarningThreshold: .2,
    HPPerLevel: 5,
    lowHealthMessage: 'I don\'t know if I can do this.  I need some good memories to balance all this out.',
    superLowHealthMessage: 'I\'m about ready to forget this.  I need a good memory NOW or I\'m out.',
    lowHealthRecoveredMessage: 'Maybe I can do this.  I can do this.',
    baseAttackMultiPerLevel: 1.05,
    baseDamageMultiPerLevel: 1.05,
    speed: 1,
    hpDropPerStep: 0,
    initialWeaponIndex: 0,
    nextLevelAt: [20, 50, 100, 200, 400, 800, 1400]
  };
  
  var itemProps = {
    origin: sharedProps.origin,
    density: 0.005,
    baseLevel: 1,
    atEndOfCorridors: true,
    distancePerLevel: sharedProps.distancePerLevel,
    weaponFreq: .4, // healingItemFreq + weaponFreq + storyItemFreq = 1
    healingItemFreq: .2,
    storyItemFreq: .4,
    weapons: [
      {type: 'weapon', name: 'alone', attackMulti: 1, damageMulti: 1, level: 0, pronoun: '', pronoun2: '',
        firstTimeMessage: 'Sometimes, you have to go it alone.'},
      {type: 'weapon', name: 'stuffed rhino', attackMulti: 1.1, damageMulti: 1.5, level: 1, pronoun: 'a', pronoun2: 'another',
        firstTimeMessage: 'This rhino kept was my best friend when I was a kid.  He\'ll help me out here.'},
      {type: 'weapon', name: 'band hoodie', attackMulti: 1.2, damageMulti: 2.5, level: 2, pronoun: 'a', pronoun2: 'another',
        firstTimeMessage: 'I wore this thing all over middle school!  Green Day got me through some shit.  Behold its power, demons!'},
      {type: 'weapon', name: 'drum sticks', attackMulti: 1, damageMulti: 4, level: 3, pronoun: 'my', pronoun2: 'some more',
        firstTimeMessage: 'Drumming gave me some serious catharsis.'},
      {type: 'weapon', name: 'guitar', attackMulti: 1.2, damageMulti: 7, level: 4, pronoun: 'my', pronoun2: 'another',
        firstTimeMessage: 'I shredded the world on this guitar.  Let\'s shred again.  Oh yes.'},
      {type: 'weapon', name: 'parents', attackMulti: 1.4, damageMulti: 9, level: 5, pronoun: 'my', pronoun2: 'my',
        firstTimeMessage: 'Coming out to my parents was the hardest thing I have ever done - I was sure they were going to kick me out.  But no.  Finally, finally  I could live as myself.'}
    ],
    healingItems: [
      {},
      {type: 'healing-item', name: 'LEGOs', hpHeal: 5, level: 1, pronoun: 'some', pronoun2: 'some more',
        firstTimeMessage: 'Sometimes the little things can make you feel so much better, like playing with those tiny bricks with my brother all those years ago.'},
      {type: 'healing-item', name: 'CD', hpHeal: 10, level: 2, pronoun: 'a', pronoun2: 'another',
        firstTimeMessage: 'We spent so much time lying on her bed and sharing headphones.'},
      {type: 'healing-item', name: 'birthday cake', hpHeal: 15, level: 3, pronoun: 'a', pronoun2: 'another',
        firstTimeMessage: 'That\'s the cake from my fifteenth birthday!  I can\'t believe I didn\'t see it coming when they pushed my nose in the first slice.'},
      {type: 'healing-item', name: 'shot glass', hpHeal: 20, level: 4, pronoun: 'a', pronoun2: 'another',
        firstTimeMessage: 'Those nights out with friends were the absolute best.  Oh man, this reminds me of the night I made out with Lauren.  That was so my first time with a girl....' },
      {type: 'healing-item', name: 'music', hpHeal: 40, level: 5, pronoun: 'our', pronoun2: 'more',
        firstTimeMessage: 'There\'s music playing here.  It\'s from our band!  Nobody ever bought our merch, but I still think our sound was just ahead of its time.  Totes.'},
      {type: 'healing-item', name: 'furniture from the apartment', hpHeal: 80, level: 6, pronoun: '', pronoun2: 'more',
        firstTimeMessage: 'I loved this apartment.  My absolute happiest memories are from here.'}
    ],
    storyItems: [
      {},
      {type: 'story-item', name: 'note passed in class', pronoun: 'a', pronoun2: 'another',
       firstTimeMessage: 'It\'s the first note Val ever passed me when we were little kids.  "Where did you move from?  You sound funny."'},
      {type: 'story-item', name: 'IM', pronoun: 'an', pronoun2: 'another',
      firstTimeMessage: 'We would spend ungodly amounts of time on AIM, chatting away about way more than we knew about.  Geeze, she sent me a link to the first porn I ever saw.  God, I was so naive.'},
      {type: 'story-item', name: 'message from my car\'s windshield', pronoun: 'a', pronoun2: 'another',
       firstTimeMessage: 'She left this on my car when she finished with class that day.  "You are invited to a seduction.  Grasssa Pasta.  7pm.  Dress nice."  Hot.'},
      {type: 'story-item', name: 'whiteboard note', pronoun: 'a', pronoun2: 'another',
      firstTimeMessage: '"Next time, put a sock on your doorknob or something!"  I could be such a bitch sometimes, really.  I seriously screwed up with that.'},
      {type: 'story-item', name: 'email', pronoun: 'an', pronoun2: 'another',
      firstTimeMessage: 'This is from when I was studying abroad in Chile.  It sounds like I was having such a great time.  I missed her so much, and told her in every single email.  I think that\'s why I found Isadora.'},
      {type: 'story-item', name: 'love letter', pronoun: 'a', pronoun2: 'another',
      firstTimeMessage: 'This letter was the first time I said "I love you."  I wrote it after we had that huge fight.  It was truest, most desparate thing I ever wrote.'},
      {type: 'story-item', name: 'note on the kitchen table', pronoun: 'a', pronoun2: 'another',
      firstTimeMessage: 'It was...the end.  I had fucked up too many times.  She couldn\'t take it any more.  I knew I didn\'t deserve her and I just lept towards the relationship self-destruct button.  I fucked him - it was so, so stupid.  When she found out what I had done...there was just no getting over it.  Even though I had steered us toward that cliff, I had no idea how much hitting the bottom would hurt.  I would do anything for just one do-over.  If there was any one thing I ever did that I wish I could change, it would be this.'}
    ]
  };
  
  var enemyProps = {
    /*
        enemies are personal demons or different versions / ages of yourself -\
          you as a little kid, etc.
          The Patriarchy
          parent of first girlfriend
          self in college
          car from an accident
          friend who I couldn't save
          disappointed brother
          self while studying abroad*/
    origin: sharedProps.origin,
    baseLevel: 0,
    atEndOfCorridors: false,
    density: 0.006,
    distancePerLevel: sharedProps.distancePerLevel,
    enemies: [
      {name: 'spider', attack: .8, damage: 1, hp: 3, xp: 10, level: 0, pronoun: 'The',
        firstTimeMessage: 'It\'s a spider!  I hate spiders.  I can squish it or try to run away.'},
      {name: '"friend"', attack: .8, damage: 1.5, hp: 5, xp: 20, level: 1, pronoun: 'My',
        firstTimeMessage: 'Oh god, it\'s dustin.  Why couldn\'t I see how horrible he was to me?'},
      {name: 'vicious dog', attack: .9, damage: 2, hp: 10, xp: 30, level: 2, pronoun: 'The neighbor\'s',
        firstTimeMessage: 'The neighbor\'s dog is such a bitch!  That scar is not going away.'},
      {name: 'heckler', attack: 1, damage: 4, hp: 20, xp: 40, level: 3, pronoun: 'The',
        firstTimeMessage: 'There was always that one douche yelling at us while we played our set.  He got way too far under my skin.'},
      {name: 'ex-lover', attack: .6, damage: 6, hp: 30, xp: 50, level: 4, pronoun: 'My',
        firstTimeMessage: 'Laura.  She was just wonderful.  I was terrible for her.  I\'ve got to face up to that.'},
      {name: 'Val', attack: .7, damage: 8, hp: 60, xp: 90, level: 5, pronoun: '',
        firstTimeMessage: 'It\'s Valerie - the love of my life and the ghost of my terrible mistakes.  She\'s the best thing that ever happened to be, and I\'m the worst thing that ever happened to her.'}
    ]
  };
  
  //////// Object Constructors
  
  function MessageList(messageProps, enemyProps, itemProps) {
    this.messageProps = messageProps;
    this.namedMessages = this.copyNamedMessages(messageProps, enemyProps, itemProps);
    this.levelMessages = this.copyLevelMessages(messageProps);
    
    this.messages = [];
    this.add(messageProps.initialMessages);
  };
  
  MessageList.prototype.copyLevelMessages = function(messageProps) {
    return messageProps.levelMessages.slice(0);
  };
  
  MessageList.prototype.copyNamedMessages = function(messageProps, enemyProps, itemProps) {
    
    var messageList = {};
    messageProps.triggeredMessages.forEach(function(trigger) {
      messageList[trigger.name] = trigger.firstTimeMessage;
    });
    
    enemyProps.enemies.forEach(function(enemy) {
      messageList[enemy.name] = enemy.firstTimeMessage;
    });
    
    itemProps.healingItems.forEach(function(item) {
      messageList[item.name] = item.firstTimeMessage;
    });
    
    itemProps.weapons.forEach(function(weapon) {
      messageList[weapon.name] = weapon.firstTimeMessage;
    });
    
    itemProps.storyItems.forEach(function(item) {
      messageList[item.name] = item.firstTimeMessage;
    });
    
    return messageList;
  };
  
  MessageList.prototype.get = function() {
    return this.messages.slice(0, this.messageProps.messagesShown);
  };
  
  MessageList.prototype.getNamedMessagesFor = function(named) {
    return this.getMessageNamed(named.name);
  };
  
  MessageList.prototype.getMessageNamed = function(name) {
    var message, namedMessages = this.namedMessages;
    if (namedMessages[name]) {
      message = namedMessages[name];
      delete namedMessages[name];
    }
    return message;
  };
  
  MessageList.prototype.getLevelMessagesFor = function(player) {
    if (player.level !== player.playerProps.baseLevel) {
      var message = this.levelMessages[player.level];
      if (message) {
        delete this.levelMessages[player.level];
      }
      return message;
    }
  };
  
  MessageList.prototype.add = function(messages) {
    if (messages) {
      if (typeof messages === 'object') {
        messages.forEach(function(message) {
          this.messages.unshift(message);
        }.bind(this));
      } else {
        this.messages.unshift(messages);
      }
    }
  };
  
  MessageList.prototype.addPendingMessage = function(message) {
    if (message) {
      if (this.pendingMessages) {
        this.pendingMessages.push(message);
      } else {
         this.pendingMessages = [message];
      }
    }
  };
  
  function Screen(screenProps, player, world) {
    this.screenProps = screenProps;
    this.player = player;
    this.world = world;
    this.grid = [];
    this.top = 0;
    this.left = 0;
    this.clearVisibleLists();
    this.setGrid();
    this.update(player.location.x, player.location.y);
  };
  
  Screen.prototype.forEachGridCell = function(callback) {
    this.grid.forEach(function(row, y) {
      row.forEach(function(cell, x) {
        callback(cell, x, y);
      }.bind(this));
    }.bind(this));
  };
  
  Screen.prototype.shiftGrid = function(x, y) {
    this.top += y;
    this.left += x;
    this.setGrid();
  };
  
  Screen.prototype.setGrid = function(left, top) {
    var x, y,
        world = this.world,
        left = left || this.left, 
        top = top || this.top,
        width = this.screenProps.width, 
        height = this.screenProps.height;
    this.grid = [];
    
    for (y = top; y < top + height; y += 1) {
      var row = [];
      for (x = left; x < left + width; x += 1) {
        row.push(world.cellAt(x, y));
      }
      this.grid.push(row);
    }
  };
  
  Screen.prototype.update = function(x, y) {
    var shift = this.shouldShift(x, y);
    if (shift) {
      this.shiftGrid(shift.x, shift.y)
    }
    
    this.updateVisible(x, y);
  };
  
  Screen.prototype.shouldShift = function(x, y) {
    var x = x || 0,
        y = y || 0,
        edgePad = this.screenProps.playerEdgePad,
        worldWidth = this.world.worldProps.worldWidth,
        worldHeight = this.world.worldProps.worldHeight,
        screenWidth = this.screenProps.width,
        screenHeight = this.screenProps.height,
        left = this.left,
        right = this.left + screenWidth,
        top = this.top,
        bottom = this.top + screenHeight,
        distFromL = x - this.left, 
        distFromR = this.left + screenWidth - x,
        distFromT = y - this.top,
        distFromB = this.top + screenHeight - y,
        xShift = 0, yShift = 0;
    
    if (left > 0 && distFromL < edgePad) {
      xShift = distFromL - edgePad;
    } else if (right < worldWidth && distFromR < edgePad) {
      xShift = edgePad - distFromR;
    }
    if (top > 0 && distFromT < edgePad) {
      yShift = distFromT - edgePad;
    } else if (bottom < worldHeight && distFromB < edgePad) {
      yShift = edgePad - distFromB;
    }
    
    if (xShift || yShift) {
      return {x: xShift, y: yShift};
    } else {
      return false;
    }
  };
  
  Screen.prototype.clearVisibleLists = function() {
    this.visibleCells = [];
    this.visibleEnemies = [];
    this.visibleHealingItems = [];
    this.visibleWeapons = [];
    this.visibleStoryItems = [];
  };
  
  Screen.prototype.updateVisible = function(x, y) {
    this.clearVisibleLists();
    var visibleCells = [], shadows = [];
    
    this.forEachGridCell(function(cell) {
      if (cell) {
        if (cell.visible) { delete cell.visible; }
        if (cell.distFromPlayer) { delete cell.distFromPlayer; }
        var distFromPlayer = cell.distanceFrom(x, y);
        if (distFromPlayer < this.player.vision) { 
          cell.distFromPlayer = distFromPlayer;
          visibleCells.push(cell);
        }
      }
    }.bind(this));
    
    if (this.player.xRayVision) {
      this.visibleCells = visibleCells;
      visibleCells.forEach(function(cell) {
        cell.visible = true;
        cell.seen = true;
        this.addCellContentsToVisibleLists(cell);
      }.bind(this));
    } else {
      visibleCells.sort(function(a, b) {
        return a.distFromPlayer < b.distFromPlayer ? -1 : 1;
      });

      visibleCells.forEach(function(cell) {
        var inShadow = cell.inShadow(x, y, shadows);
        if (!inShadow) {
          this.visibleCells.push(cell);
          cell.visible = true;
          cell.seen = true;
          if (cell.wall) {
            var newShadows = cell.shadowAnglesFrom(x, y);
            newShadows.forEach(function(newShadow) {
              shadows.push(newShadow);
            });
          }
          this.addCellContentsToVisibleLists(cell);
        }
      }.bind(this));  
    }
    
    this.world.moveEnemies(this.visibleEnemies, this.player);
  };
  
  Screen.prototype.addCellContentsToVisibleLists = function(cell) {
    if (cell.enemy) { this.visibleEnemies.push(cell.enemy); }
    if (cell.item) {
      if (cell.item.type === 'weapon') {
        this.visibleWeapons.push(cell.item);
      } else if (cell.item.type === 'healing-item') {
        this.visibleHealingItems.push(cell.item);
      } else {
        this.visibleStoryItems.push(cell.item);
      }
    }
  };
  
  Screen.prototype.fadeToBlack = function() {
    this.clearVisibleLists();
    this.forEachGridCell(function(cell) {
      delete cell.visible;
    });
  };
  
  function Cell(cell) {
    for (var key in cell) {
      this[key] = cell[key];
    };
  };

  Cell.prototype.isInVisualRangeOf = function(player) {
    return this.distanceFrom(player.location.x, player.location.y) < player.vision;
  };
  
  Cell.prototype.distanceFrom = function(x, y) {
    return Math.sqrt(Math.pow(this.x - x, 2) + Math.pow(this.y - y, 2));
  };
  
  Cell.prototype.angleFrom = function(x, y) {
    return Math.atan2(this.y - y, this.x - x);
  };
  
  Cell.prototype.shadowAnglesFrom = function(x, y) {
    var delY = this.y - y, delX = this.x - x,
        begin, end, shadowAngles, cornerAngles = [
      Math.atan2(delY + .5, delX - .5),
      Math.atan2(delY - .5, delX - .5),
      Math.atan2(delY - .5, delX + .5),
      Math.atan2(delY + .5, delX + .5)
    ]
    cornerAngles.sort(function(a, b) {
      return a - b;
    });
    
    if (delX < 0 && delY === 0) {
      shadowAngles = [{
        begin: cornerAngles[2],
        end: 5
      },{
        begin: -5,
        end: cornerAngles[1]
      }]
    } else {
      shadowAngles = [{
        begin: cornerAngles[0],
        end: cornerAngles[3]
      }]
    }
    
    return shadowAngles;
  };
  
  Cell.prototype.inShadow = function(fromX, fromY, shadows) {
    var shadowed = true, visiblePoints = 0, 
        dist = this.distanceFrom(fromX, fromY),
        visiblePointAngles = [
          this.angleFrom(fromX + .5, fromY + .5),
          this.angleFrom(fromX - .5, fromY + .5),
          this.angleFrom(fromX + .5, fromY - .5),
          this.angleFrom(fromX - .5, fromY - .5)
        ];
    
    for (var i in shadows) {
      visiblePointAngles = visiblePointAngles.filter(function(angle) {
        return !(shadows[i].begin < angle && angle < shadows[i].end);
      });
      if (visiblePointAngles.length === 0) {
        return true;
      }
    }
    
    return false;
  };
  
  
  function Item(itemProps, x, y, level, isWeapon, isHealingItem, isStoryItem) {
    var distFromOrigin = Math.sqrt(Math.pow(x - itemProps.origin.x, 2) +
                                   Math.pow(y - itemProps.origin.y, 2)),
        freq = Math.random(),
        modelItem;
    if (typeof level === 'number') {
      this.level = level;
    } else {
      this.level = Math.floor(distFromOrigin / itemProps.distancePerLevel) + 
                   itemProps.baseLevel;
    }
    
    if (isWeapon || (!isHealingItem && !isStoryItem && freq < itemProps.weaponFreq)) {
      modelItem = itemProps.weapons[this.level];
    } else if (isHealingItem || (!isStoryItem && freq < itemProps.weaponFreq + itemProps.healingItemFreq)) {
      modelItem = itemProps.healingItems[this.level];
    } else {
      modelItem = itemProps.storyItems[this.level];
    }
    
    for (var prop in modelItem) {
      modelItem.hasOwnProperty(prop) ? this[prop] = modelItem[prop] : false;
    }
    this.x = x;
    this.y = y;
  };
  
  
  function Enemy(enemyProps, x, y) {
    var distFromOrigin = Math.sqrt(Math.pow(x - enemyProps.origin.x, 2) +
                                   Math.pow(y - enemyProps.origin.y, 2)),
        modelEnemy;
    this.x = x;
    this.y = y;
    this.level = Math.floor(distFromOrigin / enemyProps.distancePerLevel) + 
                enemyProps.baseLevel; 
    modelEnemy = enemyProps.enemies[this.level];
    for (var prop in modelEnemy) {
      modelEnemy.hasOwnProperty(prop) ? this[prop] = modelEnemy[prop] : false;
    }
  };
  

  function World(worldProps, enemyProps, itemProps) {
    this.worldProps = worldProps;
    this.enemyProps = enemyProps;
    this.itemProps = itemProps;
    
    this.initialize();
  };
  
  World.prototype.initialize = function() {
    this.grid = [];
    this.items = [];
    this.enemies = [];
    this.itemsRemoved = [];
    this.enemiesRemoved = [];
    
    this.makeTabulaRasa();
    this.makeCorridors();
    this.makeRooms();
    this.addItems();
    this.addEnemies();
    this.convertToCells();
  };
  
  World.prototype.forEachGridCell = function(callback) {
    this.grid.forEach(function(row, y) {
      row.forEach(function(cell, x) {
        callback(cell, x, y);
      }.bind(this));
    }.bind(this));
  };
  
  World.prototype.makeTabulaRasa = function() {
    var y, x, key = 0;
    
    for (y = 0; y < this.worldProps.worldHeight; y += 1) {
      var row = [];
      for (x = 0; x < this.worldProps.worldWidth; x += 1) {
        var cell = {id: key, x: x, y: y, wall: true};
        key += 1;
        row.push(cell);
      }
      this.grid.push(row);
    }
  };

  World.prototype.makeCorridors = function() {
    var that = this;
    function canBeMovedTo(x, y) {
      return that.grid[y] &&
        that.grid[y][x] &&
        that.grid[y][x].wall;
    };
    
    var startX = 1, startY = 1, 
        xCursor = 1, yCursor = 1, 
        history=[[startX, startY]],
        lastHistoryLength = 0;
    
    while (history.length) {
      var validAdjacents = [], spacing = this.worldProps.wallWidth + 1;
      if (xCursor > 1 && canBeMovedTo(xCursor - spacing, yCursor)) {
        validAdjacents.push('L');
      };
      if (xCursor < this.worldProps.worldWidth - 1 && 
          canBeMovedTo(xCursor + spacing, yCursor)) {
        validAdjacents.push('R');
      };
      if (yCursor > 1 && canBeMovedTo(xCursor, yCursor - spacing)) {
        validAdjacents.push('U');
      };
      if (yCursor < this.worldProps.worldHeight - 1 && 
          canBeMovedTo(xCursor, yCursor + spacing)) {
        validAdjacents.push('D');
      };

      if (validAdjacents.length) {
        lastHistoryLength = history.length;
        history.push([xCursor, yCursor]);

        var randomIndex = Math.floor(Math.random() * validAdjacents.length)
        var moveDirection = validAdjacents[randomIndex];

        if (moveDirection == 'L') {
          for (var i = 1; i <= spacing; i += 1) {
            this.grid[yCursor][xCursor - i].wall = false;
            this.grid[yCursor][xCursor - i].corridor = true;
          }
          xCursor -= spacing;
        } else if (moveDirection === 'R') {
          for (var i = 1; i <= spacing; i += 1) {
            this.grid[yCursor][xCursor + i].wall = false;
            this.grid[yCursor][xCursor + i].corridor = true;
          }
          xCursor += spacing;
        } else if (moveDirection === 'U') {
          for (var i = 1; i <= spacing; i += 1) {
            this.grid[yCursor - i][xCursor].wall = false;
            this.grid[yCursor - i][xCursor].corridor = true;
          }
          yCursor -= spacing;
        } else if (moveDirection === 'D') {
          for (var i = 1; i <= spacing; i += 1) {
            this.grid[yCursor + i][xCursor].wall = false;
            this.grid[yCursor + i][xCursor].corridor = true;
          }
          yCursor += spacing;
        }

      } else {
        if (lastHistoryLength < history.length) {
          this.grid[yCursor][xCursor].endOfCorridor = true;
        }
        var backtrack = history.pop();

        xCursor = backtrack[0];
        yCursor = backtrack[1];
      }
    }
  };

  World.prototype.makeRooms = function() {
    function randomAToB(a, b) {
      return a + Math.floor((b - a) * Math.random());
    }
    var rooms = this.worldProps.roomCount,
        avgWidth = this.worldProps.roomAvgWidth,
        avgHeight = this.worldProps.roomAvgHeight,
        maxVariance = this.worldProps.roomMaxVariance,
        possXMin = 1, possYMin = 1,
        possXMax = this.worldProps.worldWidth - avgWidth - maxVariance,
        possYMax = this.worldProps.worldHeight - avgHeight - maxVariance;

    for (var room = 0; room < rooms; room += 1) {
      var width = avgWidth + randomAToB(-maxVariance, maxVariance),
          height = avgHeight + randomAToB(-maxVariance, maxVariance),
          xMin = randomAToB(possXMin, possXMax),
          yMin = randomAToB(possYMin, possYMax);

      for (var x = xMin; x <= xMin + width; x += 1) {
        for (var y = yMin; y <= yMin + height; y += 1) {
          this.grid[y][x].wall = false;
          this.grid[y][x].corridor = false;
          this.grid[y][x].room = true;
          delete this.grid[y][x].endOfCorridor;
        }
      }
    };
  };

  World.prototype.addEnemy = function (x, y) {
    var enemy = new Enemy(this.enemyProps, x, y);
    this.enemies.push(enemy);
    this.grid[y][x].enemy = enemy;
    return enemy;
  };

  World.prototype.addItem = function(x, y, item) {
    item = item || new Item(this.itemProps, x, y);
    this.items.push(item);
    this.grid[y][x].item = item;
    return item;
  };
  
  World.prototype.replaceItemWithHealing = function(x, y) {
    var oldItem = this.grid[y][x].item,
        newItem = new Item(this.itemProps, x, y, oldItem.level, false, true);
    this.addItem(x, y, newItem);
  };

  World.prototype.addItems = function(toAdd) {
    this.forEachGridCell(function(cell, x, y) {
      if (((cell.endOfCorridor && this.itemProps.atEndOfCorridors) || 
         (!cell.enemy && cell.wall === false && Math.random() < this.itemProps.density)) &&
         !(x === this.worldProps.origin.x && y === this.worldProps.origin.y)) {
        this.addItem(x, y);
      }
    }.bind(this));
  };
  
  World.prototype.addEnemies = function() {
    this.forEachGridCell(function(cell, x, y) {
      if (((cell.endOfCorridor && this.enemyProps.atEndOfCorridors) ||
         (!cell.item && cell.wall === false && Math.random() < this.enemyProps.density)) &&
         !(x === this.worldProps.origin.x && y === this.worldProps.origin.y)) {
        this.addEnemy(x, y);
      }
    }.bind(this));
    this.addBoss();
  };
  
  World.prototype.addBoss = function() {
    var boss, wProps = this.worldProps, 
        lastClearRow = 1 + (1 + wProps.wallWidth) * Math.floor((wProps.worldHeight - 2) / 
                                                       (wProps.wallWidth + 1)),
        lastClearCol = 1 + (1 + wProps.wallWidth) * Math.floor((wProps.worldWidth - 2) / 
                                                       (wProps.wallWidth + 1));
    boss = this.addEnemy(lastClearCol, lastClearRow);
    this.boss = boss;
    return boss;
  };
  
  World.prototype.bossIsDead = function() {
    return this.boss.hp <= 0;
  };

  World.prototype.convertToCells = function() {
    for (var i = 0; i < this.grid.length; i += 1) {
      for (var j = 0; j < this.grid.length; j += 1) {
        this.grid[i][j] = new Cell(this.grid[i][j]);
      }
    }
  };

  World.prototype.cellAt = function(x, y) {
    return this.grid[y][x];
  };

  World.prototype.removeItemAt = function(x, y) {
    var itemRemoved = this.cellAt(x, y).item;
    for (var i = this.items.length; i >= 0; i -= 1) {
      if (this.items[i] == itemRemoved) { this.items.splice(i, 1); }
    }
    if (itemRemoved.type !== 'healing-item') {
      this.items.filter(function(item) {
        return item.level == itemRemoved.level && 
               item.type == itemRemoved.type &&
               !this.cellAt(item.x, item.y).seen;
      }.bind(this)).forEach(function(item) {
        this.replaceItemWithHealing(item.x, item.y);
      }.bind(this))
    }
    this.itemsRemoved.push(itemRemoved);
    delete this.cellAt(x, y).item;
  };

  World.prototype.removeEnemyAt = function(x, y) {
    var enemyRemoved = this.cellAt(x, y).enemy;
    for (var i = this.enemies.length; i >= 0; i -= 1) {
      if (this.enemies[i] == enemyRemoved) { this.enemies.splice(i, 1); }
    }
    this.enemiesRemoved.push(enemyRemoved)
    delete this.cellAt(x, y).enemy;
  };
  
  World.prototype.moveEnemies = function(enemies, player) {
    var playerLoc = player.location;
    enemies.forEach(function(enemy) {
      if (Math.abs(enemy.x - playerLoc.x) <= 1 && Math.abs(enemy.y - playerLoc.y) <= 1) {
        player.fight(enemy, playerLoc.x, playerLoc.y);
        if (enemy.destroyed) {
          this.removeEnemyAt(enemy.x, enemy.y);
        }
      } else {
        var moved, moveX = 0, moveY = 0,
            deltaX = playerLoc.x - enemy.x, 
            deltaY = playerLoc.y - enemy.y;
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
          moveX = deltaX > 0 ? 1 : -1;
        } else {
          moveY = deltaY > 0 ? 1 : -1;
        }
        moved = this.moveEnemyTo(enemy, enemy.x + moveX, enemy.y + moveY);
        if (!moved) {
          if (moveX !== 0) {
            moveY = deltaY > 0 ? 1 : -1;
            moveX = 0;
          } else {
            moveX = deltaX > 0 ? 1 : -1;
            moveY = 0;
          }
          this.moveEnemyTo(enemy, enemy.x + moveX, enemy.y + moveY);
        }
      }
    }.bind(this))
  };
  
  World.prototype.moveEnemyTo = function(enemy, x, y) {
    var cellFrom = this.cellAt(enemy.x, enemy.y),
        cellTo = this.cellAt(x, y);
    if (!cellTo.wall && !cellTo.enemy) {
      cellTo.enemy = cellFrom.enemy;
      delete cellFrom.enemy;
      enemy.x = x;
      enemy.y = y;
      return true;
    } else {
      return false;
    }
  };

  

  function Player(playerProps, itemProps) {
    this.itemProps = itemProps;
    this.playerProps = playerProps;
    
    this.initialize();
  };
  
  Player.prototype.initialize = function() {
    this.living = true;
    this.vision = this.playerProps.vision;
    this.xRayVision = this.playerProps.xRayVision;
    this.speed = this.playerProps.speed;
    this.location = {
      x: this.playerProps.origin.x,
      y: this.playerProps.origin.y
    };
    this.distFromOrigin = 0;
    this.level = this.playerProps.baseLevel;
    this.baseAttack = this.playerProps.baseAttack;
    this.baseDamage = this.playerProps.baseDamage;
    this.hp = this.playerProps.baseHP;
    this.maxHp = this.hp;
    this.hpWarning = false;
    this.hpDireWarning = false;
    this.xp = this.playerProps.baseXP;
    var startingWeapon = new Item(this.itemProps, this.location.x, this.location.y, 0, true);
    this.weaponInventory = [startingWeapon];
    this.equipWeapon(this.weaponInventory[0]);
  };
  
  Player.prototype.moveTo = function(x, y) {
    this.changeHpBy(-this.playerProps.hpDropPerStep);
    this.location.x = x;
    this.location.y = y;
    this.distFromOrigin = Math.sqrt(Math.pow(this.location.x - this.playerProps.origin.x, 2) +
                                    Math.pow(this.location.y - this.playerProps.origin.y, 2));
  };
  
  Player.prototype.aquireItem = function(item) {
    if (item.type === 'weapon') {
      this.weaponInventory.push(item);
      if (item.level > this.equippedWeapon.level) { this.equipWeapon(item); }
    } else if (item.type === 'healing-item') {
      this.changeHpBy(item.hpHeal);
    }
  };

  Player.prototype.equipWeapon = function(weapon) {
    this.equippedWeapon = weapon;
    this.attack = this.baseAttack * weapon.attackMulti;
    this.damage = this.baseDamage * weapon.damageMulti;
  };
  
  Player.prototype.setHp = function(hp) {
    this.changeHpBy(hp - this.hp)
  };
  
  Player.prototype.changeHpBy = function(deltaHp) {
    this.hp = Math.round(this.hp * 100 + deltaHp * 100) / 100;
    if (this.hp > this.maxHp) { this.maxHp = this.hp; }
    if (this.hpWarning && this.hp > this.maxHp * this.playerProps.HPWarningThreshold) {
      this.hpWarning = false;
      this.addPendingMessage(this.playerProps.lowHealthRecoveredMessage);
    };
    if (!this.hpWarning && this.hp <= this.maxHp * this.playerProps.HPWarningThreshold) {
      this.hpWarning = true;
      this.addPendingMessage(this.playerProps.lowHealthMessage);
    };
    if (this.hp <= 0) {
      this.hp = 0;
      this.dies();
    } else if (this.hpDireWarning === false && this.hp <= 2) {
      this.addPendingMessage(this.playerProps.superLowHealthMessage);
      this.hpDireWarning = true;
    } else if (this.hpDireWarning === true && this.hp > 2) {
      this.hpDireWarning = false;
    }
  };
  
  Player.prototype.levelUpIfIShould = function() {
    if (this.xp >= this.playerProps.nextLevelAt[this.level]) {
      this.level += 1;
      this.baseAttack = this.baseAttack * this.playerProps.baseAttackMultiPerLevel;
      this.baseDamage = this.baseDamage * this.playerProps.baseDamageMultiPerLevel;
    }
  };

  Player.prototype.fight = function(enemy, x, y) {
    var messages = [];

    if (Math.random() <= enemy.attack) {
      var attackDamage = Math.round(enemy.damage + Math.round(enemy.damage * Math.random() *
                                                              this.playerProps.damageVariance));
      this.changeHpBy(-attackDamage);
      // messages.push('The ' + enemy.name + ' hit you for ' + attackDamage + ' damage.');
      messages.push(enemy.pronoun + ' ' + enemy.name + ' hit me.');
    } else {
      messages.push(enemy.pronoun + ' ' + enemy.name + ' missed me.');
    }

    if (Math.random() <= this.attack) {
      var attackDamage = Math.round(this.damage + Math.round(this.damage * Math.random() *
                                                             this.playerProps.damageVariance));
      enemy.hp -= attackDamage;
      // messages.push('You hit the ' + enemy.name + ' for ' + attackDamage + ' damage.');
      messages.push('I hit ' + enemy.pronoun.toLowerCase() + ' ' + enemy.name + '.');
    } else {
      messages.push('I missed.');
    }

    if (enemy.hp <= 0) { 
      this.xp += enemy.xp;
      enemy.destroyed = true;
      messages.push('I destroyed it!');
    };

    this.addPendingMessage(messages.join(' '));
    this.levelUpIfIShould();
  };
  
  Player.prototype.addPendingMessage = function(message) {
    if (message) {
      if (this.pendingMessages) {
        this.pendingMessages += ' ' + message;
      } else {
         this.pendingMessages = message;
      }
    }
  };
  
  Player.prototype.isAlive = function() {
    return this.living;
  };
  
  Player.prototype.dies = function() {
    this.living = false;
  };
  
  /////////// Flux Definitions
  
  var _sources, _world, _player, _messages, _screen;
  
  function InitializeGame() {
    _world = new World(worldProps, enemyProps, itemProps);
    _player = new Player(playerProps, itemProps);
    _messages = new MessageList(messageProps, enemyProps, itemProps);
    _screen = new Screen(screenProps, _player, _world);
    _sources = [_world, _player, _messages, _screen];
  };
  
  InitializeGame();
  
  var rogueDispatcher = new Flux.Dispatcher();
  
  var worldStore = new EventEmitter(),
      playerStore = new EventEmitter(),
      screenStore = new EventEmitter(),
      messageStore = new EventEmitter(),
      stores = [worldStore, playerStore, screenStore, messageStore]
  
  rogueDispatcher.register(function(payload) {
    if (payload.actionType === 'RESTART') {
      InitializeGame();
    }
  });
  
  ////World Store Methods
  worldStore.getAll = function() {
    return {grid: _world.grid,
            worldProps: _world.worldProps,
            itemProps: _world.itemProps,
            enemyProps: _world.enemyProps};
  };
  
  worldStore.emitChange = function() {
    this.emit('change');
  };

  worldStore.addChangeListener = function(callback) {
    this.on('change', callback);
  };

  worldStore.removeChangeListener = function(callback) {
    this.removeListener('change', callback);
  };
  
  worldStore.dispatchToken = rogueDispatcher.register(function(payload) {
    var actionType = payload.actionType;
    if (_player.isAlive()) {
      switch (actionType) {
        case 'AQUIRE_ITEM':
          _world.removeItemAt(payload.x, payload.y);
          break;
        case 'FIGHT_ENEMY':
          rogueDispatcher.waitFor([playerStore.dispatchToken]);
          if (payload.enemy.destroyed) {
            _world.removeEnemyAt(payload.x, payload.y);
          }
          break;
      }
      worldStore.emitChange();
    };
    return true;
  });
  
  
  //// playerStore methods
  playerStore.getAll = function() {
    //TODO: refactor this so it doesn't pass the methods, just the properties
    return _player;
  };
  
  playerStore.dispatchToken = rogueDispatcher.register(function(payload) {
    var actionType = payload.actionType;
    
    if (_player.isAlive()) {
      switch (actionType) {
        case 'MOVE_PLAYER':
          _player.moveTo(payload.x, payload.y);
          break;
        case 'AQUIRE_ITEM':
          _player.moveTo(payload.x, payload.y);
          _player.aquireItem(payload.item);
          break;
        case 'FIGHT_ENEMY':
          _player.fight(payload.enemy, payload.x, payload.y);
          if (payload.enemy.destroyed) { _player.moveTo(payload.x, payload.y); }
          break;
        case 'EQUIP_WEAPON':
          _player.equipWeapon(payload.weapon);
          break;
        default:
          return true;
      };
      
      playerStore.emitChange();
    }
    
    return true;
  });
  
  
  //// screenStore methods
  screenStore.getAll = function() {
    return _screen.grid;
  };
  
  screenStore.getVisibleEnemies = function() {
    return _screen.visibleEnemies;
  }
  
  screenStore.getVisibleItems = function() {
    return {
              weapons: _screen.visibleWeapons,
              healing: _screen.visibleHealingItems,
              story: _screen.visibleStoryItems
           };
  }
  
  screenStore.dispatchToken = rogueDispatcher.register(function(payload) {
    var actionType = payload.actionType;
    
    rogueDispatcher.waitFor([worldStore.dispatchToken]);
    
    if (_player.isAlive()) {
      switch (actionType) {
        case 'MOVE_PLAYER':
          _screen.update(payload.x, payload.y);
          screenStore.emitChange();
          break;
      };
    } else {
      _screen.fadeToBlack();
      screenStore.emitChange();
    }
    return true;
  });
  
  
  //// messageStore methods
  messageStore.getAll = function() {
    return _messages.get();
  };
  
  messageStore.add = function(item) {
    _messages.add(item);
  };
  
  messageStore.dispatchToken = rogueDispatcher.register(function(payload) {
    var changed, actionType = payload.actionType;
    
    rogueDispatcher.waitFor([playerStore.dispatchToken]);
    rogueDispatcher.waitFor([worldStore.dispatchToken]);
    
    switch (actionType) {
      case 'BEGIN':
        messageStore.add(_messages.getMessageNamed('click'));
        changed = true;
        break;
      case 'MOVE_PLAYER':
        var visibleEnemies = screenStore.getVisibleEnemies(),
            visibleItems = screenStore.getVisibleItems();
        messageStore.add(_messages.getMessageNamed('move'));
        
        if (visibleEnemies.length) {
          messageStore.add(_messages.getMessageNamed('see enemy'));
        }
        visibleEnemies.forEach(function(enemy) {
          messageStore.add(_messages.getNamedMessagesFor(enemy));
        });
        
        if (visibleItems.weapons.length) {
          messageStore.add(_messages.getMessageNamed('see weapon'));
        }
        if (visibleItems.healing.length) {
          messageStore.add(_messages.getMessageNamed('see healing item'));
        }
        if (visibleItems.story.length) {
          messageStore.add(_messages.getMessageNamed('see story item'));
        }
        
        if (_player.distFromOrigin > _player.playerProps.distancePerLevel) {
          messageStore.add(_messages.getMessageNamed('away from origin'));
        }
        if (_player.distFromOrigin > _player.playerProps.distancePerLevel * 2) {
          messageStore.add(_messages.getMessageNamed('further away from origin'));
        }
        
        changed = true;
        break;
      case 'FIGHT_ENEMY':
        if (payload.enemy.destroyed) {
          _messages.addPendingMessage(_messages.getMessageNamed('enemy destroyed'));
        }
        _messages.addPendingMessage(_messages.getMessageNamed('attack'));
        _messages.addPendingMessage(_messages.getLevelMessagesFor(_player));
        changed = true;
        break;
      case 'AQUIRE_ITEM':
        var firstTimeMessage = _messages.getNamedMessagesFor(payload.item);
        if (firstTimeMessage) {
          messageStore.add('I found ' + payload.item.pronoun + ' ' + payload.item.name + '.  ' + firstTimeMessage);
        } else {
          messageStore.add('I found ' + payload.item.pronoun2 + ' ' + payload.item.name);
        }
        changed = true;
        break;
    };
    
    _sources.forEach(function(source) {
      if (source.pendingMessages) {
        changed = true;
        messageStore.add(source.pendingMessages);
        delete source.pendingMessages;
      };
    });
    
    if (!_player.isAlive()) {
      messageStore.add(_messages.getMessageNamed('death'));
      changed = true;
    } else if (_world.bossIsDead()) {
      changed = true;
      messageStore.add(_messages.getMessageNamed('win'));
    }
    
    if (changed) { messageStore.emitChange(); }
    
    return true;
  });
  
  
  
  


  ////////// Common Store Methods

  stores.forEach(function(store) {
    store.emitChange = function() {
      this.emit('change');
    };

    store.addChangeListener = function(callback) {
      this.on('change', callback);
    };

    store.removeChangeListener = function(callback) {
      this.removeListener('change', callback);
    };
  });
  

  /////////// Actions
  
  var rogueActions = {
    restart: function() {
      rogueDispatcher.dispatch({
        actionType: 'RESTART'
      });
    },
    begin: function() {
      rogueDispatcher.dispatch({
        actionType: 'BEGIN'
      });
    },
    message: function(messages) {
      rogueDispatcher.dispatch({
        actionType: 'MESSAGE',
        messages: messages
      });
    },
    markVisibleCells: function(player) {
      rogueDispatcher.dispatch({
        actionType: 'MARK_VISIBLE_CELLS',
        player: player
      });
    },
    equipWeapon: function(weapon) {
      rogueDispatcher.dispatch({
        actionType: 'EQUIP_WEAPON',
        weapon: weapon
      })
    },
    tryToMovePlayerTo: function(x, y) {
      var cell = _world.cellAt(x, y);
      if (cell.wall) {
        rogueDispatcher.dispatch({
          actionType: 'CANT_MOVE',
          x: x, y: y, wall: cell.wall
        });
      } else if (cell.enemy) {
        rogueDispatcher.dispatch({
          actionType: 'FIGHT_ENEMY',
          x: x, y: y, enemy: cell.enemy
        });
      } else if (cell.item) {
        rogueDispatcher.dispatch({
          actionType: 'AQUIRE_ITEM',
          x: x, y: y, item: cell.item
        });
      } else {
        rogueDispatcher.dispatch({
          actionType: 'MOVE_PLAYER',
          x: x, y: y
        });
      }
    }
  };
  
  
  
  
  /////////// React Components
  
  var GridCell = React.createClass({
    render: function() {
      var classes = [], 
          content = '',
          cell = this.props.cell,
          playerLoc = this.props.player.location,
          playerHere = playerLoc.x === cell.x && playerLoc.y === cell.y;
      
      if (cell.visible) { 
        classes.push('visible'); 
        if (playerHere) { classes.push('player'); }
        if (cell.wall)  { classes.push('wall'); }
        if (cell.enemy) {
          classes.push('enemy'); 
          classes.push(cell.enemy.name);
          classes.push('enemy-' + cell.enemy.level);
        }
        if (cell.item)  { 
          classes.push(cell.item.type);
          classes.push(cell.item.type + '-' + cell.item.level);
          classes.push(cell.item.name);
        }
      } else if (cell.seen) {
        classes.push('seen');
        if (cell.wall)  { classes.push('wall'); }
      } else {
        classes.push('unseen');
      }
      
      return ( 
        <td key={cell.id} className={classes.join(' ')}>
          {content}
        </td> 
      );
    }
  });

  var Grid = React.createClass({
    render: function() {
      var gridTableNodes = this.props.screen.map(function(row, y) {
        var rowNodes = row.map(function(cell, x) {
          return ( 
            <GridCell
              player={this.props.player}
              key={cell.id}
              cell={cell}
            /> );
        }.bind(this));
        return ( <tr key={row[0].id}>{rowNodes}</tr> );
      }.bind(this));
      return (
        <table><tbody>
          {gridTableNodes}
        </tbody></table>
      );
    }
  });

  var Status = React.createClass({
    render: function() {
      var player = this.props.player;
      return (
        <div className="centered">
          HP: {player.hp}, XP: {player.xp}, Level: {player.level}
        </div>
      );
    }
  });
  
  var HealthBar = React.createClass({
    render: function() {
      var player = this.props.player,
          barHeight = player.maxHp / 10,
          healthPercentage = (player.hp / player.maxHp) * 100 + '%',
          lowBarOpacity = 0;
      if (player.hpWarning) {
        var hpWarningMax = player.maxHp * player.playerProps.HPWarningThreshold;
        lowBarOpacity = (hpWarningMax - player.hp) / hpWarningMax;
      }
      return(
        <div className="health-bar-wrapper">
          <div className="health-bar" style={{
              width: healthPercentage,
              height: barHeight
            }} />
          <div className="health-bar-low" style={{
              width: healthPercentage,
              height: barHeight,
              opacity: lowBarOpacity
          }} />
        </div>
      )
    }
  })
        
  var Weapon = React.createClass({
    clickHandler: function() {
      rogueActions.equipWeapon(this.props.weapon);
    },
    render: function() {
      var classes = ['weapon'];
      if (this.props.isEquipped) { classes.push('equipped'); }
      return (
        <span onClick={this.clickHandler} className={classes.join(' ')}>
          {this.props.weapon.name}
        </span>
      );
    }
  });

  var InventoryList = React.createClass({
    render: function() {
      var player = this.props.player,
          equippedWeapon = this.props.player.equippedWeapon,
          weaponNodes = [];
      if (player.weaponInventory.length > 1) {
        player.weaponInventory.forEach(function(weapon, i) {
          var isEquipped
          if (weapon === equippedWeapon) { isEquipped = true; }
          weaponNodes.push(
            <Weapon key={i} isEquipped={isEquipped} weapon={weapon}/>
          );
        });
        weaponNodes.sort(function(a, b) {
          return a.level < b.level ? 1 : -1;
        });
        return (
          <div className="inventory-list centered">
            {weaponNodes}
          </div>
        );
      } else {
        return (<div />)
      }
    }
  });
      
  var Messages = React.createClass({
    render: function() {
      var messages = this.props.messages,
          messageCount = this.props.messages.length,
          messageNodes = [],
          i = messageCount - 1;
      
      messages.forEach(function(message, i) {
        var opacity = 1 - (i / messageCount);
        messageNodes.push(<li key={i} style={{opacity: opacity}}>{messages[i]}</li>);
      })
      return (
        <ul>
          {messageNodes}
        </ul>
      );
    }
  });

  var keyIsPressed = false;
  var RogueBox = React.createClass({
    begin: function() {
      if (!this.state.begun) {
        this.setState({begun: true});
        rogueActions.begin();
      }
    },
    restart: function() {
      rogueActions.restart();
      this.setState(this.getInitialState());
    },
    keyboardHandler: function(event) {
      var __player = this.state.player,
          __game = this.state.game,
          __x = __player.location.x, 
          __y = __player.location.y,
          __speed = __player.speed,
          __action = 'NOTHING';
      switch (event.keyCode) {
        case 119: // w
        case 38: // up arrow
          __action = 'MOVING';
          __y -= __speed;
          break;
        case 115: // s
        case 40: // down arrow
          __action = 'MOVING';
          __y += __speed;
          break;
        case 97: // a
        case 37: // left arrow
          __action = 'MOVING';
          __x -= __speed;
          break;
        case 100: // d
        case 39: // right arrow
          __action = 'MOVING';
          __x += __speed;
          break;
      }
      
      if (__action === 'MOVING' && event.type === 'keydown') {
        event.preventDefault();
        rogueActions.tryToMovePlayerTo(__x, __y);
      }
    },
    getRogueState: function() {
      return { 
        world: worldStore.getAll(),
        player: playerStore.getAll(),
        messages: messageStore.getAll(),
        screen: screenStore.getAll()
      };
    },
    getInitialState: function() {
      var initialState = this.getRogueState();
      initialState.begun = false;
      return initialState;
    },
    onChange: function() {
      this.setState(this.getRogueState());
    },
    componentDidMount: function() {
      worldStore.addChangeListener(this.onChange);
      playerStore.addChangeListener(this.onChange);
      messageStore.addChangeListener(this.onChange);
      screenStore.addChangeListener(this.onChange);
      $('body').keydown(function(e) {
        if (!keyIsPressed) {
          keyIsPressed = true;
          this.keyboardHandler(e);
        }
      }.bind(this));
      $('body').keyup(function(e) {
        keyIsPressed = false;
      }.bind(this));
    },
    componentWillUnmount: function() {
      worldStore.removeChangeListener(this.onChange);
      playerStore.removeChangeListener(this.onChange);
      messageStore.removeChangeListener(this.onChange);
      screenStore.removeChangeListener(this.onChange);
    },
    render: function() {
      if (this.state.begun) {
        var restartButtonText = 'Restart';
        if (!this.state.player.isAlive()) {
          restartButtonText = 'My stamina is gone.  Hopefully I can get further next time. Click to restart'
        }
        return (
          <div>
            <div id="restart" 
              onClick={this.restart}
              className={this.state.player.isAlive() ? '' : 'emphasized'}>
                {restartButtonText}
            </div>
            <div className="centered player-space">
              <div className="grid-wrapper">
                <InventoryList className="centered" player={this.state.player} />
                <HealthBar player={this.state.player} />
                <Grid screen={this.state.screen} player={this.state.player}/>
              </div>
            </div>
            <div className="messages">
              <Messages messages={this.state.messages} />
            </div>
          </div>
        );
      } else {
        return (
          <div className="centered bigger">
            <div className="full-screen clickable" onClick={this.begin} />
            <h1>Love Letters</h1>
            <Messages messages={this.state.messages} />
          </div>
        )
      }
    }
  });

////////////// Root React Renderer

  var rogueBox = ReactDOM.render(
    <RogueBox />,
    document.getElementById('mount-point')
  );

})();


  /*  
      TODO
      ====
      
      Story
        Story items - love letters that are emotional or bittersweet
        enemies are personal demons or different versions / ages of yourself -\
          you as a little kid, etc.
          The Patriarchy
          parent of first girlfriend
          self in college
          car from an accident
          friend who I couldn't save
          disappointed brother
          self while studying abroad
        healing items are good memories
        weapons are ?
          What helps you better deal with your demons?
          Allies? Talking with friends and family?
          Anti-suicide hotline
          musician she really connected with
          her guitar
          jacket that was her total security jacket
        
      Messages
        fix order/trigger of messages when fight is called from screen update
        Show message opacity according to how long they've been there
          I think I'd need to initiate a step counter, then fade as the current steps divergecall 
        
      Better distribution of items / weapons / enemies.
        Not just well randomized, but well distributed
        a healing item, pocket knife, and no enemy near the origin.
        a few enemies just beyond
        statistical nudging for too many / too few healing items, weapons, and enemies
      
      Work on the Graphics - both game and info
        HP bar length should be absolute?
        Are these the right fonts?
        resize screen to fit viewable area (accounting for game info)
          dispatch a 'RESIZE' action, 
          caught by the screenStore and expanding/contracting the screen
        */
              
            
!
999px

Console