JavaScript Craps game using two arrays to generate the "point" - javascript

There are no errors on plnkr.co, yet the div button still doesn't work.
1) Am I on the right track for pulling two random numbers from two arrays, adding them and returning the result when the button is clicked.
2) I saw the undefined error when I ran the code on here, but I am not sure what to troubleshoot. The code didn't give any errors on plnkr.co.
//button event will generate 2 random numbers and add them together
var num1 = [1,2,3,4,5,6];
var num2 = [1,2,3,4,5,6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice(){
var randomNumber = Math.floor(Math.random()*(num1 + num2));
document.getElementById("roll").innerHTML = randomNumber[rollDice];
}
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
<link rel="stylesheet" href="random.css">
<script src="craps.js"></script>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="randomNumber()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>

A few issues with your code:
you need to actually call rollDice() function.
you can't find randomNumber like that, you need two random index to select two numbers from the two arrays you have defined. you can use Math.random() for this, like in the code below:
randomNumber[rollDice] is wrong since randomNumber is a number and not an object.
//button event will generate 2 random numbers and add them together
var num1 = [1,2,3,4,5,6];
var num2 = [1,2,3,4,5,6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice(){
var randomIndex1 = Math.floor(Math.random()*num1.length);
var randomIndex2 = Math.floor(Math.random()*num2.length);
var randomNumber = num1[randomIndex1] + num2[randomIndex2];
document.getElementById("roll").innerHTML = randomNumber;
}
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
<link rel="stylesheet" href="random.css">
<script src="craps.js"></script>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="rollDice()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>

I seen a few things. I refactored to what I believe you was trying to achieve.
//button event will generate 2 random numbers and add them together
var num1 = [1, 2, 3, 4, 5, 6];
var num2 = [1, 2, 3, 4, 5, 6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice() {
//random # between 1 and 6
var dice1 = Math.floor((Math.random() * num1.length) + 1);
var dice2 = Math.floor((Math.random() * num2.length) + 1);
var randomNumber = dice1 + dice2;
document.getElementById("roll").innerHTML = randomNumber;
}
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="rollDice()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>

Related

Cant change the background color of entire page with the click of a button

I was trying to change the color of body section with the click of a button with id="btn". but when I launch the index.html the background color is not changing. if any one has the solution please i want the concept behind the solution.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="butn">
<button type="button" id="btn">Click to change baackground</button>
</div>
<style src="main.js"></style>
</body>
</html>
CSS :
body {
margin: 0;
height: 100%;
text-align: center;
background-color: white;
}
.butn {
margin-top: 15%;
display: inline-block;
}
button {
height: 5rem;
width: 15rem;
border: none;
border-radius: 0.5rem;
}
JS code:
var color = [
"AntiqueWhite",
"CadetBlue",
"BurlyWood",
"Crimson",
"DarkSlateBlue",
"LightGoldenRodYellow",
"LightCyan",
];
var randomNumber = Math.round(Math.random() * 6);
document.getElementById("btn").addEventListener("click", function () {
changeBackground();
});
function changeBackground() {
console.log(color[randomNumber]);
document.body.style.backgroundColor = color[randomNumber];
}
Firstly, your js file should be in script tag and not in style tag.
Secondly, random number is getting generated only once when your js file loads, instead
move random number inside the changeBackground function, so that it can get a new number every time the button is clicked
As the randomNumber variable is outside the function, it only gets initialized once.
So you have to move the randomNumber to the function to generate random color every time you click on the button.
js
function changeBackground() {
var randomNumber = Math.round(Math.random() * 6);
console.log(color[randomNumber]);
document.body.style.backgroundColor = color[randomNumber];
}
And while including js file, you should write in this manner
<script src="main.js"></script>
You must put var randomNumber = Math.round(Math.random() * 6); inside the function changeBackground, otherwise it will only get this number once. This way, it gets a new number each time this function is called.
function changeBackground() {
var randomNumber = Math.round(Math.random() * 6);
console.log(color[randomNumber]);
document.body.style.backgroundColor = color[randomNumber];
}

Selectable() Jquery mobile alternative

I was looking for the solution for my API but I couldn't find.. All examples or advices didn't work. Could somebody help me out? Or give me any suggestion? I'm still studying JQuery, so any help would be more than welcome..
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New api</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<section>
<div id="alert"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<ul id="wordblock">
</ul>
<div id="result">Result</div>
</section>
<script src="./api.js"></script>
</main>
</body>
</html>
JQuery code:
function screenResolutionAlert(x) {
if (x.matches) {
$("#alert").html("This API doesn't work with touchpads <br> (mobiles, tablets etc) <br> please use computer or laptop with a mouse").show();
} else {
$("#alert").hide();
}
}
var x = window.matchMedia("(max-width: 1200px)")
screenResolutionAlert(x)
x.addListener(screenResolutionAlert)
//API swap words code
$(function () {
$("#wordblock").sortable();
$("#wordblock").disableSelection();
const array = ["pierogi", "gołąbki", "pies", "sześcian"];
const word = array[Math.floor(Math.random() * array.length)];
let d_word = word.split('');
shuffle(d_word);
const lis = [];
for (let i = 0; i < d_word.length; i++) {
lis.push('<li class="ui-state-default">' + d_word[i] + '</li>')
}
$('#wordblock').html(lis.join(''));
$('#wordblock').mouseup(function () {
setTimeout(() => {
let r_word = '';
$('#wordblock>li').each(function (e) {
r_word += $(this).text();
});
if (r_word == word) {
$("#result").html(`Correct! It was exactly "${r_word}"`);
} else {
$("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
}
}, 0);
});
});
function shuffle(a, b, c, d) {
c = a.length;
while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d
}
Yes I was using mobile Jquery links, didn't work... And any versions of.. I tried everything what was written in the internet ;(
I tried your code and ...it seems to work! Snippet is here below, just press Run code snippet, and order letters to "PIES".
I suggest you to read about APIs, because at the moment you're not using any API at all! 😁
function screenResolutionAlert(x) {
if (x.matches) {
$("#alert")
.html(
"This API doesn't work with touchpads <br> (mobiles, tablets etc) <br> please use computer or laptop with a mouse"
)
.show();
} else {
$("#alert").hide();
}
}
var x = window.matchMedia("(max-width: 1200px)");
screenResolutionAlert(x);
x.addListener(screenResolutionAlert);
//API swap words code
$(function () {
$("#wordblock").sortable();
$("#wordblock").disableSelection();
const array = ["pies"];
const word = array[Math.floor(Math.random() * array.length)];
let d_word = word.split("");
shuffle(d_word);
const lis = [];
for (let i = 0; i < d_word.length; i++) {
lis.push('<li class="ui-state-default">' + d_word[i] + "</li>");
}
$("#wordblock").html(lis.join(""));
$("#wordblock").mouseup(function () {
setTimeout(() => {
let r_word = "";
$("#wordblock>li").each(function (e) {
r_word += $(this).text();
});
if (r_word == word) {
$("#result").html(`Correct! It was exactly "${r_word}"`);
} else {
$("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
}
}, 0);
});
});
function shuffle(a, b, c, d) {
c = a.length;
while (c)
(b = (Math.random() * (--c + 1)) | 0),
(d = a[c]),
(a[c] = a[b]),
(a[b] = d);
}
ul#wordblock {
padding-left: 0;
}
ul#wordblock li {
display: inline-block;
font-size: 2em;
padding: 0.2em 0.2em;
cursor: pointer;
background-color: aliceblue;
border-radius: 50%;
margin: 0.5em;
width: 1em;
height: 1em;
text-align: center;
line-height: 0.9em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New api</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<section>
<div id="alert"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<ul id="wordblock">
</ul>
<div id="result">Result</div>
</section>
<script src="./api.js"></script>
</main>
</body>
</html>

Check if the last characters in a string or inputs are similar to each other in javascript [duplicate]

This question already has answers here:
Compare two last character in a string
(2 answers)
Closed 4 years ago.
I'm trying to create a simple add calculator. As of now I am successful on displaying the numbers and concatenating them. But I what I don't want is when I clicked the plus(add) button two or more times, it will also concatenate with another plus symbol. Is there a way for me that if ever I clicked the plus button twice. the second symbol will no longer display. Like if it detects that the previous input is a plus symbol. it will never concatenate with each other. Sorry if my English is not clear.
Sample Error when i clicked the add button multiple times: ( 111++++222 ) instead of just 111+222
Here's my code guys:
<!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>
<style>
body {
margin: 0px auto;
width: 600px;
}
p {
font-size: 23px;
float: left;
padding: 30px;
border: solid #336336 2px;
margin: 20px;
}
</style>
</head>
<body>
<h1 id="result">aaww </h1>
<p id="1" class="one">1</p>
<p id="2" class="two">2</p>
</br></br>
<p id="add">+</p>
</br></br>
<p id="equals">=</p>
<!-- <p class="cancel">cancel</p> <p class="cancel">cancel</p> -->
<p class="clear-tasks"> CLEAR</p>
<script>
//PLACE HOLDER FOR THE RESULT
let Result = document.getElementById("result");
Result.innerText = "RESULT HERE";
// CLEAR BUTTON
let clear = document.querySelector('.clear-tasks');
// EVENT LISTENER TO CLEAR THE BUTTON
clear.addEventListener('click', function(){
Result.textContent = '';
});
let addition = document.querySelector("#add");
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
Result.textContent += ' + ';
}
//ONE BUTTON
const numberOne = document.querySelector('.one');
// EVENT LISTENER TO CONCATINATE 1
numberOne.addEventListener('click', runEvent);
function runEvent(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 1;
} else {Result.textContent += 1;
}
}
//TWO BUTTON
const numberTwo = document.querySelector('.two');
// EVENT LISTENER TO CONCATINATE 2
numberTwo.addEventListener('click', runEvent2);
function runEvent2(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 2;
} else {Result.textContent += 2;
}
}
</script>
</body>
</html>
Just use endsWith to check if the current string ends with a +:
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
if (!Result.textContent.endsWith(' + '))
Result.textContent += ' + ';
}
Use an if statement to check if there is already an operator. I made something similar in Java with GUI instead of JS but thats what I did and it worked fine. If you do the if statement you could use if(str.indexOf(operator) == -1) {
do the concatenation.
Check the last value of your result. If it is a '+', don't add another '+'
//PLACE HOLDER FOR THE RESULT
let Result = document.getElementById("result");
Result.innerText = "RESULT HERE";
// CLEAR BUTTON
let clear = document.querySelector('.clear-tasks');
// EVENT LISTENER TO CLEAR THE BUTTON
clear.addEventListener('click', function(){
Result.textContent = '';
});
let addition = document.querySelector("#add");
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
if(Result.innerText.slice(-1) != '+')
{
Result.textContent += ' + ';
}
}
//ONE BUTTON
const numberOne = document.querySelector('.one');
// EVENT LISTENER TO CONCATINATE 1
numberOne.addEventListener('click', runEvent);
function runEvent(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 1;
} else {Result.textContent += 1;
}
}
//TWO BUTTON
const numberTwo = document.querySelector('.two');
// EVENT LISTENER TO CONCATINATE 2
numberTwo.addEventListener('click', runEvent2);
function runEvent2(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 2;
} else {Result.textContent += 2;
}
}
<!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>
<style>
body {
margin: 0px auto;
width: 600px;
}
p {
font-size: 23px;
float: left;
padding: 30px;
border: solid #336336 2px;
margin: 20px;
}
</style>
</head>
<body>
<h1 id="result">aaww </h1>
<p id="1" class="one">1</p>
<p id="2" class="two">2</p>
</br></br>
<p id="add">+</p>
</br></br>
<p id="equals">=</p>
<!-- <p class="cancel">cancel</p> <p class="cancel">cancel</p> -->
<p class="clear-tasks"> CLEAR</p>
</body>
</html>

apply jquery filter to an created div?

Hey guys i was wondering if someone could help with some issues on my code.
Basically ive created 4 elements(divs) in an onclick event.From html i've also done so that same button dissapears
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="blackjack2.css">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="blackjack1.js"></script>
</head>
<body>
<button class= "boton" id="start">Play</button>
<button class= "boton" id="hit">Hit</button>
<button class= "boton" id= "stand">Stand</button>
<script type="text/javascript">
var jugar = document.getElementById('start')
var mas = document.getElementById('hit')
var mantener = document.getElementById('stand')
var cuerpo= document.getElementsByTagName('body')[0]
var crear_cartas= function() {
var card= document.createElement('div');
var texto =document.createTextNode("CASINO");
card.setAttribute("class","cartas");
card.appendChild(texto);
cuerpo.appendChild(card);
}
jugar.onclick= function(){
crear_cartas()
crear_cartas()
crear_cartas()
crear_cartas()
jugar.setAttribute('class','ocultar')
}
</script>
</body>
</html>
Up to there is ok , but im not sure if from jquery i can apply a filter that activates on the same onclick event that appears in javascript code (on those 4 created elements )to the even ones so that they make an animation lowering slightly the margin.
I've read about it but i am a bit at sea given that the filter would apply to created elements..
Thank you in advance guys
css class ".cartas" code included:
.cartas{
/*display: none;*/
margin: 260px 75px 0 75px;
display: inline-block;
border-radius: 10px;
border: 1px solid black;
padding-top: 50px;
height:100px;
width:100px;
color: #003366;
font-family: Muli,Helvetica Neue,Helvetica,sans-serif;
text-align: center;
background-color: #f0f8ff;
}
Add an onlcick event to all event divs. This event will add a class that will push the elements below those divs downward using a margin-bottom
Snippet below
var counter = 0;
var jugar = document.getElementById('start')
var mas = document.getElementById('hit')
var mantener = document.getElementById('stand')
var cuerpo = document.getElementsByTagName('body')[0]
var crear_cartas = function() {
card = document.createElement('div');
var texto = document.createTextNode("CASINO");
card.setAttribute("class", "cartas");
card.appendChild(texto);
cuerpo.appendChild(card);
}
jugar.onclick = function() {
for (var x = 0; x < 4; ++x) {
crear_cartas();
if ((x + 1) % 2 == 0) {
card.addEventListener('click', function() {
this.classList.add("move");
})
}
}
jugar.setAttribute('class', 'ocultar')
} //end func
div {
transition: margin-bottom 0.5s;
}
.move {
margin-bottom: 50px;
}
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="blackjack2.css">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="blackjack1.js"></script>
</head>
<body>
<button class="boton" id="start">Play</button>
<button class="boton" id="hit">Hit</button>
<button class="boton" id="stand">Stand</button>
</body>
</html>

JavaScript - If statement with text doesn't work properly

I am trying to make an if statement based off of user input. I can't seem to get this code to work. It continues to say no, even when I enter 'one', which is supposed to do something different, as you can see in the code snippet. I am running the code in the latest version of Chrome.
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox").value;
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var num1 = Math.floor((Math.random() * 100) + 1);
var num2 = Math.floor((Math.random() * 100) + 1);
var ans = num1 + num2;
function question() {
ques.innerHTML = num1 + " + " + num2;
}
function checkAns() {
if(ansBox.value == "one") {
isCorrect.innerHTML = "Yes";
} else {
isCorrect.innerHTML = "No";
}
}
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
</div>
<script src="scripts.js"></script>
</body>
</html>
You had an extra .value at the end of your definition of ansBox. Removing that makes it work:
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox");
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var num1 = Math.floor((Math.random() * 100) + 1);
var num2 = Math.floor((Math.random() * 100) + 1);
var ans = num1 + num2;
function question() {
ques.innerHTML = num1 + " + " + num2;
}
function checkAns() {
if(ansBox.value == "one") {
isCorrect.innerHTML = "Yes";
} else {
isCorrect.innerHTML = "No";
}
}
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
</div>
<script src="scripts.js"></script>
</body>
</html>

Categories

Resources