Blackjack if statement - javascript

I am making a simple black jack game and I am having problems with my if
statement. When I click the stand button which triggers the if statement it always displays the prompt "you win" not no matter what the score is.
For example if the user score if 11 and the computer score is 18(which it is always set to) the prompt "you lose" should be displayed.
var randomnumber = Math.floor(Math.random() * 10 + 1);
function random() {
return randomnumber;
}
var total = randomnumber;
function dealcard() {
total += Math.floor(Math.random() * 10 + 1);
document.getElementById('playerscards').value = total;
if (total > 21) {
alert("You have gone bust click new game to play again!");
}
}
function keepcards()
{
if (total > randomnumber) {
alert("You win!");
}
else if (total < randomnumber) {
alert("You lose!");
}
else if (total === randomnumber) {
alert("It is a draw!");}
}
now = new Date();
localtime = now.toString();
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write("<h1>");
document.write(hours + ":" + mins + ":" + secs);
document.write("</h1>");
<head>
<h1><i>BLACKJACK</i></h1>
<h4>
Computers Cards: <input type="text" id="computerscards" value="18">
<br>Player 1 cards: <input type="text" id="playerscards">
</h4>
</head>
<input type="button" value="start"
onclick="document.getElementById('playerscards').value = random()">
<input type="button" value="deal" onclick="dealcard()">
<input type="button" value="stand" onclick="keepcards()">
<input type="button" value="new game" onclick="window.location.reload()">
<p>To start the game press start and draw a card<br> Press deal to add a new
card <br> press stand if you do not wish to draw a new card<br> Press new game
if you want to refresh the page to play a mew game</p>

If you debug your code you'll see that you are checking the total value against the randomNumber, but to really check if the player won, is necessary to check it against the ComputerHand right?
So I did it below in the snippet.
Right now you code fix the coumputerHand to 18, in a near future i assume that you'll change that in a way that computer receives a ramdom card like the player.
var randomnumber = Math.floor(Math.random() * 10 + 1);
function random() {
return randomnumber;
}
var total = randomnumber;
var CPUHand = parseInt(document.getElementById('computerscards').value);
function dealcard() {
total += Math.floor(Math.random() * 10 + 1);
document.getElementById('playerscards').value = total;
if (total > 21) {
alert("You have gone bust click new game to play again!");
}
}
function keepcards(){
debugger;
if (total > CPUHand) {
alert("You win!");
}
else if (total < CPUHand) {
alert("You lose!");
}
else if (total === CPUHand) {
alert("It is a draw!");
}
}
now = new Date();
localtime = now.toString();
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write("<h1>");
document.write(hours + ":" + mins + ":" + secs);
document.write("</h1>");
<head>
<h1><i>BLACKJACK</i></h1>
<h4>
Computers Cards: <input type="text" id="computerscards" value="18">
<br>Player 1 cards: <input type="text" id="playerscards">
</h4>
</head>
<input type="button" value="start"
onclick="document.getElementById('playerscards').value = random()">
<input type="button" value="deal" onclick="dealcard()">
<input type="button" value="stand" onclick="keepcards()">
<input type="button" value="new game" onclick="window.location.reload()">
<p>To start the game press start and draw a card<br> Press deal to add a new
card <br> press stand if you do not wish to draw a new card<br> Prsee new
game
if you want to refresh the page to play a mew game</p>

Related

Page doesn't load when I set variable to 0 in Javascript

var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
while (attempts < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
while learning how to use a random number generator, I wantd to add a while loop and give 3 attempts to choose from a random number.
When I create a variable to set the number of attempts, if I make the variable equal to 0, my page doesn't load, but if I leave the variable empty without a value, the script doesn't run.
Any ideas of why this may be happening?
var randomNumber = Math.floor(Math.random() * 6);
var x = 0
var maximum = 3
while (x < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
Your while loop runs synchronously, during pageload. The script never finishes, because the while loop's condition is never negated, so control is never yielded back to the browser to repaint the page, so the user never has a chance to input a number or click on the button.
While you could keep using while by promisifying the onclick and awaiting a Promise, it'd be better to create the handler outside, once, and have it check if the attempts are maxed out.
You also need to use consistent variable names: either use x or attempts, not both:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
document.getElementById("submit").onclick = function() {
if (attempts >= maximum) return;
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
You could disable the button after the maximum number of attempts has been reached, like:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0;
var maximum = 3;
document.getElementById("submit").onclick = function(e) {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
if (attempts === maximum) e.target.disabled = true;
};
<input type="text" id="input" />
<button id="submit">Submit</button>

Loop For User Input and Adding summation of Dice Rolls

I am trying to make a game with JavaScript but I am stuck. I cannot figure out how to take the rolls from the dice and put it into a table to count how many rolls were made before the player runs out of money, and the other 3 requirements at the end of the rules::::: any advice would be super helpful!
The rules
As long as there is money, play the game.
Each round, the program rolls a virtual pair of dice for the user.
If the sum of the 2 dice is equal to 7, the player wins $4
otherwise, the player loses $1.
The program asks the user how many dollars they have to bet.
If the starting bet is less than or equal to 0, display an error message.
When the user clicks the Play button, the program then rolls the dice repeatedly until all the money is gone.
Hint: Use a loop construct to keep playing until the money is gone.
Hint: We created a rollDice() function in the Rolling Dice exercise.
The program keeps track of how many rolls were taken before the money ran out.
The program keeps track of the maximum amount of money held by the player.
The program keeps track of how many rolls were taken at the point when the user held the most money.
I couldn't get my code to paste properly so I've added a snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Lucky Sevens </title>
<style>
</style>
<script>
<!--reset form field to natural state-->
function clearErrors() {
for (var loopCounter = 0;
loopCounter < document.forms["bet"].elements.length;
loopCounter++) {
if (document.forms["bet"].elements[loopCounter]
.parentElement.className.indexOf("has-") != -1) {
document.forms["bet"].elements[loopCounter]
.parentElement.className = "form-group";
}
}
}
<!--clear form fields-->
function resetForm() {
clearErrors();
document.forms["bet"]["num1"].value = "";
document.getElementById("results").style.display = "none";
document.getElementById("submitButton").innerText = "Submit";
document.forms["bet"]["num1"].focus();
alert("You have reset the form and will lose all progress.");
}
<!--verify user input is expected-->
function validateItems() {
clearErrors();
var num1 = document.forms["bet"]["num1"].value;
if (num1 == "" || isNaN(num1)) {
alert("Num1 must be filled in with a number.");
document.forms["bet"]["num1"]
.parentElement.className = "form-group has-error";
document.forms["bet"]["num1"].focus();
return false;
}
if (num1 >= 11) {
alert("Bet must be between $1-$10");
document.forms["bet"]["num1"]
.parentElement.className = "form-group has-error"
document.forms["bet"]["num1"].focus();
return false;
}
if (num1 <= 0) {
alert("Bet must be between $1-$10");
document.forms["bet"]["num1"]
.parentElement.className = "form-group has-error"
document.forms["bet"]["num1"].focus();
return false;
}
document.getElementById("results").style.display = "block";
document.getElementById("submitButton").innerText = "Roll Again";
document.getElementById("startingBet").innerText = num1;
return false;
}
function rollDice() {
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
var d1=Math.floor(Math.random() * 6) + 1;
var d2=Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 7) {
status.innerHTML += " You win $4!";
}
if(diceTotal != 7){
status.innerHTML += " You lose $1.";
}
}
</script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>Lucky Sevens</h1>
<form name="bet" onsubmit="return validateItems();"
onreset="resetForm();" class="form-inline">
<div class="form-group">
<label for="num1">Starting Bet</label>
<input type="number" class="form-control" id="num1">
</div>
<button type="submit" onclick="rollDice()" id="submitButton" class="btn btn-default">Submit</button>
</form>
<h2 id="status" style="clear:left;"></h2>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<hr />
<table id="results" class="table table-striped" style="display:none;">
<tbody>
<tr>
<td>Starting Bet</td>
<td><span id="startingBet"></span></td>
</tr>
<tr>
<td>Total Rolls Before Going Broke</td>
</tr>
<tr>
<td>Highest Amount Won</td>
</tr>
<tr>
<td>Roll Count at Highest Amount Win</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

Limit the amount of times a button is clicked

for my college project im trying to limit the amount of times one of my buttons is being clicked to 3 times, I've been looking everywhere for code to do it and found some yesterday, it does give me alert when I've it the max amount of clicks but the function continues and im not sure why, here is the code I've been using.
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has
drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total
of " + total;
if(total >21){
window.location="../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn "
+ card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch(button)
{
case "Stick":
if (total > 21) {
window.location="../End_Game/End_Lose_Bust.html";
} else if (total == 21){
window.location="../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location="../End_Game/End_Win.html";
} else if (total == compscore) {
window.location="../End_Game/End_Draw.html";
} else {
window.location="../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if(ClickCount>=clickLimit) {
alert("You have drawn the max amount of crads");
return false;
}
else
{
ClickCount++;
return true;
}
}
HTML
<!doctype html>
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick="NumberGen(); Total_Number(); countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>
Cheers in advance.
You are calling countClicks at the end of onclick. Change it to this:
if (countClicks()) { NumberGen(); Total_Number();}
Try this
var count = 0;
function myfns(){
count++;
console.log(count);
if (count>3){
document.getElementById("btn").disabled = true;
alert("You can only click this button 3 times !!!");
}
}
<button id="btn" onclick="myfns()">Click Me</button>
I have edited your code also following is your code
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total of " + total;
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn " +
card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch (button)
{
case "Stick":
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
} else if (total == 21) {
window.location = "../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location = "../End_Game/End_Win.html";
} else if (total == compscore) {
window.location = "../End_Game/End_Draw.html";
} else {
window.location = "../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if (ClickCount >= clickLimit) {
alert("You have drawn the max amount of crads");
return false;
} else {
NumberGen();
Total_Number();
ClickCount++;
return true;
}
}
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick=" countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>

Compare generated letter with user input

My problem is as followed: I want to realise a (really) small application in which I want to generate a letter (between A and E) and compare it with the user input made afterwards. If the user input is not the same as the generated letter a message should pop up, which tells the user that he made the wrong choice. If the user made the right choice, a counter gets +1 and if the user reaches at least 3 of 5 points, he wins a prize. The user has 3 tries before the script ends.
The hurdle is that my main focus lies on php. My knowledge in JavaScript is not that much.
So my script won't do anything when the user types his answer in.
SOLVED!
The Code beneath is the solution.
String.prototype.last = function(){
return this[this.length - 1]
}
;(function() {
var score = 0;
var text = "";
var possible = "ABCDE";
var noOfTries = 5;
function generateCharacter() {
var index = Math.floor(Math.random() * 100) % possible.length;
text = possible[index];
possible = possible.slice(0, index) + possible.slice(index+1);
alert(text);
return text;
}
function validate(string) {
return (string || "").trim().last() === text.last();
}
function handleChange(){
var valid = validate(this.value);
if(valid){
score++;
alert("Richtig!");
}else{
alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!");
}
console.log(this.value.length === noOfTries)
this.value.length === noOfTries ? notify() : generateCharacter();
}
function notify(){
if(score == 0) {
alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?");
}else if(score >= 1 && score <3){
alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?");
}else if(score >= 3 && score <= 5) {
alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!");
}
}
function registerEvent(){
document.getElementById('which').addEventListener('keyup', handleChange);
}
registerEvent();
generateCharacter();
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="which">Antwort? </label>
<input type="text" name="which" id="which" placeholder="#" style="width: 9px;">
And here's the fiddle: Compare generated string with user input

display and calculate score for javascript quiz

i'm a teacher and have just started learning to code for making online quizzes for my students. I'm still very new to programming like JavaScript and php, and I've tried to looked for sources online to help create my quizzes. I have 2 questions:
1). I've set a timer for the quiz but everytime when the time is up, it just keeps counting, what should I put in the
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "";
section to redirect my student to the result page or other pages?
(2) My quizzes are mostly fill-in-the-blanks questions and I wonder how to store the point of each question and then show the total score to my students at the end of the quiz? Many thanks!.
Here's my code:
<html>
<head>
<script language ="javascript" >
var tim;
var min = 0;
var sec = 30;
var f = new Date();
function f1() {
f2();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
}
function f2() {
if (parseInt(sec) > 0) {
sec = parseInt(sec) - 1;
document.getElementById("showtime").innerHTML = "Your Left Time is :"+min+" Minutes ," + sec+" Seconds";
tim = setTimeout("f2()", 1000);
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
}
</script>
<title>Quiz</title>
<h1>P.1 Grammar Quiz</h1>
<body>
<div id="ques0" class="ques">
<h2>Question</h2>
<p>She
<input type="text" name="answer0"/> a girl.</p>
</div>
<div id="ques1" class="ques">
<h2>Question</h2>
<p>"is", "am" and "are" are</p>
<ul>
<li>
<input type="radio" name="answer1" value="Present tense" />
<label>Present tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Past tense" />
<label>Past tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Future tense" />
<label>Future tense</label>
</li>
</ul>
</div>
<div id="ques2" class="ques">
<h2>Question</h2>
<p>He
<input type="text" name="answer2"/> a policeman.
</p>
</div>
Check answer!
<script src="JQ.js"></script>
<script src="function.js"></script>
<body onload="f1()" >
<form id="form1" runat="server">
<div>
<table width="100%" align="center">
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<div id="starttime"></div>
<div id="endtime"></div>
<div id="showtime"></div>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</head>
</html>
Your code is good enough for a beginner but it requires some improvements.
<script type="text/javascript" >//language ="javascript" is obsolete
//var tim; //no need at all
//var min = 0; //no need at all
//var sec = 30; //there is better way
//var f = new Date(); //no need to be global
function f1(sec) {//define (declare) sec as parameter
f2(); //call the function
var f = new Date();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
var showtime = document.getElementById("showtime"); //used many times
//Here we put (closure) f2
function f2() {
//f2 knows sec from parent scope
if (sec <= 0) {//parseInt(sec) no need. sec is int
showtime.innerHTML = 'Time is over';
//ShowAnswers(); //show on the same page or post to .php
return;
}
sec--;// = parseInt(sec) - 1;
showtime.innerHTML = "Your Left Time is :" + Math.floor(sec / 60) +" Minutes ," + (sec % 60) +" Seconds";
setTimeout(f2, 1000);//"f2()" is correct but this way is better
/* no need in remaining code
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
*/
}//f2
}//f1
</script>
<body onload="f1(90)"><!--Here we send seconds to the function -->
Also note that all your quiz starting from <h1>P.1... must be inside body container.

Categories

Resources