Thursday, April 12, 2018

JavaScript: Lon's Guessing Game

Dr. Payne's Guessing Game

Dr. Payne's Guessing Game

I have posted many articles about learning to code before on this blog. This post is my very first attempt to include Javascript in the source code for an article. The Javascript is written inside the head section which is against basic etiquette, but now there is something posted for me to work with on this blog. The CSS (for appearance) code is mine, but the HTML (content) and JavaScript (for behaviour) is copied from two short videos by Dr. Bryson Payne from North Georgia College and State University. At that time he is an Associate Professor of Computer Science. The first video on YouTube explains the HTML and JavaScript "set up" to build a game to play binary guessing of a random number between 1 to 100. The second YouTube video shows how to set the JavaScript so that the user can monitor how many tries they need to complete the narrowing down process of identifying the unknown random number.

FIRST: Enter a random number 1 to 100 below


SECOND: Click or Press Button below


THIRD: Read the results of your guess below

PLAY AGAIN

The JavaScript Code

< script rel="javascript" type="text/javascript" >
//alert( 'java' );

var theNumber = Math.floor ( Math.random() * 100 + 1 );
var numberOfGuesses = 0;
function checkguess() {

var guess = document.getElementById ( 'guess' );
var output = document.getElementById ('output');
var myNumber = guess.value;

numberOfGuesses++;

if (myNumber < theNumber) {

output.value = "Too low, please try again"
; //alert( "Too Low! Try Again" );
}

else if (myNumber > theNumber) {

output.value = "Too high, please try again";

}

else if (myNumber == theNumber){

output.value = "You got the number in " + numberOfGuesses + ", tries! Play again?";
alert("The number is " + theNumber + "! You Won After " + numberOfGuesses + " Guesses!");
theNumber = Math.floor ( Math.random() * 100 + 1 );
numberOfGuesses =0;

}
}
< /script >

Blog by LonsLens © Lonnie D. Watkins