Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>JavaScript Dijkstra's Algorithm Sample</title>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="author" content="wertrain">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style type="text/css">
      canvas {
        background-color:white;
        display: block;
      }
    </style>
    <canvas id="canvas" width="640" height="480"></canvas>
  </head>
  <body>
    <script src="scripts/map.js"></script>
    <script src="scripts/dijkstra.js"></script>
    <script src="scripts/chara.js"></script>
    <script src="scripts/item.js"></script>
    <script src="scripts/resources.js"></script>
    <script>
      "use strict";
      window.onload = function () {
          var canvas = document.getElementById('canvas');
          var context = canvas.getContext('2d');
          
          var mapchip = new Image();
          var charachip = new Image();
          var itemchip = new Image();
          var CHIP_SIZE = 32;
          mapchip.src = mapChipDataURL;
          charachip.src = charaChipDataURL;
          itemchip.src = itemChipDataURL;
          
          var map = new Map();
          map.create(mapchip, CHIP_SIZE);
          
          var chara = new Chara();
          chara.create(charachip, CHIP_SIZE);
          chara.put(1, 1);
          
          var getRandomPos = function() {
              var pos = null;
              do {
                  var movableWidth = map.getWidth() - 2 - 1, movableHeight = map.getHeight() - 2 - 1;
                  pos = {x: Math.floor(Math.random() * movableWidth) + 1, y: Math.floor(Math.random() * movableHeight) + 1};
              } while(map.isHit(pos.x, pos.y));
              return pos;
          }
          var dijkstra = new Dijkstra();
          
          var item = new Item();
          item.create(itemchip, CHIP_SIZE);
          
          var resetShortestPath = function() {
              var goal = getRandomPos();
              var route = dijkstra.findShortestPath(map.getArray(), chara.getX(), chara.getY(), goal.x, goal.y);
              item.put(goal.x, goal.y);
              chara.trace(route);
          }
          
          resetShortestPath();
          setInterval(function(){
              if (chara.update()) {
                  resetShortestPath();
              }
              map.draw(context);
              dijkstra.draw(context, CHIP_SIZE);
              item.draw(context);
              chara.draw(context);
          }, 33);
      }
    </script>
  </body>
</html>
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
wertrainpro
0viewers