Javascript - How do I clear out a previous value in a DIV? - javascript

i'm making a game where 2 players are fighting one another.
I have it setup where the document writes the objects hp out (100). However, when I make a event where the player suffers 10 damage, it should write out 90 in the hp bar. Instead it writes out 10090.
How can I get it where the previous value gets updated, rather than it continuing to write beside the previous value?
function player (hp, mana, stamina){
this.hp = hp;
this.mana = mana;
this.stamina = stamina;
}
function npc (hp, mana, stamina) {
this.hp = hp;
this.mana = mana;
this.stamina = stamina;
}
var alistar = new player (100, 50, 30);
var dragon = new npc (100, 50, 30);
document.getElementById("hp").innerHTML += alistar.hp;
if ( 0 < 1) {
alistar.hp = alistar.hp - 10;
document.getElementById("hp").innerHTML += alistar.hp;
}
Doing the = sign works, but it removed any HTML words I had in there. I suppose I can make a 2nd div box for my HTML needs and keep the value seperate.

Just put = symbol instead of +=:
The = operator overwrite the previous value. On the other hand, the += is the union between the + operator and the = operator, and is the "shortway" to achieve the next:
For example, if you want to add a value to a variable you can do this:
var a = 3,
value = 10; /* Your value, i.e. 10 */
a = a + value; /* a values 13 */
BUT, you can get the same result using the += operators:
var a = 3,
value = 10; /* Your value, i.e. 10 */
a = += value; /* This adds the value of a to the value of value variable. */
As you can think, the value of a is 13, too as the below example.
Regarding to your code...
CODE:
if ( 0 < 1) {
alistar.hp = alistar.hp - 10;
document.getElementById("hp").innerHTML = alistar.hp; /* UPDATE */
}

if ( 0 < 1) {
alistar.hp = alistar.hp - 10;
document.getElementById("hp").innerHTML = alistar.hp;
}
+= is concatenating the values and adding them together (seemingly in string format). Instead, you want to use "=" to assign the value of the hp to the hp element, overwriting the existing innerHTML.

Related

How to display text sequentially using P5.js deviceMoved() function?

I am currently trying to make a program where the text changes as the phone moves every couple value(s) using the P5.JS deviceMoved() function.
(the gif below displays how i wanted the text to change eventually as the device moved)
As seen on the code below, I've put all the text in the array and I wanted to change the index to +1 each time say the move value ads 30 and repeat until all the text is gone.
let button;
let permissionGranted = false;
let nonios13device = false;
let cx, cy
let value = 0;
var myMessages = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "The", "Lazy", "Dog"];
var index = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(255)
text(myMessages[index], width / 2, height / 2);
fill(value);
text(value, width / 3, height / 3);
textSize(30)
}
function deviceMoved() {
value = value + 5;
if (value > 255) {
value = 0;
}
}
function onMove() {
var currentValue = value + 30;
if (value = currentValue) {
index++;
return;
}
if (index >= myMessages.length) {
index = 0;
}
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.3.1/lib/p5.js"></script>
I think my problem is within the onMove function, where I need to define the current value and what values could change the text, I'm fairly new at this so any insight/solution to do this would be highly appreciated :)
Thank you!
There are several issues related to the onMove function. First and foremost it is never called, and unlike deviceMoved it is not a special function that p5.js automatically invokes. Additional issues:
function onMove() {
// You create a currentValue variable that is just value + 30.
// Within the same function, checking if value is >= currentValue,
// assuming that is what you intended, will be fruitless because it
// is never true.
// What you probably want to do is declare "currentValue" as a global
// variable and check the difference between value and currentValue.
var currentValue = value + 30;
// This is the assignment operator (single equal sign), I think you meant
// to check for equality, or more likely greater than or equal to.
if (value = currentValue) {
index++;
// You definitely do not want to return immediately here. This is where
// you need to check for the case where index is greater than or equal
// to myMessages.length
return;
}
if (index >= myMessages.length) {
index = 0;
}
}
Here's a fixed version:
function deviceMoved() {
value = value + 5;
if (value > 255) {
// When value wraps around we need to update currentValue as well to
// keep track of the relative change.
currentValue = 255 - value;
value = 0;
}
onMove();
}
let currentValue = 0;
function onMove() {
if (value - currentValue >= 30) {
// Update currentValue so that we will wait until another increment of
// 30 before making the next change.
currentValue = value;
index++;
// We only need to make this check after we've incremented index.
if (index >= myMessages.length) {
index = 0;
}
}
}
In order to test this out on my mobile device (iOS 14) I had to add some code to request access to the DeviceMotionEvent, and host it in an environment using HTTPS and not embedding in an iframe. You can see my code on glitch and run it live here.

javascript: clicking numerical boxes - increment not working

using the code below, I've created a grid of buttons, 5x5, with random 1-25 numbers assigned to each button. They are to be clicked in numerical order, each's background turns red when clicked in the correct order. I can't use a global variable for this prompt. Without a global variable, I can't figure out how to increment the correctNumbers function which checks whether the right number is clicked each time. I think I'm missing something, a js function or something that would enable an incrementing variable declared within the incrementing function. I'm not looking for the whole explanation, just tips on functions i might not know about, and whether or not what i'm trying to do just isn't logicly possible.
<div id="numbers" class="hidden"></div>
<div id="youWon" class="hidden">You Won!</div>
The relevant JS:
... /**
* Gives the numbers a random order
* the "Fisher-Yates shuffle" found at: https://www.frankmitchell.org/2015/01/fisher-yates/
* #param {*} array
*/
const shuffle = (array) => {
let i = 0,
j = 0,
temp = null
for (i = array.length - 1; i > 0; i -= 1) {
j = Math.floor(Math.random() * (i + 1))
temp = array[i]
array[i] = array[j]
array[j] = temp
}
}
/**
* Generates an array of numbers 1-25
*/
const generateNums = () => {
document.getElementById("youWon").classList.toggle("hidden", "visible");
const numberArray = [];
for (let a = 1; a <= 25; a++) {
numberArray.push(a);
}
shuffle(numberArray);
let numEl = document.getElementById('numbers'); //write into html div id "numbers"
for (let b = 0; b <= 24; b++) { //loop to create button array
let newBtn = document.createElement('button'); //create buttons
newBtn.className = 'number'; //assign newBtns 'number' class
newBtn.innerText = numberArray[b]; //assign numbers to each button
numEl.appendChild(newBtn); //match with number elements in "numbers" array
newBtn.addEventListener("click", onNumberClick) //create function trigger
}
}
/**
* Creates a function to decide correct and incorrect clicks
* When a user clicks a number, if it is the next number in order, then it turns a different color for the remainder of the test
* If it is the wrong number, nothing happens
* #param {*} event
*/
const incrementNum = (correctNumber) => {
correctNumber++;
}
const onNumberClick = (event) => {
let correctNumber = 1; //start at 1
let numberVal = event.target; //apply it to clicks on the numbers
if (Number(numberVal.innerHTML) + 1 == incrementNum(correctNumber)) {
incrementNum(correctNumber);
numberVal.classList.add("red");
}
if (correctNumber == 26) {
document.getElementById("youWon").classList.toggle("visible"); //show win message if 25 is the last button and gets clicked
}
}
I would suggest that you count the number of elements in the DOM that have the class "red" and add 1... checking if the innerHTML is equal to that number to get the sequence right. So, instead of this:
if (Number(numberVal.innerHTML) + 1 == incrementNum(correctNumber)) {
incrementNum(correctNumber);
numberVal.classList.add("red");
}
You can have something like this:
if(Number(numberVal.innerHTML) == document.getElementsByClassName('red').length + 1) {
numberVal.classList.add("red");
}

Color Spectrum Optimization

I have the following implementation, it works and functional. I am checking if fname properties are same in the following javascript object, then I assign the same color for these paired objects.
Here is one javascript object sample:
{"value": 10,"series": 1,"category": "LG","fname": "","valueColor": ""},
However, I would like to use more distinguished colors, rather than very similar color, for example in the given fiddle, colors are almost all in green spectrum. Also I do not want to give any color value where value property equals to 0
Here is the core implementation
function colorSpectrum(N) {
var colorMap = [], inc = 50, start = 1000;
for (i = start; i < start+N*inc; i+=inc) {
var num = ((4095 * i) >>> 0).toString(16);
while (num.length < 3) {
num = "0" + num;
}
colorMap.push("#" + num);
}
return colorMap;
}
function process(data){
var map = {}, colorMap = colorSpectrum(data.length);
data.forEach(function(item, index){
if(!map.hasOwnProperty(item.fname)){
map[item.fname] = colorMap[index];
}
data[index].valueColor = map[item.fname];
});
return data;
}
FIDDLE
Try picking random colors
function colorSpectrum(N) {
var colorMap = [];
for (i = 0; i < N; i+=1) {
var color = getRndColor()
colorMap.push("#"+color);
}
return colorMap;
}
function getRndColor() {
var n = Math.floor(Math.random()*255*255*255);
var hex = Number(n).toString(16);
while(hex.length < 6) {
hex = "0"+hex;
}
return hex;
}
If you want a full range of colors from black to white, you need to change this part:
var colorMap = [], inc = 50, start = 1000;
for (i = start; i < start+N*inc; i+=inc) {
You see, the loop starts from 1000, which is the color #3e8, already green. The scale should go from 0 to 4095 (for 3-character values like #007, #abc, etc...), with having the increment based on the amount of data.
However, I'd suggest getting at least a little bit of the control by having all RGB components generated separately instead of the full HEX value right away.

Javascript: Some Variables Defined, Some Undefined

I am writing a basic casino javascript game that will randomly pick 3 numbers 1-10. If each number is 7, it will display an alert box saying 'You Win!'. In the function below:
function StartSpin(){
var one;
var two;
var three;
var cone;
var ctwo;
var cthree;
var one = Math.floor((Math.random() * 10) + 1);
var two = Math.floor((Math.random() * 10) + 1);
var three = Math.floor((Math.random() * 10) + 1);
if(one == 1){var cone = "Ace";}
if(two == 1){var ctwo = "Ace";}
if(three == 1){var cthree = "Ace";}
document.getElementsByClassName("Spinner")[0].innerHTML= cone
document.getElementsByClassName("Spinner")[1].innerHTML= ctwo
document.getElementsByClassName("Spinner")[2].innerHTML= cthree
}
On the actual page before clicking the button to start randomizing it says:
--|--|--. When clicking it, it sets the --'s to the randomized number. Every number/-- set says undefined except sometimes one will say 'Ace' meaning it was 1. So it might say: undefined|Ace|undefined, or undefined|undefined|undefined, etc.
Here is the HTML:
<div id="GameOne">
<h1>~ Game One ~</h1>
<h2>Try to get three 7's!</h2>
<span class="so Spinner">--</span> |
<span class="st Spinner">--</span> |
<span class="sth Spinner">--</span>
<br/>
<button id="SpinButton" onclick="StartSpin()">Spin!</button>
</div>
EDIT: I re-defined variables to see if that would help the undefined problem(In the javascript code fyi)
The short answer is you are only giving your variables values other than undefined if you randomly get the number 1. Otherwise they stay undefined - which is the default value of variables in JavaScript.
Here's some seriously cleaned up logic:
http://jsbin.com/milibusaxe/1/edit?html,js,output
function roll() {
var n = Math.floor((Math.random() * 10) + 1);
return (n === 1 ? 'Ace!' : n);
}
function StartSpin(){
var slots = document.getElementsByClassName("Spinner");
for (var i = 0, e = slots.length; i < e; i++) {
slots[i].innerHTML = roll();
}
}
document.getElementById('SpinButton').addEventListener('click', StartSpin);
As a side note, three sevens or three ones? Might want to make up your mind on that one.
They are being set to undefined because you are only setting the variables (cone, ctwo, cthree) when a 1 is randomly selected. I assume if an ace isn't drawn you want the number to be displayed?
function StartSpin() {
for (var i = 0; i < 3; i++) {
var num = Math.floor((Math.random() * 10) + 1);
if (num == 1) {
num = 'Ace';
}
document.getElementsByClassName("Spinner")[i].innerHTML = num;
}
}
You define the cone, ctwo and ctreeonly if one, two or three (respectively) equals to 1. Otherwise, variables are not initiated and that's why they are undefined.
See undefined
You can try this:
https://jsfiddle.net/0jaxL1hb/1/
Looks like you are having some trouble with how variables work. cone, ctwo, & cthree are undefined in most cases unless you get a 1. Also you only need to declare var in front of a variable when you create it. Later references just use the variable name:
var i = 1;
var j = i + 5;
console.log("i is", i, "and j is", j); // will print `i is 1 and j is 5`
A declared variable without a set value will be undefined
var k;
console.log(k); // will print `undefined`
In you code you are trying to transform 1 into the string "Ace", but you end up throwing out the values in one, two, and three in ALL other cases. This should work instead:
function StartSpin() {
// Function to make a number between 1 and 10, if 1 return "Ace" instead
function randomNumberOrAce() {
var number = Math.floor((Math.random() * 10) + 1);
// Check here if it's a `1`, and return "Ace instead", otherwise return the previously stored value
if (number === 1) {
return "Ace";
} else {
return number;
}
}
// Fill in the first three elements of ".Spinner" with three random numbers
document.getElementsByClassName("Spinner")[0].innerHTML = randomNumberOrAce();
document.getElementsByClassName("Spinner")[1].innerHTML = randomNumberOrAce();
document.getElementsByClassName("Spinner")[2].innerHTML = randomNumberOrAce();
}
<div id="GameOne">
<h1>~ Game One ~</h1>
<h2>Try to get three 7's!</h2>
<span class="so Spinner">--</span> |
<span class="st Spinner">--</span> |
<span class="sth Spinner">--</span>
<br/>
<button id="SpinButton" onclick="StartSpin()">Spin!</button>
</div>

for loop variable expressions mathematical manipulating

I'm writing a program in JS and im feeling i'm repeating code, which is not good. I'm trying to avoid an if then else block that has two similar for loop and re-write it without an if then else using just one for loop.
Consider this: minimum has value 0. maximum has value 10. if new_value is less than old_value i wanna execute a for loop from minimum to new_value, else i wanna execute it from maximum DOWNto new_value
Lets see it in action, lets say javascript (language-agnostic answers are welcome and upvoted -but will not grant you an extra cookie)
var minimum = 0;
var maximum = 10;
var old_value = 5;
/* var new_value = taken from user input whatever ... */
if(new_value<old_value)
{
for(i=minimum;i<new_value;i++)
{
// whatever
}
}
else
{
for(i=maximum;i>new_value;i--)
{
// whatever
}
}
I have a feeling these two for loops are similar enough to be written as one in a mathematical approach maybe. Have tried a bit using absolute values Math.abs() Math.max.apply() but had no luck.
I don't want to set other helping variables using if then else to give appropriate values.
So, whats the question: I'm wondering if this can be rewritten in one for ... loop without being nested in an if then else.
A complete solution using built-in js functions will grant you an extra cookie.
Edit: Didn't see your original thing about not using the if/else with variables. Why not do something like this then? Just go from 0 to 10, using that value or 10 minus that value depending on the conditional.
for(var j = 0; j <= 10; j++) {
var i = new_value < old_value ? j : 10 - j;
// whatever
}
Assign your min, max and increment as variables, define them based on your if condition and then use them in the for loop:
var old_value = 5, start, end, inc;
if(new_value<old_value) {
start = 0;
end = 10;
inc = 1;
} else {
start = 10;
end = 0;
inc = -1;
}
for( i = start;i >= start && i <= end; i += inc) {
// whatever
}
You could abuse of the ternary operator just for fun:
var minimum = 0;
var maximum = 10;
var old_value = 5;
var new_value = 7;
/* var new_value = taken from user input whatever ... */
var check =(new_value<old_value);
var foo1 = function () { console.log("foo1") }
var foo2 = function () { console.log("foo2") }
for(i=check?minimum:maximum;
check?(i<new_value):(i>new_value);
check?i++:i--)
{
check?foo1():foo2();
}
Does the second loop have to iterate in reverse? If not you can simply use
var i0 = new_value<old_value ? minimum : new_value+1;
var i1 = new_value<old_value ? new_value : maximum+1;
for(i=i0;i<i1;++i)
{
//whatever
}
Edit: In the light of your comment, if you can be sure that you're dealing with integers you can use
var i0 = new_value<old_value ? minimum : maximum;
var d = new_value<old_value ? 1 : -1;
for(i=i0;i!=new_value;i+=d)
{
//whatever
}
If not
var i0 = new_value<old_value ? minimum : maximum;
var d = new_value<old_value ? 1 : -1;
for(i=i0;d*i<d*new_value;i+=d)
{
//whatever
}
I did it!
With this +(old_value>new_value) instead of getting true/false i am getting 1/0. I am using the 1 and 0 as multipliers to emulate the if then else functionality.
lets assume
var minimum = 0;
var maximum = 10;
var old_value = 5;
for(expression1;expression2;expression3)
For expression1:
if new value is bigger than old value then we need minimum
if new value is smaller than old value then we need maximum
I am multiplying be zero the maximum depending the above conditions with (maximum*(+(old_value>new_value)))
I am multiplying by zero the minimum depending the above conditions with (minimum*(+(old_value<new_value))
by adding these two the sum is what i am supposed to get! (maximum*(+(old_value>new_value)))+(minimum*(+(old_value<new_value)))
This will give minimum if new_value > old value and maximum if new_value < old_value
For expression2:
while i!=new_value; simple. (we just have to be sure the maximum is bigger than new_value and minimum is smaller than new_value or we have an endless loop.)
For expression3:
if new value is bigger than old value then we need i=i +1
if new value is smaller than old value then we need i=i -1
this
(+(old_value<new_value)+1)+(-1*(+(old_value>new_value)+1))
will give either 2+-1=1 or 1+(-2)=-1 so we simply use it in expression3 as
i=i+(+(old_value<new_value)+1)+(-1*(+(old_value>new_value)+1))
complete code:
http://jsfiddle.net/eBLat/
var minimum = 0;
var maximum = 10;
var old_value = 5;
var new_value = 3; // change this value
// if new value is bigger than old value then for loop from maximum downto new_value (dont include new value)
// if new value is smaller than old value then for loop from minimum upto new_value (dont include new value)
for(i=(maximum*(+(old_value>new_value)))+(minimum*(+(old_value<new_value)));i!=new_value;i=i+(+(old_value<new_value)+1)+(-1*(+(old_value>new_value)+1)) )
{
alert("Iteration:"+i);
}
Another question would be if this is actually better than just write two for in a if then else ... anyway i had fun. And i got the cookie :D :D
Hope someone will find useful in some way the fact that +true gives 1 and +false gives 0 in javascript

Categories

Resources