HTML5 game objects and sharing methods - javascript

I'm having some issues understanding the code below for HTML5 game. This what i think is happening and was wondering if my understanding is correct?
1) When the Entity function is called, the object SELF is created along with its method (test collision)
2) When the Enemy object is created, it calls the function 'actor' and INHERITS the functions from the SELF object (because self refers to itself) but it also INHERITS the perform.attack method
I'm not sure why we return the object, but in short, by creating the SELF object we can share methods, behaviors and properties allowing us to create DRY code?
I hope my understanding is correct?
Entity = function(type,id,x,y,spdX,spdY,width,height,color){
// a function to call
var self = {
type:type,
x:x,
spdX:spdX,
y:y,
spdY:spdY,
width:width,
height:height,
color:color,
};
self.testCollision = function(entity2){
var rect1 = {
x:self.x-self.width/2,
y:self.y-self.height/2,
width:self.width,
height:self.height,
}
var rect2 = {
x:entity2.x-entity2.width/2,
y:entity2.y-entity2.height/2,
width:entity2.width,
height:entity2.height,
}
return testCollisionRectRect(rect1,rect2);
}
return self;
}
//---------actor can be an enemy or player in the game-----//
Actor = function(type,id,x,y,spdX,spdY,width,height,color){
var self = Entity(type,id,x,y,spdX,spdY,width,height,color);
self.attackCounter = 0;
self.aimAngle = 0;
self.atkSpd = 1;
self.performAttack = function(){
if(self.attackCounter > 25){ //every 1 sec
self.attackCounter = 0;
generateBullet(self);
}
}
return self;
}
// ------------------Create the enemy function----------- //
Enemy = function(id,x,y,spdX,spdY,width,height){
var self = Actor('enemy',id,x,y,spdX,spdY,width,height,'red');
enemyList[id] = self;
}
randomlyGenerateEnemy = function(){
//Math.random() returns a number between 0 and 1
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 + Math.random()*30; //between 10 and 40
var width = 10 + Math.random()*30;
var id = Math.random();
var spdX = 5 + Math.random() * 5;
var spdY = 5 + Math.random() * 5;
Enemy(id,x,y,spdX,spdY,width,height);
}
Thank for the help.
P

JavaScript doesn't have native inheritance. JavaScript doesn't even classes to inherit from, yet -- but JS6 has classes.
Entity is a factory that creates & returns anonymous self objects with properties & a testCollision method.
Actor requests a new object from Entity. Actor adds properties & a performAttack method to the requested object and returns that extended object.
Enemy requests a new object from Actor. Enemy adds that object to an array.
If we examine only this code
If this is the only time Entity & Actor are used then the code is un-necessarily broken into parts. The entire final object (all properties & all methods included) could most efficiently be built in randomlyGenerateEnemy.
If there is more code that uses Entity & Actor
Presumably(!) ...
Entity creates the properties and methods that are common to all game pieces (pieces == characters, structures, etc). To borrow a math phrase, Entity creates an object with the "most common denominators".
Actor enhances the basic Entity object with properties and methods that are inherent to Actor game characters.
Enemy simply adds a new Actor object to the enemyList.
Presumably there might also be a Structure function which (like Actor) enhances the basic Entity object with properties and methods that are inherent to Structure game pieces.
Presumably there might also be a Buildings function which (like Enemy) simply adds a new Structure object to a buildingsList.
Since the Entity code is being reused by both Actor & Structure in the presumed code, the presumed code would make use of the DRY (Don't Repeat Yourself) coding pattern.

Related

Using object inheritance when both objects pass arguments

I have a Equipment parent class which takes in args and two children Weapon and Armor which also take args. I'm not sure if there is a special way to target prototypes or if my code actually isn't working but here is a shortened DEMO
I need to create the variables used for the arguments in each object based on the value of other variables as well as an algorithm that uses a random number. Each item is unique so I need to make the hp for equipment at the same time as the damage for weapons and I'm not sure how to do that.
function Equipment(hp) {
var self = this;
this.hp = hp;
}
//create subclass for weapons
function Weapon(baseDam) {
var self = this;
this.baseDam = baseDam;
}
function generateEquipment() {
hp = Math.round(Math.random() * 10);
baseDam = Math.round(Math.random() * 50);
Weapon.prototype = new Equipment(hp);
weapon = new Weapon(baseDam);
stringed = JSON.stringify(weapon);
alert(stringed);
}
generateEquipment();
First, the answer to your question :
Your code is not really wrong, and your weapon still has its hp, except that its contained in the objects prototype, so won't show when stringified.
There are ways to get around this, like I've shown here, but this according to me is not the correct way to do it.
Normally, prototypes should only store methods and not instance variables, because if you later decide to modify the prototype, the instance variable will get modified as well ,in case it is passed by reference.
A better pattern would be to use Object.assign - it is the easiest to understand and feels most natural. Further, if you expect Weapon to be a subclass of equipment, that logic should be encapsulated in Weapon itself.
Here is the proposed new way of declaring your Weapon Class :
function Weapon(baseDam) {
var self = this;
var hp = Math.round(Math.random() * 10);
Object.assign(self, Equipment.prototype, new Equipment(hp));
this.baseDam = baseDam;
}
Since hp is also generated randomly, that logic is now encapsulated in Weapon. This is also scalable, as this pattern will work for long inheritence chains as well.
Some people may recommend ES6 classes, which is also an approach that would work, but in my opinion it is syntactical sugar, which hides most of the inner workings of your code.
Here is a working demo with my approach.
The 'pattern' you're describing is called 'Composition' and can be very powerful. There're many different ways of combining/composing new classes or objects.
Reading your question and comments, it seems to me that you're mainly interested in defining many different types of equipment without too much (repeated) code.
Have you thought about passing an array of class names to your generateEquipment method and returning a new, custom constructor? Here's an example:
function Equipment(hp) {
this.hp = Math.round(hp);
}
Equipment.prototype.describe = function() {
return "This piece of equipment has " + this.hp + " hitpoints";
}
function Weapon(baseDam) {
this.baseDam = Math.round(baseDam);
}
Weapon.prototype.describe = function() {
return "The weapon does " + this.baseDam + " damage";
}
function generateCustomEquipment(types) {
var CustomEquipment = function() {
var self = this;
// Create the properties for all types
types.forEach(function(type) {
type.call(self, Math.random() * 100);
});
};
CustomEquipment.prototype.describe = function() {
var self = this;
// Combine the 'describe' methods of all composed types
return types
.map(function(type) {
return type.prototype.describe.call(self);
})
.join(". ");
}
return CustomEquipment;
}
var Sword = generateCustomEquipment([Equipment, Weapon]);
var Armor = generateCustomEquipment([Equipment]);
var Arrow = generateCustomEquipment([Weapon]);
var sword1 = new Sword();
document.writeln("A sword: " + sword1.describe() + "<br/>");
var armor1 = new Armor();
document.writeln("A piece of armor: " + armor1.describe() + "<br/>");
var arrow1 = new Arrow();
document.writeln("An arrow: " + arrow1.describe() + "<br/>");

Constructor methods in javascript affect all instances of object

I'm working on an implementation of tetris to teach myself javascript and I've run into a problem. First, the background: I have a class for each type of tetris block that inherits from a basic block template with methods like moving and returning coordinates. For instance,
function BlockTemplate(w, h, c){
var height = h;
var width = w;
var x = 0;
var y = 0;
var color = c;
this.getHeight = function(){return height;};
this.getWidth = function(){return width;};
this.getX = function(){return x;};
this.getY = function(){return y;};
this.getColor = function(){return color;};
this.moveTo = function(newX, newY){
x = newX;
y = newY;
};
this.translate = function(dx, dy){
x += dx;
y += dy;
};
}
function StraightBlock(){
this.draw = function(){
ctx.fillStyle = this.getColor();
ctx.fillRect(this.getX(), this.getY(), 20, 100);
};
}
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
All blocks currently on the screen are stored in an array, blockArr, except for the currently falling block, which is stored in curBlock.
I use a function called createRandomBlock() to create a block and put it in curBlock:
var blockTypeArr = [LBlock, SquareBlock, StraightBlock, SquigBlock];
var createRandomBlock = function(){
var block = blockTypeArr[Math.floor(Math.random()*blockTypeArr.length)];
var randomBlock = new block();
return randomBlock;
};
curBlock = createRandomBlock();
Once it's done falling I put it in the array and create a new block:
blockArr[blockArr.length] = curBlock;
curBlock = createRandomBlock();
If the newly created block hasn't yet been on screen then there's no problem. However, using the moveTo and translate methods of the new instance affect all instances of that class (I added an id property to make sure they were in fact distinct instances).
For example, using the JavaScript console,
>curBlock
SquigBlock
>blockArr
[SquareBlock, SquigBlock, SquigBlock]
As you can see, 3 SquigBlocks have fallen so far (2 in blockArr, 1 presently falling). Yet the only one I see is the one currently falling (curBlock), and checking the parameters, curBlock.getY(), blockArr[1].getY() and blockArr[2].getY() all return the same value. In other words, they're all being drawn in the same location.
How can I change it so that old blocks, no matter what the class, stay at the bottom of the screen, while the newly created block falls from the top without causing all other blocks of that class to move with it?
Thank you!
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
Well, that is only one BlockTemplate that is shared amongst with StraightBlock instances. You can see that new StraightBlock().moveTo == new StraightBlock().moveTo, ie two instances have the very same method which does affect the same x variable. Do not use new for creating the prototype, but Correct javascript inheritance:
function StraightBlock(){
BlockTemplate.call(this, 20, 100, "#00FFE5");
this.draw = function(){
ctx.fillStyle = this.getColor();
ctx.fillRect(this.getX(), this.getY(), 20, 100);
};
}
StraightBlock.prototype = Object.create(BlockTemplate.prototype);
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
Since this is called once, there is one var x that is closed over by the single getHeight that is shared among all instances of StraightBlock.
You should make two changes:
1 Use instance fields stored on this
function BlockTemplate(w, h, c){
this.height = h;
...
}
BlockTemplate.prototype.getHeight = function(){return this.height;};
...
2 Chain constructors
Have StraightBlock invoke its super-class constructor to add new versions of the methods to each instance created.
function StraightBlock(){
BlockTemplate.apply(this, arguments);
...
}
You could also just do constructor chaining, but that would mean that you are creating a new copy of each method for each instance. This can be expensive if you have a lot of short-lived instances of a "class".
The drawback of storing fields on this is that they can be unintentionally mutated by naive code. JavaScript does not have strong information hiding except via closed-over local variables, so if you want the robustness that you get via private fields in other languages, then your current design via local variables might be best.

How would you make it so a parent's values wouldn't for an inherited object

So I have this code which inherits :
enemy = new Object(hawk);
The parent is this:
function CreateEnemy(name, health, damage){
this.name = name;
this.health = health;
this.damage = damage;
}
var hawk = new CreateEnemy("Hawk", 200, 20);
Whenever I do
enemy.health -= 10;
It changes the value of hawk.health as well, and I don't want it to do that.
I think you're looking for
CreateEnemy.prototype.clone = function() {
return new CreateEnemy(this.name, this.health, this.damage);
};
then do
var enemy = hawk.clone();
Now changes on one object will not reflect upon the other, as they are distinct CreateEnemy instances.
If you are looking for prototypical inheritance, Object.create will do it. Changes on hawk will then be reflected on enemy as long as the properties are not overwritten there:
var enemy = Object.create(hawk);
enemy.name; // "Hawk" - inherited
enemy.damage = 25; // assignment creates an own property on enemy
enemy.damage; // 25
enemy.health -= 10; // as does when getting an inherited value before:
enemy.health; // 190
hawk.health; // 200
In this situation, CreateEnemy is not a parent object, it is a function that is creating an object hawk which you have previously made equal to the object called enemy. Hence, their properties are equal.

How to set a dynamically generated pseudoclass name in JavaScript to work with the instanceof operator?

I'd like to set the name of a JavaScript pseudoclass stored in an array with a specific name, for example, the non-array version works flawlessly:
var Working = new Array();
Working = new Function('arg', 'this.Arg = arg;');
Working.prototype.constructor = Working;
var instw = new Working('test');
document.write(instw.Arg);
document.write('<BR />');
document.write((instw instanceof Working).toString());
Output:
test
true
However this format does not function:
// desired name of pseudoclass
var oname = 'Obj';
var objs = new Array();
objs.push(new Function('arg', 'this.Arg = arg;'));
// set objs[0] name - DOESN'T WORK
objs[0].prototype.constructor = oname;
// create new instance of objs[0] - works
var inst = new objs[0]('test');
document.write(inst.Arg);
document.write('<BR />Redundant: ');
// check inst name - this one doesn't need to work
try { document.write((inst instanceof objs[0]).toString()); } catch (ex) { document.write('false'); }
document.write('<BR />Required: ');
// check inst name - this is the desired use of instanceof
try { document.write((inst instanceof Obj).toString()); } catch (ex) { document.write('false'); }
Output:
test
Redundant: true
Required: false
Link to JSFiddle.
You've got a couple of things going on here that are a little bit off-kilter in terms of JS fluency (that's okay, my C# is pretty hackneyed as soon as I leave the base language features of 4.0).
First, might I suggest avoiding document.write at all costs?
There are technical reasons for it, and browsers try hard to circumvent them these days, but it's still about as bad an idea as to put alert() everywhere (including iterations).
And we all know how annoying Windows system-message pop-ups can be.
If you're in Chrome, hit CTRL+Shift+J and you'll get a handy console, which you can console.log() results into (even objects/arrays/functions), which will return traversable nodes for data-set/DOM objects and strings for other types (like functions).
One of the best features of JS these days is the fact that your IDE is sitting in your browser.
Writing from scratch and saving .js files isn't particularly simple from the console, but testing/debugging couldn't be any easier.
Now, onto the real issues.
Look at what you're doing with example #1.
The rewriting of .prototype.constructor should be wholly unnecessary, unless there are some edge-case browsers/engines out there.
Inside of any function used as a constructor (ie: called with new), the function is basically creating a new object {}, assigning it to this, setting this.__proto__ = arguments.callee.prototype, and setting this.__proto__.constructor = arguments.callee, where arguments.callee === function.
var Working = function () {};
var working = new Working();
console.log(working instanceof Working); // [log:] true
Working isn't a string: you've make it a function.
Actually, in JS, it's also a property of window (in the browser, that is).
window.Working === Working; // true
window["Working"] === Working; // true
That last one is really the key to solving the dilemma in example #2.
Just before looking at #2, though, a caveat:
If you're doing heavy pseud-subclassing,
var Shape = function () {
this.get_area = function () { };
},
Square = function (w) {
this.w = w;
Shape.call(this);
};
If you want your instanceof to work with both Square and Shape, then you have to start playing with prototypes and/or constructors, depending on what, exactly, you'd like to inherit and how.
var Shape = function () {};
Shape.prototype.getArea = function () { return this.length * this.width; };
var Square = function (l) { this.length = l; this.width = l; };
Square.prototype = new Shape();
var Circle = function (r) { this.radius = r; };
Circle.prototype = new Shape();
Circle.prototype.getArea = function () { return 2 * Math.PI * this.radius; };
var circle = new Circle(4),
square = new Square(4);
circle instanceof Shape; // true
square instanceof Shape; // true
This is simply because we're setting the prototype object (reused by every single instance) to a brand-new instance of the parent-class. We could even share that single-instance among all child-classes.
var shape = new Shape();
Circle.prototype = shape;
Square.prototype = shape;
...just don't override .getArea, because prototypical-inheritance is like inheriting public-static methods.
shape, of course, has shape.__proto__.constructor === Shape, much as square.__proto__.constructor === Square. Doing an instanceof just recurses up through the __proto__ links, checking to see if the functions match the one given.
And if you're building functions in the fashion listed above (Circle.prototype = new Shape(); Circle.prototype.getArea = function () { /* overriding Shape().getArea() */};, then circle instanceof Circle && circle instanceof Shape will take care of itself.
Mix-in inheritance, or pseudo-constructors (which return objects which aren't this, etc) require constructor mangling, to get those checks to work.
...anyway... On to #2:
Knowing all of the above, this should be pretty quick to fix.
You're creating a string for the desired name of a function, rather than creating a function, itself, and there is no Obj variable defined, so you're getting a "Reference Error": instead, make your "desired-name" a property of an object.
var classes = {},
class_name = "Circle",
constructors = [];
classes[class_name] = function (r) { this.radius = r; };
constructors.push(classes.Circle);
var circle = new constructors[0](8);
circle instanceof classes.Circle;
Now everything is nicely defined, you're not overwriting anything you don't need to overwrite, you can still subclass and override members of the .prototype, and you can still do instanceof in a procedural way (assigning data.name as a property of an object, and setting its value to new Function(data.args, data.constructor), and using that object-property for lookups).
Hope any/all of this helps.

Javascript Abstract Member

I'm not sure if the title even accurately describes what I'm trying to do here, but here's the code representing the problem:
var spriteDefinitions = {};
function Sprite(x, y) {
this.x = x;
this.y = y;
}
spriteDefinitions.Player = function(x, y, state) {
Sprite.call(this, x, y);
this.state = state;
}
spriteDefinitions.Player.prototype = new Sprite();
spriteDefinitions.Player.prototype.constructor = spriteDefinitions.Player;
spriteDefinitions.Player.prototype.states = new Array();
spriteDefinitions.Player.prototype.states[0] = "state 0";
spriteDefinitions.Player.prototype.states[1] = "state 1";
spriteDefinitions.Player.prototype.statesEnum = {Right: 0,Left: 1};
var player1 = new spriteDefinitions.Player(50, 90, spriteDefinitions.Player.statesEnum.Left);
var player2 = new spriteDefinitions.Player(100, 100, spriteDefinitions.Player.statesEnum.Right);
The creation of player1 gets an error because Player.statesEnum is undefined. Player is supposed to be a class inheriting from Sprite. And Sprite should be able to access the states of all derived classes (an abstract member). But the derived classes actually define what the states are. How do I properly make statesEnum apply to all instances of Player? I assume I'm going to have the same problem with all the Player.prototype members. In a normal OO language, I think these would be abstract members, but I'm not clear on how to do this with JavaScript.
It seems like you want stateEnum to be available on the constructor, not on the instances. With prototype, you can define what properties instances inherit.
However, if you want spriteDefinitions.Player.statesEnum to be available, just define it as such:
spriteDefinitions.Player.statesEnum = {Right: 0,Left: 1};
Functions are objects which can take properties just as well. Note that this does not make instances have statusEnum available; for that you can use prototype.

Categories