Fixed spacing on some files and added comments

This commit is contained in:
Arne van Iterson 2020-01-17 21:11:15 +01:00
parent 0d1ee32fd8
commit 3264ae157e
16 changed files with 379 additions and 165 deletions

View File

@ -1,24 +1,47 @@
/**
* Container class
*/
class Container { class Container {
constructor() { constructor() {
this.pos = { x: 0, y: 0 }; this.pos = { x: 0, y: 0 };
this.children = []; this.children = [];
} }
// Contrainer methods /**
* Adds child to container
* @param {*} child Child to add
* @returns {any} Added child
*/
add(child) { add(child) {
this.children.push(child); this.children.push(child);
return child; return child;
} }
/**
* Removes child from container
* @param {*} child Child to remove
* @returns {any} Removed child
*/
remove(child) { remove(child) {
this.children = this.children.filter(c => c !== child); this.children = this.children.filter(c => c !== child);
return child; return child;
} }
/**
* Preforms a function on all children
* @param {function} f Function to preform on children
* @returns {any} Function altered array
*/
map(f) { map(f) {
return this.children.map(f); return this.children.map(f);
} }
/**
* Updates all children when called
* @param {number} dt Delta time
* @param {number} t Total time
* @returns {boolean} Returns if the child is dead or not
*/
update(dt, t) { update(dt, t) {
this.children = this.children.filter(child => { this.children = this.children.filter(child => {
if (child.update) { if (child.update) {

View File

@ -4,7 +4,17 @@ import CanvasRenderer from "./renderer/CanvasRenderer.js";
const STEP = 1 / 60; const STEP = 1 / 60;
const FRAME_MAX = 5 * STEP; const FRAME_MAX = 5 * STEP;
/**
* Game class
*/
class Game { class Game {
/**
* Set the games parameters
* @param {number} w Width of canvas
* @param {number} h Height of canvas
* @param {boolean} pixelated Turns canvas smoothening on or off
* @param {String} [parent="#board"] HTML id of element to push the canvas element too
*/
constructor(w, h, pixelated, parent = "#board") { constructor(w, h, pixelated, parent = "#board") {
this.w = w; this.w = w;
this.h = h; this.h = h;
@ -18,6 +28,10 @@ class Game {
this.scene = new Container(); this.scene = new Container();
} }
/**
* Start game loop
* @param {Function} gameUpdate Function to run next to scene updates such as debug logging, etc.
*/
run(gameUpdate = () => { }) { run(gameUpdate = () => { }) {
let dt = 0; let dt = 0;
let last = 0; let last = 0;

View File

@ -1,4 +1,11 @@
/**
* Sprite class
*/
class Sprite { class Sprite {
/**
* Draw sprite on canvas
* @param {*} texture Sprite image
*/
constructor(texture) { constructor(texture) {
this.texture = texture; this.texture = texture;
this.pos = { x: 0, y: 0 }; this.pos = { x: 0, y: 0 };

View File

@ -1,15 +1,29 @@
// XML format must be:
// <TextureAlias imagePath="">
// <SubTexture x="" y="" width="" height=""></SubTexture>
// ...
// </TextureAlias>
/**
* SpriteSheetXML - Reads XML files to get texture data
*
* **XML format must be:**
*
* <TextureAlias imagePath="">
*
* <SubTexture x="" y="" width="" height=""></SubTexture>
* ...
* </TextureAlias>
*/
class SpriteSheetXML { class SpriteSheetXML {
/**
* Set url of XML file
* @param {String} url Url to XML file
*/
constructor(url) { constructor(url) {
this.array = []; this.array = [];
this.fetchXMLtoArray(url); this.fetchXMLtoArray(url);
} }
/**
* Fetch XML file and put contents in a JS array
* @param {String} url Url to XML file
*/
fetchXMLtoArray(url) { fetchXMLtoArray(url) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); xhr.open('GET', url, false);
@ -32,6 +46,12 @@ class SpriteSheetXML {
} }
} }
/**
* Find index of XML element with attribute == value
* @param {String} attribute XML element attribute
* @param {String} value Value of XML element attribute
* @returns {number} Index of XML element
*/
findIndex(attribute, value) { findIndex(attribute, value) {
for (let index = 0; index < this.array.length; index++) { for (let index = 0; index < this.array.length; index++) {
const element = this.array[index]; const element = this.array[index];

View File

@ -1,4 +1,12 @@
/**
* Text class
*/
class Text { class Text {
/**
* Prints styled text on canvas
* @param {String} text Text to print
* @param {String} style Styles to apply to text
*/
constructor(text = "", style = {}) { constructor(text = "", style = {}) {
this.pos = { x: 0, y: 0 }; this.pos = { x: 0, y: 0 };
this.text = text; this.text = text;

View File

@ -1,4 +1,11 @@
/**
* Texture class
*/
class Texture { class Texture {
/**
* Sets url of source image and creates an instance of Image()
* @param {*} url
*/
constructor(url) { constructor(url) {
this.img = new Image(); this.img = new Image();
this.img.src = url; this.img.src = url;

View File

@ -1,7 +1,19 @@
import Container from "./Container.js"; import Container from "./Container.js";
import TileSprite from "./TileSprite.js"; import TileSprite from "./TileSprite.js";
/**
* Tilemap class
*/
class TileMap extends Container { class TileMap extends Container {
/**
* Draws array of tiles from unindexed spritesheet
* @param {[ { x: number, y: number} ]} tiles Array of x and y values of the source tile on an unindexed Spritesheet
* @param {number} mapW Amount of tiles over the width of the map
* @param {number} mapH Amount of tiles over the height of the map
* @param {number} tileW Width of source tile(s) in pixels
* @param {number} tileH Height of source tile(s) in pixels
* @param {*} texture Texture instance of source image file
*/
constructor(tiles, mapW, mapH, tileW, tileH, texture) { constructor(tiles, mapW, mapH, tileW, tileH, texture) {
super(); super();
this.mapW = mapW; this.mapW = mapW;
@ -11,7 +23,6 @@ class TileMap extends Container {
this.w = mapW * tileW; this.w = mapW * tileW;
this.h = mapH * tileH; this.h = mapH * tileH;
// Add all tile sprites
this.children = tiles.map((frame, i) => { this.children = tiles.map((frame, i) => {
const s = new TileSprite(texture, tileW, tileH); const s = new TileSprite(texture, tileW, tileH);
s.frame = frame; s.frame = frame;

View File

@ -1,7 +1,18 @@
import Container from "./Container.js"; import Container from "./Container.js";
import TileSpriteXML from "./TileSpriteXML.js"; import TileSpriteXML from "./TileSpriteXML.js";
/**
* TileMapXML class
*/
class TileMapXML extends Container { class TileMapXML extends Container {
/**
* Draws array of tiles from XML indexed spritesheet
* @param {number[]} tiles Array of XML indexes
* @param {*} mapW Amount of tiles over the width of the map
* @param {*} mapH Amount of tiles over the height of the map
* @param {*} texture Texture instance of source image file
* @param {*} xml SpriteSheetXML instance of source xml file
*/
constructor(tiles, mapW, mapH, texture, xml) { constructor(tiles, mapW, mapH, texture, xml) {
super(texture); super(texture);
this.mapW = mapW; this.mapW = mapW;
@ -11,7 +22,6 @@ class TileMapXML extends Container {
this.w = mapW * this.tileW; this.w = mapW * this.tileW;
this.h = mapH * this.tileH; this.h = mapH * this.tileH;
// Add all tile sprites
this.children = tiles.map((frame, i) => { this.children = tiles.map((frame, i) => {
const s = new TileSpriteXML(texture, xml, frame); const s = new TileSpriteXML(texture, xml, frame);
s.frame = frame; s.frame = frame;

View File

@ -1,6 +1,14 @@
import Sprite from "./Sprite.js"; import Sprite from "./Sprite.js";
/**
* TileSprite class
*/
class TileSprite extends Sprite { class TileSprite extends Sprite {
/**
* Creates sprite instance from unindexed spritesheet
* @param {*} texture Instance of Texture with source image
* @param {number} w Width of sprite on source image
* @param {number} h Height of spirte on source image
*/
constructor(texture, w, h) { constructor(texture, w, h) {
super(texture); super(texture);
this.tileW = w; this.tileW = w;

View File

@ -1,6 +1,15 @@
import Sprite from "./Sprite.js"; import Sprite from "./Sprite.js";
/**
* TileSpriteXML class
*/
class TileSpriteXML extends Sprite { class TileSpriteXML extends Sprite {
/**
* Creates sprite instance from XML indexed spritesheet
* @param {*} texture Instance of Texture with source image
* @param {*} xml Instance of SpriteSheetXML with xml index
* @param {number} index Index of XML element
*/
constructor(texture, xml, index) { constructor(texture, xml, index) {
super(texture); super(texture);
var src = xml.array[index]; var src = xml.array[index];

View File

@ -1,4 +1,10 @@
/**
* KeyControls class
*/
class KeyControls { class KeyControls {
/**
* Listens for keypresses and prevents default actions
*/
constructor() { constructor() {
this.keys = {}; this.keys = {};
// Bind event handlers // Bind event handlers
@ -12,12 +18,22 @@ class KeyControls {
this.keys[e.which] = false; this.keys[e.which] = false;
}, false); }, false);
} }
// Handle key actions
/**
* Returns value of action key (spacebar)
* @returns {boolean} Key value
*/
get action() { get action() {
// Spacebar // Spacebar
return this.keys[32]; return this.keys[32];
} }
/**
* Returns -1 on Arrow Left or A
*
* Returns 1 on Arrow Right or D
* @returns {number} Key Value
*/
get x() { get x() {
// Arrow Left or A (WASD) // Arrow Left or A (WASD)
if (this.keys[37] || this.keys[65]) { if (this.keys[37] || this.keys[65]) {
@ -30,6 +46,12 @@ class KeyControls {
return 0; return 0;
} }
/**
* Returns -1 on Arrow Up or W
*
* Returns 1 on Arrow Down or S
* @returns {number} Key value
*/
get y() { get y() {
// Arrow Up or W (WASD) // Arrow Up or W (WASD)
if (this.keys[38] || this.keys[87]) { if (this.keys[38] || this.keys[87]) {
@ -42,6 +64,12 @@ class KeyControls {
return 0; return 0;
} }
/**
* Read or write value of any key
* @param {number} key Keycode for targetted key
* @param {*} [value] Value to set to key
* @return {*} Value of key
*/
key(key, value) { key(key, value) {
if (value !== undefined) { if (value !== undefined) {
this.keys[key] = value; this.keys[key] = value;
@ -49,6 +77,9 @@ class KeyControls {
return this.keys[key]; return this.keys[key];
} }
/**
* Resets default value to all keys
*/
reset() { reset() {
for (let key in this.keys) { for (let key in this.keys) {
this.keys[key] = false; this.keys[key] = false;

View File

@ -1,4 +1,11 @@
/**
* MouseControls class
*/
class MouseControls { class MouseControls {
/**
* Sets container element where handlers will listen
* @param {*} [container] Container element, defaults to document.body
*/
constructor(container) { constructor(container) {
this.el = container || document.body; this.el = container || document.body;
// State // State
@ -12,6 +19,10 @@ class MouseControls {
document.addEventListener('mouseup', this.up.bind(this), false); document.addEventListener('mouseup', this.up.bind(this), false);
} }
/**
* Recalculates mouse position based on the position of the container
* @param {{ clientX: number, clientY: number}} param0 Native mouse event x and y values
*/
mousePosFromEvent({ clientX, clientY }) { mousePosFromEvent({ clientX, clientY }) {
const { el, pos } = this; const { el, pos } = this;
const rect = el.getBoundingClientRect(); const rect = el.getBoundingClientRect();
@ -21,26 +32,40 @@ class MouseControls {
pos.y = (clientY - rect.top) * yr; pos.y = (clientY - rect.top) * yr;
} }
/**
* Calls mousePosFromEvent() on mouse move
* @param {*} e Event
*/
move(e) { move(e) {
this.mousePosFromEvent(e); this.mousePosFromEvent(e);
} }
/**
* Handles mouseDown event and calls mousePosFromEvent() to determine the exact pixel
* @param {*} e Event
*/
down(e) { down(e) {
this.isDown = true; this.isDown = true;
this.pressed = true; this.pressed = true;
this.mousePosFromEvent(e); this.mousePosFromEvent(e);
} }
/**
* Handles mouseUp event and calls mousePosFromEvent() to determine the exact pixel
* @param {*} e Event
*/
up() { up() {
this.isDown = false; this.isDown = false;
this.released = true; this.released = true;
} }
/**
* Resets pressed and released values to make sure they are only true on a press or release
*/
update() { update() {
this.released = false; this.released = false;
this.pressed = false; this.pressed = false;
} }
} }
export default MouseControls; export default MouseControls;

View File

@ -1,13 +1,16 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ASDF Framework</title> <title>ASDF Framework</title>
</head> </head>
<body> <body>
<h2>ASDF JS Framework</h2> <h2>ASDF JS Framework</h2>
<p>Nothing to browse here, just some shared files to make these games work.</p> <p>Nothing to browse here, just some shared files to make these games work.</p>
</body> </body>
</html> </html>

View File

@ -1,4 +1,12 @@
/**
* CanvasRenderer class
*/
class CanvasRenderer { class CanvasRenderer {
/**
* Renderer for CanvasJS, defines width and height for the canvas element
* @param {*} w Width for canvas element
* @param {*} h Height for canvas element
*/
constructor(w, h) { constructor(w, h) {
const canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
this.w = canvas.width = w; this.w = canvas.width = w;
@ -8,6 +16,9 @@ class CanvasRenderer {
this.ctx.textBaseLine = "top"; this.ctx.textBaseLine = "top";
} }
/**
* Turns off image smoothening on the canvas element
*/
setPixelated() { setPixelated() {
this.ctx['imageSmoothingEnabled'] = false; /* standard */ this.ctx['imageSmoothingEnabled'] = false; /* standard */
this.ctx['mozImageSmoothingEnabled'] = false; /* Firefox */ this.ctx['mozImageSmoothingEnabled'] = false; /* Firefox */
@ -16,6 +27,12 @@ class CanvasRenderer {
this.ctx['msImageSmoothingEnabled'] = false; /* IE */ this.ctx['msImageSmoothingEnabled'] = false; /* IE */
} }
/**
* Render all children on the canvas element
* @param {*} container Containing element of the canvas element
* @param {boolean} [clear=true] Defines if the canvas element needs to be cleared for the next render
*/
render(container, clear = true) { render(container, clear = true) {
const { ctx } = this; const { ctx } = this;
function renderRec(container) { function renderRec(container) {
@ -27,7 +44,6 @@ class CanvasRenderer {
ctx.save(); ctx.save();
// Draw the leaf node
if (child.pos) { if (child.pos) {
ctx.translate(Math.round(child.pos.x), Math.round(child.pos.y)); ctx.translate(Math.round(child.pos.x), Math.round(child.pos.y));
} }
@ -81,7 +97,7 @@ class CanvasRenderer {
} }
} }
// Handle the child types // Handle children with children
if (child.children) { if (child.children) {
renderRec(child); renderRec(child);
} }

View File

@ -1,7 +1,19 @@
/**
* Returns random integer between min and max
* @param {number} min Minimum value
* @param {number} max Maximum value
* @returns {number} Random integer
*/
function rand(min, max) { function rand(min, max) {
return Math.floor(randf(min, max)); return Math.floor(randf(min, max));
} }
/**
* Returns random float between min and max
* @param {number} min Minimum value
* @param {number} max Maximum value
* @returns {number} Random value
*/
function randf(min, max) { function randf(min, max) {
if (max == null) { if (max == null) {
max = min || 1; max = min || 1;
@ -10,10 +22,20 @@ function rand(min, max) {
return Math.random() * (max - min) + min; return Math.random() * (max - min) + min;
} }
/**
* Returns random item from items array
* @param {*[]} items Array of anything
* @returns {any} Item from items array
*/
function randOneFrom(items) { function randOneFrom(items) {
return items[rand(items.length)]; return items[rand(items.length)];
} }
/**
* Returns true one out of max times
* @param {number} [max=2] Maximum value
* @returns {boolean} Outcome
*/
function randOneIn(max = 2) { function randOneIn(max = 2) {
return rand(0, max) === 0; return rand(0, max) === 0;
} }