testing 2-d array

by soggydoughnut54

HTML

<p id="p" style="font-family:monospace; letter-spacing:.8em;">hey</p>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
<br/>
<br/>
<a href="http://www.etch.wlwv.k12.or.us/~windl/tiles/index.html" target="0">Build a new map</a>

JavaScript

//2D Array defines the map!!!
var map = [
  [1, 1, 1, 1, 1, 1],
  [1, 0, 1, 0, 0, 1],
  [1, 0, 1, 0, 0, 1],
  [1, 0, 1, 0, 1, 1],
  [1, 0, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1]
];
//location of man
var playerX = 1;
var playerY = 1;
//man color
var player = "brown";
//set the tile colors
var tiles = ["maroon", "black"];
/**
Draw the game
**/
function draw() {
  context.fillStyle = "white";
  context.fillRect(0, 0, canvas.width, canvas.height);
  /**
   add code here
   **/
  //nested for loop accesses 2D array
for(var y = 0; y < map.length; y++){
for(var x = 0; x< map[y].length; x++ ){
//asssign the tile value 
var tile = map[y][x];
//draw it
context.fillStyle = tiles[tile];
context.fillRect(x*tileSize, y*tileSize, tileSize, tileSize);
	}
}
//draw

  //draw the player
  context.fillStyle = player;
  context.fillRect(playerX * tileSize, playerY * tileSize, tileSize, tileSize);
  //text output
  mapText();
}
//////////////////////////////
//access the canvas
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
//and the text output
var p = document.getElementById('p');
//variable for output
var output = "";
//size of tiles
var tileSize = canvas.width / map[0].length;
var playerText = "<span style='color:red'>X</span>";

/**
Move logic for game
**/
function moveLogic(x, y) {
  //find the target tile
  var tile = map[y][x];
  //check to see if it is a floor
  if (tile === 0) {
    //if it is, move man
    playerX = x;
    playerY = y;
  }
}
document.onkeydown = function(e) {
  //capture the event
  e = window.event || e;
  //get the key code
  var key = e.keyCode;
  //prevent default event behavior
  e.preventDefault();
  var x = 0;
  var y = 0;
  if (key === 37) {
    x -= 1;
  }
  if (key === 39) {
    x += 1;
  }
  if (key === 38) {
    y -= 1;

  }
  if (key === 40) {
    y += 1;
  }
  //tell him to move
  moveLogic(playerX + x, playerY + y);
};

function mapText() {
  output = "";
  //nested for loop accesses 2D array
  for (i = 0;...