My function seem not to work and I am not sure why. It should return true or false but it doesnt. I am trying to calculate if the value is lower than 0 and if so return false, true otherwise.
function tickets(peopleInLine){
// ...
var twentyfive = 0;
var fifty = 0;
var hundred = 0;
function checkforsales() {
if ((twentyfive < 0) || (fifty < 0) || (hundred < 0)) {
return false
} else {
return true
}
}
for (let i = 0; i < peopleInLine.length; i++) {
if(peopleInLine[i] === 25) {
twentyfive = twentyfive + 25;
} else if (peopleInLine[i] === 50) {
fifty = fifty + 50;
twentyfive = twentyfive - 25;
checkforsales();
} else {
hundred = hundred + 100;
checkforsales();
}
}
}
console.log(tickets([25, 100]));
function tickets(peopleInLine){
// ...
var twentyfive = 0;
var fifty = 0;
var hundred = 0;
function checkforsales() {
if ((twentyfive < 0) || (fifty < 0) || (hundred < 0)) {
return false
} else {
return true
}
}
for (let i = 0; i < peopleInLine.length; i++) {
if(peopleInLine[i] === 25) {
twentyfive = twentyfive + 25;
} else if (peopleInLine[i] === 50) {
fifty = fifty + 50;
twentyfive = twentyfive - 25;
} else {
hundred = hundred + 100;
}
}
return checkforsales();
}
console.log(tickets([25, 100]));
You need to return checkforsales function as below
function tickets(peopleInLine){
// ...
var twentyfive = 0;
var fifty = 0;
var hundred = 0;
function checkforsales() {
if ((twentyfive < 0) || (fifty < 0) || (hundred < 0)) {
return false
} else {
return true
}
}
for (let i = 0; i < peopleInLine.length; i++) {
if(peopleInLine[i] === 25) {
twentyfive = twentyfive + 25;
} else if (peopleInLine[i] === 50) {
fifty = fifty + 50;
twentyfive = twentyfive - 25;
} else {
hundred = hundred + 100;
}
}
return checkforsales();
}
Related
I have the mazeGen class that generates a maze using a version of prims algorithm using JS and P5.JS. Within the mazeGen class i have a display funtion that logs the maze to console. When i run this line it says it is not defined as a funtion. THe class will be used in another progect to generate multiple mazes to need it as a class
let maze1
function setup() {
maze1 = new MazeGen(11);
maze1.display()
}
function draw() {
background(220);
}
class MazeGen {
constructor(size) {
console.warn('in funt')
this.size = size
this.maze = new Array(this.size);
for (let i = 0; i < this.maze.length; i++) {
this.maze[i] = new Array(this.size);
for (let j = 0; j < this.maze.length; j++) {
this.maze[i][j] = 0
}
}
this.maze = this.PrimsAlgorithm()
this.maze[1][0] = 3;
this.maze[this.maze.length - 2][this.maze.length - 1] = 2;
console.table(this.maze);
return this.maze;
}
PrimsAlgorithm() {
this.frontAvailable = [0, 0, 0, 0];
this.currentCell = [1, 1];
while (this.Complete(this.maze, this.size) === false) {
//Console.WriteLine("Maze is not ready");
this.maze[this.currentCell[0]][this.currentCell[1]] = 1;
this.frontAvailable = this.Frontier(this.maze, this.currentCell);
//While the list of frontier cells is not empty
while (this.frontAvailable[0] !== 0 || this.frontAvailable[1] !== 0 || this.frontAvailable[2] !== 0 || this.frontAvailable[3] !== 0) {
//pick a random way
this.picked = false;
this.numSelected = 5;
while (this.picked === false) {
this.numSelected = Math.floor(Math.random() * 5);
if (this.frontAvailable[this.numSelected] === 1) {
this.picked = true;
}
}
//'Move to cell'
this.maze = this.MoveSquare();
this.frontAvailable = this.Frontier();
//Maze.PrintWhole(maze);
}
//List of frontier Cells is now empty
//Move to random cell and check if it is a path
this.currentCell = this.NewCurrent();
}
return this.maze;
}
Frontier() {
this.available = [0, 0, 0, 0];
//left check
if (((this.currentCell[1]) - 2) >= 0 && this.maze[this.currentCell[0]][(this.currentCell[1]) - 2] === 0) {
this.available[0] = 1;
} else {
this.available[0] = 0;
}
//up check
if (((this.currentCell[0]) - 2) >= 0 && this.maze[(this.currentCell[0]) - 2][(this.currentCell[1])] === 0) {
this.available[1] = 1;
} else {
this.available[1] = 0;
}
//right check
if (this.currentCell[1] + 2 < this.maze.length) {
if (this.maze[this.currentCell[0]][(this.currentCell[1]) + 2] === 0) {
this.available[2] = 1;
}
} else {
this.available[2] = 0;
}
//down check
if (this.currentCell[0] + 2 < this.maze.length) {
if (this.maze[this.currentCell[0] + 2][this.currentCell[1]] === 0) {
this.available[3] = 1;
}
} else {
this.available[3] = 0;
}
return this.available;
}
NewCurrent() {
this.found = false
this.currentCell = [];
while (this.found === false) {
this.cellX = Math.floor(Math.random() * (this.maze.length - 3) / 2)
this.cellX = this.cellX * 2 + 1
this.cellY = Math.floor(Math.random() * (this.maze.length - 3) / 2)
this.cellY = this.cellY * 2 + 1
if (this.maze[this.cellX][this.cellY] === 1) {
this.currentCell[0] = this.cellX;
this.currentCell[1] = this.cellY;
this.found = true
}
}
return this.currentCell;
}
MoveSquare() {
if (this.numSelected === 0) {
this.maze[this.currentCell[0]][(this.currentCell[1]) - 2] = 1;
this.maze[this.currentCell[0]][(this.currentCell[1]) - 1] = 1;
this.currentCell[1] = this.currentCell[1] - 2;
}
if (this.numSelected === 1) {
this.maze[(this.currentCell[0]) - 2][(this.currentCell[1])] = 1;
this.maze[(this.currentCell[0]) - 1][(this.currentCell[1])] = 1;
this.currentCell[0] = this.currentCell[0] - 2;
}
if (this.numSelected === 2) {
this.maze[this.currentCell[0]][(this.currentCell[1]) + 2] = 1;
this.maze[this.currentCell[0]][(this.currentCell[1]) + 1] = 1;
this.currentCell[1] = this.currentCell[1] + 2;
}
if (this.numSelected === 3) {
this.maze[(this.currentCell[0]) + 2][(this.currentCell[1])] = 1;
this.maze[(this.currentCell[0]) + 1][(this.currentCell[1])] = 1;
this.currentCell[0] = this.currentCell[0] + 2;
}
return this.maze;
}
Complete() {
let counter = 0;
//Console.WriteLine(counter);
for (let i = 0; i < (this.size - 1) / 2; i++) {
for (let j = 0; j < (this.size - 1) / 2; j++) {
let X = (2 * i) + 1;
let Y = (2 * j) + 1;
if (this.maze[X][Y] === 1) {
counter++;
}
}
}
return counter === (this.size - 1) / 2 * (this.size - 1) / 2;
}
display(){
console.table(this.maze);
}
}
If you return this.maze on constructor it will be an Array, Arrays don't have a display funcion
let maze1;
function setup() {
maze1 = new MazeGen(11);
maze1.display();
}
class MazeGen {
constructor(size) {
this.size = size;
this.maze = new Array(this.size).fill(1);
return this;//This is not really need it
}
display() {
console.log("In Display function");
console.log(this.maze);
}
}
setup();
The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.
More examples here : What does a JavaScript constructor return?
Are you trying to show the maze, or get what type of display it is on a webpage?
P5.js does not have such a method called .display(). However, there is a method called .show(), which makes the element visible. In normal web JavaScript, if you want to get or change the display type, you need to use the .style.display property.
I'm using a number of boxes that are floating around the screen, I want for them to bounce away from each other when they collide and I am testing this by just changing their colours instead when they collide, for some reason their colour changes at the start(their starting colour is white and if they collide it should change to red but they start and stays red). Is there something I am doing wrong? I would also like for everything to be done within the constructor function. I am sorry for not commenting my code as yet.
function BoxSplash()
{
this.sample = [];
var test = false;
this.col = color(129)
this.changeColour = function()
{
this.col = color(random(0,255),random(0,128),random(0,255))
}
this.intersect = function(other)
{
for(var i = 0; i < numberss; i++)
{ var currentBox = this.sample[i]
var d = dist(currentBox.x,currentBox.y,other.x,other.y)
if(d < currentBox.width + other.width)
{
return true;
}
else
{
return false
}
}
noLoop()
}
this.draw = function()
{
stroke(255)
line(0,windowHeight/2,windowWidth,windowHeight/2)
stroke(0)
for(var i = 0; i < numberss; i++)
{
var box = {
x:random(0,windowWidth - 50),
y:random(windowHeight/2 ,windowHeight - 50),
width:50,
height:50,
speedX:random(1,5),
speedY:random(1,5)
}
this.sample.push(box)
}
//use numberss variable to work with gui
for(var i = 0; i < numberss; i++)
{
fill(this.col)
rect(this.sample[i].x,this.sample[i].y,50,50)
}
this.move()
}
this.move = function()
{
for(var i = 0; i < numberss; i++)
{
var shape = this.sample[i]
shape.x += shape.speedX
shape.y += shape.speedY
if(shape.x + shape.width >= windowWidth || shape.x <= 0 )
{
shape.speedX = -shape.speedX
}
if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2)
{
shape.speedY = -shape.speedY;
}
for(var j = 0; j < numberss; j++)
{
var others = this.sample[j]
var d = dist(shape.x,shape.y,others.x,others.y)
if( i != j && d < shape.width + others.width)
{
test = true;
}
else
{
test = false
}
if(test)
{
this.col = color(255,0,0)
}
}
}
}
}
You should visit this link and transform their circles into your boxes.
1st: Calculate dist(object1.x, object.y, object2.x, object2.y) and save into a variable called d
2nd:
if (d < object1.h + object2.h) {
// Enter your code here
}
I'm trying to code a game and I want to make it so that when you click a button, it increases the number. My game is like a mining game and you click to get ores and at the top right is a box which tells you what you are mining and you can see what you are mining, except when I click the mine button, it comes with the error which says ReferenceError: hello is not defined. The function hello is the function which gives you the ores.
I have tried fixing up some other functions which give you helpers in exchange for help but it didn't change anything, also I checked on stack overflow, but there wasn't anything that could help me. (Keep in mind I am 10 years old)
HTML:
<div class="mwrapper">
<button id="minebutton" onclick="hello()">Mine!</button>
</div>
JavaScript:
//defining the vars.
var stonei = 0;
var deepness = 0;
var stone = 0;
var silveri = 0;
var silver = 0;
var goldi = 0;
var gold = 0;
var platinumi = 0;
var platinum = 0;
var diamondi = 0;
var diamond = 0;
var alexandritei = 0;
var alexandrite = 0;
var amethysti = 0;
var amethyst = 0;
var unobtaniumi = 0;
var unobtanium = 0;
var emeraldi = 0;
var emerald = 0;
var tubi = 0;
var tub = 0;
var blockN;
var block = 0;
var money = 0;
var stoneSold = 0;
var silverSold = 0;
var goldSold = 0;
var clickers = 0;
var moneyEver = 0;
var BpS = 0;
//defining element to shorten code later
var blockEl = document.getElementById("block");
var btxtEL = document.getElementById("btxt");
var moneyEl = document.getElementById("money");
//changing what the 'Block you are mining' says
var findBlock = function(b) {
if (b === 0) {
blockEl.style.backgroundColor = "grey";
btxt.innerHTML = "Stone";
blockN = "stone";
}
else if (b === 1) {
blockEl.style.backgroundColor = "silver";
btxt.innerHTML = "Silver";
blockN = "silver";
}
else if (b === 2) {
blockEl.style.backgroundColor = "gold";
btxt.innerHTML = "Gold";
blockN = "gold";
}
else if (b === 3) {
blockEl.style.backgroundColor = "rgb(90, 89, 89)";
btxt.innerHTML = "Platinum"
blockN = "platinum";
}
else if (b === 4) {
blockEl.style.backgroundColor = "rgb(185, 242, 255)";
btxt.innerHTML = "Diamond"
blockN = "diamond";
}
else if (b <= 10) {
btxt.innerHTML = "Not coded yet";
}
//hehe
else {
btxt.innerHTML = "WHAAAA?????????";
}
}
//adds materials to the left sidebar
var createBlock = function(b) {
if (b === 0) {
stonei += 1;
stone += 1;
document.getElementById("stonei").innerHTML = stonei;
document.getElementById("stone").innerHTML = stone;
}
else if (b === 1) {
silveri += 1;
silver += 1;
document.getElementById("silveri").innerHTML = silveri;
document.getElementById("silver").innerHTML = silver;
}
else if (b === 2) {
goldi += 1;
gold += 1;
document.getElementById("goldi").innerHTML = goldi;
document.getElementById("gold").innerHTML = gold;
}
else if (b === 3) {
platinumi += 1;
platinum += 1;
document.getElementById("platinumi").innerHTML = platinumi;
document.getElementById("platinum").innerHTML = platinum;
}
else if (b === 4) {
diamondi += 1;
diamond += 1;
document.getElementById("diamondi").innerHTML = diamondi;
document.getElementById("diamond").innerHTML = diamond;
}
//not coded rest
}
//From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
//for finding the block when you mine
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
//when you click the mine button it does this
var hello = function() {
if (deepness === stone + silver + gold + platinum + diamond && stone >= stonei && silver >= silveri && gold >= goldi && platinum >= platinumi && diamond >= diamondi && stoneSold == stone - stonei && moneyEver == money + clickers &&typeof hsjsahjkd === 'undefined' || hsjsahjkd === null) {
if (deepness <= 50) {
block = 0;
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 50, deepness < 150) {
block = getRandomInt(0, 2);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 150, deepness < 250) {
block = getRandomInt(0, 3);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 250, deepness < 350) {
block = getRandomInt(0, 4);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 350) {
block = getRandomInt(0, 5);
findBlock(block);
deepness += 1;
createBlock(block)
}
}
else {
btxt.innerHTML = "Cheater.";
stonei = 0;
deepness = 0;
stone = 0;
silveri = 0;
silver = 0;
goldi = 0;
gold = 0;
platinumi = 0;
platinum = 0;
diamondi = 0;
diamond = 0;
alexandritei = 0;
alexandrite = 0;
amethysti = 0;
amethyst = 0;
unobtaniumi = 0;
unobtanium = 0;
emeraldi = 0;
emerald = 0;
tubi = 0;
tub = 0;
stoneSold = 0;
silverSold = 0;
goldSold = 0;
clickers = 0;
moneyEver = 0;
BpS = 0;
console.log("You cheated. The game restarted.")
if (typeof hsjsahjkd == 'undefined') {
var hsjsahjkd = 1;
}
else {
hsjsahjkd += 1;
}
document.getElementById("cheat").innerHTML = hsjsahjkd;
}
}
Sorry, but the functions needed are quite long. If you want to see the whole code, go to megagames.me/games/mining.html
I expected the out put of hello() to increment some of the ores, but it gave ReferenceError: hello is not defined.
Make sure your JavaScript is linked in the head tag or above the button. Otherwise you'll be calling a function that doesn't exist yet. An easy way to remember is to think of it as a book, you read from top to bottom the same way JavaScript executes top to bottom.
Also, try using Let and Const instead of Var and try using Switch Cases instead of if else all over. :-)
i have this 2 codes and want change the JS file.
Currently that's how it works:
--> the animation starts only when you click in the navigation.
I want play the animation if my site is loaded but i don't finde the function to change the code.
you can find the animation here: https://tympanus.net/Development/ShapeOverlays/index3.html
Thank you so much.
html:
<div class="animation">
<svg class="shape-overlays" viewBox="0 0 100 100" preserveAspectRatio="none">
<path class="shape-overlays__path"></path>
<path class="shape-overlays__path"></path>
<path class="shape-overlays__path"></path>
</svg>
</div>
JS-File:
setTimeout(() => document.body.classList.add('render'), 60);
class ShapeOverlays {
constructor(elm) {
this.elm = elm;
this.path = elm.querySelectorAll('path');
this.numPoints = 2;
this.duration = 600;
this.delayPointsArray = [];
this.delayPointsMax = 0;
this.delayPerPath = 200;
this.timeStart = Date.now();
this.isOpened = false;
this.isAnimating = false;
}
toggle() {
this.isAnimating = true;
for (var i = 0; i < this.numPoints; i++) {
this.delayPointsArray[i] = 0;
}
if (this.isOpened === false) {
this.open();
} else {
this.close();
}
}
open() {
this.isOpened = true;
this.elm.classList.add('is-opened');
this.timeStart = Date.now();
this.renderLoop();
}
close() {
this.isOpened = false;
this.elm.classList.remove('is-opened');
this.timeStart = Date.now();
this.renderLoop();
}
*/
updatePath(time) {
const points = [];
for (var i = 0; i < this.numPoints; i++) {
const thisEase = this.isOpened ?
(i == 1) ? ease.cubicOut : ease.cubicInOut:
(i == 1) ? ease.cubicInOut : ease.cubicOut;
points[i] = thisEase(Math.min(Math.max(time - this.delayPointsArray[i], 0) / this.duration, 1)) * 100
}
let str = '';
str += (this.isOpened) ? `M 0 0 V ${points[0]} ` : `M 0 ${points[0]} `;
for (var i = 0; i < this.numPoints - 1; i++) {
const p = (i + 1) / (this.numPoints - 1) * 100;
const cp = p - (1 / (this.numPoints - 1) * 100) / 2;
str += `C ${cp} ${points[i]} ${cp} ${points[i + 1]} ${p} ${points[i + 1]} `;
}
str += (this.isOpened) ? `V 0 H 0` : `V 100 H 0`;
return str;
}
render() {
if (this.isOpened) {
for (var i = 0; i < this.path.length; i++) {
this.path[i].setAttribute('d', this.updatePath(Date.now() - (this.timeStart + this.delayPerPath * i)));
}
} else {
for (var i = 0; i < this.path.length; i++) {
this.path[i].setAttribute('d', this.updatePath(Date.now() - (this.timeStart + this.delayPerPath * (this.path.length - i - 1))));
}
}
}
renderLoop() {
this.render();
if (Date.now() - this.timeStart < this.duration + this.delayPerPath * (this.path.length - 1) + this.delayPointsMax) {
requestAnimationFrame(() => {
this.renderLoop();
});
}
else {
this.isAnimating = false;
}
}
}
Well, you missed last part
(function() {
const elmHamburger = document.querySelector('.hamburger');
const gNavItems = document.querySelectorAll('.global-menu__item');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
elmHamburger.addEventListener('click', () => {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
elmHamburger.classList.add('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.add('is-opened');
}
} else {
elmHamburger.classList.remove('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.remove('is-opened');
}
}
});
}());
There is event listener click attached to button elmHamburger, That is executing anonymous arrow function. If you want to run that animation on load, you need to replace click event with load.
That is:
elmHamburger.addEventListener('click', () => {...};
with
window.document.addEventListener('load', () => {...};
If you want to start animation on load and keep button event, then
(function() {
const elmHamburger = document.querySelector('.hamburger');
const gNavItems = document.querySelectorAll('.global-menu__item');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
const func = () => {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
elmHamburger.classList.add('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.add('is-opened');
}
} else {
elmHamburger.classList.remove('is-opened-navi');
for (var i = 0; i < gNavItems.length; i++) {
gNavItems[i].classList.remove('is-opened');
}
}
}
elmHamburger.addEventListener('click', func);
window.addEventListener('load', func);
}());
I get my password spec from an API which then I split the object into the needed fields and check that I have the required number of lower, upper, special and length of my password.
function isStrong(passwordChecker) {
if (!passwordChecker) {
return false;
}
debugger;
var securityOption = JSON.parse(localStorage.getItem("Security"));
var MinLength = securityOption.PasswordMinRequiredLength;
var SpecialChars = securityOption.PasswordMinRequiredNonalphanumericCharacters;
var MinLowercase = securityOption.PasswordMinRequiredLowercase;
var MinUppercase = securityOption.PasswordMinRequiredUppercase;
//LenghtCheck
if (passwordChecker.length < MinLength);
return false;
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
if (MinLowercase > 0) {
if (!CountLowerCase(passwordChecker) > MinLowercase) {
return false;
}
}
if (MinUppercase > 0) {
if (!CountUpperCase(passwordChecker) > MinLowercase) {
return false;
}
}
}
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
function MinLowercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 97 && text[i] <= 122) {
Count++;
}
}
}
function MinUppercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 65 && text[i] <= 90) {
Count++;
}
}
}
Now what I want to do is, check the different conditions as a whole and if all of the conditions are true then change the class to green..
$(pageId + ' #password').bind('keyup', function () {
var currentpassword = $(pageId + ' #password').val();
if (isStrong(currentpassword)) {
$(pageId + ' #password').addClass('green');
} else {
$(pageId + ' #password').addClass('red');
}
});
I am not sure how to check the conditions as a whole and return an overall true because as I start trying in my password it instantly changes to green as in my password spec you do not need any UpperCase or LowerCase letters so on any input of a char it returns true..
You should refactor your functions so that they accept both the string and the parameter and return true or false. For example:
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
Should instead be:
function CountSpecialChars(text, min) {
var count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
count++;
}
}
return count > min;
}
return CountSpecialChars(passwordChecker, SpecialChars);
Also, as a bonus, you could also avoid that for loop for those functions by using replace, like so:
function MinChars(text, min) {
return text.length > min;
}
function MinUppercase(text, min) {
var non_uppers = /[^A-Z]/g;
var uppers = text.replace(non_uppers, text);
return uppers.length > min;
}
function MinLowercase(text, min) {
var non_lowers = /[^a-z]/g;
var lowers = text.replace(non_lowers, text);
return lowers.length > min;
}
function MinSpecialChars(text, min) {
var non_specials = /[^!-\?]/g;
var specials = text.replace(non_specials, text);
return specials.length > min;
}
Now with those functions, you can have:
if !MinChars(pw, MinLength) return false;
if !MinSpecialChars(pw, SpecialChars) return false;
if !MinLowercase(pw, MinLowercase) return false;
if !MinUppercase(pw, MinUppercase) return false;
return true;