How to show a word from the specified result - javascript

I'm having trouble displaying words on the screen. I want result 1,2,3,4,5,6,7,8,9,10 then it is Fail and 11,12,13,14,15,16,17,18 it is true but I am not expert family. Someone help me please? Sorry if it's hard for you to understand because I use google translate. Here is my code
let images = ["dice-01.svg",
"dice-02.svg",
"dice-03.svg",
"dice-04.svg",
"dice-05.svg",
"dice-06.svg"];
let dice = document.querySelectorAll("img");
function roll(){
dice.forEach(function(die){
die.classList.add("shake");
});
setTimeout(function(){
dice.forEach(function(die){
die.classList.remove("shake");
});
let dieOneValue = Math.floor(Math.random()*6);
let dieTwoValue = Math.floor(Math.random()*6);
let dieTthreeValue = Math.floor(Math.random()*6);
console.log(dieOneValue,dieTwoValue);
document.querySelector("#die-1").setAttribute("src", images[dieOneValue]);
document.querySelector("#die-2").setAttribute("src", images[dieTwoValue]);
document.querySelector("#die-3").setAttribute("src", images[dieTthreeValue]);
document.querySelector("#total").innerHTML = "Your roll is " + ( (dieOneValue +1) + (dieTwoValue + 1) + (dieTthreeValue + 1) );
},
1000
);
}
roll();
<div id="die-1"></div>
<div id="die-2"></div>
<div id="die-3"></div>
<div id="total"></div>

I'd suggest creating an array rollResults to contain the results of rolling each die.
We can then get the total score, using Array.reduce() to add the roll results together.
We would then output the individual die rolls along with the total and whether the roll was successful (e.g. if it was > 10):
let images = [
'https://upload.wikimedia.org/wikipedia/commons/0/09/Dice-1.svg',
'https://upload.wikimedia.org/wikipedia/commons/3/34/Dice-2.svg',
'https://upload.wikimedia.org/wikipedia/commons/c/ca/Dice-3.svg',
"https://upload.wikimedia.org/wikipedia/commons/1/16/Dice-4.svg",
"https://upload.wikimedia.org/wikipedia/commons/d/dc/Dice-5.svg",
"https://upload.wikimedia.org/wikipedia/commons/1/14/Dice-6.svg"
];
let dice = document.querySelectorAll("img");
function getDieResult() {
return Math.floor(Math.random() * 6) + 1;
}
function roll(){
dice.forEach(function(die){
die.classList.add("shake");
});
setTimeout(function(){
dice.forEach(function(die){
die.classList.remove("shake");
});
let rollResults = Array.from({ length: dice.length }, (v,k) => getDieResult());
let total = rollResults.reduce((total, roll) => total + roll);
rollResults.forEach((result, idx) => {
document.querySelector(`#die-${idx+1}`).setAttribute("src", images[result - 1]);
})
const success = (total > 10) ? "True": "False"
document.querySelector("#total").innerHTML = "<br>Your roll is " + rollResults.join(", ") + "<br> Total = " + total;
document.querySelector("#total").innerHTML += "<br>Success = " + success;
},
250
);
}
roll();
<img id='die-1' width='50px'>
<img id='die-2' width='50px'>
<img id='die-3' width='50px'>
<div id='total'></div>
<br>
<button onclick='roll()'>Roll the dice!</button>

You can simply sum up the values and use that
const dieSum = (dieOneValue +1) + (dieTwoValue + 1) + (dieTthreeValue + 1);
let result = (dieSum > 10); // true if <=10 or false if >=11
you can instead use this result in order to put whatever you want in the UI
document.querySelector("#total").innerHTML = dieSum > 10 ? "Pass" : "Fail"

As per the image it appears (& hence assumed) that the objective is to show each of the individual die-roll. Instead, the numbers are getting added and rendered.
Please replace this:
document.querySelector("#total").innerHTML = "Your roll is " + ( (dieOneValue +1) + (dieTwoValue + 1) + (dieTthreeValue + 1) );
With this:
document.querySelector("#total").innerHTML = "Your roll is " + (dieOneValue +1) + ', ' + (dieTwoValue + 1) + ', ' + (dieTthreeValue + 1);
Or, as suggested by DBS in comment below, we may use Template Strings like this:
document.querySelector("#total").innerHTML = `Your roll is $(dieOneValue +1), $(dieTwoValue + 1), $(dieTthreeValue + 1)`;
Either of the above methods would introduce a , ('comma') between each die-roll result. If 'comma' is not desired, you may use space.
Also: in case the objective is to display 'fail' if the total is 1, 2, ...10 and 'true' if the total is 11, 12, ... 18, then try this:
document.querySelector("#total").innerHTML = `Your roll is ${(dieOneValue + dieTwoValue + dieTthreeValue + 3) < 11 ? 'fail' : 'true'}`;

Related

Can't get a simple text-based fighting game function called from my html file to work properly (loops and if... else-statements)

I'm new to JavaScript (and programming in general). I was just playing around with this script that checks how many combat rounds it takes for fighter1 to knock out fighter2 and writes out all the combat events to the page.
When I call the fightClub(); function from my HTML-file, all that gets printed is "Test". How can I get this to work? Is my logic flawed?
Any help would be much appreciated! <3
const fighter1 = array ("Jimmy", 10, 2);
const fighter2 = array ("Chet", 10, 2);
function fightClub(fighter1, fighter2){
document.write('Test');
let hitcheck = math.ceil(math.random() * 10);
while (fighter2[1] > 0){
let roundNumber = 1;
roundNumber++;
if(hitcheck >= 5){
fighter2[1] = fighter2[1] - fighter1[2];
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' deals ' + fighter1[2] + ' damage to ' + fighter2[0]);
}else {
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' swung in the air and... missed ' + fighter2[0]);
}
if(fighter2[1] <= 0){
document.write(fighter2[0] + ' was knocked out.');
break;
}
}
}
You have several syntax errors in your code. Fix them and you'll see the result.
Here it is:
const fighter1 = ["Jimmy", 10, 2];
const fighter2 = ["Chet", 10, 2];
function fightClub(fighter1, fighter2){
document.write('Test');
let hitcheck = Math.ceil(Math.random() * 10); // use 'Math' not math
while (fighter2[1] > 0){
let roundNumber = 1;
roundNumber++;
if(hitcheck >= 5){
fighter2[1] = fighter2[1] - fighter1[2];
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' deals ' + fighter1[2] + ' damage to ' + fighter2[0]);
}else {
document.write('Round' + roundNumber);
document.write(fighter1[0] + ' swung in the air and... missed ' + fighter2[0]);
}
if(fighter2[1] <= 0){
document.write(fighter2[0] + ' was knocked out.');
break;
}
}
}
fightClub(fighter1, fighter2);

How to make a string non-appendable?

Is this even possible?
function from_country_to_country(country_from, country_to) {
// get the right zone prices
var zone_price = zone_finder(country_to['zone']);
$('#country_to_country').html(country_from['land']);
$('#call').html(formatPrice(country_from[zone_price]) + ' kr/min');
$('#recieve').html(formatPrice(country_from['receive_calls']) + ' kr/min');
$('#send_sms').html(formatPrice(country_from['send_sms']) + ' kr/SMS');
$('#recieve_sms').html(formatPrice(country_from['receive_sms']) + ' kr/SMS');
$('#opening_fee').html(formatPrice(country_from['opening_fee']) + ' kr');
}
function within_the_country(country) {
$('#from_within').html(country['land']);
$('#from_domestic').html(formatPrice(country['domestic']) + ' kr/min');
$('#from_RCF').html(formatPrice(country['receive_calls']) + ' kr/min');
$('#from_send_sms').html(formatPrice(country['send_sms']) + ' kr/SMS');
$('#from_recieve_sms').html(formatPrice(country['receive_sms']) + ' kr/SMS');
$('#from_opening_fee').html(formatPrice(country['opening_fee']) + ' kr');
$('#from_gprs_data').html(formatPrice(country['data_price'])+ ' kr/mb');
}
// Format prices from ex: turns 1 into 1,00
function formatPrice(n) {
if (!isNaN(parseFloat(n))) {
n = parseFloat(n);
n = Math.round(n * 100) / 100
n = n.toFixed(2);
return n;
} else {
// IF WE CAN MAKE "n" NON-APPENDABLE HERE
return n;
}
}
If n is not a number I dont want ' kr/mb' to be appended to the string. I know that I can check if it is a number and if not, dont append. But I have many different suffixes that I append onto the returning string of formatPrice(). So then I will need to check this everywhere. Is there a nice work around to this?
Adjust your formatPrice function to conditionally take in a unit:
function formatPrice(n, unit) {
if(!isNan(...)) {
...
return n + " " + unit;
}
else {
return n;
}
}
formatPrice(500, 'kr/mb');

Reversing my encrypt method

I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}

Flipping Shape Over Axis in JS

Here is the link to what i'm trying to do. I want to flip the blue bars to face to opposite way on the male side then I will fill in the female side as normal. This will create a tornado chart. I've been working on this for hours and I cant figure it out. I'm using Raphael JS.
http://math.mercyhurst.edu/~cmihna/DataViz/Butterfly.html
Just finished up reviewing your website's source code. No need for transforms, or anything of the such. Just some simple math added to your graph generating for-loop.
Your Code below
ind = 0
for (var key in gender) { // loop over all possible gender
for ( var i = 0; i < people.length; i++ ) { // loop over people
if (people[i][key] != 0) {
var barmale = paper.rect((w+leftPadding-rightPadding)/2,topPadding + vs*0 + i*vs, people[i][key],vs)
barmale.attr({'fill': '#0000A0', 'stroke-width':1})
var barfemale = paper.rect((w+leftPadding-rightPadding)/2, topPadding + vs*0 + i*vs, people2[i][key],-vs)
barfemale.attr({'fill': '#FFC0CB', 'stroke-width':1})
barmale.scale(1,-1)
//var dp = paper.circle(leftPadding + ind*hs + 0.5*hs, topPadding + vs*0.5 + i*vs, people[i][key])
//dp.attr({ 'fill': colors[ind] })
barmale.id = people[i][key] + " " + gender[key] + " people in this age range"
barmale.hover(hoverStart, hoverEnd)
barfemale.id = people[i][key] + " " + gender[key] + " people in this age range"
barfemale.hover(hoverStart, hoverEnd)
}
}
ind++
My Code Below
ind = 0
for (var key in gender) { // loop over all possible gender
for ( var i = 0; i < people.length; i++ ) { // loop over people
if (people[i][key] != 0) {
var barmale = paper.rect((w+leftPadding-rightPadding)/2 - people[i][key],topPadding + vs*0 + i*vs, people[i][key],vs)
barmale.attr({'fill': '#0000A0', 'stroke-width':1})
var barfemale = paper.rect((w+leftPadding-rightPadding)/2, topPadding + vs*0 + i*vs, people2[i][key],vs)
barfemale.attr({'fill': '#FFC0CB', 'stroke-width':1})
barmale.scale(1,-1)
//var dp = paper.circle(leftPadding + ind*hs + 0.5*hs, topPadding + vs*0.5 + i*vs, people[i][key])
//dp.attr({ 'fill': colors[ind] })
barmale.id = people[i][key] + " " + gender[key] + " people in this age range"
barmale.hover(hoverStart, hoverEnd)
barfemale.id = people2[i][key] + " " + gender[key] + " people in this age range"
barfemale.hover(hoverStart, hoverEnd)
}
}
ind++
You can see that I am subtracting the value of the Males from the placement on the graph. This causes the offset to "flip". Then, I modified the code a bit more the bring the female graph into the picture and properly label it.
Please let me know if any questions.
Proof below

Edit a variable within an array

I'm attempting to create a Choose Your Own Adventure type of game, and I'm currently trying to write a 'battle' script. What I've got so far is:
var name = "Anon";
var health = 100;
var youAttack = [name + " hits the " + opp + " with his sword", name + " uses magic!", name + " is too scared to fight!"];
var youBattle = function() {
var youBattle = youAttack[Math.floor(Math.random() * 3)];
return youBattle;
};
var opp = "Orc";
var oppHealth = 100;
var oppAttack = ["The " + opp + " hits you with his hammer!", "The " + opp + " does nothing!", "The " + opp + " back hands you!"];
var oppBattle = function() {
var oppBattle = oppAttack[Math.floor(Math.random() * 3)];
return oppBattle;
};
oppBattle();
youBattle();
I've done it like this so the opponent and player names can easily be changed.
What I'm struggling to figure out is how I can add / remove health from both the opponent and the player depending what attack is used. Obviously no health would be removed if the opp / player does nothing.
Is there a way I can do this without a bunch of messy if / else statements?
I was hoping for something easy like name + " hits the " + opp + " with his sword" + health = health - 10; but obviously that didn't work.
Thanks in advance!
http://jsbin.com/qerud/3/edit
Hope this isn't too much code:
var Attack = function(hero,opp,damageReceived,damageGiven,message){
this.message = message;
this.damageGiven = damageGiven;
this.damageReceived = damageReceived;
this.opp = opp;
this.hero = hero;
this.attack = function(opp){
this.hero.health -= damageReceived;
this.opp.health -= damageGiven;
return this.message;
};
};
var Character = function(name,health){
this.name = name;
this.health = health;
};
hero = new Character('Anon',100);
orc = new Character('Orc',150);
attack1 = new Attack(hero,orc,5,0,"The " + orc.name + " back hands you!");
attack2 = new Attack(hero,orc,0,0,hero.name + " is too scared to fight!");
attack3 = new Attack(hero,orc,15,0,"The " + orc.name + " hits you with his hammer!");
attack4 = new Attack(hero,orc,0,25,hero.name + " uses magic!");
attacks = [attack1,attack2,attack3,attack4];
while(hero.health > 0 && orc.health > 0){
console.log(attacks[Math.floor(Math.random() * 4)].attack());
console.log('Hero Health: '+ hero.health);
console.log('Orc Health: '+ orc.health);
}
if(hero.health > 0 ){
console.log(hero.name + ' won');
} else {
console.log('The ' + orc.name + ' won');
}
I can tell you first hand that trying to write this type of code uses a lot of if/else and more statements, regardless of what language you're using. You can use an array to hold the values of your attack patterns:
var attackName = ["Punch", "Sword", "Magic"]
var attackDamage = [3, 5, 4]
function youAttack(ATK, PHit) {
if(playerHit) {
playerDamage = ATK + PHit;
oppHealth = oppHealth - playerDamage;
return oppHeath;
} else {
alert("You missed!");
}
}
But, without seeing exactly what you're doing I cannot say how you should do your attacks and damages. I can only assume. You will need a system of evaluating attacks, misses, etc. that does use IF/ELSE Statements at least somewhere.

Categories

Resources