js-browser-tile-game/js/main.js
Aaron Yarborough 4b4e124c57 Initial commit
2019-12-02 10:05:48 +00:00

136 lines
No EOL
2.7 KiB
JavaScript

var keysdown = {};
var canvas;
var canvasCtx;
var level;
var player;
var tileEngine;
var tileset;
function onDOMReady() {
// Initialize main game objects
initCanvas();
initTileEngine();
initTileset();
initPlayer();
initLevel();
// Define event listeners
defineListeners();
// Start the game loop
setInterval(run, 1000 / 50);
}
function run() {
update();
draw();
}
function update() {
// Move player and update player state
if (isKeyDown(37) || isKeyDown(38) || isKeyDown(39) || isKeyDown(40)) {
if (isKeyDown(37)) player.move(1);
if (isKeyDown(39)) player.move(3);
if (isKeyDown(38)) player.move(0);
if (isKeyDown(40)) player.move(2);
player.setState("moving");
} else if (player.getState() == "moving") {
player.setState("idle");
}
}
function draw() {
draw_level();
}
function draw_level() {
if (tileset.loaded == false) return;
var rowIndex = 0;
for (var i = 0; i < level.tiles.length; i++) {
for (var j = 0; j < level.tiles[i].length; j++) {
var levelTileID = cellPosToTilePos([rowIndex, j]);
var tilesetPos = tileset.tileIDToTilesetPos(level.tiles[i][j].getID());
// var tilePos = [rowIndex * tileEngine.tileSize, j * tileEngine.tileSize];
canvasCtx.drawImage(
tileset.image,
tilesetPos[0],
tilesetPos[1],
tileEngine.tileSize,
tileEngine.tileSize,
Math.ceil((levelTileID % level.width) * tileEngine.tileSize),
Math.floor((levelTileID / level.height)) * tileEngine.tileSize,
tileEngine.tileSize, tileEngine.tileSize
);
}
rowIndex ++;
}
}
function initCanvas() {
// Store references to canvas and context
// in global variables for easy access
canvas = $("#canvas")[0];
canvasCtx = canvas.getContext("2d");
// Resize canvas accordingly
canvas.width = $("#container").width();
canvas.height = $("#container").height();
// Fill canvas
canvasCtx.fillStyle = "lightgray";
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
}
function initTileEngine() {
// Create a new tile engine object
tileEngine = new TileEngine();
}
function initTileset() {
// Create a new tileset object
tileset = new Tileset();
// Set the tileset
tileset.setTileset("DefaultTileset.png");
}
function initPlayer() {
// Create the player object
player = new Player();
}
function initLevel() {
// Create the level object
level = new Level();
level.loadLevel("start.tglvl");
}
function defineListeners() {
addEventListener("keydown", function (e) {
onKeyDown(e);
}, false);
addEventListener("keyup", function (e) {
onKeyUp(e);
}, false);
}
/*
* Listeners
**/
function onKeyDown(e) {
keysdown[e.keyCode] = true;
}
function onKeyUp(e) {
keysdown[e.keyCode] = false;
}
/*
* Prototypes
**/