SlideShare a Scribd company logo
1 of 101
Jack Eastwood
Contents
Programming 1.1 Welcome...........................................................................................................1
Programming 1.2 graphical welcome............................................................................................. 6
Programming 1.3 Expressions...................................................................................................... 12
Programming 1.4 Shape area....................................................................................................... 14
Programming 1.5 interest rates................................................................................................... 17
Programming 1.6 Framing a picture............................................................................................. 18
Programming 2.1 getting input from the user............................................................................... 21
Programming 2.2 Numerical input............................................................................................... 24
Programming 2.3 personal details ............................................................................................... 28
2.4 String operations................................................................................................................... 32
2.5 date operations .................................................................................................................... 37
2.6 How old are you?.................................................................................................................. 42
2.7 Event timer........................................................................................................................... 45
3.1 Grading work........................................................................................................................ 47
3.2 Date validation...................................................................................................................... 53
3.3 Coloured event timer............................................................................................................ 59
3.4 Truth tables.......................................................................................................................... 61
Programming 1.1 Welcome
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:”
Jack Eastwood
 The “alert” variable displaysthe “message”variable onanotherwindow afterthe userhas
put an inputinthe promptwindow.
 Wheneversomethingisstoredasa prompt it’sstoredas a string.
 == meansequals,!=meansnotequal
 parseIntmeansparse integer,meaningthisonlypicksoutanynumerical valuesfromastring
of charactersidentifiedinavariable.
 Don’trelyon > or <, use rangeswithdefinedupperandlower limits.
 Don’tput a semi-colonatthe endof a for loop.
 Var ++ isthe same as var= var + 1
 && meansand, ||meansor
For Weathergraph:
// Ex5-1: Weather Data Graph
var canvas;
canvas = openGraphics();
//You may have to decide where this is best placed
var xOS = 10;
var yOS = 10;
var yAlen = 100;
var xAlen = 150;
//Y axis
canvas.drawLine(xOS, yOS, xOS, yOS+ yAlen);
//X axis
canvas.drawLine(xOS, yOS + yAlen, xOS + xAlen, yOS + yAlen);
canvas.paint();
Jack Eastwood
// Ex5-1: Weather Data Graph
var canvas;
canvas = openGraphics();
var xos = 50;
var yos = 50;
var yal = 200;
var xal = 400;
var ylabel = 0;
var ylabelnum = 0;
var xlabel = 0;
var xlabelnum = 0;
//Calculations for points on axis.
//A= xos, yos
//B= xos, yos + yal
//C= xos + xal, yos + yal
canvas.drawLine(xos, yos, xos, yos + yal);
canvas.drawLine(xos, yos + yal, xos + xal, yos + yal);
for(ylabelnum = 0; ylabelnum <= 5; ylabelnum++ )
{
canvas.drawString(ylabel, xos/2, (yos + yal) - ( 40 *
ylabelnum ));
ylabel = ylabel + 40;
}
//You may have to decide where this is best placed
canvas.paint();
Some commentsare actuallyputas commentswithinthe code andhighlightedindarkblue i.e.
//(comment)
Jack Eastwood
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
alert( message );
Jack Eastwood
var phrase1;
phrase1 = "Hello there ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var phrase3;
phrase3 = " I hope that you enjoy it.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2 + phrase3;
alert( message );
Jack Eastwood
Comments:
I changedthe phrase1 message to“hello there”,meaningthatthe window afterItypedmyname in
wouldchange itsfirstsentence promptto“hellothere Jack,”.Phrase3meansthatthere isa new
sentence of the nextwindow,inthiscase to“I hope youenjoyit”,butyouneedto addit to the
variable message.
Programming 1.2 graphical welcome
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.drawString( message, 20, 40 );
canvas.paint();
Jack Eastwood
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.drawString( message, 0, 0 );
canvas.paint();
Comments:
Jack Eastwood
By changingthe “canvas . drawString( message, (value),(value) )”,itwill change the position of the
outputon the graphical window,byincreasingthe valuesitwill change tobe loweredandmore to
the right.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.drawString( message, 20, 40);
canvas.drawString( message, 0, 0);
canvas.paint();
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
Jack Eastwood
var message;
message = phrase1 + name + phrase2;
canvas.setColor( "red" );
canvas.drawString( message, 20, 40);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
Comments:
 The “setColor”variable isAmerican.The setColorfunctionchangesanytextunderneath
where itisdeclaredtothe chosencolour. If the userwant to make a differentsentencein
anothercolourthentheywill have todeclare itagainjustabove the string.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", <br />welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.setColor( "red" );
Jack Eastwood
canvas.drawString( message, 20, 40);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
Comments:
 The <br /> puts the outputon the line underneathafterithasbeendeclared.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", <br />welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.setFont( "times", "20px", Font.BOLD );
canvas.setColor( "red" );
canvas.drawString( message, 20, 40);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
Jack Eastwood
Comments:
 “canvas.setFont( “times”,“20px”,Font.BOLD);” setsthe fontof the outputto timesnew
roman,make the fontsize to20 pixelsandsetsthe outputto bold.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", <br />welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.setFont( "comic sans ms", "40px", Font.BOLD_ITALIC );
canvas.setColor( "red" );
canvas.drawString( message, 40, 90);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
Jack Eastwood
Programming 1.3 Expressions
var a;
a = 0;
var b;
b = 0;
var c;
c = 0;
var result;
result = a + b + c;
alert( result );
var a;
a = 5;
var b;
b = 15;
var c;
c = 7;
var result;
Jack Eastwood
result = a + b - c;
alert( result );
var a;
a = 2;
var b;
b = 3;
var c;
c = 4;
var result;
result = a*b + b*c + a*c;
alert( result );
var a;
a = 5;
var b;
b = 4;
var result;
result = (a+b)*(a-b);
alert( result );
Jack Eastwood
Comments:
 Variablesare assigneddifferentnumericvalues.
 “var result”worksout the resultof the valuesgiventoa,band c
 * hasto be usedtomultiplyvaluesi.e.“a*b”is“a x b”
 “alert( result);”showsthe resultof calculatingthe variablesonawindow
Programming 1.4 Shape area
var canvas;
canvas = openGraphics();
var size;
size = 100;
var area;
area = size * size;
canvas.drawRect( 10, 10, size, size );
// drawRect, short for drawRectangle, requires four values:
// drawRect( x, y, width, height );
// x and y are the coordinates of the top left corner
// width and height are what they say!
// Setting width and height to the same value draws a square
canvas.drawString( "Square of size:", 10, 250 );
canvas.drawString( size, 120, 250 );
canvas.drawString( "Square of area:", 10, 290 );
canvas.drawString( area, 120, 290 );
canvas.paint();
Jack Eastwood
Comments
 The “can=openGraphics();”opensanew graphical window.
 “var size;size 100” setsthe base size of the rectangle to100.
 “var area; area size * size “; calculatesthe areaby calculatingsize x size.
 “canvas.drawRect( 10, 10 size,size );”the “( 10, 10)” setsthe co-ordinatesof where the
rectangle isbeingplacedinthe window,whilst“(size,size)”setsthe widthandheight
parameters.
var canvas;
canvas = openGraphics();
var size;
size = 200;
var radius;
radius = size/2;
var area;
area = radius*radius*Math.PI;
canvas.drawEllipse( 10, 10, size, size );
//there is a graphics function drawEllipse that requires the same
four values as drawRect but draws an oval shape within the bounds
of the rectangle specified by width and height.
Jack Eastwood
//The area of a circle is calculated using the formula: area =
radius2 X pi
//JavaScript already knows the value of pi, it is access using
Math.PI
//A circle of radius 10 has an area of 314.159
canvas.drawString( "Circle of size:", 10, 250 );
canvas.drawString( size, 120, 250 );
canvas.drawString( "Radius of circle:", 10, 290 );
canvas.drawString( radius, 120, 290 );
canvas.drawString( "Area of circle:", 10, 330 );
canvas.drawString( area, 120, 330 );
canvas.paint();
var canvas;
canvas = openGraphics();
var size;
size = 200;
var radius;
radius = size/2;
var area;
area = (radius*radius)*Math.PI;
canvas.setColor( "blue" );
canvas.fillEllipse( 10, 10, size, size );
//there is a graphics function drawEllipse that requires the same
four values as drawRect but draws an oval shape within the bounds
of the rectangle specified by width and height.
//The area of a circle is calculated using the formula: area =
radius2 X pi
//JavaScript already knows the value of pi, it is access using
Math.PI
//A circle of radius 10 has an area of 314.159
canvas.setColor( "black" );
canvas.drawString( "Circle of size:", 10, 250 );
canvas.drawString( size, 120, 250 );
canvas.drawString( "Radius of circle:", 10, 290 );
canvas.drawString( radius, 120, 290 );
canvas.drawString( "Area of circle:", 10, 330 );
canvas.drawString( area, 120, 330 );
canvas.paint();
Jack Eastwood
Comments
 Canvas.setColor( “blue”);changesthe colourof all objectsinthe window underneathto
blue. Byputtingcanvas.setColor("black");justabove the textthisfillsall objects
underneathtoblackagain.
Programming 1.5 interest rates
var amount;
amount = 250;
var rate;
rate = 10;
var years;
years = 1;
// declare, and initialise, identifiers for rate and time
var interest;
interest = (amount * rate * years)/100;
// input a formula to calculate the interest
//250 x 10=2500 x 1 = 2500/100=25
alert( interest );
Jack Eastwood
Programming 1.6 Framing a picture
var canvas;
canvas = openGraphics();
var imageName;
var xPosition;
var yPosition;
var width;
var height;
imageName = "Honeysuckle.jpeg";
xPosition = 80;
yPosition = 100;
//sets the co-ordinates for the position of the image within the
window
width = 200;
height = 150;
//sets the width and height parameters for the image
canvas.setColor ( "white" );
canvas.fillRect ( 30, 30, 300, 300 );
//sets background for the image coloured in white
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
canvas.paint();
Jack Eastwood
var canvas;
canvas = openGraphics();
var imageName;
var xPosition;
var yPosition;
var width;
var height;
imageName = "Honeysuckle.jpeg";
xPosition = 80;
yPosition = 100;
//sets the co-ordinates for the position of the image within the
window
width = 200;
height = 150;
//sets the width and height parameters for the image
canvas.setColor ( "white" );
canvas.fillRect ( 30, 30, 300, 300 );
//sets background for the image colored in white
canvas.setColor ( "black" );
canvas.drawRect ( 30, 30, 300, 300 );
//sets a border for the background colored black
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
Jack Eastwood
canvas.paint();
var canvas;
canvas = openGraphics();
var imageName;
var xPosition;
var yPosition;
var width;
var height;
imageName = "Honeysuckle.jpeg";
xPosition = 80;
yPosition = 100;
//sets the co-ordinates for the position of the image within the
window
width = 200;
height = 150;
//sets the width and height parameters for the image
canvas.setColor ( "white" );
canvas.fillRect ( 30, 30, 300, 300 );
//sets background for the image colored in white
canvas.setColor ( "black" );
canvas.setStroke( 6 );
//sets width for the width of the frame
canvas.drawRect ( 30, 30, 300, 300 );
//sets a border for the background colored black
Jack Eastwood
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
canvas.paint();
Programming 2.1 getting input from the user
// Ex2-1: Based on Ex1-2, Graphical Welcome
// All graphics programs require a canvas on which to draw
var canvas;
canvas = openGraphics();
// comment
var phrase1;
phrase1 = "Hello, ";
// First line that appears in the graphical environment after the
user has inputted their name
// comment
var phrase2;
phrase2 = ",<br />welcome to the Programming module.";
// the "<br>" will place this line underneath the "hello, (name)"
line
// comment
var name;
name = prompt( "Please enter your name:" );
// the first window that appears that prompts the user to input
their name
Jack Eastwood
// comment
var message;
message = phrase1 + name + phrase2;
// This will add phrase1 (hello), followed by (name) when the user
inputs their name at the prompt then phrase2 ("welcome to the
programming module") underneath phrase1+name in the graphical
enviroment
// comment
canvas.setFont( "comic sans ms", "15px", Font.BOLD );
// sets the font the graphical environment to comic sans, 15px in
size and sets it to bold letters
// comment
canvas.setColor( "darkred" );
//sets the colour of the output in the graphical environment to
dark red colour
// comment
canvas.drawString( message, 30, 50 );
// sets the co-ordinates of the output either more to the right or
further down (x, y)
// All graphics programs must instruct the browser to
// carry out the commands and render the output
canvas.paint();
Jack Eastwood
// Ex2-1: Based on Ex1-2, Graphical Welcome
// All graphics programs require a canvas on which to draw
var canvas;
Jack Eastwood
canvas = openGraphics();
// comment
var phrase1;
phrase1 = "Hello, ";
// comment
var phrase2;
phrase2 = ",<br />welcome to the Programming module.";
// comment
var name;
name = prompt( "Please enter your name:" );
var font;
font = prompt( "Enter font style:" );
var color;
color = prompt( "Enter font color:" );
var size;
size = prompt( "Enter font size:" );
// comment
var message;
message = phrase1 + name + phrase2;
// comment
canvas.setFont( font, size, Font.BOLD );
// comment
canvas.setColor( color );
// comment
canvas.drawString( message, 30, 50 );
// All graphics programs must instruct the browser to
// carry out the commands and render the output
canvas.paint();
Programming 2.2 Numerical input
// Ex2-2 : based on Ex1-4
var canvas;
canvas = openGraphics();
var width;
width = prompt( "Enter width of the square" );
width = parseInt(width, 10);
var height;
height = prompt( "Enter height of the square" );
height = parseInt(height, 10);
var size;
size = width*height;
canvas.drawRect( 10, 10, width, height );
// drawRect, short for drawRectangle, requires four values:
// drawRect( x, y, width, height );
Jack Eastwood
// x and y are the coordinates of the top left corner
// width and height are what they say!
// Setting width and height to the same value draws a square
canvas.drawRect( 10, 10, width, height );
canvas.drawString( "Area of rectangle:", 10, 250 );
canvas.drawString( size, 10, 270 );
canvas.drawString( "Width of rectangle:", 10, 290 );
canvas.drawString( width, 10, 310 );
canvas.drawString( "height of rectangle:", 10, 330 );
canvas.drawString( height, 10, 350 );
canvas.paint();
Jack Eastwood
// Ex2-2 : based on Ex1-4
var canvas;
canvas = openGraphics();
var x = parseInt(prompt( "Enter x co-ordinate for the circle:" ),
10);
var y = parseInt(prompt( "Enter y co-ordinate for the circle" ),
10);
var radius = parseInt(prompt( "Enter radius for the circle" ),
10);
var diameter;
diameter = radius*2;
var area;
area = (radius*radius)*Math.PI;
canvas.drawEllipse( x, y, diameter, diameter );
// drawEllipse, short for drawRectangle, requires four values:
// drawEllipse( x, y, diameter, diameter );
// x and y are the coordinates of the top left corner
// diameter and diameter are needed to draw the circle
// radius of a circle is half of the diameter
// to work out the radius of a circle it is radius x radius x pi
// Math.PI is short for pi (3.1415)
canvas.drawString( "Area of circle:", 10, 250 );
canvas.drawString( area, 10, 270 );
Jack Eastwood
canvas.drawString( "Radius of circle:", 10, 290 );
canvas.drawString( radius, 10, 310 );
canvas.drawString( "Diameter of circle:", 10, 330 );
canvas.drawString( diameter, 10, 350 );
canvas.paint();
Jack Eastwood
Programming 2.3 personal details
Comments
Forgotto start string witha “.
// Ex 2-3: Personal Details
var canvas;
canvas = openGraphics();
var name;
Jack Eastwood
name = prompt( "Please enter your name:" );
var mobile;
mobile = prompt( "Please enter your mobile number: ");
var email;
email = prompt( "Please enter your email address: ");
var dobDay;
dobDay = prompt( "Please enter your birth day: ");
dobDay = parseInt(dobDay, 10);
var dobMonth;
dobMonth = prompt( "Please enter your birth month: ");
dobMonth = parseInt(dobMonth, 10);
var dobYear;
dobYear = prompt( "Please enter your birth year: ");
dobYear = parseInt(dobYear, 10);
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
canvas.setColor( "purple" );
canvas.fillRect(5, 5, 500 ,250);
canvas.setFont( "Arial" , "20px" );
canvas.setColor( "orange" );
canvas.setStroke( 5 );
canvas.drawRect(5, 5, 500, 250);
canvas.setColor( "pink" );
canvas.drawString( "Name: " + name, 10, 10);
canvas.drawString( "Mobile: " + mobile, 10, 50);
canvas.drawString( "Email: " + email, 10, 90);
canvas.drawString( "Date of birth: " + dobDay + "/" + dobMonth +
"/" + dobYear, 10, 130);
canvas.drawString( "Age: " + "19", 10, 170);
canvas.drawString( "Date: " + dd + "/" + mm + "/"+ yyyy, 10, 210);
canvas.paint();
Jack Eastwood
Jack Eastwood
Jack Eastwood
2.4 String operations
canvas.drawString( "Hello".bold());
canvas.drawString( "My name is
Jack Eastwood", 0, 20 );
canvas.drawString( " Hello" .link());
canvas.drawString( "My name is
Jack Eastwood", 0, 20 );
Jack Eastwood
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
canvas.drawString( "Hello".fixed());
canvas.drawString( "My name is
Jack Eastwood", 0, 20 );
canvas.drawString( "Hello".strike());
canvas.drawString( "My name is Jack
Eastwood", 0, 20 );
Jack Eastwood
var name = "Jack";
var nameLength;
nameLength = name.length;
canvas.drawString( "Number of characters in my name: ");
canvas.drawString( nameLength, 250, 0);
//aString.length calculates the number of characters assigned to a
variable
canvas.paint();
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
var name = "Jack";
var nameCharAt;
nameCharAt = name.charAt(3);
canvas.drawString( " 4th character of my name: ");
canvas.drawString( nameCharAt, 200, 0);
//aString.charAt() finds the specified character in a variable
i.e. charAt(0) finds the first character in a variable, in my case
it will be J
canvas.paint();
Jack Eastwood
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
var name = "Jack";
var nameCharAt;
nameCharAt = name.charAt(0) + name.substr(1);
canvas.drawString( " Separate 1st letter of my name from the rest: ");
canvas.drawString( name.charAt(0), 0, 30);
canvas.drawString( name.substr(1), 30, 30);
//aString.charAt() finds the specified character in a variable i.e.
charAt(0) finds the first character in a variable, in my case it will
be J
canvas.paint();
Jack Eastwood
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
var name = "jack";
var nameCharAt;
nameCharAt = name.charAt + name.substr;
canvas.drawString( " Separate 1st letter of my name from the rest:
");
canvas.drawString( name.charAt(0).toUpperCase(), 0, 30);
canvas.drawString( name.substr(1).toLowerCase(), 30, 30);
// .toUpperCase will select the 1st letter chosen from name.charAt
and will put it into upper case, whilst .toLowerCase will select
the other characters and put them into lower case.
canvas.paint();
Jack Eastwood
2.5 date operations
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date();
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getYear();
canvas.drawString( "Year is: " + value , 10, 60 );
canvas.paint();
Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date();
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getFullYear();
canvas.drawString( "Year is: " + value , 10, 60 );
value = aDate.getMonth();
canvas.drawString( "Month is: " + value, 10, 80 );
value = aDate.getDay();
canvas.drawString( "Day is: " + value, 10, 100 );
value = aDate.getDate();
canvas.drawString( "Date is: " + value, 10, 120 );
canvas.paint();
Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date( 1995, 6, 6);
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getFullYear();
canvas.drawString( "Year is: " + value , 10, 60 );
value = aDate.getMonth();
canvas.drawString( "Month is: " + value, 10, 80 );
value = aDate.getDay();
canvas.drawString( "Day is: " + value, 10, 100 );
value = aDate.getDate();
canvas.drawString( "Date is: " + value, 10, 120 );
canvas.paint();
Ranges from 0-11 , 0=
January, 11= December
Day 1 = Monday, Day 7 = Sunday
Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date( 1995, 11, 25 );
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getFullYear();
canvas.drawString( "Year is: " + value , 10, 60 );
value = aDate.getMonth();
canvas.drawString( "Month is: " + value, 10, 80 );
value = aDate.getDay();
canvas.drawString( "Day is: " + value, 10, 100 );
value = aDate.getDate();
canvas.drawString( "Date is: " + value, 10, 120 );
canvas.paint();
I was bornon a Thursday
Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
Christmasin1995 was ona Monday
Put : insteadof ; at the endand only
supposedtoputa numberfrom0-9
Jack Eastwood
aDate = new Date();
value = aDate.setDate(29);
canvas.drawString( "Date is: " + value, 10, 20 );
value = aDate.setMonth(11);
canvas.drawString( "Month is: " + value, 10, 40 );
value = aDate.setFullYear(1980);
canvas.drawString( "Year is: " + value, 10, 60 );
canvas.paint();
The toLocaleStringcovertsthe newDate functioninto adate format,the getDate,getDay,getMonth
and getFullYearall retrievethe date fromthe computer’sclock.The setDate functionsallow the user
to inputthe day,monthand year,howeverthe outputis displayedinminutes,sothiswill needtobe
dividedtogetthe properdate,monthand year.
2.6 How old are you?
Jack Eastwood
// Ex2-6
var canvas;
canvas = openGraphics();
var day;
var month;
var year;
var birthday;
// get user's birthday details
// create two dates
day = parseInt(prompt( "Please enter your birthday: "), 10);
month = parseInt(prompt( "Please enter your birth month: "), 10);
year = parseInt(prompt( "Please enter your birth year: "), 10);
var aDate = new Date(year, month-1, day);
canvas.drawString ( "Date of birth: " + aDate, 10, 20);
var today = new Date();
canvas.drawString ( "Today's date: " + today, 10, 100);
var age = today - aDate;
canvas.drawString ("Your age: " + age, 10, 140);
var ageindays = age/86400000;
canvas.drawString( "Your age in days: " +ageindays.toFixed(0), 10,
180);
var ageinyears = ageindays/365;
canvas.drawString( "Your age in years: " + ageinyears.toFixed(0),
10, 220);
Identifierisdate1,notdate
Jack Eastwood
// calculate age in mS and convert to days and then years
canvas.paint();
Jack Eastwood
Comments
Thisasks the userto inputtheirbirthdate,monthand yearand formatit intoa date usingthe new
Date functionandplacingthe variableswithinthe (). Because Januaryisassignedto0 and December
is11, month-1is usedtomake the months1-12 insteadof 0-11.
2.7 Event timer
// Ex2-7: Event Timer
// This program calculates the difference in time
// between two events: the user clearing alerts
// The difference is a measure of the time it
// Takes to make two keypresses or mouse clicks
var canvas;
canvas = openGraphics();
// Put a Title on the output screen
canvas.setColor( "Yellow" );
canvas.setFont( "Comic sans ms", "30px", Font.UNDERLINE );
canvas.fillRect( 10, 10, 300, 200 );
canvas.setColor( "Red" );
canvas.drawString( "Timer",150,0 );
// uncomment the next line to see the title
// canvas.paint();
// create a Date object and store the current time
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;
Jack Eastwood
canvas.setFont( "Comic sans ms", "20px" );
canvas.drawString( " Difference in time: " + difference + "ms",
10, 60);
// calculate the difference between the two times
// output a suitable message to the user
canvas.paint();
Comments
Jack Eastwood
Thisworksby pressingthe firstalertwindow will collectthe exactcurrenttime all the wayto
millisecondsandthe nextalertwindowwill alsocollectthe exactcurrenttime. Thisisthen
subtractedbythe variable calleddifference whichminus’sthe seconddate (“stoptimeralert”)
againstthe firstdate (“start timeralert”).
3.1 Grading work
// Ex: 3-1 Grading Work
var mark;
var grade;
grade = "Not Yet Graded";
mark = prompt( "Please input the mark(%)" );
mark = parseInt( mark, 10 ); // see comment
if( mark > 69 )
{
grade = "First Class";
}
else if ( mark > 59 )
{
grade = "Upper Class (2.1)";
}
else if (mark > 49 )
{
grade = "Lower Class (2.2)";
}
else if (mark > 39 )
{
grade = "Third Class";
}
alert( "Mark: " + mark + "% - Grade: " + grade );
Jack Eastwood
Forgotto close stringwith“
Jack Eastwood
Jack Eastwood
// Ex: 3-1 Grading Work
var mark;
var grade;
grade = "Not Yet Graded";
mark = prompt( "Please input the mark(%)" );
mark = parseInt( mark, 10 ); // see comment
if ( mark >= 0 && mark <=100 )
{
if( mark > 69 )
{
grade = "First Class";
}
else if ( mark > 59 && mark < 70)
{
grade = "Upper Class
(2.1)";
}
else if (mark > 49 && mark < 60)
{
grade = "Lower Class
(2.2)";
}
else if (mark > 39 && mark < 50)
{
grade = "Third Class";
}
else if (mark < 40 )
{
grade = "Fail";
Jack Eastwood
}
}
else
{
alert( "Invalid mark, grade needs to be between 0-100" );
}
alert( "Mark: " + mark + "% - Grade: " + grade );
Jack Eastwood
Jack Eastwood
Comments
Thisprogram promptsthe userto input the grade percentage whichgetsparsedwithparseInt(),
thenthe IF statementssetsboundariesforthe inputi.e.if markisabove 70 thenthat’s a firstand if
the mark is between 50-59thena 2:2 isawarded.If a negative numberora numberover100 is
entered,thenthe program createsanalertthat the inputtednumberorcharacter isinvalid.
3.2 Date validation
Jack Eastwood
// Ex 2-3: Personal Details
var canvas;
canvas = openGraphics();
var name;
name = prompt( "Please enter your name:" );
Forgotto endwith} afterIF
statement
Forgotto put variable name after
&&
Jack Eastwood
var mobile;
mobile = prompt( "Please enter your mobile number: ");
var email;
email = prompt( "Please enter your email address: ");
var dobDay;
dobDay = prompt( "Please enter your birth day: ");
dobDay = parseInt(dobDay, 10);
var dobMonth;
dobMonth = prompt( "Please enter your birth month: ");
dobMonth = parseInt(dobMonth, 10);
var dobYear;
dobYear = prompt( "Please enter your birth year: ");
dobYear = parseInt(dobYear, 10);
var birthday;
birthday = new Date(dobYear, dobMonth-1, dobDay );
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var age;
age = today - birthday;
var ageindays;
ageindays = age/86400000;
var ageinyears;
ageinyears = ageindays/365;
canvas.setColor( "purple" );
canvas.fillRect(5, 5, 700 ,250);
canvas.setFont( "Arial" , "20px" );
canvas.setColor( "orange" );
canvas.setStroke( 5 );
canvas.drawRect(5, 5, 700, 250);
canvas.setColor( "pink" );
canvas.drawString( "Name: " + name, 10, 10);
canvas.drawString( "Mobile: " + mobile, 10, 50);
canvas.drawString( "Email: " + email, 10, 90);
canvas.drawString( "Date of birth: " + birthday, 10, 130);
canvas.drawString( "Age: " + ageinyears.toFixed(0), 10, 170);
canvas.drawString( "Date: " + today, 10, 210);
if (ageinyears.toFixed(0) == 20)
{
alert("Age is correct");
}
else if (ageinyears.toFixed(0) != 20)
{
alert( "Age is incorrect");
}
if (dobDay >=1 && dobDay<=31)
{
alert ("Day is valid");
Jack Eastwood
}
else
{
alert ("Day is invalid");
}
if (dobMonth >=1 && dobMonth <=12)
{
alert("Month is valid");
}
else
{
alert("Month is invalid");
}
if (dobYear > 0 && dobYear < 2015)
{
alert("Year is valid");
}
else
{
alert("Year is invalid");
}
canvas.paint();
Valid entries
Jack Eastwood
Invalid entries
Jack Eastwood
Jack Eastwood
3.3 Coloured event timer
// Ex2-7: Event Timer
// This program calculates the difference in time
// between two events: the user clearing alerts
// The difference is a measure of the time it
// Takes to make two keypresses or mouse clicks
var canvas;
canvas = openGraphics();
// Put a Title on the output screen
canvas.setFont( "Comic sans ms", "30px", Font.UNDERLINE );
canvas.drawString( "Timer",150,0 );
// uncomment the next line to see the title
// canvas.paint();
// create a Date object and store the current time
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;
canvas.setFont( "Comic sans ms", "20px" );
canvas.drawString( "Difference in time: ", 10, 60 );
if (difference <= 150)
{
canvas.setColor( "green" );
canvas.drawString( difference + "ms", 200, 60);
}
else if ( difference >=151 && difference <= 350 )
{
canvas.setColor( "orange" );
canvas.drawString( difference + "ms", 200, 60);
}
else if (difference > 350 )
{
canvas.setColor( "red" );
canvas.drawString( difference + "ms", 200, 60);
}
// calculate the difference between the two times
// output a suitable message to the user
canvas.paint();
Jack Eastwood
Jack Eastwood
Comments
I separatedthe “difference intime:”fromthe resultdue tothe “difference intime:”alsobeing
coloured,sothiswouldhave beenputbefore the if statements.
3.4 Truth tables
AND Table
// Ex: 3-4
var canvas;
canvas = openGraphics();
Jack Eastwood
var operation;
operation = "AND";
var heading;
heading = "Truth Table for the " + operation + " operation.";
canvas.drawStringRect( heading.big(), 0, 5, 400, "center" );
var message;
message = "An entry in the table is the result of the operation ";
message = message + "A " + operation + " B";
canvas.drawStringRect( message, 0, 30, 400, "center" );
message = "i.e. result = a && b;";
canvas.drawStringRect( message, 0, 65, 400, "center" );
var x; // left edge of table
var y; // top of table
x = 50;
y = 100;
// draw table outline
canvas.setStroke( 3 );
canvas.drawLine( x, y, x+300, y );
canvas.drawLine( x, y, x, y+150 );
canvas.drawLine( x, y+50, x+300, y+50 );
canvas.drawLine( x, y+150, x+300, y+150 );
canvas.drawLine( x+100, y, x+100, y+150 );
canvas.drawLine( x+300, y, x+300, y+150 );
canvas.setStroke( 1 );
canvas.drawLine( x, y+100, x+300, y+100 );
canvas.drawLine( x+200, y, x+200, y+150 );
canvas.setStroke( Stroke.DOTTED );
canvas.drawLine( x, y, x + 100, y + 50 );
// Put in column and row labels
canvas.setFont( "lucida console", "20px", Font.BOLD );
canvas.setColor( "darkred" );
canvas.drawStringRect( "A", x+15, y+20, 50, "left" );
canvas.drawStringRect( "B", x+5, y+5, 80, "right" );
canvas.drawStringRect( "true", x, y+50+15, 100, "center" );
canvas.drawStringRect( "false", x, y+100+15, 100, "center" );
canvas.drawStringRect( "true", x+100, y+15, 100, "center" );
canvas.drawStringRect( "false", x+200, y+15, 100, "center" );
// Now to put the results in the table
var result;
var a;
var b;
canvas.setColor( "Darkblue" );
a = true;
b = true;
Jack Eastwood
result = a && b;
canvas.drawStringRect( result, x+100, y+50+15, 100, "center" );
a = true;
b = false;
result = a && b;
canvas.drawStringRect( result, x+200, y+50+15, 100, "center" );
a = false;
b = true;
result = a && b;
canvas.drawStringRect( result, x+100, y+100+15, 100, "center" );
a = false;
b = false;
result = a && b;
canvas.drawStringRect( result, x+200, y+100+15, 100, "center" );
canvas.paint();
OR Table
// Ex: 3-4
var canvas;
canvas = openGraphics();
var operation;
operation = "OR";
var heading;
heading = "Truth Table for the " + operation + " operation.";
canvas.drawStringRect( heading.big(), 0, 5, 400, "center" );
Jack Eastwood
var message;
message = "An entry in the table is the result of the operation ";
message = message + "A " + operation + " B";
canvas.drawStringRect( message, 0, 30, 400, "center" );
message = "i.e. result = a || b;";
canvas.drawStringRect( message, 0, 65, 400, "center" );
var x; // left edge of table
var y; // top of table
x = 50;
y = 100;
// draw table outline
canvas.setStroke( 3 );
canvas.drawLine( x, y, x+300, y );
canvas.drawLine( x, y, x, y+150 );
canvas.drawLine( x, y+50, x+300, y+50 );
canvas.drawLine( x, y+150, x+300, y+150 );
canvas.drawLine( x+100, y, x+100, y+150 );
canvas.drawLine( x+300, y, x+300, y+150 );
canvas.setStroke( 1 );
canvas.drawLine( x, y+100, x+300, y+100 );
canvas.drawLine( x+200, y, x+200, y+150 );
canvas.setStroke( Stroke.DOTTED );
canvas.drawLine( x, y, x + 100, y + 50 );
// Put in column and row labels
canvas.setFont( "lucida console", "20px", Font.BOLD );
canvas.setColor( "darkred" );
canvas.drawStringRect( "A", x+15, y+20, 50, "left" );
canvas.drawStringRect( "B", x+5, y+5, 80, "right" );
canvas.drawStringRect( "true", x, y+50+15, 100, "center" );
canvas.drawStringRect( "false", x, y+100+15, 100, "center" );
canvas.drawStringRect( "true", x+100, y+15, 100, "center" );
canvas.drawStringRect( "false", x+200, y+15, 100, "center" );
// Now to put the results in the table
var result;
var a;
var b;
canvas.setColor( "Darkblue" );
a = true;
b = true;
result = a || b;
canvas.drawStringRect( result, x+100, y+50+15, 100, "center" );
a = true;
b = false;
result = a || b;
canvas.drawStringRect( result, x+200, y+50+15, 100, "center" );
Jack Eastwood
a = false;
b = true;
result = a || b;
canvas.drawStringRect( result, x+100, y+100+15, 100, "center" );
a = false;
b = false;
result = a || b;
canvas.drawStringRect( result, x+200, y+100+15, 100, "center" );
canvas.paint();
Comments
The difference betweenANDandORisthat ANDoperationsare definedby&&between2variables
whilst||isusedto define OR.
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;
y = 0;
size = 500;
Jack Eastwood
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();
// Ex3-5 : Graphics Experiments
// Part of demo program:
var canvas;
canvas = openGraphics();
var x;
var y;
var width;
Jack Eastwood
var height;
x = 0;
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
3.6 Graphical Event timer
// Ex 3-6 : Graphical Event Timer
Jack Eastwood
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) {
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();
}
Jack Eastwood
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;
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;
}
Jack Eastwood
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
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";
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();
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)
{
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 ......
Jack Eastwood
canvas.paint();
Jack Eastwood
// Ex4-2: Guess the Number
var canvas;
canvas = openGraphics();
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) {
message = guess + " Correct";
Jack Eastwood
guessed = true;
}
canvas.drawString( message, x, y);
y = y + 20;
canvas.paint();
}
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 );
Jack Eastwood
//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 );
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 );
canvas.paint();
// Ex4-4: BMI Calculator
var canvas;
canvas = openGraphics();
Jack Eastwood
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";
}
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
Jack Eastwood
// Ex4-4: BMI Calculator
var canvas;
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 = 185;
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;
while( !reset ){
canvas.setFont( "Comic Sans MS", "20px", Font.BOLD
);
canvas.drawString( "BMI calculator bitch's", 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 height = parseFloat(prompt("Please enter your
height in cm: ") ,10)/100;
var weight = parseFloat(prompt("Please enter your
weight in kg: ") ,10);
Jack Eastwood
var calculation = weight/(height * height);
var bmi = calculation.toFixed(2);
var classification;
canvas.setFont( "Comic Sans MS", "14px" );
canvas.setColor( "DarkBlue" );
canvas.drawString( "Height " + ":" + height + "
m", 120, 100 );
canvas.drawString( "Weight " + ":" + weight + "
kg", 0, 100 );
if (bmi <= 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 (bmi > 18.4999 && bmi <= 24.999){
canvas.setColor( "black");
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 (bmi > 24.999 && bmi <= 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 (bmi > 29.999 && bmi <= 39.999){
canvas.setColor( "black" );
canvas.setStroke(3);
classification = " Obese";
Jack Eastwood
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 (bmi > 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( bmi + ":" + classification, 0, 150 );
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);
//canvas.drawEllipse(300, 290, 20, 20);
//canvas.fillEllipse(295, 310, 30, 70);
//canvas.drawLine( RArmPos, ArmYPos, RArmPos + ArmLength, ArmYPos
);
//canvas.drawLine( LArmPos, ArmYPos, LArmPos + ArmLength, ArmYPos
);
//canvas.drawLine( LLegPos, LegYPos, LLegPos, LegYPos + LegLength
);
//canvas.drawLine( RLegPos, LegYPos, RLegPos, LegYPos + LegLength
);
//canvas.drawEllipse(xos + 3, 290, 20, 20);
//canvas.fillEllipse(xos, 310, 30, 70);
Jack Eastwood
//canvas.drawLine( xos + 50, ArmYPos, xos + ArmLength, ArmYPos );
//canvas.drawLine( xos - 50, ArmYPos, xos + ArmLength, ArmYPos );
//canvas.drawLine( xos + 5, LegYPos, xos + 5, LegYPos + LegLength
);
//canvas.drawLine( xos + 20, LegYPos, xos + 20, LegYPos +
LegLength );
for( labelnum = 0; labelnum <= 9; labelnum++ )
{
canvas.drawString( label, xos + (labelnum * 60),
(yos + lineHeight));
label = label + 5;
}
canvas.paint();
reset = prompt( "Would you like to start over?
(Y/N)" );
if ( reset == "y"){
reset = false;
canvas.clear();
}
else {
reset = true;
}
}
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");
//Calculations for points on axis.
//A= xos, yos
//B= xos, yos + yal
//C= xos + xal, yos + yal
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) - rainfall);
}
//You may have to decide where this is best placed
canvas.paint();
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 i;
var imageName = "Honeysuckle.jpeg";
canvas.setColor ("Beige");
canvas.fillRect (75, 25, 250, 200);
canvas.setColor ("Firebrick");
canvas.setStroke (3);
canvas.drawRect (73, 23, 250, 200);
canvas.setStroke(1);
canvas.setColor("Black");
xPos = 326;
yTop = 22;
yBottom = 226;
for( i = 0; i<2; i++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos += 1;
yTop -= 1;
yBottom += 1;
}
xPos = 76;
yTop = 26;
yBottom = 222;
for(i = 0; i<4; i++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos += 1;
yTop += 1;
yBottom -= 1;
}
xLeft = 80;
xRight = 318;
yPos = 29;
Jack Eastwood
for( i = 0; i<4; i++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
xLeft -= 1;
xRight += 1;
yPos -= 1;
}
xLeft = 73;
xRight = 325;
yPos = 226;
for( i = 0; i<2; i++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
xLeft -= 1;
xRight += 1;
yPos += 1;
}
canvas.setColor("Red");
xPos = 322;
yTop = 26;
yBottom = 222;
for(i = 0; i<4; i++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos -= 1;
yTop += 1;
yBottom -= 1;
}
xPos = 72;
yTop = 22;
yBottom = 226;
for( i = 0; i<2; i++){
canvas.drawLine(xPos, yTop, xPos, yBottom);
xPos -= 1;
yTop -= 1;
yBottom += 1;
}
xLeft = 73;
xRight = 325;
yPos = 22;
for( i = 0; i<2; i++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
xLeft -= 1;
xRight += 1;
yPos -= 1;
}
xLeft = 77;
xRight = 321;
yPos = 222;
for( i = 0; i<4; i++){
canvas.drawLine(xLeft, yPos, xRight, yPos);
xLeft += 1;
xRight -= 1;
yPos -= 1;
}
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
canvas.paint();
5.3 Interest calculator html
<html>
<head>
Jack Eastwood
<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">
<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>
5.4 Date validation form
Jack Eastwood
<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>
<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
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>
<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 );
Jack Eastwood
var miles = kilometers / 8 * 5;
document.getElementById( "milesBox" ).value
= miles.toFixed(2);
}
</script>
</head>
<body>
<h1>
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();" />
</body>
</html>
Jack Eastwood
6.2 Interest Calculator Page
<html>
<head>
<title>
Interest Calculator
</title>
<script type = "text/Javascript">
Jack Eastwood
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 );
// declare, and initialise, identifiers for rate and time
var interest;
interest = (amount * rate * years)/100;
// input a formula to calculate the interest
//250 x 10=2500 x 1 = 2500/100=25
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>
</html>
Jack Eastwood
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;
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();
Jack Eastwood
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)
{
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>
<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>
Jack Eastwood
<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>
</html>
Jack Eastwood
6.4 BMI calculatorhtml
<html>
<head>
<title>
BMI Calculator
Jack Eastwood
</title>
<script type ="text/Javascript">
function BMIcalculation()
{
var height;
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 );
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>
Jack Eastwood
<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();">
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

Similar to program logbook

building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
Drawing on canvas
Drawing on canvasDrawing on canvas
Drawing on canvassuitzero
 
Introduction to Coding
Introduction to CodingIntroduction to Coding
Introduction to CodingFabio506452
 
HTML5って必要?
HTML5って必要?HTML5って必要?
HTML5って必要?GCS2013
 
Computer graphics lab assignment
Computer graphics lab assignmentComputer graphics lab assignment
Computer graphics lab assignmentAbdullah Al Shiam
 
JavaOne 2009 - 2d Vector Graphics in the browser with Canvas and SVG
JavaOne 2009 -  2d Vector Graphics in the browser with Canvas and SVGJavaOne 2009 -  2d Vector Graphics in the browser with Canvas and SVG
JavaOne 2009 - 2d Vector Graphics in the browser with Canvas and SVGPatrick Chanezon
 
2Bytesprog2 course_2014_c9_graph
2Bytesprog2 course_2014_c9_graph2Bytesprog2 course_2014_c9_graph
2Bytesprog2 course_2014_c9_graphkinan keshkeh
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
bfd23fd7-0d89-45c0-8b82-c991b30ed375.pdf
bfd23fd7-0d89-45c0-8b82-c991b30ed375.pdfbfd23fd7-0d89-45c0-8b82-c991b30ed375.pdf
bfd23fd7-0d89-45c0-8b82-c991b30ed375.pdfshehabhamad_90
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
Gotta code them all, a Pokémon and HTML5 love story!
Gotta code them all, a Pokémon and HTML5 love story!Gotta code them all, a Pokémon and HTML5 love story!
Gotta code them all, a Pokémon and HTML5 love story!Home
 
I Can't Believe It's Not Flash
I Can't Believe It's Not FlashI Can't Believe It's Not Flash
I Can't Believe It's Not FlashThomas Fuchs
 

Similar to program logbook (20)

building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Drawing on canvas
Drawing on canvasDrawing on canvas
Drawing on canvas
 
Introduction to Coding
Introduction to CodingIntroduction to Coding
Introduction to Coding
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
 
HTML5って必要?
HTML5って必要?HTML5って必要?
HTML5って必要?
 
Computer graphics lab assignment
Computer graphics lab assignmentComputer graphics lab assignment
Computer graphics lab assignment
 
Canvas al ajillo
Canvas al ajilloCanvas al ajillo
Canvas al ajillo
 
JavaOne 2009 - 2d Vector Graphics in the browser with Canvas and SVG
JavaOne 2009 -  2d Vector Graphics in the browser with Canvas and SVGJavaOne 2009 -  2d Vector Graphics in the browser with Canvas and SVG
JavaOne 2009 - 2d Vector Graphics in the browser with Canvas and SVG
 
Introduction to graphics programming in c
Introduction to graphics programming in cIntroduction to graphics programming in c
Introduction to graphics programming in c
 
2Bytesprog2 course_2014_c9_graph
2Bytesprog2 course_2014_c9_graph2Bytesprog2 course_2014_c9_graph
2Bytesprog2 course_2014_c9_graph
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
bfd23fd7-0d89-45c0-8b82-c991b30ed375.pdf
bfd23fd7-0d89-45c0-8b82-c991b30ed375.pdfbfd23fd7-0d89-45c0-8b82-c991b30ed375.pdf
bfd23fd7-0d89-45c0-8b82-c991b30ed375.pdf
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Gotta code them all, a Pokémon and HTML5 love story!
Gotta code them all, a Pokémon and HTML5 love story!Gotta code them all, a Pokémon and HTML5 love story!
Gotta code them all, a Pokémon and HTML5 love story!
 
Clock For My
Clock For MyClock For My
Clock For My
 
Groovy
GroovyGroovy
Groovy
 
I Can't Believe It's Not Flash
I Can't Believe It's Not FlashI Can't Believe It's Not Flash
I Can't Believe It's Not Flash
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 

program logbook

  • 1. Jack Eastwood Contents Programming 1.1 Welcome...........................................................................................................1 Programming 1.2 graphical welcome............................................................................................. 6 Programming 1.3 Expressions...................................................................................................... 12 Programming 1.4 Shape area....................................................................................................... 14 Programming 1.5 interest rates................................................................................................... 17 Programming 1.6 Framing a picture............................................................................................. 18 Programming 2.1 getting input from the user............................................................................... 21 Programming 2.2 Numerical input............................................................................................... 24 Programming 2.3 personal details ............................................................................................... 28 2.4 String operations................................................................................................................... 32 2.5 date operations .................................................................................................................... 37 2.6 How old are you?.................................................................................................................. 42 2.7 Event timer........................................................................................................................... 45 3.1 Grading work........................................................................................................................ 47 3.2 Date validation...................................................................................................................... 53 3.3 Coloured event timer............................................................................................................ 59 3.4 Truth tables.......................................................................................................................... 61 Programming 1.1 Welcome 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:”
  • 2. Jack Eastwood  The “alert” variable displaysthe “message”variable onanotherwindow afterthe userhas put an inputinthe promptwindow.  Wheneversomethingisstoredasa prompt it’sstoredas a string.  == meansequals,!=meansnotequal  parseIntmeansparse integer,meaningthisonlypicksoutanynumerical valuesfromastring of charactersidentifiedinavariable.  Don’trelyon > or <, use rangeswithdefinedupperandlower limits.  Don’tput a semi-colonatthe endof a for loop.  Var ++ isthe same as var= var + 1  && meansand, ||meansor For Weathergraph: // Ex5-1: Weather Data Graph var canvas; canvas = openGraphics(); //You may have to decide where this is best placed var xOS = 10; var yOS = 10; var yAlen = 100; var xAlen = 150; //Y axis canvas.drawLine(xOS, yOS, xOS, yOS+ yAlen); //X axis canvas.drawLine(xOS, yOS + yAlen, xOS + xAlen, yOS + yAlen); canvas.paint();
  • 3. Jack Eastwood // Ex5-1: Weather Data Graph var canvas; canvas = openGraphics(); var xos = 50; var yos = 50; var yal = 200; var xal = 400; var ylabel = 0; var ylabelnum = 0; var xlabel = 0; var xlabelnum = 0; //Calculations for points on axis. //A= xos, yos //B= xos, yos + yal //C= xos + xal, yos + yal canvas.drawLine(xos, yos, xos, yos + yal); canvas.drawLine(xos, yos + yal, xos + xal, yos + yal); for(ylabelnum = 0; ylabelnum <= 5; ylabelnum++ ) { canvas.drawString(ylabel, xos/2, (yos + yal) - ( 40 * ylabelnum )); ylabel = ylabel + 40; } //You may have to decide where this is best placed canvas.paint(); Some commentsare actuallyputas commentswithinthe code andhighlightedindarkblue i.e. //(comment)
  • 4. Jack Eastwood var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", welcome to the Programming module."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2; alert( message );
  • 5. Jack Eastwood var phrase1; phrase1 = "Hello there "; var phrase2; phrase2 = ", welcome to the Programming module."; var phrase3; phrase3 = " I hope that you enjoy it."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2 + phrase3; alert( message );
  • 6. Jack Eastwood Comments: I changedthe phrase1 message to“hello there”,meaningthatthe window afterItypedmyname in wouldchange itsfirstsentence promptto“hellothere Jack,”.Phrase3meansthatthere isa new sentence of the nextwindow,inthiscase to“I hope youenjoyit”,butyouneedto addit to the variable message. Programming 1.2 graphical welcome var canvas; canvas = openGraphics(); var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", welcome to the Programming module."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2; canvas.drawString( message, 20, 40 ); canvas.paint();
  • 7. Jack Eastwood var canvas; canvas = openGraphics(); var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", welcome to the Programming module."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2; canvas.drawString( message, 0, 0 ); canvas.paint(); Comments:
  • 8. Jack Eastwood By changingthe “canvas . drawString( message, (value),(value) )”,itwill change the position of the outputon the graphical window,byincreasingthe valuesitwill change tobe loweredandmore to the right. var canvas; canvas = openGraphics(); var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", welcome to the Programming module."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2; canvas.drawString( message, 20, 40); canvas.drawString( message, 0, 0); canvas.paint(); var canvas; canvas = openGraphics(); var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", welcome to the Programming module."; var name; name = prompt( "Please enter your name:" );
  • 9. Jack Eastwood var message; message = phrase1 + name + phrase2; canvas.setColor( "red" ); canvas.drawString( message, 20, 40); canvas.setColor( "blue" ); canvas.drawString( message, 0, 0); canvas.paint(); Comments:  The “setColor”variable isAmerican.The setColorfunctionchangesanytextunderneath where itisdeclaredtothe chosencolour. If the userwant to make a differentsentencein anothercolourthentheywill have todeclare itagainjustabove the string. var canvas; canvas = openGraphics(); var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", <br />welcome to the Programming module."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2; canvas.setColor( "red" );
  • 10. Jack Eastwood canvas.drawString( message, 20, 40); canvas.setColor( "blue" ); canvas.drawString( message, 0, 0); canvas.paint(); Comments:  The <br /> puts the outputon the line underneathafterithasbeendeclared. var canvas; canvas = openGraphics(); var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", <br />welcome to the Programming module."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2; canvas.setFont( "times", "20px", Font.BOLD ); canvas.setColor( "red" ); canvas.drawString( message, 20, 40); canvas.setColor( "blue" ); canvas.drawString( message, 0, 0); canvas.paint();
  • 11. Jack Eastwood Comments:  “canvas.setFont( “times”,“20px”,Font.BOLD);” setsthe fontof the outputto timesnew roman,make the fontsize to20 pixelsandsetsthe outputto bold. var canvas; canvas = openGraphics(); var phrase1; phrase1 = "Hello, "; var phrase2; phrase2 = ", <br />welcome to the Programming module."; var name; name = prompt( "Please enter your name:" ); var message; message = phrase1 + name + phrase2; canvas.setFont( "comic sans ms", "40px", Font.BOLD_ITALIC ); canvas.setColor( "red" ); canvas.drawString( message, 40, 90); canvas.setColor( "blue" ); canvas.drawString( message, 0, 0); canvas.paint();
  • 12. Jack Eastwood Programming 1.3 Expressions var a; a = 0; var b; b = 0; var c; c = 0; var result; result = a + b + c; alert( result ); var a; a = 5; var b; b = 15; var c; c = 7; var result;
  • 13. Jack Eastwood result = a + b - c; alert( result ); var a; a = 2; var b; b = 3; var c; c = 4; var result; result = a*b + b*c + a*c; alert( result ); var a; a = 5; var b; b = 4; var result; result = (a+b)*(a-b); alert( result );
  • 14. Jack Eastwood Comments:  Variablesare assigneddifferentnumericvalues.  “var result”worksout the resultof the valuesgiventoa,band c  * hasto be usedtomultiplyvaluesi.e.“a*b”is“a x b”  “alert( result);”showsthe resultof calculatingthe variablesonawindow Programming 1.4 Shape area var canvas; canvas = openGraphics(); var size; size = 100; var area; area = size * size; canvas.drawRect( 10, 10, size, size ); // drawRect, short for drawRectangle, requires four values: // drawRect( x, y, width, height ); // x and y are the coordinates of the top left corner // width and height are what they say! // Setting width and height to the same value draws a square canvas.drawString( "Square of size:", 10, 250 ); canvas.drawString( size, 120, 250 ); canvas.drawString( "Square of area:", 10, 290 ); canvas.drawString( area, 120, 290 ); canvas.paint();
  • 15. Jack Eastwood Comments  The “can=openGraphics();”opensanew graphical window.  “var size;size 100” setsthe base size of the rectangle to100.  “var area; area size * size “; calculatesthe areaby calculatingsize x size.  “canvas.drawRect( 10, 10 size,size );”the “( 10, 10)” setsthe co-ordinatesof where the rectangle isbeingplacedinthe window,whilst“(size,size)”setsthe widthandheight parameters. var canvas; canvas = openGraphics(); var size; size = 200; var radius; radius = size/2; var area; area = radius*radius*Math.PI; canvas.drawEllipse( 10, 10, size, size ); //there is a graphics function drawEllipse that requires the same four values as drawRect but draws an oval shape within the bounds of the rectangle specified by width and height.
  • 16. Jack Eastwood //The area of a circle is calculated using the formula: area = radius2 X pi //JavaScript already knows the value of pi, it is access using Math.PI //A circle of radius 10 has an area of 314.159 canvas.drawString( "Circle of size:", 10, 250 ); canvas.drawString( size, 120, 250 ); canvas.drawString( "Radius of circle:", 10, 290 ); canvas.drawString( radius, 120, 290 ); canvas.drawString( "Area of circle:", 10, 330 ); canvas.drawString( area, 120, 330 ); canvas.paint(); var canvas; canvas = openGraphics(); var size; size = 200; var radius; radius = size/2; var area; area = (radius*radius)*Math.PI; canvas.setColor( "blue" ); canvas.fillEllipse( 10, 10, size, size ); //there is a graphics function drawEllipse that requires the same four values as drawRect but draws an oval shape within the bounds of the rectangle specified by width and height. //The area of a circle is calculated using the formula: area = radius2 X pi //JavaScript already knows the value of pi, it is access using Math.PI //A circle of radius 10 has an area of 314.159 canvas.setColor( "black" ); canvas.drawString( "Circle of size:", 10, 250 ); canvas.drawString( size, 120, 250 ); canvas.drawString( "Radius of circle:", 10, 290 ); canvas.drawString( radius, 120, 290 ); canvas.drawString( "Area of circle:", 10, 330 ); canvas.drawString( area, 120, 330 ); canvas.paint();
  • 17. Jack Eastwood Comments  Canvas.setColor( “blue”);changesthe colourof all objectsinthe window underneathto blue. Byputtingcanvas.setColor("black");justabove the textthisfillsall objects underneathtoblackagain. Programming 1.5 interest rates var amount; amount = 250; var rate; rate = 10; var years; years = 1; // declare, and initialise, identifiers for rate and time var interest; interest = (amount * rate * years)/100; // input a formula to calculate the interest //250 x 10=2500 x 1 = 2500/100=25 alert( interest );
  • 18. Jack Eastwood Programming 1.6 Framing a picture var canvas; canvas = openGraphics(); var imageName; var xPosition; var yPosition; var width; var height; imageName = "Honeysuckle.jpeg"; xPosition = 80; yPosition = 100; //sets the co-ordinates for the position of the image within the window width = 200; height = 150; //sets the width and height parameters for the image canvas.setColor ( "white" ); canvas.fillRect ( 30, 30, 300, 300 ); //sets background for the image coloured in white canvas.drawImage( imageName, xPosition, yPosition, width, height ); canvas.paint();
  • 19. Jack Eastwood var canvas; canvas = openGraphics(); var imageName; var xPosition; var yPosition; var width; var height; imageName = "Honeysuckle.jpeg"; xPosition = 80; yPosition = 100; //sets the co-ordinates for the position of the image within the window width = 200; height = 150; //sets the width and height parameters for the image canvas.setColor ( "white" ); canvas.fillRect ( 30, 30, 300, 300 ); //sets background for the image colored in white canvas.setColor ( "black" ); canvas.drawRect ( 30, 30, 300, 300 ); //sets a border for the background colored black canvas.drawImage( imageName, xPosition, yPosition, width, height );
  • 20. Jack Eastwood canvas.paint(); var canvas; canvas = openGraphics(); var imageName; var xPosition; var yPosition; var width; var height; imageName = "Honeysuckle.jpeg"; xPosition = 80; yPosition = 100; //sets the co-ordinates for the position of the image within the window width = 200; height = 150; //sets the width and height parameters for the image canvas.setColor ( "white" ); canvas.fillRect ( 30, 30, 300, 300 ); //sets background for the image colored in white canvas.setColor ( "black" ); canvas.setStroke( 6 ); //sets width for the width of the frame canvas.drawRect ( 30, 30, 300, 300 ); //sets a border for the background colored black
  • 21. Jack Eastwood canvas.drawImage( imageName, xPosition, yPosition, width, height ); canvas.paint(); Programming 2.1 getting input from the user // Ex2-1: Based on Ex1-2, Graphical Welcome // All graphics programs require a canvas on which to draw var canvas; canvas = openGraphics(); // comment var phrase1; phrase1 = "Hello, "; // First line that appears in the graphical environment after the user has inputted their name // comment var phrase2; phrase2 = ",<br />welcome to the Programming module."; // the "<br>" will place this line underneath the "hello, (name)" line // comment var name; name = prompt( "Please enter your name:" ); // the first window that appears that prompts the user to input their name
  • 22. Jack Eastwood // comment var message; message = phrase1 + name + phrase2; // This will add phrase1 (hello), followed by (name) when the user inputs their name at the prompt then phrase2 ("welcome to the programming module") underneath phrase1+name in the graphical enviroment // comment canvas.setFont( "comic sans ms", "15px", Font.BOLD ); // sets the font the graphical environment to comic sans, 15px in size and sets it to bold letters // comment canvas.setColor( "darkred" ); //sets the colour of the output in the graphical environment to dark red colour // comment canvas.drawString( message, 30, 50 ); // sets the co-ordinates of the output either more to the right or further down (x, y) // All graphics programs must instruct the browser to // carry out the commands and render the output canvas.paint();
  • 23. Jack Eastwood // Ex2-1: Based on Ex1-2, Graphical Welcome // All graphics programs require a canvas on which to draw var canvas;
  • 24. Jack Eastwood canvas = openGraphics(); // comment var phrase1; phrase1 = "Hello, "; // comment var phrase2; phrase2 = ",<br />welcome to the Programming module."; // comment var name; name = prompt( "Please enter your name:" ); var font; font = prompt( "Enter font style:" ); var color; color = prompt( "Enter font color:" ); var size; size = prompt( "Enter font size:" ); // comment var message; message = phrase1 + name + phrase2; // comment canvas.setFont( font, size, Font.BOLD ); // comment canvas.setColor( color ); // comment canvas.drawString( message, 30, 50 ); // All graphics programs must instruct the browser to // carry out the commands and render the output canvas.paint(); Programming 2.2 Numerical input // Ex2-2 : based on Ex1-4 var canvas; canvas = openGraphics(); var width; width = prompt( "Enter width of the square" ); width = parseInt(width, 10); var height; height = prompt( "Enter height of the square" ); height = parseInt(height, 10); var size; size = width*height; canvas.drawRect( 10, 10, width, height ); // drawRect, short for drawRectangle, requires four values: // drawRect( x, y, width, height );
  • 25. Jack Eastwood // x and y are the coordinates of the top left corner // width and height are what they say! // Setting width and height to the same value draws a square canvas.drawRect( 10, 10, width, height ); canvas.drawString( "Area of rectangle:", 10, 250 ); canvas.drawString( size, 10, 270 ); canvas.drawString( "Width of rectangle:", 10, 290 ); canvas.drawString( width, 10, 310 ); canvas.drawString( "height of rectangle:", 10, 330 ); canvas.drawString( height, 10, 350 ); canvas.paint();
  • 26. Jack Eastwood // Ex2-2 : based on Ex1-4 var canvas; canvas = openGraphics(); var x = parseInt(prompt( "Enter x co-ordinate for the circle:" ), 10); var y = parseInt(prompt( "Enter y co-ordinate for the circle" ), 10); var radius = parseInt(prompt( "Enter radius for the circle" ), 10); var diameter; diameter = radius*2; var area; area = (radius*radius)*Math.PI; canvas.drawEllipse( x, y, diameter, diameter ); // drawEllipse, short for drawRectangle, requires four values: // drawEllipse( x, y, diameter, diameter ); // x and y are the coordinates of the top left corner // diameter and diameter are needed to draw the circle // radius of a circle is half of the diameter // to work out the radius of a circle it is radius x radius x pi // Math.PI is short for pi (3.1415) canvas.drawString( "Area of circle:", 10, 250 ); canvas.drawString( area, 10, 270 );
  • 27. Jack Eastwood canvas.drawString( "Radius of circle:", 10, 290 ); canvas.drawString( radius, 10, 310 ); canvas.drawString( "Diameter of circle:", 10, 330 ); canvas.drawString( diameter, 10, 350 ); canvas.paint();
  • 28. Jack Eastwood Programming 2.3 personal details Comments Forgotto start string witha “. // Ex 2-3: Personal Details var canvas; canvas = openGraphics(); var name;
  • 29. Jack Eastwood name = prompt( "Please enter your name:" ); var mobile; mobile = prompt( "Please enter your mobile number: "); var email; email = prompt( "Please enter your email address: "); var dobDay; dobDay = prompt( "Please enter your birth day: "); dobDay = parseInt(dobDay, 10); var dobMonth; dobMonth = prompt( "Please enter your birth month: "); dobMonth = parseInt(dobMonth, 10); var dobYear; dobYear = prompt( "Please enter your birth year: "); dobYear = parseInt(dobYear, 10); var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); canvas.setColor( "purple" ); canvas.fillRect(5, 5, 500 ,250); canvas.setFont( "Arial" , "20px" ); canvas.setColor( "orange" ); canvas.setStroke( 5 ); canvas.drawRect(5, 5, 500, 250); canvas.setColor( "pink" ); canvas.drawString( "Name: " + name, 10, 10); canvas.drawString( "Mobile: " + mobile, 10, 50); canvas.drawString( "Email: " + email, 10, 90); canvas.drawString( "Date of birth: " + dobDay + "/" + dobMonth + "/" + dobYear, 10, 130); canvas.drawString( "Age: " + "19", 10, 170); canvas.drawString( "Date: " + dd + "/" + mm + "/"+ yyyy, 10, 210); canvas.paint();
  • 32. Jack Eastwood 2.4 String operations canvas.drawString( "Hello".bold()); canvas.drawString( "My name is Jack Eastwood", 0, 20 ); canvas.drawString( " Hello" .link()); canvas.drawString( "My name is Jack Eastwood", 0, 20 );
  • 33. Jack Eastwood // Ex2-4 : String operations var canvas; canvas = openGraphics(); canvas.drawString( "Hello".fixed()); canvas.drawString( "My name is Jack Eastwood", 0, 20 ); canvas.drawString( "Hello".strike()); canvas.drawString( "My name is Jack Eastwood", 0, 20 );
  • 34. Jack Eastwood var name = "Jack"; var nameLength; nameLength = name.length; canvas.drawString( "Number of characters in my name: "); canvas.drawString( nameLength, 250, 0); //aString.length calculates the number of characters assigned to a variable canvas.paint(); // Ex2-4 : String operations var canvas; canvas = openGraphics(); var name = "Jack"; var nameCharAt; nameCharAt = name.charAt(3); canvas.drawString( " 4th character of my name: "); canvas.drawString( nameCharAt, 200, 0); //aString.charAt() finds the specified character in a variable i.e. charAt(0) finds the first character in a variable, in my case it will be J canvas.paint();
  • 35. Jack Eastwood // Ex2-4 : String operations var canvas; canvas = openGraphics(); var name = "Jack"; var nameCharAt; nameCharAt = name.charAt(0) + name.substr(1); canvas.drawString( " Separate 1st letter of my name from the rest: "); canvas.drawString( name.charAt(0), 0, 30); canvas.drawString( name.substr(1), 30, 30); //aString.charAt() finds the specified character in a variable i.e. charAt(0) finds the first character in a variable, in my case it will be J canvas.paint();
  • 36. Jack Eastwood // Ex2-4 : String operations var canvas; canvas = openGraphics(); var name = "jack"; var nameCharAt; nameCharAt = name.charAt + name.substr; canvas.drawString( " Separate 1st letter of my name from the rest: "); canvas.drawString( name.charAt(0).toUpperCase(), 0, 30); canvas.drawString( name.substr(1).toLowerCase(), 30, 30); // .toUpperCase will select the 1st letter chosen from name.charAt and will put it into upper case, whilst .toLowerCase will select the other characters and put them into lower case. canvas.paint();
  • 37. Jack Eastwood 2.5 date operations // Ex2-5 var canvas; canvas = openGraphics(); var value; var aDate; aDate = new Date(); canvas.drawString( "The date is: " + aDate, 10, 20 ); value = aDate.toLocaleString(); canvas.drawString( "toLocalString: " + value, 10, 40 ); value = aDate.getYear(); canvas.drawString( "Year is: " + value , 10, 60 ); canvas.paint();
  • 38. Jack Eastwood // Ex2-5 var canvas; canvas = openGraphics(); var value; var aDate; aDate = new Date(); canvas.drawString( "The date is: " + aDate, 10, 20 ); value = aDate.toLocaleString(); canvas.drawString( "toLocalString: " + value, 10, 40 ); value = aDate.getFullYear(); canvas.drawString( "Year is: " + value , 10, 60 ); value = aDate.getMonth(); canvas.drawString( "Month is: " + value, 10, 80 ); value = aDate.getDay(); canvas.drawString( "Day is: " + value, 10, 100 ); value = aDate.getDate(); canvas.drawString( "Date is: " + value, 10, 120 ); canvas.paint();
  • 39. Jack Eastwood // Ex2-5 var canvas; canvas = openGraphics(); var value; var aDate; aDate = new Date( 1995, 6, 6); canvas.drawString( "The date is: " + aDate, 10, 20 ); value = aDate.toLocaleString(); canvas.drawString( "toLocalString: " + value, 10, 40 ); value = aDate.getFullYear(); canvas.drawString( "Year is: " + value , 10, 60 ); value = aDate.getMonth(); canvas.drawString( "Month is: " + value, 10, 80 ); value = aDate.getDay(); canvas.drawString( "Day is: " + value, 10, 100 ); value = aDate.getDate(); canvas.drawString( "Date is: " + value, 10, 120 ); canvas.paint(); Ranges from 0-11 , 0= January, 11= December Day 1 = Monday, Day 7 = Sunday
  • 40. Jack Eastwood // Ex2-5 var canvas; canvas = openGraphics(); var value; var aDate; aDate = new Date( 1995, 11, 25 ); canvas.drawString( "The date is: " + aDate, 10, 20 ); value = aDate.toLocaleString(); canvas.drawString( "toLocalString: " + value, 10, 40 ); value = aDate.getFullYear(); canvas.drawString( "Year is: " + value , 10, 60 ); value = aDate.getMonth(); canvas.drawString( "Month is: " + value, 10, 80 ); value = aDate.getDay(); canvas.drawString( "Day is: " + value, 10, 100 ); value = aDate.getDate(); canvas.drawString( "Date is: " + value, 10, 120 ); canvas.paint(); I was bornon a Thursday
  • 41. Jack Eastwood // Ex2-5 var canvas; canvas = openGraphics(); var value; var aDate; Christmasin1995 was ona Monday Put : insteadof ; at the endand only supposedtoputa numberfrom0-9
  • 42. Jack Eastwood aDate = new Date(); value = aDate.setDate(29); canvas.drawString( "Date is: " + value, 10, 20 ); value = aDate.setMonth(11); canvas.drawString( "Month is: " + value, 10, 40 ); value = aDate.setFullYear(1980); canvas.drawString( "Year is: " + value, 10, 60 ); canvas.paint(); The toLocaleStringcovertsthe newDate functioninto adate format,the getDate,getDay,getMonth and getFullYearall retrievethe date fromthe computer’sclock.The setDate functionsallow the user to inputthe day,monthand year,howeverthe outputis displayedinminutes,sothiswill needtobe dividedtogetthe properdate,monthand year. 2.6 How old are you?
  • 43. Jack Eastwood // Ex2-6 var canvas; canvas = openGraphics(); var day; var month; var year; var birthday; // get user's birthday details // create two dates day = parseInt(prompt( "Please enter your birthday: "), 10); month = parseInt(prompt( "Please enter your birth month: "), 10); year = parseInt(prompt( "Please enter your birth year: "), 10); var aDate = new Date(year, month-1, day); canvas.drawString ( "Date of birth: " + aDate, 10, 20); var today = new Date(); canvas.drawString ( "Today's date: " + today, 10, 100); var age = today - aDate; canvas.drawString ("Your age: " + age, 10, 140); var ageindays = age/86400000; canvas.drawString( "Your age in days: " +ageindays.toFixed(0), 10, 180); var ageinyears = ageindays/365; canvas.drawString( "Your age in years: " + ageinyears.toFixed(0), 10, 220); Identifierisdate1,notdate
  • 44. Jack Eastwood // calculate age in mS and convert to days and then years canvas.paint();
  • 45. Jack Eastwood Comments Thisasks the userto inputtheirbirthdate,monthand yearand formatit intoa date usingthe new Date functionandplacingthe variableswithinthe (). Because Januaryisassignedto0 and December is11, month-1is usedtomake the months1-12 insteadof 0-11. 2.7 Event timer // Ex2-7: Event Timer // This program calculates the difference in time // between two events: the user clearing alerts // The difference is a measure of the time it // Takes to make two keypresses or mouse clicks var canvas; canvas = openGraphics(); // Put a Title on the output screen canvas.setColor( "Yellow" ); canvas.setFont( "Comic sans ms", "30px", Font.UNDERLINE ); canvas.fillRect( 10, 10, 300, 200 ); canvas.setColor( "Red" ); canvas.drawString( "Timer",150,0 ); // uncomment the next line to see the title // canvas.paint(); // create a Date object and store the current time 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;
  • 46. Jack Eastwood canvas.setFont( "Comic sans ms", "20px" ); canvas.drawString( " Difference in time: " + difference + "ms", 10, 60); // calculate the difference between the two times // output a suitable message to the user canvas.paint(); Comments
  • 47. Jack Eastwood Thisworksby pressingthe firstalertwindow will collectthe exactcurrenttime all the wayto millisecondsandthe nextalertwindowwill alsocollectthe exactcurrenttime. Thisisthen subtractedbythe variable calleddifference whichminus’sthe seconddate (“stoptimeralert”) againstthe firstdate (“start timeralert”). 3.1 Grading work // Ex: 3-1 Grading Work var mark; var grade; grade = "Not Yet Graded"; mark = prompt( "Please input the mark(%)" ); mark = parseInt( mark, 10 ); // see comment if( mark > 69 ) { grade = "First Class"; } else if ( mark > 59 ) { grade = "Upper Class (2.1)"; } else if (mark > 49 ) { grade = "Lower Class (2.2)"; } else if (mark > 39 ) { grade = "Third Class"; } alert( "Mark: " + mark + "% - Grade: " + grade );
  • 50. Jack Eastwood // Ex: 3-1 Grading Work var mark; var grade; grade = "Not Yet Graded"; mark = prompt( "Please input the mark(%)" ); mark = parseInt( mark, 10 ); // see comment if ( mark >= 0 && mark <=100 ) { if( mark > 69 ) { grade = "First Class"; } else if ( mark > 59 && mark < 70) { grade = "Upper Class (2.1)"; } else if (mark > 49 && mark < 60) { grade = "Lower Class (2.2)"; } else if (mark > 39 && mark < 50) { grade = "Third Class"; } else if (mark < 40 ) { grade = "Fail";
  • 51. Jack Eastwood } } else { alert( "Invalid mark, grade needs to be between 0-100" ); } alert( "Mark: " + mark + "% - Grade: " + grade );
  • 53. Jack Eastwood Comments Thisprogram promptsthe userto input the grade percentage whichgetsparsedwithparseInt(), thenthe IF statementssetsboundariesforthe inputi.e.if markisabove 70 thenthat’s a firstand if the mark is between 50-59thena 2:2 isawarded.If a negative numberora numberover100 is entered,thenthe program createsanalertthat the inputtednumberorcharacter isinvalid. 3.2 Date validation
  • 54. Jack Eastwood // Ex 2-3: Personal Details var canvas; canvas = openGraphics(); var name; name = prompt( "Please enter your name:" ); Forgotto endwith} afterIF statement Forgotto put variable name after &&
  • 55. Jack Eastwood var mobile; mobile = prompt( "Please enter your mobile number: "); var email; email = prompt( "Please enter your email address: "); var dobDay; dobDay = prompt( "Please enter your birth day: "); dobDay = parseInt(dobDay, 10); var dobMonth; dobMonth = prompt( "Please enter your birth month: "); dobMonth = parseInt(dobMonth, 10); var dobYear; dobYear = prompt( "Please enter your birth year: "); dobYear = parseInt(dobYear, 10); var birthday; birthday = new Date(dobYear, dobMonth-1, dobDay ); var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); var age; age = today - birthday; var ageindays; ageindays = age/86400000; var ageinyears; ageinyears = ageindays/365; canvas.setColor( "purple" ); canvas.fillRect(5, 5, 700 ,250); canvas.setFont( "Arial" , "20px" ); canvas.setColor( "orange" ); canvas.setStroke( 5 ); canvas.drawRect(5, 5, 700, 250); canvas.setColor( "pink" ); canvas.drawString( "Name: " + name, 10, 10); canvas.drawString( "Mobile: " + mobile, 10, 50); canvas.drawString( "Email: " + email, 10, 90); canvas.drawString( "Date of birth: " + birthday, 10, 130); canvas.drawString( "Age: " + ageinyears.toFixed(0), 10, 170); canvas.drawString( "Date: " + today, 10, 210); if (ageinyears.toFixed(0) == 20) { alert("Age is correct"); } else if (ageinyears.toFixed(0) != 20) { alert( "Age is incorrect"); } if (dobDay >=1 && dobDay<=31) { alert ("Day is valid");
  • 56. Jack Eastwood } else { alert ("Day is invalid"); } if (dobMonth >=1 && dobMonth <=12) { alert("Month is valid"); } else { alert("Month is invalid"); } if (dobYear > 0 && dobYear < 2015) { alert("Year is valid"); } else { alert("Year is invalid"); } canvas.paint(); Valid entries
  • 59. Jack Eastwood 3.3 Coloured event timer // Ex2-7: Event Timer // This program calculates the difference in time // between two events: the user clearing alerts // The difference is a measure of the time it // Takes to make two keypresses or mouse clicks var canvas; canvas = openGraphics(); // Put a Title on the output screen canvas.setFont( "Comic sans ms", "30px", Font.UNDERLINE ); canvas.drawString( "Timer",150,0 ); // uncomment the next line to see the title // canvas.paint(); // create a Date object and store the current time 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; canvas.setFont( "Comic sans ms", "20px" ); canvas.drawString( "Difference in time: ", 10, 60 ); if (difference <= 150) { canvas.setColor( "green" ); canvas.drawString( difference + "ms", 200, 60); } else if ( difference >=151 && difference <= 350 ) { canvas.setColor( "orange" ); canvas.drawString( difference + "ms", 200, 60); } else if (difference > 350 ) { canvas.setColor( "red" ); canvas.drawString( difference + "ms", 200, 60); } // calculate the difference between the two times // output a suitable message to the user canvas.paint();
  • 61. Jack Eastwood Comments I separatedthe “difference intime:”fromthe resultdue tothe “difference intime:”alsobeing coloured,sothiswouldhave beenputbefore the if statements. 3.4 Truth tables AND Table // Ex: 3-4 var canvas; canvas = openGraphics();
  • 62. Jack Eastwood var operation; operation = "AND"; var heading; heading = "Truth Table for the " + operation + " operation."; canvas.drawStringRect( heading.big(), 0, 5, 400, "center" ); var message; message = "An entry in the table is the result of the operation "; message = message + "A " + operation + " B"; canvas.drawStringRect( message, 0, 30, 400, "center" ); message = "i.e. result = a && b;"; canvas.drawStringRect( message, 0, 65, 400, "center" ); var x; // left edge of table var y; // top of table x = 50; y = 100; // draw table outline canvas.setStroke( 3 ); canvas.drawLine( x, y, x+300, y ); canvas.drawLine( x, y, x, y+150 ); canvas.drawLine( x, y+50, x+300, y+50 ); canvas.drawLine( x, y+150, x+300, y+150 ); canvas.drawLine( x+100, y, x+100, y+150 ); canvas.drawLine( x+300, y, x+300, y+150 ); canvas.setStroke( 1 ); canvas.drawLine( x, y+100, x+300, y+100 ); canvas.drawLine( x+200, y, x+200, y+150 ); canvas.setStroke( Stroke.DOTTED ); canvas.drawLine( x, y, x + 100, y + 50 ); // Put in column and row labels canvas.setFont( "lucida console", "20px", Font.BOLD ); canvas.setColor( "darkred" ); canvas.drawStringRect( "A", x+15, y+20, 50, "left" ); canvas.drawStringRect( "B", x+5, y+5, 80, "right" ); canvas.drawStringRect( "true", x, y+50+15, 100, "center" ); canvas.drawStringRect( "false", x, y+100+15, 100, "center" ); canvas.drawStringRect( "true", x+100, y+15, 100, "center" ); canvas.drawStringRect( "false", x+200, y+15, 100, "center" ); // Now to put the results in the table var result; var a; var b; canvas.setColor( "Darkblue" ); a = true; b = true;
  • 63. Jack Eastwood result = a && b; canvas.drawStringRect( result, x+100, y+50+15, 100, "center" ); a = true; b = false; result = a && b; canvas.drawStringRect( result, x+200, y+50+15, 100, "center" ); a = false; b = true; result = a && b; canvas.drawStringRect( result, x+100, y+100+15, 100, "center" ); a = false; b = false; result = a && b; canvas.drawStringRect( result, x+200, y+100+15, 100, "center" ); canvas.paint(); OR Table // Ex: 3-4 var canvas; canvas = openGraphics(); var operation; operation = "OR"; var heading; heading = "Truth Table for the " + operation + " operation."; canvas.drawStringRect( heading.big(), 0, 5, 400, "center" );
  • 64. Jack Eastwood var message; message = "An entry in the table is the result of the operation "; message = message + "A " + operation + " B"; canvas.drawStringRect( message, 0, 30, 400, "center" ); message = "i.e. result = a || b;"; canvas.drawStringRect( message, 0, 65, 400, "center" ); var x; // left edge of table var y; // top of table x = 50; y = 100; // draw table outline canvas.setStroke( 3 ); canvas.drawLine( x, y, x+300, y ); canvas.drawLine( x, y, x, y+150 ); canvas.drawLine( x, y+50, x+300, y+50 ); canvas.drawLine( x, y+150, x+300, y+150 ); canvas.drawLine( x+100, y, x+100, y+150 ); canvas.drawLine( x+300, y, x+300, y+150 ); canvas.setStroke( 1 ); canvas.drawLine( x, y+100, x+300, y+100 ); canvas.drawLine( x+200, y, x+200, y+150 ); canvas.setStroke( Stroke.DOTTED ); canvas.drawLine( x, y, x + 100, y + 50 ); // Put in column and row labels canvas.setFont( "lucida console", "20px", Font.BOLD ); canvas.setColor( "darkred" ); canvas.drawStringRect( "A", x+15, y+20, 50, "left" ); canvas.drawStringRect( "B", x+5, y+5, 80, "right" ); canvas.drawStringRect( "true", x, y+50+15, 100, "center" ); canvas.drawStringRect( "false", x, y+100+15, 100, "center" ); canvas.drawStringRect( "true", x+100, y+15, 100, "center" ); canvas.drawStringRect( "false", x+200, y+15, 100, "center" ); // Now to put the results in the table var result; var a; var b; canvas.setColor( "Darkblue" ); a = true; b = true; result = a || b; canvas.drawStringRect( result, x+100, y+50+15, 100, "center" ); a = true; b = false; result = a || b; canvas.drawStringRect( result, x+200, y+50+15, 100, "center" );
  • 65. Jack Eastwood a = false; b = true; result = a || b; canvas.drawStringRect( result, x+100, y+100+15, 100, "center" ); a = false; b = false; result = a || b; canvas.drawStringRect( result, x+200, y+100+15, 100, "center" ); canvas.paint(); Comments The difference betweenANDandORisthat ANDoperationsare definedby&&between2variables whilst||isusedto define OR. 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; y = 0; size = 500;
  • 66. Jack Eastwood 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(); // Ex3-5 : Graphics Experiments // Part of demo program: var canvas; canvas = openGraphics(); var x; var y; var width;
  • 67. Jack Eastwood var height; x = 0; 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();
  • 68. Jack Eastwood 3.6 Graphical Event timer // Ex 3-6 : Graphical Event Timer
  • 69. Jack Eastwood 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) { 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(); }
  • 70. Jack Eastwood 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; 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; }
  • 71. Jack Eastwood 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();
  • 72. 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"; 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();
  • 73. 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) { 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 ......
  • 75. Jack Eastwood // Ex4-2: Guess the Number var canvas; canvas = openGraphics(); 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) { message = guess + " Correct";
  • 76. Jack Eastwood guessed = true; } canvas.drawString( message, x, y); y = y + 20; canvas.paint(); } 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 );
  • 77. Jack Eastwood //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 ); 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 ); canvas.paint(); // Ex4-4: BMI Calculator var canvas; canvas = openGraphics();
  • 78. Jack Eastwood 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"; } 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();
  • 80. Jack Eastwood // Ex4-4: BMI Calculator var canvas; 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 = 185; 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; while( !reset ){ canvas.setFont( "Comic Sans MS", "20px", Font.BOLD ); canvas.drawString( "BMI calculator bitch's", 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 height = parseFloat(prompt("Please enter your height in cm: ") ,10)/100; var weight = parseFloat(prompt("Please enter your weight in kg: ") ,10);
  • 81. Jack Eastwood var calculation = weight/(height * height); var bmi = calculation.toFixed(2); var classification; canvas.setFont( "Comic Sans MS", "14px" ); canvas.setColor( "DarkBlue" ); canvas.drawString( "Height " + ":" + height + " m", 120, 100 ); canvas.drawString( "Weight " + ":" + weight + " kg", 0, 100 ); if (bmi <= 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 (bmi > 18.4999 && bmi <= 24.999){ canvas.setColor( "black"); 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 (bmi > 24.999 && bmi <= 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 (bmi > 29.999 && bmi <= 39.999){ canvas.setColor( "black" ); canvas.setStroke(3); classification = " Obese";
  • 82. Jack Eastwood 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 (bmi > 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( bmi + ":" + classification, 0, 150 ); 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); //canvas.drawEllipse(300, 290, 20, 20); //canvas.fillEllipse(295, 310, 30, 70); //canvas.drawLine( RArmPos, ArmYPos, RArmPos + ArmLength, ArmYPos ); //canvas.drawLine( LArmPos, ArmYPos, LArmPos + ArmLength, ArmYPos ); //canvas.drawLine( LLegPos, LegYPos, LLegPos, LegYPos + LegLength ); //canvas.drawLine( RLegPos, LegYPos, RLegPos, LegYPos + LegLength ); //canvas.drawEllipse(xos + 3, 290, 20, 20); //canvas.fillEllipse(xos, 310, 30, 70);
  • 83. Jack Eastwood //canvas.drawLine( xos + 50, ArmYPos, xos + ArmLength, ArmYPos ); //canvas.drawLine( xos - 50, ArmYPos, xos + ArmLength, ArmYPos ); //canvas.drawLine( xos + 5, LegYPos, xos + 5, LegYPos + LegLength ); //canvas.drawLine( xos + 20, LegYPos, xos + 20, LegYPos + LegLength ); for( labelnum = 0; labelnum <= 9; labelnum++ ) { canvas.drawString( label, xos + (labelnum * 60), (yos + lineHeight)); label = label + 5; } canvas.paint(); reset = prompt( "Would you like to start over? (Y/N)" ); if ( reset == "y"){ reset = false; canvas.clear(); } else { reset = true; } } 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"); //Calculations for points on axis. //A= xos, yos //B= xos, yos + yal //C= xos + xal, yos + yal 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; }
  • 84. 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) - rainfall); } //You may have to decide where this is best placed canvas.paint(); 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 i; var imageName = "Honeysuckle.jpeg"; canvas.setColor ("Beige"); canvas.fillRect (75, 25, 250, 200); canvas.setColor ("Firebrick"); canvas.setStroke (3); canvas.drawRect (73, 23, 250, 200); canvas.setStroke(1); canvas.setColor("Black"); xPos = 326; yTop = 22; yBottom = 226; for( i = 0; i<2; i++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos += 1; yTop -= 1; yBottom += 1; } xPos = 76; yTop = 26; yBottom = 222; for(i = 0; i<4; i++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos += 1; yTop += 1; yBottom -= 1; } xLeft = 80; xRight = 318; yPos = 29;
  • 85. Jack Eastwood for( i = 0; i<4; i++){ canvas.drawLine(xLeft, yPos, xRight, yPos); xLeft -= 1; xRight += 1; yPos -= 1; } xLeft = 73; xRight = 325; yPos = 226; for( i = 0; i<2; i++){ canvas.drawLine(xLeft, yPos, xRight, yPos); xLeft -= 1; xRight += 1; yPos += 1; } canvas.setColor("Red"); xPos = 322; yTop = 26; yBottom = 222; for(i = 0; i<4; i++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos -= 1; yTop += 1; yBottom -= 1; } xPos = 72; yTop = 22; yBottom = 226; for( i = 0; i<2; i++){ canvas.drawLine(xPos, yTop, xPos, yBottom); xPos -= 1; yTop -= 1; yBottom += 1; } xLeft = 73; xRight = 325; yPos = 22; for( i = 0; i<2; i++){ canvas.drawLine(xLeft, yPos, xRight, yPos); xLeft -= 1; xRight += 1; yPos -= 1; } xLeft = 77; xRight = 321; yPos = 222; for( i = 0; i<4; i++){ canvas.drawLine(xLeft, yPos, xRight, yPos); xLeft += 1; xRight -= 1; yPos -= 1; } canvas.drawImage( imageName, xPosition, yPosition, width, height ); canvas.paint(); 5.3 Interest calculator html <html> <head>
  • 86. Jack Eastwood <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"> <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> 5.4 Date validation form
  • 87. Jack Eastwood <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> <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>
  • 88. Jack Eastwood 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> <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>
  • 89. 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 );
  • 90. Jack Eastwood var miles = kilometers / 8 * 5; document.getElementById( "milesBox" ).value = miles.toFixed(2); } </script> </head> <body> <h1> 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();" /> </body> </html>
  • 91. Jack Eastwood 6.2 Interest Calculator Page <html> <head> <title> Interest Calculator </title> <script type = "text/Javascript">
  • 92. Jack Eastwood 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 ); // declare, and initialise, identifiers for rate and time var interest; interest = (amount * rate * years)/100; // input a formula to calculate the interest //250 x 10=2500 x 1 = 2500/100=25 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> </html>
  • 94. 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; 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();
  • 95. Jack Eastwood 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) { 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> <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>
  • 96. Jack Eastwood <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> </html>
  • 97. Jack Eastwood 6.4 BMI calculatorhtml <html> <head> <title> BMI Calculator
  • 98. Jack Eastwood </title> <script type ="text/Javascript"> function BMIcalculation() { var height; 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 ); 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>
  • 99. Jack Eastwood <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();"> Calculate BMI </button> <form action = "server_program_name" method="get"> <label> BMI: </label> <input id="BMIbox" type="number"></form> </body> </html>