Multiple objects aren't getting displayed - javascript

I've been messing around with objects in Javascript and I've come across a problem. Basically I'm trying to print certain properties from objects I've created and it's not working properly.
Here's the code:
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
var CanadaHotel = new Hotel("CanadaIn", 50, 10);
var AmericanHotel = new Hotel("AmericanIn", 60, 3);
document.write(CanadaHotel.rooms);
document.write(AmericanHotel.booked);
None of the properties are being displayed and I don't know why.. any help is greatly appreciated.
Thank you

SyntaxError: missing } after function body
Fixed
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
}
var CanadaHotel = new Hotel("CanadaIn", 50, 10);
var AmericanHotel = new Hotel("AmericanIn", 60, 3);
console.log(CanadaHotel.rooms);
console.log(AmericanHotel.booked);

Related

Phaser 3 : Add arguments to callback functions (time event, keyboard event)

I'm developing a game on Phaser 3 and I'm currently struggling on callback use.
I have created two classes, one called "Entitee" and the other one called "objet"
class Entitee extends Phaser.Physics.Arcade.Sprite{
constructor(scene, x, y, pv, mana, speed, poise, asset){
//Private
var _pv = pv;
var _pvMax = pv;
var _mana = mana;
var _manaMax = mana;
var _speed = speed;
var _poise = poise;
var _asset = asset;
super(scene, x, y, _asset);
scene.add.existing(this);
scene.physics.world.enableBody(this);
//Public
this.hurt = function(objet){
console.log(_pv);
console.log(objet);
_pv += objet.getPvMod();
console.log(_pv);
}
}//END CONSTRUCTOR
}
class Objet {
constructor(name, price, range, cd, ammo, lag, pvMod, manaMod, poiseMod, speedMod, animAtt, animZone){
var _name = name;
var _price = price;
var _range = range;
var _cooldown = cd;
var _ammo = ammo;
var _direction;
var _lag = lag;
var _pvMod = pvMod;
var _manaMod = manaMod;
var _poiseMod = poiseMod;
var _speedMod = speedMod;
var _animAtt = animAtt;
var _animZone = animZone;
this.getName= function(){ return _name};
this.getPrice= function(){ return _price};
this.getRange= function(){ return _range};
this.getCooldown= function(){ return _cooldown};
this.getAmmo= function(){return _ammo};
this.getDirection = function(){return _direction};
this.getPvMod = function(){return _pvMod};
this.getManaMod = function(){return _manaMod};
this.getPoiseMod = function(){return _poiseMod};
this.getSpeedMod = function(){return _speedMod};
this.getAnimAtt = function(){return _animAtt};
this.getAnimZone = function(){return _animZone};
}
}
Now i'm trying to get my entitee (entity in English) hurt by an object i created, called "hammer". But i would like to be able to get it hurts by many different object.
I try to get it hurt when I press "P" and/or every 1 sec.
But I can't found how to give to the callback function the object I want the entity to get hurt with.
class Scene1 extends Phaser.Scene{
constructor() {
super("Scene1")
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> INIT
init(){
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PRELOAD
preload(){
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> CREATE
create(){
this.joueur = new Entitee(this, 100, 100, 100, 10, 200, 42, "square");
this.hammer = new Objet("Hammer", 12, 12, 12, 12, 0, -10, 0, 10, "empty", "empty");
this.timer_test = this.time.addEvent({ delay: 1000, callback: this.joueur.hurt, args: [this.joueur, this.hammer], loop: true });
this.input.keyboard.on('keydown-P', this.joueur.hurt, this.joueur, this.hammer);
this.joueur.hurt(this.hammer);
}//END CREATE
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> UPDATE
update(){
}//END UPDATE
}//END SCENE
i have this.joueur.hurt(this.hammer); working.
this.timer_test = this.time.addEvent({ delay: 1000, callback: this.joueur.hurt, args: [this.joueur, this.hammer], loop: true }); send me the following error :
Entitee.js:60 Uncaught TypeError: objet.getPvMod is not a function
at Function.Entitee.hurt (Entitee.js:60)
at Clock.update (phaser.js:183771)
at EventEmitter.emit (phaser.js:1774)
at Systems.step (phaser.js:35504)
at SceneManager.update (phaser.js:77851)
at Game.step (phaser.js:139643)
at TimeStep.step (phaser.js:67227)
at step (phaser.js:67474)
And when I press "p" i get
Entitee.js:60 Uncaught TypeError: objet.getPvMod is not a function
at Entitee.hurt (Entitee.js:60)
at KeyboardPlugin.emit (phaser.js:1752)
at KeyboardPlugin.update (phaser.js:166926)
at EventEmitter.emit (phaser.js:1751)
at onKeyDown (phaser.js:71462)
I figure how to avoid callback functions but it would be so easiest if I may give to those callback the arguments I want.
I've been lurking around internet for solutions but none of it have been useful. Some people seems to use console.log() but I can't understand why and how.
Thanks for considering my issue !
Sheolis
I suppose that args should be just [this.hammer] since we don't need joueur as input to the hurt function
this.timer_test = this.time.addEvent({
delay: 1000,
callback: this.joueur.hurt,
args: [this.hammer],
loop: true });
You may also look at callbackScope at the docs.

Create class with dynamic properties

I create a class for my RPG games, and I would like to ask the user the name of their character, how can I do this ?
Pitch is the base name I created, but I would like pitch to be replaced by the name given by the user
class Personnage {
constructor(nom, sante, force) {
this.nom = nom;
this.sante = sante;
this.force = force;
this.xp = 0;
}
const principal = new Personnage("Pitch", 150, 25);
Thx for your answers ! (sorry for my english aha)
Consider this version to achieve what you are trying.
class Personnage {
var _nom;
var _force;
var _xp;
constructor(nom, sante, force) {
_nom = nom;
_sante = sante;
_force = force;
_xp = 0;
}
const principal = new Personnage(some_user_variable, 150, 25);
Though it is unclear what you are trying to do. Does this help?

JavaScript, Trying to get buttons to move on click

/*
var young_link = {
power: 30,
cpower: 20,
hp: 3,
image: "../images/young_link.jpg",
};
var young_zelda = {
power: 30,
cpower: 20,
hp: 3,
}
var impa = {
power: 30,
cpower: 20,
hp: 3,
}
var hey = {
power: 30,
cpower: 20,
hp: 3,
}
//$("#test").html(young_link);
console.log(young_link);*/
$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
//var test = "<img src= '../images/young_link.jpg'>";
//var young_hero = ["young_link","young_zelda","impa", "malon"];
var young_hero = ["Link", "Bongo Bongo","Gandondorf","Queen Gohma"];
var health = [100, 70, 120, 50];
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<buttons>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({"data-name":young_hero[i],"data-health":health[i],"data-image":hero_image[i]});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
$(".hero_button").on("click" , function() {
var battle_ground = $("<div>");
battle_ground.addClass("hero hero_button");
battle_ground.text($(this).data("data-name"));
$("#battle").append(battle_ground);
});
});
The for loop is working and appending the buttons on the screen. But in $(".hero_button").on("click" , function() it is just putting a empty box on the page with a click. So, it is not taking the data that is attached to the button.
Sam answered your question correctly and rightly deserves the accepted answer. But I wanted to give you an insight into how you can do this in a cleaner way, without lots of arrays which must line up. Also without using jQuery at all. Below you can see a more object oriented way to do this.
You can see it in action in this jsFiddle
// Now we have an object which represents a hero. No need to duplicate loads of code.
function Hero(heroData) {
this.name = heroData.name;
this.health = heroData.health;
this.setImage = function() {
this.image = new Image();
this.image.src = heroData.imageSrc;
this.image.id = heroData.imageId;
}
this.createHeroButton = function() {
this.createButtonElement();
this.addButtonToPage();
this.attachButtonEvents();
}
this.createButtonElement = function() {
var heroButton = document.createElement('button');
heroButton.classList.add('hero,hero_button');
heroButton.setAttribute('name', this.name);
heroButton.setAttribute('health', this.health);
heroButton.appendChild(this.image);
this.button = heroButton;
}
this.attachButtonEvents = function() {
this.button.addEventListener('click', this.addButtonToPage.bind(this));
}
this.addButtonToPage = function() {
var container = document.getElementById('container');
container.appendChild(this.button);
}
this.takeDamage = function(damageValue) {
this.health -= damageValue;
this.button.setAttribute('health', this.health);
}
this.setImage();
}
// So here we create a Hero instance, in this case Link, we can use now describe links attributes, image, name, health...
var link = new Hero({
name: 'Link',
health: 100,
imageSrc: 'http://orig12.deviantart.net/8bb7/f/2011/276/4/e/four_swords_link_avatar_by_the_missinglink-d4bq8qn.png',
imageId: 'link-image'
});
var mario = new Hero({
name: 'Mario',
health: 100,
imageSrc: 'http://rs568.pbsrc.com/albums/ss123/stvan000/thumb-super-mario-bros-8bit-Mario.jpg~c200',
imageId: 'mario-image'
});
// Now we can easily make a button and add it to the page
link.createHeroButton();
mario.createHeroButton();
// Lets try decreasing the health on mario
mario.takeDamage(10);
// Because we have an object reference which handles all of our heros state we can decrease his health and update the buttons data without much trouble.
A couple of changes to get the data set and read correctly:
make button tags instead of buttons
use .attr() instead of .data() to get the attributes
See comments inline in the code below.
Also, instead of adding an attribute for the Image object of each item (which will add an attribute like data-image="[Object object]") just add an integer corresponding to the iterator index and use that to reference into the hero_image array when you need to get the corresponding image.
Additionally, you can use Array.forEach() to iterate over the items in the heroes array with a callback function. That way you don't have to worry about updating the iterator variable (i in this case) and indexing into the array. You should take a look at this functional programming guide which has some good exercises.
$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_heroes = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
young_heroes.forEach(function(young_hero,i) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero,
"data-health": health[i],
//instead of adding an attribute for the image object, just add an index
"data-index": i
});
hero_btns.text(young_hero);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
});
$(".hero_button").on("click", function() {
var battle_ground = $("<div>");
battle_ground.addClass("hero hero_button");
//use .attr() here instead of .data()
battle_ground.text($(this).attr("data-name"));
/** My additions -
* I am not sure exactly how this should be done
* so adjust accordingly
**/
//additionally, you can add attributes to the new battle_ground item
battle_ground.attr('data-health',$(this).attr("data-health"));
battle_ground.append(hero_image[$(this).attr("data-index")]);
battle_ground.append($(this).attr("data-health"));
/** End my additions **/
$("#battle").append(battle_ground);
});
});
#battle div {
border: 1px solid #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons"></div>
Battle ground:
<div id="battle"></div>

Javascript OOP : Help retrieving value from my this.obj.value [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
Enchant.js is not familiarly used, but since it using same OOP style like prototype.js i think i've got a chance to ask it here.
this is my main.js:
var DIR_LEFT = 0;
var DIR_RIGHT = 1;
var DIR_UP = 2;
var DIR_DOWN = 3;
enchant();
window.onload = function () {
game = new Core(320, 320);
game.preload(
'res/map0.png',
'res/chara0.png'
);
game.fps = 30;
game.onload = function() {
var sceneGame = new SceneGame();
game.pushScene(sceneGame);
}
game.start();
//main gameplay scene
var SceneGame = Class.create(Scene, {
initialize: function() {
Scene.apply(this);
var stage, map, player, label;
stage = new Group();
map = tileMap(game.assets['res/map0.png']);
player = new Player();
label = new Label("hi!");
player.addEventListener(Event.ENTER_FRAME, this.update);
this.player = player;
this.map = map;
stage.addChild(map);
stage.addChild(player);
this.Elx = 1;
this.label = label;
this.addChild(stage);
this.addChild(label);
var pad = new Pad();
pad.y = 220;
this.addChild(pad);
},
update: function() {
this.Elx = 2;
console.log("Elx :" + this.Elx );
console.log(this.player.x);
}
});
var Player = Class.create(Sprite, {
initialize: function() {
Sprite.apply(this, [32, 32]);
this.image = game.assets['res/chara0.png'];
this.x = 2 * 16;
this.y = 16;
this.dir = DIR_DOWN;
this.anim = [
9, 10, 11, 10,
18, 19, 20, 19,
27, 28, 29, 28,
0, 1, 2, 1];
// Frame setting
if (!game.input.up && !game.input.down && !game.input.right && !game.input.left) {
this.age = 1;
this.frame = this.anim[this.dir * 4 + (this.age % 4)];
}
},
update: function (evt) {
}
});
}
initialize is the Enchant.js object constructor method,
the code above successfully returning the stage group child ( map and player) images on screen, but when i want to use on update SceneGame's method,
the console returned 2 for the this.Elx
but returning undefined error for this.player.x .
Why this is happening ?
any help are appreciated . thank you
thank you guys for your answer, so basically is my fault for lack of understanding about the Grouping method. So in the line i declared :
map = tileMap(game.assets['res/map0.png']);
this.map = map;
player = new Player();
this.player = player;
stage = new Group();
stage.addChild(player);
stage.addChild(map);
map.addChild(stage);
and in the update i tried to call console.log(this.player)
of course it wont work because the player inserted in scene as a child. I tried to change above line to :
map = tileMap(game.assets['res/map0.png']);
player = new Player();
stage = new Group();
stage.addChild(player);
this.player = stage.childNodes[0];
stage.addChild(map);
this.map = stage.childNodes[1];
map.addChild(stage);
above code succesfully return any property of this.player.
So this is solved . thank you :)

objects in an array alerted randomly

I have built this code using javascript that makes a few objects called monster. I then put those monsters in an array and finally am trying to call one of thous monsters to the console randomly. Unfortunately it displays in my console log as undefined. Any advice on how to get a random monster in the console log every time I refresh the page?
function Monster(type, level, mAttack, mAgility, mHP) {
this.type = type;
this.level = level;
this.mAttack = mAttack;
this.mAgility = mAgility;
this.mHP = mHP;
}
Monster.prototype.logInfo = function() {
console.log("I am a : ", this.type);
console.log("I am level : ", this.level);
console.log("I have the attack of : ", this.mAttack);
console.log("I have the agility : ", this.mAgility);
console.log("I have the health : ", this.mHP);
}
var troll = new Monster("troll", 1, 10, 10, 10);
var skeleton = new Monster("skeleton", 1, 10, 10, 10);
var slime = new Monster("slime", 1, 10, 10);
var boar = new Monster("boat", 1, 10, 10);
var monsterList = new Array();
monsterList[0] = troll;
monsterList[1] = skeleton;
monsterList[3] = slime;
monsterList[4] = boar;
var summonRandomMonster = function (){
monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
}
console.log(monsterSummoner);
You create a function but never call it. Therefor monsterSummoner is never set.
// THIS IS NEVER CALLED
var summonRandomMonster = function (){
monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
}
console.log(monsterSummoner);
Try this instead. Notice that now that the function is called the value is set.
var monsterSummoner;
var summonRandomMonster = function (){
monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
}
summonRandomMonster();
console.log(monsterSummoner);
You're close... Change your last four lines as follows -
var monsterList = [troll,skeleton,slime,boar];
var summonRandomMonster = function (){
monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
console.log(monsterSummoner);
}
for (var i = 0; i < 100; i++) {
summonRandomMonster();
}
There are atleast two problems in this code. The variable "monsterSummoner" is not defined, and the function "summonRandomMonster" is not called.

Categories

Resources