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.
Related
I've been developing a speed test typing game for some time now, and I've been stuck on how to take the time you finish from one HTML page (the game itself) to an alternate one (the score page). I've been trying to use import{} export{}, but I'm not 100% sure how they function and so they haven't exactly worked. I'll attach both the game HTML and Javascript code and the score HTML and Javascript code.
<!-- THIS IS THE HTML PAGE FOR THE GAME -->
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Typeboss || Speed Typing Web Game</title>
<link rel="stylesheet" href="../css/gamestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
<script src="../js/gamescript.js" defer></script>
<script src="../../main/js/mainscript.js" type="module" defer></script>
<script src="./scorescript.js" type="module" defer></script>
</head>
<body>
<div id="all">
<div id="stats">
<h1 id="bossHealth" class="stat">BOSS HEALTH:</h1>
<h1 id="time" class="stat"><span id="minutes">0</span>:<span id="seconds">00</span></h1>
</div>
<div id="boss">
<img src="../imgs/boss.png" width="400px" height="400px" id="bossSprite">
</div>
<div id="input">
<h3 id="outcome"></h3>
<center><p id="prompt"></p></center>
<textarea id="userInput" name="TypeBox" rows="4" cols="100" autofocus></textarea>
</div>
</div>
</body>
</html>
// THIS IS THE JAVASCRIPT CODE
let scoreTime;
var seconds = 0;
var minutes = 0;
let score = 0;
const userInput = document.getElementById("userInput");
const promptBox = document.getElementById("prompt");
const outcomeText = document.getElementById("outcome");
const bossHealthtText = document.getElementById("bossHealth");
const timer = document.getElementById("time");
const bossSprite = document.getElementById("bossSprite");
const secondsText = document.getElementById("seconds");
const minutesText = document.getElementById("minutes");
let gameActive = true;
document.addEventListener('keypress', function(event){
if (event.key === 'Enter'){
checkInput();
}
});
let bossHealth = 100;
let multiplier = 10;
let mistakes = 0;
//
const prompts = ["How much wood could a woodchuck chuck if a woodchuck could chuck wood?", "I will not lose another pilot.", "I can't find my keys!", "Live as if you were to die tomorrow.", "Toto, I've got a feeling we're not in Kansas anymore...", "May the force be with you.", "If our lives are already written, it would take a courageous man to change the script.", "An apple a day keeps the doctor away.", "Frankly, my dear, I don't give a damn.", "Hello, world!", "My favorite sport is basketball!", "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.", "You only live once, but if you do it right, once is enough.", "I'm the fastest typer in the wild west!", "Frosty the snowman!", "I'm not a big fan of ice cream.", "If birds can fly, then we should too.", "I don't like trucks, they look weird.", "I love typing!", "I'm a rocket man, burning on a fuse out there alone.", "The water was blue and the skies the same, it was summer."];
//GAME INIT
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
function getNewPrompt() {
promptChoice = Math.floor(Math.random() * prompts.length);
let previousPrompt = prompts[promptChoice];
if (previousPrompt === prompts[promptChoice]){
promptChoice = Math.floor(Math.random() * prompts.length);
console.log("COPY OFF");
}
promptBox.innerHTML = prompts[promptChoice];
}
function checkInput(){
if (userInput.value.trim() === promptBox.innerHTML.trim()){
outcome.innerHTML = "Correct";
bossHealth -= 10;
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
let hitSprite = Math.floor(Math.random() *2);
if(hitSprite === 0){
bossSprite.src = "../imgs/bosshit/bosshit1.png";
}
if(hitSprite === 1){
bossSprite.src = "../imgs/bosshit/bosshit2.png";
}
setTimeout(function(){
bossSprite.src = "../imgs/boss.png";
}, 1000);
if (bossHealth <= 0){
console.log("WORKING");
window.location.href = "./score.html";
createScore();
}
getNewPrompt();
userInput.value = null;
}
else{
outcome.innerHTML = "Try again...";
userInput.value = null;
multiplier --;
mistakes ++;
return;
}
}
function gameTimer(){
console.log("working");
setTimeout(function(){
setInterval(function(){
seconds++;
if(seconds === 60){
minutes ++;
seconds = 0;
}
if (seconds < 9){
secondsText.innerHTML = "0" + seconds;
}
if (seconds > 9){
secondsText.innerHTML = seconds;
}
if(minutes < 9){
minutesText.innerHTML = minutes;
}
if(minutes > 9){
minutesText.innerHTML = minutes;
}
if (seconds < 9){
scoreTime = minutes + ":" + "0" + seconds;
}
if (seconds > 9){
scoreTime = minutes + ":" + seconds;
}
timePoints = minutes + seconds * 2;
return scoreTime;
return timePoints;
}, 1000)
}, 1000);
}
function game(){
gameTimer();
getNewPrompt();
createHeart();
}
function createScore(){
let bonus = Math.floor(Math.random() * 500);
score = timePoints * multiplier + bonus;
export { score };
}
game();
<!-- THIS IS THE SCORE HTML PAGE -->
<!DOCTYPE html>
<!DOCTYPE html>
<html onclick="celebrate()">
<head>
<meta charset="utf-8">
<title>Typeboss || Your Score!</title>
<link rel="stylesheet" href="../css/scorestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
</head>
<body>
<center><h1 style="color: whitesmoke;" id="header">YOU BEAT THE BOSS!</h1></center>
<center><p>(CLICK FOR VICTORY MUSIC)</p></center>
<h3 id="time">TIME:</h3>
<p id="playertime"></p>
<h3 id="score">SCORE:</h3>
<p id="playertime"></p>
<h3 id="mistakes">MISTAKES:</h3>
<p id="playertime"></p>
<h2 id="highscore"></h2>
<button id="redirect">BACK TO HOME</button>
</body>
<script type="module" src="../js/gamescript.js" defer></script>
</html>
// AND HERE IS THE SCORE'S CODE
winMusic = new Audio();
winMusic.src = "./winmusic.mp3";
function celebrate(){
winMusic.play();
winMusic.loop = tru
}
import { score } from "./gamescript.js";
const scoreText = document.getElementById("score");
scoreText.innerHTML = score + " points!"
I hope I can get this issue resolved, and I hope this post was clear enough to understand. This is my first post on stack so please do let me know if I formatted it wrong, and any feedback that could make it easier to understand in the future. Thank you in advance and have a good day.
use cookie for saving variables!
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
You can use Session Storage or for this.
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>
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>
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>
I am have displayed the Timer and Countdown Timer from 59 seconds to 0 seconds in decrease order using AngularJS. I have 2 problems,can anyone help to solve this 2 problems
Problem 1:
But there is a problem in displaying the countdown time i.e. it is displaying the alert message before 0:1 seconds .But it should display the alert message after the count completes form 59 to 0 seconds.
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UFT-8">
<link rel="stylesheet" href="menu.css">
<link rel="stylesheet" href="layout.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script>
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
[ "Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C" ],
[ "Which of the following is an interface ?", "Thread", "Date", "Calender", "A" ],
[ "Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A" ],
[ "What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C" ],
[ "What is the default value of Java datatype boolean?","true","false","0","A"]
];
function _(x){
return document.getElementById(x);
}
function renderQuestion(){
test = _("test");
if(pos >= questions.length){
var showscore=Math.round(correct/questions.length*100);
var minuteleft = parseInt((totalsecoriginal-totalsec) / 60, 10);
var sec = (totalsecoriginal-totalsec) - (minuteleft * 60);
document.getElementById("online_start").src = "animatedthankyou.gif";
document.getElementById("showtime")
test.innerHTML = "<h3>You got "+correct+" correct of "+questions.length+" questions</h3>";
test.innerHTML += "<h3> Your Grade : "+showscore +"% </h3>";
test.innerHTML += "<h4>Exam Finished in Time :" + minuteleft + " Minutes :" + sec + " Seconds</h4>";
test.innerHTML += "<button onclick='EndExam()'>End the Exam</button>";
_("test_status").innerHTML = "<h3>Test Completed</h3>";
pos = 0;
correct = 0;
clearTimeout(tim);
document.getElementById("starttime").style.display += 'none';
document.getElementById("showtime").style.display += 'none';
document.getElementById("endtime").style.display += 'none';
return false;
}
_("test_status").innerHTML = "<h3>Question "+(pos+1)+" of "+questions.length+"</h3>";
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
test.innerHTML = "<h3>"+question+"</h3>";
test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
test.innerHTML += "<button onclick='checkAnswer()'>Next</button><br><br>";
}
function checkAnswer(){
choices = document.getElementsByName("choices");
choice=-1;
for(var i=0; i<choices.length; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
if(choice == questions[pos][4]){
correct++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
function EndExam(){
location.href="Loginpage.htm";
}
var tim;
var showscore=Math.round(correct/questions.length*100);
var totalsec = 60;
var totalsecoriginal = totalsec;
var f = new Date();
function starttime() {
showtime();
var showcurtime = moment();
var curtimeformat = showcurtime.format('h:mm:ss a');
var showendtime = showcurtime.add(totalsec, 's');
var endtimeFormat = showendtime.format('h:mm:ss a');
document.getElementById("starttime").innerHTML = "<h4>Starting Time " + curtimeformat + "</h4>";
document.getElementById("endtime").innerHTML = "<h4>Ending Time " + endtimeFormat + "</h4>";
}
// Using Angular JS
var app = angular.module('MyApp',[])
app.controller('MyController',function($scope,$window,$interval,$timeout,$filter){
var date=new Date();
$scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
$scope.currentTime = new Date();
$scope.currentTime .setSeconds($scope.currentTime .getSeconds() + 60);
//CountDown TImer
var tim;
$scope.totalsec = 60;
var countdowntime= function(){
$scope.totalsec--;
$scope.min = parseInt($scope.totalsec / 60, 10);
$scope.sec = $scope.totalsec - ($scope.min * 60);
if($scope.sec >0){
tim = $timeout(countdowntime, 1000);
}else if($scope.sec== 0){
$timeout.cancel(tim);
$window.alert("Time Up");
}
};
countdowntime();
});
</script>
</head>
<body onload="starttime()" >
<div id="Holder">
<div id="Header"></div>
<div id="NavBar">
<nav>
<ul>
<li> Login</li>
<li>Registration</li>
</ul>
</div>
<div id="Content">
<div id="PageHeading">
<h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
</div>
<div id="ContentLeft">
<h2></h2><br>
<img id="online_start">
<br>
<h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based
examination system that provides an easy to use environment for both
Test Conducters and Students appearing for Examination.</h6>
</div>
<div id="ContentRight">
<section class="loginform_cf">
<div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
<table>
<tr>
<td id="test_status" style="text-align:left" ></td>
<td> Exam Starts :<span ng-bind = "hhmmss"> </span> </td>
<td> Exam Ends : {{currentTime | date:'HH:mm:ss a'}} </td>
</tr>
<tr>
<td id="test" colspan="3"></td>
</tr>
</table>
<br>
Your Left Time is :{{min}} Minutes:{{sec}} Seconds<br>
</div>
<br>
</section>
</div>
</div>
<div id="Footer">Developed by - K.P.RAJU</div>
</div>
<script src="moment.js"></script>
</body>
</html>
Problem 2:
At the end of the exam Exam Starts :10:35:39 AM and Exam Ends : 10:36:39 AM timer should disable .The page should display as shown below
Test Completed
You got 0 correct of 5 questions
Your Grade : 0%
Exam Finished in Time :0 Minutes :4 Seconds
To try solve your 1st problem, try putting alert inside timeout, like
$timeout(function() {
$window.alert("Time Up");
},0);
Because JavaScript is single thread, AngularJS must be run in callback mode, so the alert is called before AngularJS rendering getting called.
2nd, sorry didn't get you
I have changed your code to angular and used interval to run the time and ng-show and ng-hide directives.
SCRIPT and HTML
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $compile, $window, $interval, $timeout, $filter) {
$scope.pos = 0, $scope.correct = 0, $scope.ques = true;
$scope.questions = [
["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],
["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],
["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],
["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],
["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
];
$scope.totalsecoriginal = $scope.totalsec = 60;
$scope.totalsec--;
$scope.min = parseInt($scope.totalsec / 60, 10);
$scope.sec = $scope.totalsec - ($scope.min * 60);
$scope.date = new Date();
$scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
$scope.currentTime = new Date();
$scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);
function _(x) {
console.log(angular.element(document.getElementById(x)));
return angular.element(document.getElementById(x))[0];
}
$scope.interval = $interval(function() {
if ($scope.sec === 0) {
$scope.min--;
$scope.sec = 60;
}
$scope.sec--;
}, 1000);
$scope.$watch('sec', function() {
if ($scope.min === 0 && $scope.sec === 0) {
$interval.cancel($scope.interval);
window.alert('Time Up!!!');
$scope.pos = $scope.questions.length;
$scope.temp = true;
$scope.renderQuestion();
}
})
$scope.renderQuestion = function() {
if ($scope.pos >= $scope.questions.length) {
$scope.ques = false;
if (!$scope.temp) { $scope.temp = false;
$interval.cancel($scope.interval);
}
$scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
$scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);
$scope.pos = 0;
return false;
}
$scope.question = $scope.questions[$scope.pos][0];
$scope.chA = $scope.questions[$scope.pos][1];
$scope.chB = $scope.questions[$scope.pos][2];
$scope.chC = $scope.questions[$scope.pos][3];
}
$scope.checkAnswer = function() {
$scope.choices = angular.element(document.getElementsByName('choices'));
$scope.choice = -1;
for (var i = 0; i < $scope.choices.length; i++) {
if ($scope.choices[i].checked) {
$scope.choice = $scope.choices[i].value;
$scope.choices[i].checked = false;
}
}
if ($scope.choice == $scope.questions[$scope.pos][4]) {
$scope.correct++;
}
$scope.pos++;
$scope.renderQuestion();
}
$scope.renderQuestion();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div id="Holder">
<div id="Header"></div>
<div id="NavBar">
<ul>
<li> Login</li>
<li>Registration</li>
</ul>
</div>
<div id="Content">
<div id="PageHeading">
<h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
</div>
<div id="ContentLeft">
<h2></h2>
<br>
<img id="online_start">
<br>
<h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based
examination system that provides an easy to use environment for both
Test Conducters and Students appearing for Examination.</h6>
</div>
<div id="ContentRight">
<section class="loginform_cf">
<div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
<table>
<tr>
<td id="test_status" style="text-align:left">
<h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
<h3 ng-hide='ques'>Test Completed </h3>
</td>
<td ng-show='ques'> Exam Starts :<span ng-bind="hhmmss"> </span> </td>
<td ng-show='ques'> Exam Ends : {{currentTime | date:'hh:mm:ss a'}} </td>
</tr>
<tr>
<td id="test" colspan="3">
<div ng-show="ques">
<h3>{{question}}</h3>
<input type='radio' name='choices' value='A'>{{chA}}
<br>
<input type='radio' name='choices' value='B'>{{chB}}
<br>
<input type='radio' name='choices' value='C'>{{chC}}
<br>
<br>
<button ng-click='checkAnswer()'>Next</button>
</div>
<div ng-hide='ques'>
<h3>You got {{correct}} correct of {{questions.length}} questions</h3>
<h3> Your Grade : {{showscore}}% </h3>
<h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
<button ng-click='EndExam()'>End the Exam</button>
</div>
<br>
<br>
</td>
</tr>
</table>
<br> Your Left Time is :{{min}} Minutes {{sec}} Seconds
<br>
</div>
<br>
</section>
</div>
</div>
<div id="Footer">Developed by - K.P.RAJU</div>
</div>
</body>