The Game

Text game engine

by marakoss

HTML

<h1>The game</h1>

<form id="form">
  <input id="command" placeholder="type something">
  <button>Odeslat</button>
</form>
<div id="console" class="console">
</div>

CSS

* {
  box-sizing: border-box;
}
.console {
  width: 100%;
  min-height: 100px;
  max-height: 500px;
  height: 100%;
  padding: 20px;
  border: 1px solid black;
  overflow: auto;
}

#command {
  width: 100%;
  padding: 10px 20px;
  font-size: 16px;
  font-family: monospace;
}

#form {
  position: relative;
}

#form button {
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  background: black;
  border: none;
  color: white;
}

.command {
  color: green;
}

.response {
  color: red;
}

JavaScript

const chat = document.getElementById("console");
const form = document.getElementById("form");
const input = document.getElementById("command");
const saveGameFile = 'myGame';
loadGame();

const historyTypeEnum = Object.freeze({
  COMMAND: Symbol('command'),
  RESPONSE: Symbol('response')
});

form
  .addEventListener("submit", function(event) {
    event.preventDefault();

    const text = readInput();

    gameState.history.push({
      type: historyTypeEnum.COMMAND,
      text: text,
      data: createCommand(text),
      time: new Date().getTime()
    })

    gameState.history.push({
      type: historyTypeEnum.RESPONSE,
      text: getResponse(),
      time: new Date().getTime()
    })

    clearInput();
    writeAllNewMessagesToChat();
    saveGame();
  });

function saveGame() {
  if (!isLocalStorageAvailable()) return

  const gameData = {
    gameState: gameState
  }

  localStorage.setItem(saveGameFile, JSON.stringify(gameData))
}

function loadGame() {
  if (!isLocalStorageAvailable()) return;

  const data = localStorage.getItem(saveGameFile);
  if (data !== null) {
    const gameData = JSON.parse(data);
    gameState = gameData.gameState;
  }
}

function isLocalStorageAvailable() {
  var test = 'test';
  try {
    localStorage.setItem(test, test);
    localStorage.removeItem(test);
    return true;
  } catch (e) {
    console.warn('Cannot store/load gameData');
		return false;
  }
}

const levenshteinDistance = (str1 = '', str2 = '') => {
  const track = Array(str2.length + 1).fill(null).map(() =>
    Array(str1.length + 1).fill(null));
  for (let i = 0; i <= str1.length; i += 1) {
    track[0][i] = i;
  }
  for (let j = 0; j <= str2.length; j += 1) {
    track[j][0] = j;
  }
  for (let j = 1; j <= str2.length; j += 1) {
    for (let i = 1; i <= str1.length; i += 1) {
      const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
      track[j][i] = Math.min(
        track[j][i - 1] + 1, // deletion
        track[j - 1][i] + 1, // insertion
       ...