SlideShare a Scribd company logo
Jack Eastwood
Top tips:
 Put semi-colonsatthe endof everything
 2 equalssigns=comparison
 Variablescanbe overwritten
 Watch out for grammar
 All variableshave tobe declaredusing“VAR”thenavalue needstobe assignedtothe
variable.
 Code iscase sensitive
 Orderingof variablesisveryimportant
 “//” can be usedtoapplycommentsinyourcode withoutbeingappliedwhenrunningthe
program.
 The “prompt” variable displaysawindow thatasksthe userfor an input,inthiscase “Please
enteryourname:”
 The “alert” variable displaysthe “message”variable onanotherwindow afterthe userhas
put an inputinthe promptwindow.
 Wheneversomethingisstoredasa promptit’sstoredas a string.
 == meansequals,!=meansnotequal
 parseIntmeansparse integer,meaningthisonlypicksoutanynumerical valuesfromastring
of charactersidentifiedinavariable.
 Don’trelyon > or <, use rangeswithdefinedupperandlowerlimits.
 Don’tput a semi-colonatthe endof a for loop.
 Var ++ isthe same as var= var + 1
 && meansand, ||meansor
 ParseFloat= returnsanyfloatingpointnumber
3.5 Experiments with graphics
// Ex3-5 : Graphics Experiments
// Part of demo program:
var canvas;
canvas = openGraphics();
var x;
var y;
var size;
x = 0;
Jack Eastwood
y = 0;
size = 500;
while( size > 0 )
{
canvas.setColor( "white" );
canvas.fillEllipse( x, y, size, size );
canvas.setColor( "blue" );
canvas.drawEllipse( x, y, size, size );
x = x + 10;
y = y + 10;
size = size - 20;
}
canvas.paint();
Jack Eastwood
// Ex3-5 : Graphics Experiments
// Part of demo program:
var canvas;
canvas = openGraphics();
var x;
var y;
var width;
var height;
x = 0;
Jack Eastwood
y = 0;
width = 200;
height = 700;
while( (width > 0 ) && (height > 0) )
{
canvas.setColor( "white" );
canvas.fillEllipse( x, y, width, height );
canvas.setColor( "blue" );
canvas.drawEllipse( x, y, width, height );
x = x + 23;
y = y + 3;
width = width - 7;
height = height - 70;
}
canvas.paint();
Jack Eastwood
Comments
Changingthe size orwidth/heightvariableswill change how small orbigthe overall shape willbe
outputtedonthe canvas. In the two examplesI’vegiven,byreducingthe size inthe loopfromthe
Jack Eastwood
size setwhenthe variable isdeclaredwill influence how manycircleswillbe drawni.e if size issetto
800 thensize wasreducedby20 inthe loop,then40 circleswouldbe outputted.
3.6 Graphical Event timer
// Ex 3-6 : Graphical Event Timer
var canvas;
canvas = openGraphics();
var textX = 20;
var textY = 30;
var lineX = 180;
var lineY = textY + 5;
for (var i = 0; i < 10; i++) {
// Put your event timer code here
alert( "Press "OK" to start the timer." );
var date = new Date();
// create another Date object and store the time now
alert( "Press "OK" to stop the timer." );
var date1 = new Date();
var difference = date1 - date;
var previoustime;
canvas.setStroke(3);
canvas.setColor("black");
canvas.drawString( "Timer", 150, 0 );
canvas.drawString( " Difference in time: " + difference +
"ms", 10, textY);
if (previoustime>difference) {
Jack Eastwood
canvas.setColor("Green");
}
else if (previoustime<difference){
canvas.setColor("Red");
}
else {
canvas.setColor("black");
}
canvas.drawLine( lineX, lineY, lineX + difference, lineY );
textY = textY + 20;
lineY = lineY + 20;
previoustime=difference;
canvas.paint();
}
Comments
The program calculatesthe difference intime bysettingup2 datesthat gathersthe exacttime,then
findsthe difference betweenthe twotimeswhenthe userhitsthe “start” and“stop” prompts.The
Jack Eastwood
difference betweenthe 2timesisthenoutputtedasa line andthe higherthe difference,the higher
the line length,sothe difference isaddedtothe line’sx length.The forloopmeansthatthe userwill
askedto calculate the difference intime 10times(10 starts + 10 stops).If the difference intime is
lessthanthe earliertime,thenthe line colourwill be settogreenandif the difference ishigherthan
the line colourwill be settoredusingif statementsondifference +previoustime variables.Atthe
endof the loopthe line andtextY positionsare plusedby20, meaningthateveryline andtext
outputwhenthe userhitsstart and stopwill be placedbelow the previousoutput.
3.7 Sudoku Grid
// Ex3-7 : Blank Sudoku Grid
var canvas;
canvas = openGraphics();
var x;
var y;
var gap;
x = 20;
y = 20;
gap = 25;
// so not much help here!
var count;
for( count=0; count<11; count++ )
{
canvas.drawLine( x,y,x+225,y );
y = x+count*gap;
} //endfor
x = 20;
y = 20;
Jack Eastwood
for( count=0; count<11; count++ )
{
canvas.drawLine(x,y,x,y+225);
x = y+count*gap;
}
x = 20;
y = 20;
for( count=0; count<5; count++ )
{
canvas.setStroke(3);
canvas.drawLine(x,y,x+225,y);
y = x+count*gap*3;
}
x = 20;
y = 20;
for( count=0; count<5; count++)
{
canvas.setStroke(3);
canvas.drawLine(x,y,x,y+225);
x = y+count*gap*3;
}
canvas.paint();
Jack Eastwood
Comments
4 forloopsare usedto create thisSudokugrid.The firstfor loopdraw out all the horizontal lines10
timesandbecause the gap size issetto 25 thenthe X line lengthswill be setto225 as each 3x3 box
is75x75, sothisis addedto the X axislengthparameteraswell asthe Y axisoffsetbeingplaced25
pixelsbeloweverytime ahorizontal lineisplaced.The secondforloopplotsthe vertical linesand
thisisthe same as the previousforloopapartfrom that the valuesare addedto the Y line lengthand
X offset.Finally,the final2loopsaddthe thickblacklinestoformthe grid and the onlydifference is
that the setStroke issetto 3, count setto 5 (prints4 times) andthe gapis timesby3 whichwill
create each 3 x 3 box.The X and Y co-ordinateshave tobe resetaftereachloop otherwise the next
loopwouldjustprintonthe Xand Y co-ordinatescalculatedbythe previousloops.
Jack Eastwood
4.1 Garfield cartoon
// Ex4-1: Garfield Cartoon
var canvas;
canvas = openGraphics();
var imageName1;
var imageName2;
var imageName3;
var xPosition;
var yPosition;
var width;
var height;
imageName1 = "garfield1.gif";
xPosition = 10;
yPosition = 10;
canvas.drawImage(imageName1, xPosition,yPosition);
imageName2 = "garfield2.gif";
xPosition = 210;
yPosition = 10;
canvas.drawImage(imageName2, xPosition, yPosition);
imageName3 = "garfield3.gif";
Jack Eastwood
xPosition = 400;
yPosition = 10;
canvas.drawImage(imageName3, xPosition, yPosition);
canvas.setFont( "comic sans ms","10.5px", Font.BOLD );
canvas.drawStringRect("THERE'S A GOOD SCARY MOVIE ON TV TONIGHT",
30, 13, 150);
canvas.drawStringRect("YEAH, SURE", 140, 55, 50);
canvas.drawStringRect("YOU SAY THAT EVERY NIGHT", 328, 40, 61);
canvas.drawStringRect("''INVASION OF THE 50-FOOT ADOLESCENTS''",
415, 12, 150);
canvas.drawStringRect("TONIGHT, THOUGH, YOU WOULD BE CORRECT",
530, 40, 70);
canvas.paint();
Comments
The canvas.drawStringRectfunctionbasicallydrawsastringinan invisiblerectangle.Inmore simple
termsstringscan onlybe drawn at a fixedwidthbychangingthe widthvalue
(drawstringRect(x),(y),(width).The higherthe usersetsthe widthvalue thenthe longerastringcan
be drawn outhorizontallyonacanvas.
Jack Eastwood
4.2 guess the number
// Ex4-2: Guess the Number
var canvas;
canvas = openGraphics();
var max;
max = 100;
var numberToGuess;
numberToGuess = 50; // use a known value for testing
canvas.drawString("Welcome to Jack Eastwood's guessing game", 50,
10);
var guess;
guess = parseInt(prompt("Please input a number between 0 and
100"),10);
var guessed = false;
var message;
// (3) if too high .....
if (guess < numberToGuess)
{
canvas.drawString("You was wrong, try a higher
number", 10, 30);
}
// (4) if too low .....
if (guess > numberToGuess)
{
Jack Eastwood
canvas.drawString("You was wrong again fool, try a
lower number", 10, 30);
}
// (5) "just right" said Goldilocks .....
if (guess == numberToGuess)
{
canvas.drawString("You was right",10,30);
}
// (6) canvas.drawString( message ......
canvas.paint();
Jack Eastwood
// Ex4-2: Guess the Number
var canvas;
canvas = openGraphics();
Jack Eastwood
var max;
max = 100;
var numberToGuess = Math.floor( Math.random() * max ) +1;
canvas.drawString("Welcome to Jack Eastwood's guessing game", 50,
10);
var x = 20;
var y = 20;
var guess;
var guessed = false;
while( !guessed ){
guess = parseInt(prompt("Please input a number
between 0 and 100"),10);
var message;
// (3) if too high .....
if (guess > numberToGuess){
message = guess + " Too high";
}
// (4) if too low .....
if (guess < numberToGuess) {
message = guess + " Too low";
}
// (5) "just right" said Goldilocks .....
if (guess == numberToGuess) {
Jack Eastwood
message = guess + " Correct";
guessed = true;
}
canvas.drawString( message, x, y);
y = y + 20;
canvas.paint();
}
Jack Eastwood
Comments
Thisprogram setsthe userto guessa numberbetween0and 100. The Math.floor( Math.random() *
max ) +1 functionsetsa numbertoguessbetween0and the max variable,whichIsetto 100, so will
selectarandom numberupto 100 and giventhe variable numberToGuess.The variableguessedto
setto false anda while loopisusedsothateverytime the userincorrectlyguessesthe number,then
theywill have toguessagainuntil theygetitcorrect. 3 if statementsare alsousedwithinthe while
loop,onsayingthat if the userguessestohighthenit will printtohighon the canvas,anotherone
sayingto lowonthe canvasand the last if statementisif the usercorrectlyguessesthe numberto
guess,thenthe guessedvariablewill be setto“true”,so the while loopwillend and the number
that wascorrectlyguessedwill be printedon the canvas. Everytime the userincorrectlyguesses,
thenthe Y value forthe user’snumberguessand“Too high/low”isincreasedby20 everytime,so
each message will be printedunderneaththe previousmessage.
4.3 Square root calculator
// Ex4-3 : Square Root Calculator
var canvas;
canvas = openGraphics();
//var number = prompt( "Enter a number: " );
//number = parseInt( number, 10 );
//var sqRoot;
//sqRoot = Math.sqrt( number );
//var message;
//message = "Using the JavaScript library,<br>";
//message = message + "The square root of " + number + "<br>";
//message = message + "is " + sqRoot;
// Put your version here
var lowGuess = 0;
var highGuess = 10;
var squareRoot = Math.sqrt( highGuess );
Jack Eastwood
var guess = prompt( "Please enter a number: ");
var message;
if( guess > squareRoot){
message = guess + " Too high";
}
if( guess < squareRoot){
message = guess + " Too low";
}
if( guess == squareRoot){
message = guess + " Correct";
}
canvas.drawString( message, 10, 10 );
canvas.paint();
4.4 BMI calculator
// Ex4-4: BMI Calculator
var canvas;
canvas = openGraphics();
var height = 160/100;
var weight = 40;
var bmi = weight/(height * height);
alert( bmi );
Jack Eastwood
canvas.paint();
// Ex4-4: BMI Calculator
var canvas;
canvas = openGraphics();
canvas.setFont( "Comic Sans MS", "20px", Font.BOLD );
canvas.drawString( "BMI calculator bitch's", 150, 0);
var height = parseFloat(prompt("Please enter your height in cm: ")
,10)/100;
var weight = parseFloat(prompt("Please enter your weight in kg: ")
,10);
var calculation = weight/(height * height);
var bmi = calculation.toFixed(2);
var classification;
if (bmi <= 18.4999){
classification = " Underweight";
}
else if (bmi > 18.4999 && bmi <= 24.999){
classification = " Ideal";
}
else if (bmi > 24.999 && bmi <= 29.999){
classification = " Overweight";
Jack Eastwood
}
else if (bmi > 29.999 && bmi <= 39.999){
classification = " Obese";
}
else if (bmi > 39.999){
classification = " Very obese";
}
canvas.setFont( "Comic Sans MS", "14px" );
canvas.drawString( bmi + ":" + classification, 0, 50 );
canvas.paint();
Jack Eastwood
// Ex4-4: BMI Calculator
var canvas;
Jack Eastwood
canvas = openGraphics();
var reset = false;
var xos = 20;
var xosGreen = 125;
var xosOrange = 205;
var xosBrown = 265;
var xosRed = 385;
var yos = 20;
var lineHeight = 400;
var lineHeight2 = 396.5;
var lineLength = 550;
var lineYellow = 105;
var lineGreen = 80;
var lineOrange = 60;
var lineBrown = 120;
var lineRed = 184;
var label = 10;
var labelnum = 0;
var ArmLength = 30;
var ArmYPos = 330;
var LArmPos = 265;
var RArmPos = 320;
var LegLength = 70;
var LegYPos = 350;
var LLegPos = 300;
var RLegPos = 320;
var metricKg;
Jack Eastwood
var metricCM;
var imperialInches;
var imperialStone;
while( !reset ){
canvas.setFont( "Comic Sans MS", "20px", Font.BOLD
);
canvas.drawString( "BMI calculator", 150, 0);
canvas.setFont( "Comic Sans MS", "14px");
canvas.drawString( "This program will calculate
your body mass index which is an indication of the status of your
weight.", 0 ,30 );
canvas.drawString( "The higher the BMI figure, the
more likely it is that you are overweight.", 0, 50);
var measureType = prompt( "Would you like to use
Metric or Imperial conversion? (Metric/Imperial): ");
if (measureType == "metric"){
var heightMetric = parseFloat(prompt("Please enter
your height in cm: ") ,10)/100;
var weightMetric = parseFloat(prompt("Please enter
your weight in kg: ") ,10);
var calculationMetric = weightMetric/(heightMetric
* heightMetric);
var bmiMetric = calculationMetric.toFixed(2);
metricKg = " Kg";
metricCM = " Cm";
}
else if (measureType == "imperial"){
var heightImperial = parseFloat(prompt( "Please
enter your height in inches: "), 10);
Jack Eastwood
var weightImperial = parseFloat(prompt( "Please
enter your weight in pounds: "), 10);
var calculationImperial = weightImperial *
703/(heightImperial * heightImperial);
var bmiImperial = calculationImperial.toFixed(2);
imperialInches = " inches";
imperialStone = " stones";
}
var classification;
canvas.setFont( "Comic Sans MS", "14px" );
canvas.setColor( "DarkBlue" );
if (bmiMetric || bmiImperial <= 18.4999){
canvas.setColor( "black" );
canvas.setStroke(3);
classification = " Underweight";
canvas.drawEllipse(xos + 3 + 50, 290, 20, 20);
canvas.fillEllipse(xos + 50, 310, 30, 70);
canvas.drawLine( xos + 50 + 50, ArmYPos, xos + 50
+ ArmLength, ArmYPos );
canvas.drawLine( xos - 50 + 50, ArmYPos, xos + 50
+ ArmLength, ArmYPos );
canvas.drawLine( xos + 5 + 50, LegYPos, xos + 5 +
50, LegYPos + LegLength );
canvas.drawLine( xos + 20 + 50, LegYPos, xos + 20
+ 50, LegYPos + LegLength );
}
else if (bmiMetric || bmiImperial > 18.4999 &&
bmiMetric || bmiImperial <= 24.999){
canvas.setColor( "black");
Jack Eastwood
canvas.setStroke(3);
classification = " Ideal";
canvas.drawEllipse(xos + 3 + 150, 290, 20, 20);
canvas.fillEllipse(xos + 150, 310, 30, 70);
canvas.drawLine( xos + 50 + 150, ArmYPos, xos +
150 + ArmLength, ArmYPos );
canvas.drawLine( xos - 50 + 150, ArmYPos, xos +
150 + ArmLength, ArmYPos );
canvas.drawLine( xos + 5 + 150, LegYPos, xos + 5 +
150, LegYPos + LegLength );
canvas.drawLine( xos + 20 + 150, LegYPos, xos + 20
+ 150, LegYPos + LegLength );
}
else if (bmiMetric || bmiImperial > 24.999 &&
bmiMetric || bmiImperial <= 29.999){
canvas.setColor( "black" );
canvas.setStroke(3);
classification = " Overweight";
canvas.drawEllipse(xos + 3 + 200, 290, 20, 20);
canvas.fillEllipse(xos + 200, 310, 30, 70);
canvas.drawLine( xos + 50 + 200, ArmYPos, xos +
200 + ArmLength, ArmYPos );
canvas.drawLine( xos - 50 + 200, ArmYPos, xos +
200 + ArmLength, ArmYPos );
canvas.drawLine( xos + 5 + 200, LegYPos, xos + 5 +
200, LegYPos + LegLength );
canvas.drawLine( xos + 20 + 200, LegYPos, xos + 20
+ 200, LegYPos + LegLength );
}
else if (bmiMetric || bmiImperial > 29.999 &&
bmiMetric || bmiImperial <= 39.999){
canvas.setColor( "black" );
canvas.setStroke(3);
Jack Eastwood
classification = " Obese";
canvas.drawEllipse(xos + 3 + 300, 290, 20, 20);
canvas.fillEllipse(xos + 300, 310, 30, 70);
canvas.drawLine( xos + 50 + 300, ArmYPos, xos +
300 + ArmLength, ArmYPos );
canvas.drawLine( xos - 50 + 300, ArmYPos, xos +
300 + ArmLength, ArmYPos );
canvas.drawLine( xos + 5 + 300, LegYPos, xos + 5 +
300, LegYPos + LegLength );
canvas.drawLine( xos + 20 + 300, LegYPos, xos + 20
+ 300, LegYPos + LegLength );
}
else if (bmiMetric || bmiImperial > 39.999){
canvas.setColor( "black" );
canvas.setStroke(3);
classification = " Very obese";
canvas.drawEllipse(xos + 3 + 450, 290, 20, 20);
canvas.fillEllipse(xos + 450, 310, 30, 70);
canvas.drawLine( xos + 50 + 450, ArmYPos, xos +
450 + ArmLength, ArmYPos );
canvas.drawLine( xos - 50 + 450, ArmYPos, xos +
450 + ArmLength, ArmYPos );
canvas.drawLine( xos + 5 + 450, LegYPos, xos + 5 +
450, LegYPos + LegLength );
canvas.drawLine( xos + 20 + 450, LegYPos, xos + 20
+ 450, LegYPos + LegLength );
}
canvas.setColor("Purple");
canvas.drawString( bmiMetric||bmiImperial + ":" + classification,
0, 150 );
canvas.drawString( "Height " + ":" + heightMetric||heightImperial
+ metricCM||imperialInches, 120, 100 );
Jack Eastwood
canvas.drawString( "Weight " + ":" + weightMetric||weightImperial
+ metricKg||imperialStone, 0, 100 );
canvas.setStroke(5);
canvas.setColor ( "Yellow" );
canvas.drawLine( xos, yos + lineHeight2, xos + lineYellow, yos +
lineHeight2 );
canvas.setColor( 'Green' );
canvas.drawLine( xosGreen, yos + lineHeight2, xosGreen +
lineGreen, yos + lineHeight2 );
canvas.setColor( "Orange" );
canvas.drawLine( xosOrange, yos + lineHeight2, xosOrange +
lineOrange, yos + lineHeight2 );
canvas.setColor( "Brown" );
canvas.drawLine( xosBrown, yos + lineHeight2, xosBrown +
lineBrown, yos + lineHeight2 );
canvas.setColor( "Red" );
canvas.drawLine( xosRed, yos + lineHeight2, xosRed + lineRed, yos
+ lineHeight2 );
canvas.setStroke( 3 );
canvas.setColor( "Black" );
canvas.drawLine( xos, yos + lineHeight, xos + lineLength, yos +
lineHeight);
for( labelnum = 0; labelnum <= 9; labelnum++ )
{
canvas.drawString( label, xos + (labelnum * 60),
(yos + lineHeight));
label = label + 5;
}
canvas.paint();
Jack Eastwood
reset = prompt( "Would you like to start over?
(Y/N)" );
if ( reset == "y"){
reset = false;
canvas.clear();
}
else {
reset = true;
}
}
Jack Eastwood
Jack Eastwood
Jack Eastwood
Jack Eastwood
Comments
The vast majorityof the program iscontainedwithinawhile loop thatissetto false.The useris
promptedif theywantto use a metricor imperial calculation.Thiswillthengointo2 if statements
whetherthe userhasselectedmetricorimperial conversions,andbothstatementswillpromptthe
userto type intheirheightandweightvalues(kgandcm formetric,inchesandpoundsforimperial)
thenboththe weightandheightvariablesare calculatedagainsteachothertocalculate the BMI
valuesforbothtypesthenroundedupto 2 decimal placesusing.toFIxed(2).If statementsare then
usedto classifythe BMIfrom the value calculatedbythe var BMi metric/Imperial,soif the BMI value
isbelow18.5 thenthiswouldbe classifiedas“Underweight”andthe exactbmi will be printedonthe
canvas alongwithwhatclassificationitfallsunder.Ineachif statementare anumberof drawRect’s
and drawLine’swhichdrawafigure.Thisfigure willthenmove tothe colouredareasonthe line
representingwhatclassificationthe bmi hasfallenunderbychangingthe valuesof eachline’sXos
value.Finally,the userispromptedwhethertheywanttorunthe programagain andif the user
Jack Eastwood
typesyes(“y”) thenresetwill remainfalse andthe programisresetby usingthe canvas.clear
functionotherwiseanythingelsetypedinthe promptwill endthe program.
Errors: I alsoencounteredsome unusual errors,whenusingmetricconversionthe heightandweight
valuesare correctlydisplayed,butwhenIuse imperial the heightandweightvaluessay“undefined”.
The classificationafterwherethe Bmi value isdisplayedonlyworksforimperial conversionandnot
metric.
5.1 Weather graph
// Ex5-1: Weather Data Graph
var canvas;
canvas = openGraphics();
var xos = 50;
var yos = 100;
var yal = 400;
var xal = 400;
var ylabel = 0;
var ylabelnum = 0;
var xlabel = 0;
var xlabelnum = 0;
var monthwidth = 30;
var month;
var rainfall;
var monthString = ("JFMAMJJUSOND");
canvas.drawLine(xos, yos, xos, yos + yal);
canvas.drawLine(xos, yos + yal, xos + xal, yos + yal);
for(ylabelnum = 0; ylabelnum <= 10; ylabelnum++ )
{
canvas.drawString(ylabel, xos/2, (yos + yal) - (
40 * ylabelnum ));
ylabel = ylabel + 50;
Jack Eastwood
}
for(month = 0; month <=11; month++ )
{
rainfall= prompt( "Please enter rainfall." );
parseInt (rainfall, 10);
canvas.setColor( "blue" );
canvas.fillRect(xos+(monthwidth*month), (yos +
yal) - rainfall, monthwidth, rainfall);
canvas.setColor( "black" );
canvas.drawRect(xos+(monthwidth*month), (yos +
yal) - rainfall, monthwidth, rainfall);
canvas.drawString( monthString.charAt(month), xos+
10 +(monthwidth*month), (yos + yal));
}
canvas.paint();
Jack Eastwood
// Ex5-1: Weather Data Graph
var canvas;
canvas = openGraphics();
var xos = 60;
var yos = 100;
var yal = 400;
Jack Eastwood
var xal = 500;
var ylabel = 0;
var ylabelnum = 0;
var xlabel = 0;
var xlabelnum = 0;
var monthwidth = 30;
var month;
var rainfall;
var monthString = ("JFMAMJJUSOND");
canvas.drawLine(xos, yos, xos, yos + yal);
canvas.drawLine(xos, yos, xos + xal, yos);
for(month = 0; month <= 11; month++ )
{
rainfall= prompt( "Please enter rainfall." );
parseInt (rainfall, 10);
canvas.setColor( "blue" );
canvas.fillRect(xos, yos+(monthwidth*month),
rainfall, monthwidth);
canvas.setColor( "black" );
canvas.drawString( monthString.charAt(month),
xos/2, yos+(monthwidth*month));
}
for(xlabelnum = 0; xlabelnum <=10; xlabelnum++ )
{
canvas.drawString(xlabel, xos + (xlabelnum * 50),
yos-15);
xlabel = xlabel + 50;
}
Jack Eastwood
canvas.paint();
//canvas.fillRect(xos+(monthwidth*month), (yos + yal) - rainfall,
monthwidth, rainfall);
Comments
The charAt() function selectsasingle characterina stringthenprintsiton the canvas. For instance
charAt(0) selectsthe 1st
character withinastring.The variable monthStringhasall the initialsof all
the monthslistedandwhenplottedonthe Xaxisinthe loop,charAt(month) selectseachinitialin
orderthenplotsthemone at a time until the loopends.
Jack Eastwood
5.2 Picture frame revisited
var canvas = openGraphics();
var xPosition = 100;
var yPosition = 50;
var width = 200;
var height = 150;
var xPos;
var xLeft;
var xRight;
var yPos;
var yTop;
var yBottom;
var line;
var imageName = "Honeysuckle.jpeg";
canvas.setColor ("Gold");
canvas.fillRect (75, 25, 250, 200);
canvas.setColor ("Darkred");
canvas.setStroke (3);
canvas.drawRect (73, 23, 250, 200);
canvas.setStroke(1);
canvas.setColor("Black");
xPos = 326;
yTop = 22;
yBottom = 226;
for( line = 0; line<4; line++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos += 1;
yTop -= 1;
Jack Eastwood
yBottom += 1;
}
xPos = 76;
yTop = 26;
yBottom = 222;
for(line = 0; line<4; line++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos += 1;
yTop += 1;
yBottom -= 1;
}
xLeft = 80;
xRight = 318;
yPos = 29;
for( line = 0; line<4; line++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
xLeft -= 1;
xRight += 1;
yPos -= 1;
}
xLeft = 73;
xRight = 325;
yPos = 226;
for( line = 0; line<4; line++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
Jack Eastwood
xLeft -= 1;
xRight += 1;
yPos += 1;
}
canvas.setColor("Red");
xPos = 322;
yTop = 26;
yBottom = 222;
for(line = 0; line<4; line++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos -= 1;
yTop += 1;
yBottom -= 1;
}
xPos = 72;
yTop = 22;
yBottom = 226;
for( line = 0; line<4; line++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos -= 1;
yTop -= 1;
yBottom += 1;
}
xLeft = 73;
xRight = 325;
Jack Eastwood
yPos = 22;
for( line = 0; line<4; line++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
xLeft -= 1;
xRight += 1;
yPos -= 1;
}
xLeft = 77;
xRight = 321;
yPos = 222;
for( line = 0; line<4; line++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
xLeft += 1;
xRight -= 1;
yPos -= 1;
}
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
canvas.paint();
Jack Eastwood
Comments
For loopsare usedto print4 linesoneachside of the image,andeverytime a line getsprintedthen
the X and Y positionwill change by1 eachtime a line isprintedthatgivesthe line atriangularshape
at the end.The X andY co-ordinate variableswill have tobe givendifferentvaluestobe setat a
specificplace onall 4 sidesof the image otherwise the lineswill be printedfromthe previousXandY
valuesgivenonthe previousloop.
5.3 Interest calculator html
<html>
<head>
<title>
Interest Calculator
</title>
</head>
<body>
<h1> Interest Calculator </h1>
<p> This will calculate the interest on any amount
of money from the interest rate and investment period. </p>
<form action="server_program_name" method="get"
id="money">
Jack Eastwood
<label for="money">
Amount of money:
</label>
<input type="number" name="money"></form>
<form action="server_program_name" method="get"
id="interest_rate">
<label for="interest_rate">
Interest rate(%):
</label>
<input type="number" name="money"></form>
<form action="server_program_name" method="get"
id="investment_period">
<label for="investment_period">
Investment period (years):
</label>
<input type="number" name="investment_period"
min=”0”></form>
<button value="submit" type="submit">
Calculate Interest
</button>
</body>
</html>
Jack Eastwood
5.4 Date validation form
<html>
<head>
<title>
Date Validation
</title>
</head>
<body>
<h1> Date validation </h1>
<p> Page to validate the day, month and year</p>
<form id="day" action="server_program_name"
method="get">
<label for="day">
Day:
</label>
<input type="number" name="money" min="1"
max="31"></form>
Jack Eastwood
<form id="month" action="server_program_name"
method="get">
<label for="month">
Month:
</label>
<input type="number" name="month" min="1"
max="12"></form>
<form id="year" action="server_program_name"
method="get">
<label for="month">
Year:
</label>
<input type="number" name="year" value="2000"
></form>
<button value="submit" type="submit">
Validate date
</button>
</body>
</html>
Jack Eastwood
Comments
Inputbox’scan be givena minimumvalue toacceptbyput min=”value”asan element.A starting
value can alsobe put inside aninputbytypingvalue=”value”.
5.5 Bmi calculator html
<html>
<head>
<title>
BMI Calculator
</title>
</head>
<body>
<h1> BMI calculator </h1>
<p> Body Mass Index is derived from calculating an
individuals weight and height. The calculation to work out an
individuals BMI for a metric conversion is weight/height x height.
</p>
<p> There are classifications for different bmi
values: </p>
<p> 18.5 or under: Underweight </p>
<p> 18.5 - 25: Ideal </p>
<p> 25 - 30: Overweight </p>
<p> 30 - 40: Obese </p>
<p> 40 or over: Very Obese </p>
<form id="weight" action="server_program_name"
method="get">
<label for="weight">
Please enter your weight (KG):
</label>
<input type="number" name="weight" min="0"></form>
Jack Eastwood
<form id="height" action="server_program_name"
method="get">
<label for="height">
Please enter your height (CM):
</label>
<input type="number" name="height" min="0"></form>
<button value="submit" type="submit">
Calculate BMI
</button>
</body>
</html>
Jack Eastwood
6.1 Metric Conversion
<html>
<head>
<title>
Metric Conversions
</title>
<script type = "text/JavaScript">
function milesToKilometers()
{
var miles;
miles = document.getElementById(
"milesBox" ).value;
miles = parseFloat( miles );
var kilometers = miles / 5 * 8;
document.getElementById( "kilometersBox"
).value = kilometers.toFixed(2);
}
function KilometersToMiles()
{
var kilometers;
kilometers = document.getElementById(
"kilometersBox" ).value;
kilometers = parseFloat( kilometers );
var miles = kilometers / 8 * 5;
document.getElementById( "milesBox" ).value
= miles.toFixed(2);
}
</script>
</head>
<body>
<h1>
Jack Eastwood
Metric Conversions
</h1>
<h2>
Miles : Kilometers
</h2>
<p>
The conversion factor for miles and
kilometers
is based on the fact that 5 miles is the
same
distance as 8 kilometers.
</p>
Miles:
<input type = "text"
id = "milesBox"
value = "" />
<br />
Kilometers:
<input type = "text"
id = "kilometersBox"
value = "" />
<br /><br />
<input type = "button"
id= "convert1"
value = "Miles to Kilometers"
onclick = "milesToKilometers();" />
<br /><br />
<input type = "button"
id = "convert2"
value = "Kilometers to Miles"
onclick = "KilometersToMiles();" />
Jack Eastwood
</body>
</html>
Comments
Jack Eastwood
The document.getElementByIdfunctionlooksforthe value togive toa specificvariablefromanhtml
objectwiththatspecificidname.Inthiscase,the kilometresbox idwasgiventothe inputbox for
the userto type how manykilometres.The buttonsare linkedtothe scriptwhentheyare givenan
onclickelement,sothe milestokilometre buttonhasbeengivenonclick=”milesToKilometers();”that
linkstothe milestokilometersfunction inthe script.Anyscriptsdeclared will have tobe declaredby
statingthat itusestextand javascriptasits data type.
6.2 Interest Calculator Page
<html>
<head>
<title>
Interest Calculator
</title>
<script type = "text/Javascript">
function InterestCalculator()
{
var amount;
amount = document.getElementById( "money").value;
amount = parseFloat( amount );
var rate;
rate = document.getElementById( "Interest_rate" ).value;
rate = parseFloat( rate );
var years;
years = document.getElementById( "Investment_period"
).value;
years = parseFloat( years );
var interest;
interest = (amount * rate * years)/100;
Jack Eastwood
alert( interest );
}
</script>
</head>
<body>
<h1> Interest Calculator </h1>
<p> This will calculate the interest on any amount of money
from the interest rate and investment period. </p>
<form action="server_program_name" method="get">
<label for="money">
Amount of money:
</label>
<input type="number"id="money" name="money"></form>
<form action="server_program_name" method="get">
<label for="interest_rate">
Interest rate(%):
</label>
<input type="number" id="Interest_rate"
name="money"></form>
<form action="server_program_name" method="get">
<label for="investment_period">
Investment period (years):
</label>
<input type="number" id="Investment_period"
name="Investment money" min="0">
<br /><br />
<input type = "button"
id = "CalculateInterest"
value = "Calculate Interest"
onclick = "InterestCalculator();" />
</form>
</body>
Jack Eastwood
</html>
Jack Eastwood
6.3 Validating a date
<html>
<head>
<title>
Date Validation
</title>
<script type = "text/Javascript">
function DateValidation()
{
var day;
day = document.getElementById( "day" ).value;
Jack Eastwood
day = parseFloat( day );
var month;
month = document.getElementById( "month" ).value;
month = parseFloat( month );
var year;
year = document.getElementById( "year" ).value;
year = parseFloat( year );
var today = new Date();
var tDay = today.getDate();
var tMonth = today.getMonth()+1;
var tYear = today.getFullYear();
var birthday;
birthday = new Date( year, month-1, day );
var age;
age = today - birthday;
var ageindays;
ageindays = age/86400000;
var ageinyears;
ageinyears = ageindays/365;
if (day >=1 && day<=31)
{
Jack Eastwood
alert ("Day is valid");
}
else
{
alert ("Day is invalid");
}
if (month >=1 && month <=12)
{
alert("Month is valid");
}
else
{
alert("Month is invalid");
}
if (year >= 0 && year <= 2015)
{
alert("Year is valid");
}
else
{
alert("Year is invalid");
}
document.getElementById( "ageBox" ).value =
ageinyears.toFixed(2);
}
</script>
</head>
Jack Eastwood
<body>
<h1> Date validation </h1>
<p> Page to validate the user's birthday</p>
<form action="server_program_name" method="get">
<label for="day">
Day:
</label>
<input type="number" name="money" id="day"
min="1"></form>
<form action="server_program_name" method="get">
<label for="month">
Month:
</label>
<input type="number" name="month" id="month"
min="1"></form>
<form action="server_program_name" method="get">
<label for="year">
Year:
</label>
<input type="number" name="year" id="year" ></form>
<form action="server_program_name" method="get">
<label for="age">
Age:
</label>
<input type="number" id="ageBox" value=" " ></form>
<br /><br />
<input type = "button"
id = "ValidateDate"
value = "Validate Date's"
onclick = "DateValidation();" />
</body>
Jack Eastwood
</html>
Jack Eastwood
6.4 BMI calculator html
<html>
<head>
<title>
BMI Calculator
</title>
<script type ="text/Javascript">
function BMIcalculation()
{
var height;
Jack Eastwood
height = document.getElementById(
"Height" ).value/100;
height = parseFloat( height );
var weight;
weight = document.getElementById(
"Weight" ).value;
weight = parseFloat( weight );
var calculation = weight/(height *
height);
var bmi = calculation.toFixed(2);
var classification;
if (bmi <= 18.4999){
classification = " Underweight";
}
else if (bmi > 18.4999 && bmi <=
24.999){
classification = " Ideal";
}
else if (bmi > 24.999 && bmi <= 29.999){
classification = " Overweight";
}
else if (bmi > 29.999 && bmi <= 39.999){
classification = " Obese";
}
else if (bmi > 39.999){
classification = " Very obese";
}
alert( bmi + classification );
Jack Eastwood
document.getElementById( "BMIbox"
).value = bmi;
}
</script>
</head>
<body>
<h1> BMI calculator </h1>
<p> Body Mass Index is derived from
calculating an individuals weight and height. The calculation to
work out an individuals BMI for a metric conversion is
weight/height x height. </p>
<p> There are classifications for
different bmi values: </p>
<p> 18.5 or under: Underweight </p>
<p> 18.5 - 25: Ideal </p>
<p> 25 - 30: Overweight </p>
<p> 30 - 40: Obese </p>
<p> 40 or over: Very Obese </p>
<form action="server_program_name"
method="get">
<label for="weight">
Please enter your weight (KG):
</label>
<input id = "Weight" type="number"
name="weight" min="0"></form>
<form action="server_program_name"
method="get">
<label for="height">
Please enter your height (CM):
</label>
<input id = "Height" type="number"
name="height" min="0"></form>
<button value="submit" type="submit"
onclick = "BMIcalculation();">
Jack Eastwood
Calculate BMI
</button>
<form action = "server_program_name"
method="get">
<label> BMI: </label>
<input id="BMIbox"
type="number"></form>
</body>
</html>
Jack Eastwood
Jack Eastwood

More Related Content

PDF
Hands-on ML - CH3
PPTX
Rhino script 101 creativity
PDF
Александр Зимин – Анимация как средство самовыражения
KEY
Exploring Canvas
KEY
The Canvas API for Rubyists
DOCX
program logbook
PPTX
von Neumann Poker
PDF
Of class2
Hands-on ML - CH3
Rhino script 101 creativity
Александр Зимин – Анимация как средство самовыражения
Exploring Canvas
The Canvas API for Rubyists
program logbook
von Neumann Poker
Of class2

Viewers also liked (11)

PDF
New Insights Into Preventing Cancer
DOCX
SERVICIO DE TORNO CNC
PDF
My Introduction
PDF
Livre Blanc Blockchain & Immobilier 26 avril 2016
PPT
Mecanizado 1
PPTX
Immobilier commercial à Genève: dynamique territoriale des zones industrielles
PDF
Mehrsprachigkeit 26.2.16
PDF
Subtilezas do erro. pdf
PPTX
Livre blanc l'annonce immobilière
New Insights Into Preventing Cancer
SERVICIO DE TORNO CNC
My Introduction
Livre Blanc Blockchain & Immobilier 26 avril 2016
Mecanizado 1
Immobilier commercial à Genève: dynamique territoriale des zones industrielles
Mehrsprachigkeit 26.2.16
Subtilezas do erro. pdf
Livre blanc l'annonce immobilière
Ad

Similar to program logbook 2 (20)

PDF
need help with code I wrote. This code is a maze gui, and i need hel.pdf
DOCX
Review questions and answers
PDF
Standford 2015 week3: Objective-C Compatibility, Property List, Views
PDF
Exploring Canvas
PPTX
Programming ppt files (final)
PPT
conditional.ppt
PDF
C in 10 Hours learn programming easily.pdf.pdf
DOCX
Computer science project work on C++
PDF
Creative Coding 1 - 2 Variables
DOCX
Computer graphics lab assignment
PDF
Mini-curso JavaFX Aula1
PPTX
Css5 canvas
PDF
2Bytesprog2 course_2014_c9_graph
PPTX
Crush Candy with DukeScript
PDF
Anomalies in X-Ray Engine
DOCX
Write a Matlab code (a computerized program) for calculating plane st.docx
PDF
C Language Lecture 17
ODP
Creating masterpieces with raphael
PDF
PART 5: RASTER DATA
PPTX
C Programming Example
need help with code I wrote. This code is a maze gui, and i need hel.pdf
Review questions and answers
Standford 2015 week3: Objective-C Compatibility, Property List, Views
Exploring Canvas
Programming ppt files (final)
conditional.ppt
C in 10 Hours learn programming easily.pdf.pdf
Computer science project work on C++
Creative Coding 1 - 2 Variables
Computer graphics lab assignment
Mini-curso JavaFX Aula1
Css5 canvas
2Bytesprog2 course_2014_c9_graph
Crush Candy with DukeScript
Anomalies in X-Ray Engine
Write a Matlab code (a computerized program) for calculating plane st.docx
C Language Lecture 17
Creating masterpieces with raphael
PART 5: RASTER DATA
C Programming Example
Ad

program logbook 2

  • 1. Jack Eastwood Top tips:  Put semi-colonsatthe endof everything  2 equalssigns=comparison  Variablescanbe overwritten  Watch out for grammar  All variableshave tobe declaredusing“VAR”thenavalue needstobe assignedtothe variable.  Code iscase sensitive  Orderingof variablesisveryimportant  “//” can be usedtoapplycommentsinyourcode withoutbeingappliedwhenrunningthe program.  The “prompt” variable displaysawindow thatasksthe userfor an input,inthiscase “Please enteryourname:”  The “alert” variable displaysthe “message”variable onanotherwindow afterthe userhas put an inputinthe promptwindow.  Wheneversomethingisstoredasa promptit’sstoredas a string.  == meansequals,!=meansnotequal  parseIntmeansparse integer,meaningthisonlypicksoutanynumerical valuesfromastring of charactersidentifiedinavariable.  Don’trelyon > or <, use rangeswithdefinedupperandlowerlimits.  Don’tput a semi-colonatthe endof a for loop.  Var ++ isthe same as var= var + 1  && meansand, ||meansor  ParseFloat= returnsanyfloatingpointnumber 3.5 Experiments with graphics // Ex3-5 : Graphics Experiments // Part of demo program: var canvas; canvas = openGraphics(); var x; var y; var size; x = 0;
  • 2. Jack Eastwood y = 0; size = 500; while( size > 0 ) { canvas.setColor( "white" ); canvas.fillEllipse( x, y, size, size ); canvas.setColor( "blue" ); canvas.drawEllipse( x, y, size, size ); x = x + 10; y = y + 10; size = size - 20; } canvas.paint();
  • 3. Jack Eastwood // Ex3-5 : Graphics Experiments // Part of demo program: var canvas; canvas = openGraphics(); var x; var y; var width; var height; x = 0;
  • 4. Jack Eastwood y = 0; width = 200; height = 700; while( (width > 0 ) && (height > 0) ) { canvas.setColor( "white" ); canvas.fillEllipse( x, y, width, height ); canvas.setColor( "blue" ); canvas.drawEllipse( x, y, width, height ); x = x + 23; y = y + 3; width = width - 7; height = height - 70; } canvas.paint();
  • 5. Jack Eastwood Comments Changingthe size orwidth/heightvariableswill change how small orbigthe overall shape willbe outputtedonthe canvas. In the two examplesI’vegiven,byreducingthe size inthe loopfromthe
  • 6. Jack Eastwood size setwhenthe variable isdeclaredwill influence how manycircleswillbe drawni.e if size issetto 800 thensize wasreducedby20 inthe loop,then40 circleswouldbe outputted. 3.6 Graphical Event timer // Ex 3-6 : Graphical Event Timer var canvas; canvas = openGraphics(); var textX = 20; var textY = 30; var lineX = 180; var lineY = textY + 5; for (var i = 0; i < 10; i++) { // Put your event timer code here alert( "Press "OK" to start the timer." ); var date = new Date(); // create another Date object and store the time now alert( "Press "OK" to stop the timer." ); var date1 = new Date(); var difference = date1 - date; var previoustime; canvas.setStroke(3); canvas.setColor("black"); canvas.drawString( "Timer", 150, 0 ); canvas.drawString( " Difference in time: " + difference + "ms", 10, textY); if (previoustime>difference) {
  • 7. Jack Eastwood canvas.setColor("Green"); } else if (previoustime<difference){ canvas.setColor("Red"); } else { canvas.setColor("black"); } canvas.drawLine( lineX, lineY, lineX + difference, lineY ); textY = textY + 20; lineY = lineY + 20; previoustime=difference; canvas.paint(); } Comments The program calculatesthe difference intime bysettingup2 datesthat gathersthe exacttime,then findsthe difference betweenthe twotimeswhenthe userhitsthe “start” and“stop” prompts.The
  • 8. Jack Eastwood difference betweenthe 2timesisthenoutputtedasa line andthe higherthe difference,the higher the line length,sothe difference isaddedtothe line’sx length.The forloopmeansthatthe userwill askedto calculate the difference intime 10times(10 starts + 10 stops).If the difference intime is lessthanthe earliertime,thenthe line colourwill be settogreenandif the difference ishigherthan the line colourwill be settoredusingif statementsondifference +previoustime variables.Atthe endof the loopthe line andtextY positionsare plusedby20, meaningthateveryline andtext outputwhenthe userhitsstart and stopwill be placedbelow the previousoutput. 3.7 Sudoku Grid // Ex3-7 : Blank Sudoku Grid var canvas; canvas = openGraphics(); var x; var y; var gap; x = 20; y = 20; gap = 25; // so not much help here! var count; for( count=0; count<11; count++ ) { canvas.drawLine( x,y,x+225,y ); y = x+count*gap; } //endfor x = 20; y = 20;
  • 9. Jack Eastwood for( count=0; count<11; count++ ) { canvas.drawLine(x,y,x,y+225); x = y+count*gap; } x = 20; y = 20; for( count=0; count<5; count++ ) { canvas.setStroke(3); canvas.drawLine(x,y,x+225,y); y = x+count*gap*3; } x = 20; y = 20; for( count=0; count<5; count++) { canvas.setStroke(3); canvas.drawLine(x,y,x,y+225); x = y+count*gap*3; } canvas.paint();
  • 10. Jack Eastwood Comments 4 forloopsare usedto create thisSudokugrid.The firstfor loopdraw out all the horizontal lines10 timesandbecause the gap size issetto 25 thenthe X line lengthswill be setto225 as each 3x3 box is75x75, sothisis addedto the X axislengthparameteraswell asthe Y axisoffsetbeingplaced25 pixelsbeloweverytime ahorizontal lineisplaced.The secondforloopplotsthe vertical linesand thisisthe same as the previousforloopapartfrom that the valuesare addedto the Y line lengthand X offset.Finally,the final2loopsaddthe thickblacklinestoformthe grid and the onlydifference is that the setStroke issetto 3, count setto 5 (prints4 times) andthe gapis timesby3 whichwill create each 3 x 3 box.The X and Y co-ordinateshave tobe resetaftereachloop otherwise the next loopwouldjustprintonthe Xand Y co-ordinatescalculatedbythe previousloops.
  • 11. Jack Eastwood 4.1 Garfield cartoon // Ex4-1: Garfield Cartoon var canvas; canvas = openGraphics(); var imageName1; var imageName2; var imageName3; var xPosition; var yPosition; var width; var height; imageName1 = "garfield1.gif"; xPosition = 10; yPosition = 10; canvas.drawImage(imageName1, xPosition,yPosition); imageName2 = "garfield2.gif"; xPosition = 210; yPosition = 10; canvas.drawImage(imageName2, xPosition, yPosition); imageName3 = "garfield3.gif";
  • 12. Jack Eastwood xPosition = 400; yPosition = 10; canvas.drawImage(imageName3, xPosition, yPosition); canvas.setFont( "comic sans ms","10.5px", Font.BOLD ); canvas.drawStringRect("THERE'S A GOOD SCARY MOVIE ON TV TONIGHT", 30, 13, 150); canvas.drawStringRect("YEAH, SURE", 140, 55, 50); canvas.drawStringRect("YOU SAY THAT EVERY NIGHT", 328, 40, 61); canvas.drawStringRect("''INVASION OF THE 50-FOOT ADOLESCENTS''", 415, 12, 150); canvas.drawStringRect("TONIGHT, THOUGH, YOU WOULD BE CORRECT", 530, 40, 70); canvas.paint(); Comments The canvas.drawStringRectfunctionbasicallydrawsastringinan invisiblerectangle.Inmore simple termsstringscan onlybe drawn at a fixedwidthbychangingthe widthvalue (drawstringRect(x),(y),(width).The higherthe usersetsthe widthvalue thenthe longerastringcan be drawn outhorizontallyonacanvas.
  • 13. Jack Eastwood 4.2 guess the number // Ex4-2: Guess the Number var canvas; canvas = openGraphics(); var max; max = 100; var numberToGuess; numberToGuess = 50; // use a known value for testing canvas.drawString("Welcome to Jack Eastwood's guessing game", 50, 10); var guess; guess = parseInt(prompt("Please input a number between 0 and 100"),10); var guessed = false; var message; // (3) if too high ..... if (guess < numberToGuess) { canvas.drawString("You was wrong, try a higher number", 10, 30); } // (4) if too low ..... if (guess > numberToGuess) {
  • 14. Jack Eastwood canvas.drawString("You was wrong again fool, try a lower number", 10, 30); } // (5) "just right" said Goldilocks ..... if (guess == numberToGuess) { canvas.drawString("You was right",10,30); } // (6) canvas.drawString( message ...... canvas.paint();
  • 15. Jack Eastwood // Ex4-2: Guess the Number var canvas; canvas = openGraphics();
  • 16. Jack Eastwood var max; max = 100; var numberToGuess = Math.floor( Math.random() * max ) +1; canvas.drawString("Welcome to Jack Eastwood's guessing game", 50, 10); var x = 20; var y = 20; var guess; var guessed = false; while( !guessed ){ guess = parseInt(prompt("Please input a number between 0 and 100"),10); var message; // (3) if too high ..... if (guess > numberToGuess){ message = guess + " Too high"; } // (4) if too low ..... if (guess < numberToGuess) { message = guess + " Too low"; } // (5) "just right" said Goldilocks ..... if (guess == numberToGuess) {
  • 17. Jack Eastwood message = guess + " Correct"; guessed = true; } canvas.drawString( message, x, y); y = y + 20; canvas.paint(); }
  • 18. Jack Eastwood Comments Thisprogram setsthe userto guessa numberbetween0and 100. The Math.floor( Math.random() * max ) +1 functionsetsa numbertoguessbetween0and the max variable,whichIsetto 100, so will selectarandom numberupto 100 and giventhe variable numberToGuess.The variableguessedto setto false anda while loopisusedsothateverytime the userincorrectlyguessesthe number,then theywill have toguessagainuntil theygetitcorrect. 3 if statementsare alsousedwithinthe while loop,onsayingthat if the userguessestohighthenit will printtohighon the canvas,anotherone sayingto lowonthe canvasand the last if statementisif the usercorrectlyguessesthe numberto guess,thenthe guessedvariablewill be setto“true”,so the while loopwillend and the number that wascorrectlyguessedwill be printedon the canvas. Everytime the userincorrectlyguesses, thenthe Y value forthe user’snumberguessand“Too high/low”isincreasedby20 everytime,so each message will be printedunderneaththe previousmessage. 4.3 Square root calculator // Ex4-3 : Square Root Calculator var canvas; canvas = openGraphics(); //var number = prompt( "Enter a number: " ); //number = parseInt( number, 10 ); //var sqRoot; //sqRoot = Math.sqrt( number ); //var message; //message = "Using the JavaScript library,<br>"; //message = message + "The square root of " + number + "<br>"; //message = message + "is " + sqRoot; // Put your version here var lowGuess = 0; var highGuess = 10; var squareRoot = Math.sqrt( highGuess );
  • 19. Jack Eastwood var guess = prompt( "Please enter a number: "); var message; if( guess > squareRoot){ message = guess + " Too high"; } if( guess < squareRoot){ message = guess + " Too low"; } if( guess == squareRoot){ message = guess + " Correct"; } canvas.drawString( message, 10, 10 ); canvas.paint(); 4.4 BMI calculator // Ex4-4: BMI Calculator var canvas; canvas = openGraphics(); var height = 160/100; var weight = 40; var bmi = weight/(height * height); alert( bmi );
  • 20. Jack Eastwood canvas.paint(); // Ex4-4: BMI Calculator var canvas; canvas = openGraphics(); canvas.setFont( "Comic Sans MS", "20px", Font.BOLD ); canvas.drawString( "BMI calculator bitch's", 150, 0); var height = parseFloat(prompt("Please enter your height in cm: ") ,10)/100; var weight = parseFloat(prompt("Please enter your weight in kg: ") ,10); var calculation = weight/(height * height); var bmi = calculation.toFixed(2); var classification; if (bmi <= 18.4999){ classification = " Underweight"; } else if (bmi > 18.4999 && bmi <= 24.999){ classification = " Ideal"; } else if (bmi > 24.999 && bmi <= 29.999){ classification = " Overweight";
  • 21. Jack Eastwood } else if (bmi > 29.999 && bmi <= 39.999){ classification = " Obese"; } else if (bmi > 39.999){ classification = " Very obese"; } canvas.setFont( "Comic Sans MS", "14px" ); canvas.drawString( bmi + ":" + classification, 0, 50 ); canvas.paint();
  • 22. Jack Eastwood // Ex4-4: BMI Calculator var canvas;
  • 23. Jack Eastwood canvas = openGraphics(); var reset = false; var xos = 20; var xosGreen = 125; var xosOrange = 205; var xosBrown = 265; var xosRed = 385; var yos = 20; var lineHeight = 400; var lineHeight2 = 396.5; var lineLength = 550; var lineYellow = 105; var lineGreen = 80; var lineOrange = 60; var lineBrown = 120; var lineRed = 184; var label = 10; var labelnum = 0; var ArmLength = 30; var ArmYPos = 330; var LArmPos = 265; var RArmPos = 320; var LegLength = 70; var LegYPos = 350; var LLegPos = 300; var RLegPos = 320; var metricKg;
  • 24. Jack Eastwood var metricCM; var imperialInches; var imperialStone; while( !reset ){ canvas.setFont( "Comic Sans MS", "20px", Font.BOLD ); canvas.drawString( "BMI calculator", 150, 0); canvas.setFont( "Comic Sans MS", "14px"); canvas.drawString( "This program will calculate your body mass index which is an indication of the status of your weight.", 0 ,30 ); canvas.drawString( "The higher the BMI figure, the more likely it is that you are overweight.", 0, 50); var measureType = prompt( "Would you like to use Metric or Imperial conversion? (Metric/Imperial): "); if (measureType == "metric"){ var heightMetric = parseFloat(prompt("Please enter your height in cm: ") ,10)/100; var weightMetric = parseFloat(prompt("Please enter your weight in kg: ") ,10); var calculationMetric = weightMetric/(heightMetric * heightMetric); var bmiMetric = calculationMetric.toFixed(2); metricKg = " Kg"; metricCM = " Cm"; } else if (measureType == "imperial"){ var heightImperial = parseFloat(prompt( "Please enter your height in inches: "), 10);
  • 25. Jack Eastwood var weightImperial = parseFloat(prompt( "Please enter your weight in pounds: "), 10); var calculationImperial = weightImperial * 703/(heightImperial * heightImperial); var bmiImperial = calculationImperial.toFixed(2); imperialInches = " inches"; imperialStone = " stones"; } var classification; canvas.setFont( "Comic Sans MS", "14px" ); canvas.setColor( "DarkBlue" ); if (bmiMetric || bmiImperial <= 18.4999){ canvas.setColor( "black" ); canvas.setStroke(3); classification = " Underweight"; canvas.drawEllipse(xos + 3 + 50, 290, 20, 20); canvas.fillEllipse(xos + 50, 310, 30, 70); canvas.drawLine( xos + 50 + 50, ArmYPos, xos + 50 + ArmLength, ArmYPos ); canvas.drawLine( xos - 50 + 50, ArmYPos, xos + 50 + ArmLength, ArmYPos ); canvas.drawLine( xos + 5 + 50, LegYPos, xos + 5 + 50, LegYPos + LegLength ); canvas.drawLine( xos + 20 + 50, LegYPos, xos + 20 + 50, LegYPos + LegLength ); } else if (bmiMetric || bmiImperial > 18.4999 && bmiMetric || bmiImperial <= 24.999){ canvas.setColor( "black");
  • 26. Jack Eastwood canvas.setStroke(3); classification = " Ideal"; canvas.drawEllipse(xos + 3 + 150, 290, 20, 20); canvas.fillEllipse(xos + 150, 310, 30, 70); canvas.drawLine( xos + 50 + 150, ArmYPos, xos + 150 + ArmLength, ArmYPos ); canvas.drawLine( xos - 50 + 150, ArmYPos, xos + 150 + ArmLength, ArmYPos ); canvas.drawLine( xos + 5 + 150, LegYPos, xos + 5 + 150, LegYPos + LegLength ); canvas.drawLine( xos + 20 + 150, LegYPos, xos + 20 + 150, LegYPos + LegLength ); } else if (bmiMetric || bmiImperial > 24.999 && bmiMetric || bmiImperial <= 29.999){ canvas.setColor( "black" ); canvas.setStroke(3); classification = " Overweight"; canvas.drawEllipse(xos + 3 + 200, 290, 20, 20); canvas.fillEllipse(xos + 200, 310, 30, 70); canvas.drawLine( xos + 50 + 200, ArmYPos, xos + 200 + ArmLength, ArmYPos ); canvas.drawLine( xos - 50 + 200, ArmYPos, xos + 200 + ArmLength, ArmYPos ); canvas.drawLine( xos + 5 + 200, LegYPos, xos + 5 + 200, LegYPos + LegLength ); canvas.drawLine( xos + 20 + 200, LegYPos, xos + 20 + 200, LegYPos + LegLength ); } else if (bmiMetric || bmiImperial > 29.999 && bmiMetric || bmiImperial <= 39.999){ canvas.setColor( "black" ); canvas.setStroke(3);
  • 27. Jack Eastwood classification = " Obese"; canvas.drawEllipse(xos + 3 + 300, 290, 20, 20); canvas.fillEllipse(xos + 300, 310, 30, 70); canvas.drawLine( xos + 50 + 300, ArmYPos, xos + 300 + ArmLength, ArmYPos ); canvas.drawLine( xos - 50 + 300, ArmYPos, xos + 300 + ArmLength, ArmYPos ); canvas.drawLine( xos + 5 + 300, LegYPos, xos + 5 + 300, LegYPos + LegLength ); canvas.drawLine( xos + 20 + 300, LegYPos, xos + 20 + 300, LegYPos + LegLength ); } else if (bmiMetric || bmiImperial > 39.999){ canvas.setColor( "black" ); canvas.setStroke(3); classification = " Very obese"; canvas.drawEllipse(xos + 3 + 450, 290, 20, 20); canvas.fillEllipse(xos + 450, 310, 30, 70); canvas.drawLine( xos + 50 + 450, ArmYPos, xos + 450 + ArmLength, ArmYPos ); canvas.drawLine( xos - 50 + 450, ArmYPos, xos + 450 + ArmLength, ArmYPos ); canvas.drawLine( xos + 5 + 450, LegYPos, xos + 5 + 450, LegYPos + LegLength ); canvas.drawLine( xos + 20 + 450, LegYPos, xos + 20 + 450, LegYPos + LegLength ); } canvas.setColor("Purple"); canvas.drawString( bmiMetric||bmiImperial + ":" + classification, 0, 150 ); canvas.drawString( "Height " + ":" + heightMetric||heightImperial + metricCM||imperialInches, 120, 100 );
  • 28. Jack Eastwood canvas.drawString( "Weight " + ":" + weightMetric||weightImperial + metricKg||imperialStone, 0, 100 ); canvas.setStroke(5); canvas.setColor ( "Yellow" ); canvas.drawLine( xos, yos + lineHeight2, xos + lineYellow, yos + lineHeight2 ); canvas.setColor( 'Green' ); canvas.drawLine( xosGreen, yos + lineHeight2, xosGreen + lineGreen, yos + lineHeight2 ); canvas.setColor( "Orange" ); canvas.drawLine( xosOrange, yos + lineHeight2, xosOrange + lineOrange, yos + lineHeight2 ); canvas.setColor( "Brown" ); canvas.drawLine( xosBrown, yos + lineHeight2, xosBrown + lineBrown, yos + lineHeight2 ); canvas.setColor( "Red" ); canvas.drawLine( xosRed, yos + lineHeight2, xosRed + lineRed, yos + lineHeight2 ); canvas.setStroke( 3 ); canvas.setColor( "Black" ); canvas.drawLine( xos, yos + lineHeight, xos + lineLength, yos + lineHeight); for( labelnum = 0; labelnum <= 9; labelnum++ ) { canvas.drawString( label, xos + (labelnum * 60), (yos + lineHeight)); label = label + 5; } canvas.paint();
  • 29. Jack Eastwood reset = prompt( "Would you like to start over? (Y/N)" ); if ( reset == "y"){ reset = false; canvas.clear(); } else { reset = true; } }
  • 33. Jack Eastwood Comments The vast majorityof the program iscontainedwithinawhile loop thatissetto false.The useris promptedif theywantto use a metricor imperial calculation.Thiswillthengointo2 if statements whetherthe userhasselectedmetricorimperial conversions,andbothstatementswillpromptthe userto type intheirheightandweightvalues(kgandcm formetric,inchesandpoundsforimperial) thenboththe weightandheightvariablesare calculatedagainsteachothertocalculate the BMI valuesforbothtypesthenroundedupto 2 decimal placesusing.toFIxed(2).If statementsare then usedto classifythe BMIfrom the value calculatedbythe var BMi metric/Imperial,soif the BMI value isbelow18.5 thenthiswouldbe classifiedas“Underweight”andthe exactbmi will be printedonthe canvas alongwithwhatclassificationitfallsunder.Ineachif statementare anumberof drawRect’s and drawLine’swhichdrawafigure.Thisfigure willthenmove tothe colouredareasonthe line representingwhatclassificationthe bmi hasfallenunderbychangingthe valuesof eachline’sXos value.Finally,the userispromptedwhethertheywanttorunthe programagain andif the user
  • 34. Jack Eastwood typesyes(“y”) thenresetwill remainfalse andthe programisresetby usingthe canvas.clear functionotherwiseanythingelsetypedinthe promptwill endthe program. Errors: I alsoencounteredsome unusual errors,whenusingmetricconversionthe heightandweight valuesare correctlydisplayed,butwhenIuse imperial the heightandweightvaluessay“undefined”. The classificationafterwherethe Bmi value isdisplayedonlyworksforimperial conversionandnot metric. 5.1 Weather graph // Ex5-1: Weather Data Graph var canvas; canvas = openGraphics(); var xos = 50; var yos = 100; var yal = 400; var xal = 400; var ylabel = 0; var ylabelnum = 0; var xlabel = 0; var xlabelnum = 0; var monthwidth = 30; var month; var rainfall; var monthString = ("JFMAMJJUSOND"); canvas.drawLine(xos, yos, xos, yos + yal); canvas.drawLine(xos, yos + yal, xos + xal, yos + yal); for(ylabelnum = 0; ylabelnum <= 10; ylabelnum++ ) { canvas.drawString(ylabel, xos/2, (yos + yal) - ( 40 * ylabelnum )); ylabel = ylabel + 50;
  • 35. Jack Eastwood } for(month = 0; month <=11; month++ ) { rainfall= prompt( "Please enter rainfall." ); parseInt (rainfall, 10); canvas.setColor( "blue" ); canvas.fillRect(xos+(monthwidth*month), (yos + yal) - rainfall, monthwidth, rainfall); canvas.setColor( "black" ); canvas.drawRect(xos+(monthwidth*month), (yos + yal) - rainfall, monthwidth, rainfall); canvas.drawString( monthString.charAt(month), xos+ 10 +(monthwidth*month), (yos + yal)); } canvas.paint();
  • 36. Jack Eastwood // Ex5-1: Weather Data Graph var canvas; canvas = openGraphics(); var xos = 60; var yos = 100; var yal = 400;
  • 37. Jack Eastwood var xal = 500; var ylabel = 0; var ylabelnum = 0; var xlabel = 0; var xlabelnum = 0; var monthwidth = 30; var month; var rainfall; var monthString = ("JFMAMJJUSOND"); canvas.drawLine(xos, yos, xos, yos + yal); canvas.drawLine(xos, yos, xos + xal, yos); for(month = 0; month <= 11; month++ ) { rainfall= prompt( "Please enter rainfall." ); parseInt (rainfall, 10); canvas.setColor( "blue" ); canvas.fillRect(xos, yos+(monthwidth*month), rainfall, monthwidth); canvas.setColor( "black" ); canvas.drawString( monthString.charAt(month), xos/2, yos+(monthwidth*month)); } for(xlabelnum = 0; xlabelnum <=10; xlabelnum++ ) { canvas.drawString(xlabel, xos + (xlabelnum * 50), yos-15); xlabel = xlabel + 50; }
  • 38. Jack Eastwood canvas.paint(); //canvas.fillRect(xos+(monthwidth*month), (yos + yal) - rainfall, monthwidth, rainfall); Comments The charAt() function selectsasingle characterina stringthenprintsiton the canvas. For instance charAt(0) selectsthe 1st character withinastring.The variable monthStringhasall the initialsof all the monthslistedandwhenplottedonthe Xaxisinthe loop,charAt(month) selectseachinitialin orderthenplotsthemone at a time until the loopends.
  • 39. Jack Eastwood 5.2 Picture frame revisited var canvas = openGraphics(); var xPosition = 100; var yPosition = 50; var width = 200; var height = 150; var xPos; var xLeft; var xRight; var yPos; var yTop; var yBottom; var line; var imageName = "Honeysuckle.jpeg"; canvas.setColor ("Gold"); canvas.fillRect (75, 25, 250, 200); canvas.setColor ("Darkred"); canvas.setStroke (3); canvas.drawRect (73, 23, 250, 200); canvas.setStroke(1); canvas.setColor("Black"); xPos = 326; yTop = 22; yBottom = 226; for( line = 0; line<4; line++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos += 1; yTop -= 1;
  • 40. Jack Eastwood yBottom += 1; } xPos = 76; yTop = 26; yBottom = 222; for(line = 0; line<4; line++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos += 1; yTop += 1; yBottom -= 1; } xLeft = 80; xRight = 318; yPos = 29; for( line = 0; line<4; line++){ canvas.drawLine(xLeft, yPos, xRight, yPos); xLeft -= 1; xRight += 1; yPos -= 1; } xLeft = 73; xRight = 325; yPos = 226; for( line = 0; line<4; line++){ canvas.drawLine(xLeft, yPos, xRight, yPos);
  • 41. Jack Eastwood xLeft -= 1; xRight += 1; yPos += 1; } canvas.setColor("Red"); xPos = 322; yTop = 26; yBottom = 222; for(line = 0; line<4; line++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos -= 1; yTop += 1; yBottom -= 1; } xPos = 72; yTop = 22; yBottom = 226; for( line = 0; line<4; line++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos -= 1; yTop -= 1; yBottom += 1; } xLeft = 73; xRight = 325;
  • 42. Jack Eastwood yPos = 22; for( line = 0; line<4; line++){ canvas.drawLine(xLeft, yPos, xRight, yPos); xLeft -= 1; xRight += 1; yPos -= 1; } xLeft = 77; xRight = 321; yPos = 222; for( line = 0; line<4; line++){ canvas.drawLine(xLeft, yPos, xRight, yPos); xLeft += 1; xRight -= 1; yPos -= 1; } canvas.drawImage( imageName, xPosition, yPosition, width, height ); canvas.paint();
  • 43. Jack Eastwood Comments For loopsare usedto print4 linesoneachside of the image,andeverytime a line getsprintedthen the X and Y positionwill change by1 eachtime a line isprintedthatgivesthe line atriangularshape at the end.The X andY co-ordinate variableswill have tobe givendifferentvaluestobe setat a specificplace onall 4 sidesof the image otherwise the lineswill be printedfromthe previousXandY valuesgivenonthe previousloop. 5.3 Interest calculator html <html> <head> <title> Interest Calculator </title> </head> <body> <h1> Interest Calculator </h1> <p> This will calculate the interest on any amount of money from the interest rate and investment period. </p> <form action="server_program_name" method="get" id="money">
  • 44. Jack Eastwood <label for="money"> Amount of money: </label> <input type="number" name="money"></form> <form action="server_program_name" method="get" id="interest_rate"> <label for="interest_rate"> Interest rate(%): </label> <input type="number" name="money"></form> <form action="server_program_name" method="get" id="investment_period"> <label for="investment_period"> Investment period (years): </label> <input type="number" name="investment_period" min=”0”></form> <button value="submit" type="submit"> Calculate Interest </button> </body> </html>
  • 45. Jack Eastwood 5.4 Date validation form <html> <head> <title> Date Validation </title> </head> <body> <h1> Date validation </h1> <p> Page to validate the day, month and year</p> <form id="day" action="server_program_name" method="get"> <label for="day"> Day: </label> <input type="number" name="money" min="1" max="31"></form>
  • 46. Jack Eastwood <form id="month" action="server_program_name" method="get"> <label for="month"> Month: </label> <input type="number" name="month" min="1" max="12"></form> <form id="year" action="server_program_name" method="get"> <label for="month"> Year: </label> <input type="number" name="year" value="2000" ></form> <button value="submit" type="submit"> Validate date </button> </body> </html>
  • 47. Jack Eastwood Comments Inputbox’scan be givena minimumvalue toacceptbyput min=”value”asan element.A starting value can alsobe put inside aninputbytypingvalue=”value”. 5.5 Bmi calculator html <html> <head> <title> BMI Calculator </title> </head> <body> <h1> BMI calculator </h1> <p> Body Mass Index is derived from calculating an individuals weight and height. The calculation to work out an individuals BMI for a metric conversion is weight/height x height. </p> <p> There are classifications for different bmi values: </p> <p> 18.5 or under: Underweight </p> <p> 18.5 - 25: Ideal </p> <p> 25 - 30: Overweight </p> <p> 30 - 40: Obese </p> <p> 40 or over: Very Obese </p> <form id="weight" action="server_program_name" method="get"> <label for="weight"> Please enter your weight (KG): </label> <input type="number" name="weight" min="0"></form>
  • 48. Jack Eastwood <form id="height" action="server_program_name" method="get"> <label for="height"> Please enter your height (CM): </label> <input type="number" name="height" min="0"></form> <button value="submit" type="submit"> Calculate BMI </button> </body> </html>
  • 49. Jack Eastwood 6.1 Metric Conversion <html> <head> <title> Metric Conversions </title> <script type = "text/JavaScript"> function milesToKilometers() { var miles; miles = document.getElementById( "milesBox" ).value; miles = parseFloat( miles ); var kilometers = miles / 5 * 8; document.getElementById( "kilometersBox" ).value = kilometers.toFixed(2); } function KilometersToMiles() { var kilometers; kilometers = document.getElementById( "kilometersBox" ).value; kilometers = parseFloat( kilometers ); var miles = kilometers / 8 * 5; document.getElementById( "milesBox" ).value = miles.toFixed(2); } </script> </head> <body> <h1>
  • 50. Jack Eastwood Metric Conversions </h1> <h2> Miles : Kilometers </h2> <p> The conversion factor for miles and kilometers is based on the fact that 5 miles is the same distance as 8 kilometers. </p> Miles: <input type = "text" id = "milesBox" value = "" /> <br /> Kilometers: <input type = "text" id = "kilometersBox" value = "" /> <br /><br /> <input type = "button" id= "convert1" value = "Miles to Kilometers" onclick = "milesToKilometers();" /> <br /><br /> <input type = "button" id = "convert2" value = "Kilometers to Miles" onclick = "KilometersToMiles();" />
  • 52. Jack Eastwood The document.getElementByIdfunctionlooksforthe value togive toa specificvariablefromanhtml objectwiththatspecificidname.Inthiscase,the kilometresbox idwasgiventothe inputbox for the userto type how manykilometres.The buttonsare linkedtothe scriptwhentheyare givenan onclickelement,sothe milestokilometre buttonhasbeengivenonclick=”milesToKilometers();”that linkstothe milestokilometersfunction inthe script.Anyscriptsdeclared will have tobe declaredby statingthat itusestextand javascriptasits data type. 6.2 Interest Calculator Page <html> <head> <title> Interest Calculator </title> <script type = "text/Javascript"> function InterestCalculator() { var amount; amount = document.getElementById( "money").value; amount = parseFloat( amount ); var rate; rate = document.getElementById( "Interest_rate" ).value; rate = parseFloat( rate ); var years; years = document.getElementById( "Investment_period" ).value; years = parseFloat( years ); var interest; interest = (amount * rate * years)/100;
  • 53. Jack Eastwood alert( interest ); } </script> </head> <body> <h1> Interest Calculator </h1> <p> This will calculate the interest on any amount of money from the interest rate and investment period. </p> <form action="server_program_name" method="get"> <label for="money"> Amount of money: </label> <input type="number"id="money" name="money"></form> <form action="server_program_name" method="get"> <label for="interest_rate"> Interest rate(%): </label> <input type="number" id="Interest_rate" name="money"></form> <form action="server_program_name" method="get"> <label for="investment_period"> Investment period (years): </label> <input type="number" id="Investment_period" name="Investment money" min="0"> <br /><br /> <input type = "button" id = "CalculateInterest" value = "Calculate Interest" onclick = "InterestCalculator();" /> </form> </body>
  • 55. Jack Eastwood 6.3 Validating a date <html> <head> <title> Date Validation </title> <script type = "text/Javascript"> function DateValidation() { var day; day = document.getElementById( "day" ).value;
  • 56. Jack Eastwood day = parseFloat( day ); var month; month = document.getElementById( "month" ).value; month = parseFloat( month ); var year; year = document.getElementById( "year" ).value; year = parseFloat( year ); var today = new Date(); var tDay = today.getDate(); var tMonth = today.getMonth()+1; var tYear = today.getFullYear(); var birthday; birthday = new Date( year, month-1, day ); var age; age = today - birthday; var ageindays; ageindays = age/86400000; var ageinyears; ageinyears = ageindays/365; if (day >=1 && day<=31) {
  • 57. Jack Eastwood alert ("Day is valid"); } else { alert ("Day is invalid"); } if (month >=1 && month <=12) { alert("Month is valid"); } else { alert("Month is invalid"); } if (year >= 0 && year <= 2015) { alert("Year is valid"); } else { alert("Year is invalid"); } document.getElementById( "ageBox" ).value = ageinyears.toFixed(2); } </script> </head>
  • 58. Jack Eastwood <body> <h1> Date validation </h1> <p> Page to validate the user's birthday</p> <form action="server_program_name" method="get"> <label for="day"> Day: </label> <input type="number" name="money" id="day" min="1"></form> <form action="server_program_name" method="get"> <label for="month"> Month: </label> <input type="number" name="month" id="month" min="1"></form> <form action="server_program_name" method="get"> <label for="year"> Year: </label> <input type="number" name="year" id="year" ></form> <form action="server_program_name" method="get"> <label for="age"> Age: </label> <input type="number" id="ageBox" value=" " ></form> <br /><br /> <input type = "button" id = "ValidateDate" value = "Validate Date's" onclick = "DateValidation();" /> </body>
  • 60. Jack Eastwood 6.4 BMI calculator html <html> <head> <title> BMI Calculator </title> <script type ="text/Javascript"> function BMIcalculation() { var height;
  • 61. Jack Eastwood height = document.getElementById( "Height" ).value/100; height = parseFloat( height ); var weight; weight = document.getElementById( "Weight" ).value; weight = parseFloat( weight ); var calculation = weight/(height * height); var bmi = calculation.toFixed(2); var classification; if (bmi <= 18.4999){ classification = " Underweight"; } else if (bmi > 18.4999 && bmi <= 24.999){ classification = " Ideal"; } else if (bmi > 24.999 && bmi <= 29.999){ classification = " Overweight"; } else if (bmi > 29.999 && bmi <= 39.999){ classification = " Obese"; } else if (bmi > 39.999){ classification = " Very obese"; } alert( bmi + classification );
  • 62. Jack Eastwood document.getElementById( "BMIbox" ).value = bmi; } </script> </head> <body> <h1> BMI calculator </h1> <p> Body Mass Index is derived from calculating an individuals weight and height. The calculation to work out an individuals BMI for a metric conversion is weight/height x height. </p> <p> There are classifications for different bmi values: </p> <p> 18.5 or under: Underweight </p> <p> 18.5 - 25: Ideal </p> <p> 25 - 30: Overweight </p> <p> 30 - 40: Obese </p> <p> 40 or over: Very Obese </p> <form action="server_program_name" method="get"> <label for="weight"> Please enter your weight (KG): </label> <input id = "Weight" type="number" name="weight" min="0"></form> <form action="server_program_name" method="get"> <label for="height"> Please enter your height (CM): </label> <input id = "Height" type="number" name="height" min="0"></form> <button value="submit" type="submit" onclick = "BMIcalculation();">
  • 63. Jack Eastwood Calculate BMI </button> <form action = "server_program_name" method="get"> <label> BMI: </label> <input id="BMIbox" type="number"></form> </body> </html>