Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Помощь в отображении кода js (https://javascript.ru/forum/misc/70593-pomoshh-v-otobrazhenii-koda-js.html)

Quorio 18.09.2017 14:09

Помощь в отображении кода js
 
Добрый день! Возник вопрос по отображению кода на странице html. Код позаимствовал у автора, разобраться как это все работает, но увы, запустить у меня его не получается.
<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="utf-8">
  <title>alpha v1.2</title>
<script>
(function(elid, wi, he, exp, pot, gld, hp, lvl, cur_e, e_sz, lap, a, d) {
  var gen = function() {
    evs = [];
    for (var i = 0; i < e_sz - 1; i++)
      evs.push(e_tp[Math.floor(Math.random() * Math.min(8, lap + 2))].slice(0));
    evs.push(e_tp[8].slice(0));
    evs[Math.random() > 0.7 ? e_sz - 3 : e_sz - 2] = e_tp[0].slice(0);
    for (var i = 0; i < e_sz; i++)
      if (evs[i].length > 8)
        for (var j = 8; j < 12; j++) evs[i][j] = Math.floor(evs[i][j] * (lap + 1) / 2);
  }
  var hit = function() {
    evs[cur_e][8] -= lvl * 5 + a;
    if (evs[cur_e][8] <= 0) {
      alert("Monster is defeated and you got " + evs[cur_e][10] + "EXP and $" + evs[cur_e][11]);
      exp += evs[cur_e][10];
      gld += evs[cur_e][11];
      while (exp >= lvl * 10) {
        exp -= lvl * 10;
        lvl++;
        alert("Level Up!")
      }
      cur_e++;
      if (cur_e == e_sz) {
        alert("Victory! You have killed dragon!")
        if (lap < 7) alert("But your princess in another castle")
        else if (lap == 7) {
          alert("You saved the princess! Thank you!")
          alert("But you can continue your journey and kill more dragons")
        } else alert("What about one more dragon?")
        cur_e = 0;
        lap++;
        gen();
      }
    } else {
      hp -= Math.max(0, evs[cur_e][9] - lvl * 2 - d);
      if (hp <= 0) alert("Game Over!")
    }
  }
  var use = function() {
    if (pot > 0) {
      pot--;
      hp += 10;
      if (hp > 100) hp = 100
    }
  }
  var nxt = function() {
    cur_e++
  }
  var battle = ["Attack", "Use Potion +10HP", "Skip Battle", hit, use, nxt];
  var canvas = document.querySelector(elid) ,
    ctx = canvas.getContext("2d");
  canvas.width = wi;
  canvas.height = he;
  var evs = [],
    e_tp = [
      ["Shop", "Wizard provides his services", "Buy Potion $20", "Full Heal $100", "Leave",
        function() {
          if (gld >= 20) {
            gld -= 20;
            pot++
          }
        },
        function() {
          if (gld >= 100) {
            gld -= 100;
            hp = 100
          }
        },
        nxt
      ],
      ["Slime", "What the strange jelly monster?"].concat(battle, 20, 6, 7, 20), ["Goblin", "Green goblin wants to get your money"].concat(battle, 50, 10, 15, 35), ["Skeleton", "A terrible skeleton on your way"].concat(battle, 70, 13, 25, 50), ["Arena", "You can train your skills here", "Train $100->50EXP", "Leave", "-",
        function() {
          if (gld >= 100) {
            gld -= 100;
            exp += 50;
            while (exp >= lvl * 10) {
              exp -= lvl * 10;
              lvl++;
              alert("Level Up!")
            }
          }
        },
        nxt
      ],
      ["Werewolf", "Werewolf attacked you in the woods at night"].concat(battle, 100, 16, 30, 70), ["Forge", "Blacksmith can ungrade your stuff", "Upgrade sword $50", "Upgrade armor $50",
        "Leave",
        function() {
          if (gld >= 50) {
            gld -= 50;
            a++
          }
        },
        function() {
          if (gld >= 50) {
            gld -= 50;
            d++
          }
        },
        nxt
      ],
      ["Ogre", "Hungry two-headed ogre wants to eat you"].concat(battle, 120, 18, 35, 90), ["Castle", "Omg! It is evil Dragon!", "Attack", "Use Potion +10HP", "-", hit, use, , 200, 20, 50, 120]
    ];
  gen();
  var game = setInterval(function() {
    ctx.clearRect(0, 0, wi, he);
    ctx.fillText("TinyRPG in 4Kb of JavaScript by ripatti", 10, 15);
    if (lap > 1) ctx.fillText("Dragons killed " + (lap - 1), 220, 15);
    ctx.fillText("World " + lap + "-" + (cur_e + 1), 310, 15);
    ctx.fillText("LVL " + lvl + "  HP " + hp + "/100  EXP " + exp + "/" + lvl * 10 + "  ATK " + (lvl * 5 + a) +
      "  DEF " + (lvl * 2 + d) + "  Gold $" + gld + "  Potions " + pot, 10, 30);
    for (var i = 0; i < e_sz; i++) ctx.fillText((i == e_sz - 1 || i <= cur_e) ? evs[i][0] : "??", i * 50 + 15, 70);
    ctx.fillText("@", cur_e * 50 + 25, 60);
    ctx.fillText(evs[cur_e][1], 20, 100);
    if (evs[cur_e].length > 8)
      ctx.fillText("Enemy HP " + evs[cur_e][8] + "  ATK " + evs[cur_e][9], 240, 100);
    for (var i = 0; i < 3; i++) {
      ctx.strokeRect(i * 120 + 5, 120, 110, 20);
      ctx.fillText(evs[cur_e][i + 2], i * 120 + 10, 133);
    }
  }, 100);
  document.addEventListener('click', function(e) {
    if (hp > 0)
      for (var i = 0; i < 3; i++)
        if (i * 120 + 5 <= e.pageX && e.pageX < i * 120 + 115 && 120 <= e.pageY && e.pageY < 140)
          evs[cur_e][i + 5]()
  }, false);
  alert("You are brave knight. You should defeat dragon and save princess.");
})
"#canvas", 400, 150, 0, 3, 100, 100, 1, 0, 7, 1, 5, 1;
</script>
</head>
 <body>
   <canvas id="canvas" style="background:#eeeeee"></canvas>
 </body>
</html>

помогите разобраться, что не так?
В консоле никаких ошибок нет

рони 18.09.2017 15:09

Quorio,
строку 136 обернуть в круглые скобки и скрипт поставить после canvas

Quorio 18.09.2017 16:12

По поводу
Цитата:

скрипт поставить после canvas
можно в виде кода? не совсем понял :)

Quorio 18.09.2017 16:21

После того как взял в скобки canvas в console ошибка по строкам
index.html:58 Uncaught TypeError: Cannot read property 'getContext' of null
at index.html:58
at index.html:136
не совсем понимаю в чем дело...

рони 18.09.2017 16:28

Quorio,
<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="utf-8">
  <title>alpha v1.2</title>

</head>
 <body>
   <canvas id="canvas" style="background:#eeeeee"></canvas> <script>
(function(elid, wi, he, exp, pot, gld, hp, lvl, cur_e, e_sz, lap, a, d) {
  var gen = function() {
    evs = [];
    for (var i = 0; i < e_sz - 1; i++)
      evs.push(e_tp[Math.floor(Math.random() * Math.min(8, lap + 2))].slice(0));
    evs.push(e_tp[8].slice(0));
    evs[Math.random() > 0.7 ? e_sz - 3 : e_sz - 2] = e_tp[0].slice(0);
    for (var i = 0; i < e_sz; i++)
      if (evs[i].length > 8)
        for (var j = 8; j < 12; j++) evs[i][j] = Math.floor(evs[i][j] * (lap + 1) / 2);
  }
  var hit = function() {
    evs[cur_e][8] -= lvl * 5 + a;
    if (evs[cur_e][8] <= 0) {
      alert("Monster is defeated and you got " + evs[cur_e][10] + "EXP and $" + evs[cur_e][11]);
      exp += evs[cur_e][10];
      gld += evs[cur_e][11];
      while (exp >= lvl * 10) {
        exp -= lvl * 10;
        lvl++;
        alert("Level Up!")
      }
      cur_e++;
      if (cur_e == e_sz) {
        alert("Victory! You have killed dragon!")
        if (lap < 7) alert("But your princess in another castle")
        else if (lap == 7) {
          alert("You saved the princess! Thank you!")
          alert("But you can continue your journey and kill more dragons")
        } else alert("What about one more dragon?")
        cur_e = 0;
        lap++;
        gen();
      }
    } else {
      hp -= Math.max(0, evs[cur_e][9] - lvl * 2 - d);
      if (hp <= 0) alert("Game Over!")
    }
  }
  var use = function() {
    if (pot > 0) {
      pot--;
      hp += 10;
      if (hp > 100) hp = 100
    }
  }
  var nxt = function() {
    cur_e++
  }
  var battle = ["Attack", "Use Potion +10HP", "Skip Battle", hit, use, nxt];
  var canvas = document.querySelector(elid) ,
    ctx = canvas.getContext("2d");
  canvas.width = wi;
  canvas.height = he;
  var evs = [],
    e_tp = [
      ["Shop", "Wizard provides his services", "Buy Potion $20", "Full Heal $100", "Leave",
        function() {
          if (gld >= 20) {
            gld -= 20;
            pot++
          }
        },
        function() {
          if (gld >= 100) {
            gld -= 100;
            hp = 100
          }
        },
        nxt
      ],
      ["Slime", "What the strange jelly monster?"].concat(battle, 20, 6, 7, 20), ["Goblin", "Green goblin wants to get your money"].concat(battle, 50, 10, 15, 35), ["Skeleton", "A terrible skeleton on your way"].concat(battle, 70, 13, 25, 50), ["Arena", "You can train your skills here", "Train $100->50EXP", "Leave", "-",
        function() {
          if (gld >= 100) {
            gld -= 100;
            exp += 50;
            while (exp >= lvl * 10) {
              exp -= lvl * 10;
              lvl++;
              alert("Level Up!")
            }
          }
        },
        nxt
      ],
      ["Werewolf", "Werewolf attacked you in the woods at night"].concat(battle, 100, 16, 30, 70), ["Forge", "Blacksmith can ungrade your stuff", "Upgrade sword $50", "Upgrade armor $50",
        "Leave",
        function() {
          if (gld >= 50) {
            gld -= 50;
            a++
          }
        },
        function() {
          if (gld >= 50) {
            gld -= 50;
            d++
          }
        },
        nxt
      ],
      ["Ogre", "Hungry two-headed ogre wants to eat you"].concat(battle, 120, 18, 35, 90), ["Castle", "Omg! It is evil Dragon!", "Attack", "Use Potion +10HP", "-", hit, use, , 200, 20, 50, 120]
    ];
  gen();
  var game = setInterval(function() {
    ctx.clearRect(0, 0, wi, he);
    ctx.fillText("TinyRPG in 4Kb of JavaScript by ripatti", 10, 15);
    if (lap > 1) ctx.fillText("Dragons killed " + (lap - 1), 220, 15);
    ctx.fillText("World " + lap + "-" + (cur_e + 1), 310, 15);
    ctx.fillText("LVL " + lvl + "  HP " + hp + "/100  EXP " + exp + "/" + lvl * 10 + "  ATK " + (lvl * 5 + a) +
      "  DEF " + (lvl * 2 + d) + "  Gold $" + gld + "  Potions " + pot, 10, 30);
    for (var i = 0; i < e_sz; i++) ctx.fillText((i == e_sz - 1 || i <= cur_e) ? evs[i][0] : "??", i * 50 + 15, 70);
    ctx.fillText("@", cur_e * 50 + 25, 60);
    ctx.fillText(evs[cur_e][1], 20, 100);
    if (evs[cur_e].length > 8)
      ctx.fillText("Enemy HP " + evs[cur_e][8] + "  ATK " + evs[cur_e][9], 240, 100);
    for (var i = 0; i < 3; i++) {
      ctx.strokeRect(i * 120 + 5, 120, 110, 20);
      ctx.fillText(evs[cur_e][i + 2], i * 120 + 10, 133);
    }
  }, 100);
  document.addEventListener('click', function(e) {
    if (hp > 0)
      for (var i = 0; i < 3; i++)
        if (i * 120 + 5 <= e.pageX && e.pageX < i * 120 + 115 && 120 <= e.pageY && e.pageY < 140)
          evs[cur_e][i + 5]()
  }, false);
  alert("You are brave knight. You should defeat dragon and save princess.");
})
("#canvas", 400, 150, 0, 3, 100, 100, 1, 0, 7, 1, 5, 1);
</script>
 </body>
</html>

Quorio 18.09.2017 16:30

дай бог вам здоровья!:thanks:


Часовой пояс GMT +3, время: 21:00.