Javascript Abstract Member - javascript

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.

Related

I can't seem to access a object's prototype method in Phaser with a custom tile object. What am I doing wrong?

I am extending a basic Sprite object in Phaser to include some additional functions, mainly the ability to switch the textures with shortcut words. However, when I try to access the method, I get
"hex.switchSprite is not a function"
After some basic research, most of the answers are saying to include .prototype - however.. it's already in the method. This is the object itself that I have so far. Everything in switchSprite has been removed for testing purposes:
hexTile = function(game, x, y)
{
Phaser.Sprite.call(this, game, x, y, 'masterTileSheet', 'Gemstone_Missing');
this.scale.x = 0.75;
this.scale.y = 0.75;
this.anchor.x = 0.5;
this.anchor.y = 0.5;
}
hexTile.prototype.switchSprite = function(name)
{
}
hexTile.prototype = Object.create(Phaser.Sprite.prototype);
hexTile.prototype.constructor = hexTile;
I followed the example set out in the Phaser docs, and when I don't use switchSprite, it works:
var hex = new hexTile(game, 0, 0);
var point = calculateGrid(x,y);
hex.x = point.x;
hex.y = point.y;
gameContainer.add(hex);
//console.log(returnRandomHex());
hex.switchSprite();
The above is how I'm accessing and running it - it should be right, but for switchSprite I just get the above error.
An observation: you're overwriting your prototype:
hexTile.prototype.switchSprite = function(name)
{
}
hexTile.prototype = Object.create(Phaser.Sprite.prototype);
You set the prototype of hexTile after you added the switchSprite function to it. Try switching the order of these two statements.

HTML5 game objects and sharing methods

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.

Javascript Class/Static Variables

I'm learning Javascript from Head First Javascript (Morrison).
In one example, the author declares a variable 'signature' to be a class property of a class called Blog by doing the following:
Blog.prototype.signature = "by Blogger-Name";
Is there difference between the above and declaring it like how I have below?
Blog.signature = "by Blogger-Name";
All instances of Blog will have signature when you using .prototype. So when you instantiate var blog = new Blog. It will have a signature property.
If you were to just use Blog.signature = x Then when you create an object with new it wouldn't be there.
Setting a property of a prototype member of a constructor makes the property visible (when reading) from all instances.
This can be done to emulate static members of C++ classes and is often done in Javascript form methods (because methods are indeed just regular data members, differently from C++).
One example where this could be used instead for "data" is keeping all instances of a certain "class" in a container:
function Widget(x0, y0, x1, y1, name) {
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
this.name = name;
this.all_instances.push(this);
}
Widget.prototype.all_instances = [];
var w1 = new Widget(10, 20, 30, 40, "First");
var w2 = new Widget(10, 20, 30, 40, "Second");
Note that however when writing to such a "static" property you're creating instead an instance property; push works because it's not writing to .all_instances but modifying its content (the array).

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.

Categories