JQuery change variable / cost after click - javascript

Hey I'm trying to create a incremental game and am stuck.
You press one button and get a currency which is called "Evos". With these "Evos" you can buy a storyteller who will start to generate "Evos" on his own.
this is the code:
$(document).ready(function() {
"use strict";
var evoAmount = 0;
var storytellerAmount = 0;
var evoIncrement = 1;
var storyteller = {
Amount: 0,
Cost: 10,
Increment: 1
};
var tick = 1000;
var runstoryteller = setInterval(function () {
evoAmount = evoAmount + (storyteller.Increment * storyteller.Amount);
updateValues();
}, tick);
function updateValues(){
$('#evoAmount').html(evoAmount);
$('#storytellerAmount').html(storyteller.Amount);
}
/* Buy storytellers */
$('#storytellerBuy').click(function () {
if (evoAmount >= storyteller.Cost) {
evoAmount = evoAmount - storyteller.Cost;
storyteller.Amount++;
storyteller.Cost = (storyteller.Cost / 100) * 20;
updateValues();
}
});
$('#click').click(function(){
evoAmount = evoAmount + evoIncrement;
document.getElementById("evoAmount").innerHTML = evoAmount;
});
});
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://bootswatch.com/slate/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
<title>Evo-Clicker v1.0.0</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/click.js"></script>
<div class="main">
<button id="click" class="btn btn-default">Click</button>
<span id="evoAmount">0</span> EVOs <br><br>
<button id="storytellerBuy" class="btn btn-danger">Buy Storyteller</button><span id ="storytellerAmount">0</span> Storytellers
</div>
</body>
</html>
Basically i can buy the first storyteller for 10 Evos. But i want to increase the cost with each bought storyteller by 20%. But if i change the code it either goes into negative "Evos" or in this example you only have to pay once and then buy storytellers for free.
/* Buy storytellers */
$('#storytellerBuy').click(function () {
if (evoAmount >= storyteller.Cost) {
evoAmount = evoAmount - storyteller.Cost;
storyteller.Amount++;
updateValues();
}
});
This works but the stays the same. (Which i want to increase by 20% each time)

You should replace the calculation of cost
this is the right one
storyteller.Cost = (storyteller.Cost * 1.2);

Related

Create a multifuctional Javascript reveal function that works without duplicating the code

This is my first post on stackflow. I am pretty new to programming but I am trying to figure out how to efficiently produce a multi-functional function that will allow me to reveal information one step at a time for multiple divs/blocks seperately. For instance, this function only work for this specific button and div.
<!-- Function 1 -->
(function () {
var n = 1;
window.ShowStep1 = function () {
document.getElementById("Step1" + "-" + n++).style.visibility = "visible";
if (!document.getElementById("Step1" + "-" + n)) {
document.getElementById("step1").disabled = true;
}
document.getElementById("reset1").disabled = false;
}
window.ResetSteps1 = function () {
document.getElementById("step1").disabled = false;
document.getElementById("reset1").disabled = true;
var i = 1, step1; n = 1;
while (step1 = document.getElementById("Step1" + "-" + i)) {
step1.style.visibility = "hidden";
i++
}
}
})();
Where it will only work for the following:
<p>
<input type="button" onclick="ShowStep1()" value="Steps" id="step1"/>
<input type="button" onclick="ResetSteps1()" value="Reset" id="reset1" disabled="true"/>
</p>
But I want to do this with for many buttons with unique id's without having to manually make new functions. As of right now, in order for me to make multiple functions I have to manually create several of the Function 1 sets of code. How can I do this more efficiently if say I wanted to do 10 of these? The code works fine but I dont want to repeat myself. This code comes from the following link:
MathJax-demos-web-link
But I modified it in my own way. Any help and tips would be appreciated! Thanks in advance. For some reason there is an error in snippet but if you run it on jsfiddle it works fine. This is the entire script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width">
<title>MathJax v3 dynamic equations using CSS and javascript</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script>
MathJax = {
tex: {inlineMath: [['$', '$'], ['\\(', '\\)']]},
chtml: {
displayAlign: 'left'
},
startup: {
pageReady: function () {
//
// Do the usual startup (which does a typeset).
// When that is all done, un-hide the page.
//
return MathJax.startup.defaultPageReady().then(function () {
document.getElementById("hidden").disabled = true;
});
}
}
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-chtml.js"></script>
<script type="text/javascript">
<!-- Function 1 -->
(function () {
var n = 1;
window.ShowStep1 = function () {
document.getElementById("Step1" + "-" + n++).style.visibility = "visible";
if (!document.getElementById("Step1" + "-" + n)) {
document.getElementById("step1").disabled = true;
}
document.getElementById("reset1").disabled = false;
}
window.ResetSteps1 = function () {
document.getElementById("step1").disabled = false;
document.getElementById("reset1").disabled = true;
var i = 1, step1; n = 1;
while (step1 = document.getElementById("Step1" + "-" + i)) {
step1.style.visibility = "hidden";
i++
}
}
})();
<!-- Function 2 -->
(function () {
var n = 1;
window.ShowStep2 = function () {
document.getElementById("Step2" + "-" + n++).style.visibility = "visible";
if (!document.getElementById("Step2" + "-" + n)) {
document.getElementById("step2").disabled = true;
}
document.getElementById("reset2").disabled = false;
}
window.ResetSteps2 = function () {
document.getElementById("step2").disabled = false;
document.getElementById("reset2").disabled = true;
var i = 1, step2; n = 1;
while (step2 = document.getElementById("Step2" + "-" + i)) {
step2.style.visibility = "hidden";
i++
}
}
})();
</script>
<style>
#Step1-1, #Step1-2, #Step1-3, #Step1-4, #Step1-5,
#Step2-1, #Step2-2, #Step2-3, #Step2-4, #Step2-5 {
visibility: hidden;
}
</style>
</head>
<body>
<h1>Dynamic Equations in MathJax</h1>
<div id="frame">
<p>
Expand the following:
\begin{align}
(x+1)^2
&= \cssId{Step1-1}{(x+1)(x+1)} \\[3px]
&\cssId{Step1-2}{{} = x(x+1) + 1(x+1)} \\[3px]
&\cssId{Step1-3}{{} = (x^2+x) + (x+1)} \\[3px]
&\cssId{Step1-4}{{} = x^2 + (x + x) + 1} \\[3px]
&\cssId{Step1-5}{{} = x^2 + 2x + 1}
\end{align}
</p>
<p>
<input type="button" onclick="ShowStep1()" value="Steps" id="step1"/>
<input type="button" onclick="ResetSteps1()" value="Reset" id="reset1" disabled="true"/>
</p>
</div>
<div id="frame">
<p>
Expand the following:
\begin{align}
(x+1)^2
&= \cssId{Step2-1}{(x+1)(x+1)} \\[3px]
&\cssId{Step2-2}{{} = x(x+1) + 1(x+1)} \\[3px]
&\cssId{Step2-3}{{} = (x^2+x) + (x+1)} \\[3px]
&\cssId{Step2-4}{{} = x^2 + (x + x) + 1} \\[3px]
&\cssId{Step2-5}{{} = x^2 + 2x + 1}
\end{align}
</p>
<p>
<input type="button" onclick="ShowStep2()" value="Steps" id="step2"/>
<input type="button" onclick="ResetSteps2()" value="Reset" id="reset2" disabled="true"/>
</p>
</div>
</body>
</html>
The main change will be to create one version each of the two functions which take parameters rather than storing step information in variables which happens now.
However, before that, a couple of other observations:
The HTML is not 'legal' - ids need to be unique and frame ids are not unique in the given code.
This extra CSS styling a slight alarm bell, does it mean you can't have more than 5 steps?
#Step1-1, #Step1-2, #Step1-3, #Step1-4, #Step1-5,
#Step2-1, #Step2-2, #Step2-3, #Step2-4, #Step2-5 {
visibility: hidden;
}
This snippet renames the frame ids so they are unique, removes the multi-style settings above and substitutes the more general 'style elements whose id starts with Step'.
It then makes just one step-revealing function and one reset function and calls them with parameters. It does not try to store values of 'n' to show where the revealing has got to in each case but instead works it out each time by looking for those steps that are already visible.
Note that (as noted in the question) it is not possible to run this in the SO snippet system which is sandboxed so here is the complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width">
<title>MathJax v3 dynamic equations using CSS and javascript</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script>
MathJax = {
tex: {inlineMath: [['$', '$'], ['\\(', '\\)']]},
chtml: {
displayAlign: 'left'
},
startup: {
pageReady: function () {
//
// Do the usual startup (which does a typeset).
// When that is all done, un-hide the page.
//
return MathJax.startup.defaultPageReady().then(function () {
document.getElementById("hidden").disabled = true;
});
}
}
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-chtml.js"></script>
<script>
(function () {
window.ShowStep = function (el, id) {
//go through all the elements with id id-n and set the first non visible one to visible
const steps = document.querySelectorAll('[id^="' + id + '"]');
for (let i = 0; i < steps.length; i++) {
if (steps[i].style.visibility != 'visible') {
steps[i].style.visibility = 'visible';
break;
}
}
el.nextElementSibling.disabled = false;
}
window.ResetSteps = function (el, id, reset) {
el.disabled = false;
//go through all the elements with id id-n and set them all to hidden
const steps = document.querySelectorAll('[id^="' + id + '"]');
for (let i = 0; i < steps.length; i++) {
steps[i].style.visibility = 'hidden';
}
}
})();
</script>
<style>
[id^="Step"] {
visibility : hidden;
}
</style>
</head>
<body>
<h1>Dynamic Equations in MathJax</h1>
<div id="frame1">
<p>
Expand the following:
\begin{align}
(x+1)^2
&= \cssId{Step1-1}{(x+1)(x+1)} \\[3px]
&\cssId{Step1-2}{{} = x(x+1) + 1(x+1)} \\[3px]
&\cssId{Step1-3}{{} = (x^2+x) + (x+1)} \\[3px]
&\cssId{Step1-4}{{} = x^2 + (x + x) + 1} \\[3px]
&\cssId{Step1-5}{{} = x^2 + 2x + 1}
\end{align}
</p>
<p>
<input type="button" onclick="ShowStep(this, 'Step1', 'reset1');" value="Steps"/>
<input type="button" onclick="ResetSteps(this, 'Step1', 'reset1')" value="Reset" disabled="true"/>
</p>
</div>
<div id="frame2">
<p>
Expand the following:
\begin{align}
(x+1)^2
&= \cssId{Step2-1}{(x+1)(x+1)} \\[3px]
&\cssId{Step2-2}{{} = x(x+1) + 1(x+1)} \\[3px]
&\cssId{Step2-3}{{} = (x^2+x) + (x+1)} \\[3px]
&\cssId{Step2-4}{{} = x^2 + (x + x) + 1} \\[3px]
&\cssId{Step2-5}{{} = x^2 + 2x + 1}
\end{align}
</p>
<p>
<input type="button" onclick="ShowStep(this, 'Step2', 'reset2');" value="Steps" id="step2"/>
<input type="button" onclick="ResetSteps(this, 'Step2', 'reset2')" value="Reset" id="reset2" disabled="true"/>
</p>
</div>
</body>
</html>

Why does my Fish Game score overlay itself as it updates?

The game works by a fish eating smaller fish and slowly growing bigger. The score is supposed to update each time the fish eats another fish. The score will update to one right when you eat a fish, but it won't update to a 2 until you eat a bunch of fish(it varies), and then the 2 shows up over the 1.
Read at your own risk:
<!DOCTYPE html>
<html>
<head>
<title> Fish Game! </title>
<script src="https://simplycodingcourses.com/files/simplyjs/simply.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
function start(){
sjs.open("target", 800, 500);
var background = new sjs.Image("Images/background.png");
background.setSize(sjs.getWidth(), sjs.getHeight());
//Player Properties below here
var player = new sjs.Image("Images/fish_left.png");
player.type = "player";
player.setSize(100,50);
player.friction = .1;
player.accel = .6;
sjs.keyDown(RIGHT_KEY, function(){
player.setImage("Images/fish_right.png");
player.pushRight();
});
sjs.keyDown(LEFT_KEY, function(){
player.setImage("Images/fish_left.png");
player.pushLeft();
});
sjs.keyDown(UP_KEY, function(){
player.pushUp();
});
sjs.keyDown(DOWN_KEY, function(){
player.pushDown();
});
//Powerup
setInterval(function(){
var x = Math.floor(Math.random() * 783);
var y = Math.floor(Math.random() * 470);
var powerUp = new
sjs.Image("Images/crumbs.png");
powerUp.type = "powerUp";
powerUp.setGravity();
powerUp.setSize(17,30);
powerUp.noBounds = true;
powerUp.moveTo(x, y);
powerUp.friction = 0.2;
}, 5000);
sjs.onHit("powerUp", "bottom_screen", function(x,y){
x.destroy();
});
sjs.onHit("player","powerUp", function(x,y){
x.grow(60,30);
setTimeout(function(){
x.grow(-60,-30)
}, 5000);
y.destroy();
});
//Enemies
setInterval(function(){
var speed = Math.round(1 + Math.random()*10);
if(Math.random() > 0.5){
var enemy = new sjs.Image("Images/fish2_right.png");
enemy.type = "enemy";
enemy.setSize(100,50);
enemy.noBounds = true;
enemy.friction = 0;
enemy.pushRight(speed);
enemy.scaleSize(.5 + Math.random() *1.2);
enemy.moveTo(-enemy.getWidth(), Math.random()*(enemy.getClamp().y));
} else{
var enemy = new sjs.Image("Images/fish2_left.png");
enemy.type = "enemy";
enemy.setSize(100,50);
enemy.noBounds = true
enemy.friction = 0;
enemy.pushLeft(speed);
enemy.scaleSize(.5 + Math.random() * 1.2);
enemy.moveTo(sjs.getWidth(), Math.random()*(enemy.getClamp().y));
}
sjs.left_screen.offset(-500);
sjs.right_screen.offset(500);
sjs.onHit("enemy",["right_screen","left_screen"],function(x,y){
x.destroy();
});
//Score
var score = 0;
var score_txt = new sjs.Text("Score: ", 21, "orange");
sjs.onHit("player","enemy",function(x,y){
if(x.getWidth() > y.getWidth() && x.getHeight() > y.getHeight()) {
score = score + 1;
score_txt.setText("Score: " + score);
localStorage.setItem("score", score);
x.grow(10,5);
if(score >= 20){
window.location = "win.html";
}
} else {
//x.destroy();
//window.location = "gameover.html";
console.log("Normally I would die but that got annoying so for now you will just get me AAAAA");
}
y.destroy();
});
},1000);
} //end start
</script>
</head>
<body onload="start()">
<h1>Fish Dominance</h1>
<div id="target" style="margin:auto;background:white;"></div>
</body>
</html>
Actually, I know nothing about that library Simply.js but it looks from the picture that you are drawing on the same text, and by looking at your code, I see the object score_txt = new sjs.Text("Score: ", 21, "orange"); that's being created every 1 second, so you should just create it once inside the start function at the beginning and the same goes for the score variable to keep track of the score for example
function start(){
var score = 0;
var score_txt = new sjs.Text("Score: ", 21, "orange");
// the rest of your code
}

want a bit of clarification of what this simple js function does and how

hey guys i got a balloon game that speeds up the balloon when i hover the mouse over one of them, got a few questions:
1.doesn't the speedup function just add to that balloons cell value?
it doesn't seem to change the pixels it should go up in any way,just updates the objects speed value
2.this function: onmouseover="speedUp(' + i + ')
when i hover the the object does it get a number associated with that object that was set by the render balloons function like a data attribute? i don't quite get this
here is the code:
'use strict';
var gNextId = 101;
var gBalloons = createBalloons()
var gInterval;
function startGame() {
renderBalloons();
gInterval = setInterval(() => {
moveBalloons();
}, 500);
}
function renderBalloons() {
var strHtml = '';
for (let i = 0; i < gBalloons.length; i++) {
var balloon = gBalloons[i];
strHtml += '<div class="balloon balloon' + (i + 1) +
'" onclick="popBalloon(this)" ' +
'" onmouseover="speedUp(' + i + ')" >' +
balloon.txt +
'</div>'
}
// console.log('strHTML', strHtml);
document.querySelector('.balloon-container').innerHTML = strHtml;
}
function moveBalloons() {
var elBalloons = document.querySelectorAll('.balloon');
for (let i = 0; i < elBalloons.length; i++) {
var balloon = gBalloons[i];
var elBalloon = elBalloons[i];
balloon.bottom += balloon.speed;
elBalloon.style.bottom = balloon.bottom + 'px';
if (balloon.bottom >= 800) clearInterval(gInterval);
}
}
function popBalloon(elBalloon) {
var popSound = new Audio('sounds/pop.mp3');
popSound.play();
elBalloon.classList.add('fade');
}
function speedUp(idxBalloon) {
console.log('Speeding up: ', gBalloons[idxBalloon])
gBalloons[idxBalloon].speed += 10;
}
function createBalloons() {
var ballons = [
createBalloon('A'),
createBalloon('B'),
createBalloon('C')
];
return ballons
}
function createBalloon(txt) {
return { id: gNextId++, bottom: 0, speed: 45, txt: txt }
}
The HTML if its needed:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./css/main.css">
</head>
<body onload="startGame()">
<div class="balloon-container"></div>
</body>
<script src="./javascript/main.js"></script>
</html>
Each balloon has an object associated with it:
{ id: gNextId++, bottom: 0, speed: 45, txt: txt }
and stored in ballons array (aliased to gBalloons in top-level scope).
When the game starts, every 500ms each balloon is moved by the number of pixels defined in its speed property (performed by moveBalloons() function).
When you hover over a particular balloon, its speed increases by 10.
onmouseover handler knows which balloon speed to increase because it gets its position (index i) in gBalloons array: speedUp(' + i + ') upon creation of html.

How to display the div with content in a vbhtml using Javascript

I am trying to display content in a div inside a popover using Javascript and facing some issue. Below is the code. Hope someone can help..
1) ASP.Net master page that calls the pop up vbhtml page
window.izenda=false;
$("#NextGenReportsLink").click(function(){
if(!window.izenda)
{
PleaseWaitOpen();
window.izenda=true;
$.get("/Report/NextGenReportViewer", function(data){
$("#NextGenReportSelectorNew").append(data)
});
}
});
2) The vbhtml page that should pop up on click of #NextGenReportsLink
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<link href="~/Scripts/EmbeddedUI/izenda-ui.css?db1ebd9b10aa86f1fd76" rel="stylesheet">
<link href="~/Content/ReportsFiles/Css/jquery.webui-popover.css" rel="stylesheet" />
<link href="~/Content/ReportsFiles/Css/nanoscroller.css" rel="stylesheet" />
<link href="~/Content/ReportsFiles/Css/reports.css" rel="stylesheet" />
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="~/Content/ReportsFiles/Js/jquery.webui-popover.js"></script>
<script src="~/Content/ReportsFiles/Js/jquery.nanoscroller.min.js"></script>
</head>
<body>
<div class="row" id="data" >
<div class="container" id="izenda-root"></div>
</div>
<script type="text/javascript" src="~/Scripts/EmbeddedUI/izenda_common.js?db1ebd9b10aa86f1fd76"></script>
<script type="text/javascript" src="~/Scripts/EmbeddedUI/izenda_locales.js?db1ebd9b10aa86f1fd76"></script>
<script type="text/javascript" src="~/Scripts/EmbeddedUI/izenda_vendors.js?db1ebd9b10aa86f1fd76"></script>
<script type="text/javascript" src="~/Scripts/EmbeddedUI/izenda_ui.js?db1ebd9b10aa86f1fd76"></script>
<script type="text/javascript" src="~/Scripts/izenda.integrate.js"></script>
<script type="text/javascript">
$(document).ready(function () {
debugger;
//$("#NextGenReportsLink").click();
PleaseWaitClose();
DoIzendaConfig();
izendaInit();
document.getElementById('NextGenReportSelectorNew').style.display = "block";
var Wid = $(window).width();
var Hei = $(window).height() - (38 + 85);
var Per98 = parseInt(98 / 100 * Wid)
var Per1 = parseInt((Wid - Per98) / 2);
var options = {
valueNames: ['name']
};
$('#NextGenReportsLink').webuiPopover({
placement: 'vertical',
trigger: 'click',
width: Per98,
offsetTop: -10,
height: Hei,
arrow: true,
title: 'NextGenReports',
closeable: true,
animation: 'fade',
onHide: function () { $("#loadingDiv").hide(); },
onShow: function () {
var Wid = $(window).width();
var Hei = $(window).height() - (38 + 85);
var Per98 = parseInt(98 / 100 * Wid)
var Per1 = parseInt((Wid - Per98) / 2);
$('.webui-popover.fade').css('left', Per1);
var ll = $('#NextGenReportsLink').offset().left + ($('#NextGenReportsLink').width() / 2)
$('.webui-arrow').css('left', (ll - Per1) + 10);
},
content: $('#data').html(),
type: 'html'
});
$(window).resize(function () {
debugger;
if ($('.webui-popover').is(':visible')) {
var Wid = $(window).width();
var Hei = $(window).height() - (38 + 85);
var Per98 = parseInt(98 / 100 * Wid)
var Per1 = parseInt((Wid - Per98) / 2);
var ll = $('#NextGenReportsLink').offset().left + ($('#NextGenReportsLink').width() / 2)
$('.webui-arrow').css('left', ll - Per1 + 9);
}
})
});
</script>
</body>
</html>
izendaInit(); function loads a UI into the izenda-root div, however that div is not getting displayed. Instead the below div is getting displayed
I can see another div with the same id "izenda-root" being loaded with the data but I'm not sure how to display that div. Any help is much appreciated.. Please let me know if you need any more documentation on the js/css files referred to in the vbhtml..
3) Below is the izenda.integrate.js
//This function will point the front-end at an Izenda API
var DoIzendaConfig = function () {
var configJson = {
"WebApiUrl": "http://x.x.x.x:yy/api/",
"BaseUrl": "/",
"RootPath": "Scripts/EmbeddedUI",
"CssFile": "izenda-ui.css",
"Routes": {
"Settings": "settings",
"New": "new",
"Dashboard": "dashboard",
"Report": "report",
"ReportViewer": "reportviewer",
"ReportViewerPopup": "reportviewerpopup",
"Viewer": "viewer"
},
"Timeout": 3600,
};
IzendaSynergy.config(configJson);
};
//Error checking during token generation
function errorFunc() {
alert('Token was not generated correctly.');
}
//DoRender will called via successFunc
var DoRender = function (successFunc) {
$.ajax({
type: "GET",
url: "https://xxxx.mock.pstmn.io/GenerateToken",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
};
//The IzendaSynergy.render function will render the entire Izenda front-end with an independent navigation
var izendaInit = function () {
function successFunc(data, status) {
var currentUserContext = {
token: data.token
};
IzendaSynergy.setCurrentUserContext(currentUserContext);
IzendaSynergy.render(document.getElementById('izenda-root'));
}
this.DoRender(successFunc);
};

Function with if-else doesn't work properly

I made a function which should disable a button if a variable isn't greater than or equal to another one. This function is run every second on a setInterval(), and the first variable to compare is also incremented by one on the setInterval(). But, the function (evitarNegs()), isn't working properly, and the button is always disabled. Sorry that part of the code is in spanish.
Javascript:
var GmB = {cantidad: 0, perSec: 1};
function Upgrade (pb, ps) {
this.precioBase = pb;
this.perSec = ps;
this.cantidad = 0;
this.precio = pb;
}
Upgrade.prototype.comprar = function() {
GmB.cantidad = GmB.cantidad - this.precio;
GmB.perSec = GmB.perSec + this.perSec;
this.cantidad++;
document.getElementById("gmb").innerHTML = GmB.cantidad;
this.precio = Math.ceil(this.precioBase*Math.pow(1.15, this.cantidad));
evitarNegs();
};
function loop() {
GmB.cantidad = GmB.cantidad + GmB.perSec;
document.getElementById("gmb").innerHTML = GmB.cantidad;
evitarNegs();
}
var upg = new Upgrade(10, 1);
var boton1 = document.getElementById("boton1");
boton1.disabled = true;
window.setInterval(loop, 1000);
//Problematic function
function evitarNegs() {
if (!(GmB >= upg.precio)) {
boton1.disabled = true;
}else {
boton1.disabled = false;
}
}
boton1.onclick = function() {
upg.comprar();
};
HTML:
<html>
<head>
<title>Gummy Bears</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="gmb">0</p>
<button id="boton1" type="button">Upgrade 1</button>
<script src="main.js"></script>
</body>
</html>
You are comparing GmB to upg.precio, but GmB is an object. So you want
function evitarNegs() {
if (!(GmB.cantidad >= upg.precio)) {
boton1.disabled = true;
} else {
boton1.disabled = false;
}
}
However, this can be written much easier as
function evitarNegs() {
boton1.disabled = GmB.cantidad < upg.precio;
}
Fiddle: http://jsfiddle.net/4rRmp/
It seems that you are comparing an object to an integer in GmB >= upg.precio. You probably have to replace it by GmB.cantidad >= upg.precio.

Categories

Resources