Upload
griffin-lane
View
218
Download
0
Embed Size (px)
Citation preview
Java ProgrammingJava Programming
Khan Academy and Khan Academy and
Mrs. Beth CueniMrs. Beth Cueni
Table of contentsTable of contents Drawing basics Coloring Variables http://www.youtube.com/watch?v=Rwbg_0YGdfs
Animation basicsAnimation basics Text and stringsText and strings FunctionsFunctions Logic and If statementsLogic and If statements LoopingLooping ArraysArrays ObjectsObjects Object oriented programmingObject oriented programming
Drawing BasicsDrawing Basics
CommandsCommands RectRect EllipsisEllipsis LineLine
These commands are considered to be These commands are considered to be functions and accept parametersfunctions and accept parameters
RectanglesRectangles
Rect (10, 20, 100, 200);Rect (10, 20, 100, 200); 10 is the x position (upper left corner)10 is the x position (upper left corner) 20 is the y position (upper left corner)20 is the y position (upper left corner) 100 is the width of the rectangle in pixels100 is the width of the rectangle in pixels 200 is the height of the rectangle in pixels200 is the height of the rectangle in pixels
Screen position is measured in pixels Screen position is measured in pixels and the screen is 400 x 400 pixelsand the screen is 400 x 400 pixels
EllipseEllipse
Ellipse (200, 200, 100, 50);Ellipse (200, 200, 100, 50); 200, 200 pixel location for the center of the 200, 200 pixel location for the center of the
circlecircle 100 width in pixels of the ellipse100 width in pixels of the ellipse 50 height in pixels of the ellipse50 height in pixels of the ellipse If the last two numbers are the same, you can If the last two numbers are the same, you can
make a perfect circlemake a perfect circle
LinesLines
Line (34, 67, 123, 231);Line (34, 67, 123, 231); 34 and 67 – how far over and down the line 34 and 67 – how far over and down the line
should startshould start 123 and 231 – how far over and down the line 123 and 231 – how far over and down the line
should endshould end
ColoringColoring
CommandsCommands Stroke (255,0,0);Stroke (255,0,0); Fill (0,0,255);Fill (0,0,255); noFill;noFill; noStroke;noStroke;
StrokeStroke
Border color of the objectBorder color of the object Stroke (r, g, b);Stroke (r, g, b);
The first number indicates the intensity of the The first number indicates the intensity of the color red - stroke (255, 0, 0);color red - stroke (255, 0, 0);
The second number indicates the intensity of The second number indicates the intensity of the color green – stroke (0, 255, 0);the color green – stroke (0, 255, 0);
The third number indicates the intensity of the The third number indicates the intensity of the color blue – stroke (0, 0, 255);color blue – stroke (0, 0, 255);
FillFill
Color of the inside of the object being Color of the inside of the object being drawndrawn
Rect (10, 20, 100, 200);Rect (10, 20, 100, 200); Fill (0, 255, 0);Fill (0, 255, 0);
Will draw a rectangle and color it greenWill draw a rectangle and color it green
noStroke noFillnoStroke noFill
noStroke(); – no outline will display for the noStroke(); – no outline will display for the objectobject
noFill(); – the object will not be colorednoFill(); – the object will not be colored
VariablesVariables
Think of a variable as a bucket The value is the contents of the bucket no spaces in variable name Must be in this format
variable = value Don’t say equals say “gets” The value is assigned to the variable
Using variables as parametersUsing variables as parameters
var faceX = 200;
var faceY = 200;
var faceSize = 100;
fill(0, 0, 0);
Ellipse (faceX, faceY, faceSize, faceSize);
// face
Defining variables relative to othersDefining variables relative to others
// now we use those variables to place and size// the ears relative to the face
ellipse(faceX - faceSize * 0.7, faceY - faceSize * 0.6, faceSize * 1.1, faceSize * 1.1); // left earellipse(faceX + faceSize * 0.7, faceY - faceSize * 0.6, faceSize * 1.1, faceSize * 1.1); // right ear
Animation basicsAnimation basics
Bunch of drawings played fast enough it Bunch of drawings played fast enough it looks like it is movinglooks like it is moving
Use a functionUse a function
Animation functionAnimation function
var draw = function() { var draw = function() { // this is the draw loop! everything inside these // this is the draw loop! everything inside these
// brackets will be run over and over again. // brackets will be run over and over again.
};};
Get into the habit of indenting all code within Get into the habit of indenting all code within the { } for easier readabilitythe { } for easier readability
Animated Car example explainedAnimated Car example explained
Identify the X command outside the loop to Identify the X command outside the loop to startstart
Incrementing the value of x within the loopIncrementing the value of x within the loop
X = X + 1X = X + 1
May need to refresh the background within May need to refresh the background within the loopthe loop
mouseX and mouseYmouseX and mouseY
mouseX – x position of your mousemouseX – x position of your mouse
mouseY – y position of your mousemouseY – y position of your mouse
New way to incrementNew way to increment
X = x + 1;X = x + 1;Can be writtenCan be writtenX +=1;X +=1;
x += 1; x += 1; y -= 2;y -= 2;ballWidth *= 0.99; ballWidth *= 0.99; ballHeight /= 1.01;ballHeight /= 1.01;
Another shortcutAnother shortcut
eyeSize = eyeSize + 1eyeSize = eyeSize + 1
OROR
eyeSize +=1;eyeSize +=1;
OROR
eyeSize ++;eyeSize ++;
Text and Strings commandsText and Strings commands
textSize(46);textSize(46); Similar to font sizeSimilar to font size
fill(8, 142, 204);fill(8, 142, 204); Similar to font colorSimilar to font color
text("Sophia", 114, 120);text("Sophia", 114, 120); Identifying the actual text and the locationIdentifying the actual text and the location
Text and stringsText and strings
Text (“hello”, 60, 55);Text (“hello”, 60, 55); where 60, 55 locates the lower left start point where 60, 55 locates the lower left start point
of the text NOT the upper right as in of the text NOT the upper right as in rectanglesrectangles
String commandString command
// think of string = text// think of string = text
fill (92, 24, 219);fill (92, 24, 219);
textSize (30);textSize (30);
var myName = “Mrs. Cueni";var myName = “Mrs. Cueni";
text(myName, 41, 30);text(myName, 41, 30);
text(myName, 41, 60);text(myName, 41, 60);
text(myName, 41, 90);text(myName, 41, 90);
Adding stringsAdding strings
textSize(30);textSize(30);
var myName = “Mrs. Cueni";var myName = “Mrs. Cueni";
var message = myName + "!!!";var message = myName + "!!!";
text(message, 41, 30);text(message, 41, 30);
This displays Mrs. Cueni!!!This displays Mrs. Cueni!!!
Animate textAnimate text
You can animate text by putting the text You can animate text by putting the text inside the draw function and it will be inside the draw function and it will be repeated over and overrepeated over and over
If you replace the screen location with If you replace the screen location with mouseX and mouseY the string or text will mouseX and mouseY the string or text will follow your mousefollow your mouse
Making text largerMaking text larger
var howBig = 30;var howBig = 30;var draw = function() { var draw = function() {
howBig = howBig + 1; howBig = howBig + 1; textSize(howBig); textSize(howBig); background(0, 238, 255);background(0, 238, 255); var myName = “Mrs. Cueni"; var myName = “Mrs. Cueni"; var message = myName + "!!!"; var message = myName + "!!!"; text(message, mouseX, mouseY);text(message, mouseX, mouseY);
};};
FunctionsFunctions
Java has built in functions but you can Java has built in functions but you can also make your own functionsalso make your own functions
Var drawComputer = function() {Var drawComputer = function() {}}
Var tells it to run the functionVar tells it to run the functiondrawComputer is the name of the functiondrawComputer is the name of the function
New JAVA commandsNew JAVA commands
Random (50, 350);Random (50, 350); Generates a random number from 50 -350Generates a random number from 50 -350
Passing parametersPassing parameters
You can pass parameters in a functionYou can pass parameters in a functiondrawCircles (10, 30);drawCircles (10, 30);drawCircles (200, 30);drawCircles (200, 30);
Var drawCircles = function (circleX, circleY){Var drawCircles = function (circleX, circleY){};};
Passes 10 to circleX and 30 to circleYPasses 10 to circleX and 30 to circleYPasses 200 to circleX and 30 to circleYPasses 200 to circleX and 30 to circleY
Global functionsGlobal functions
Sometimes called Magic functionsSometimes called Magic functions For example the function Draw gets called For example the function Draw gets called
over and over againover and over again Sometimes this is not efficientSometimes this is not efficient Custom functions can be calledCustom functions can be called
Local and Global functionsLocal and Global functions
If the variable is defined in a function, it is If the variable is defined in a function, it is considered a local value to the functionconsidered a local value to the function
You can turn the variable into a global You can turn the variable into a global variable if it is defined outside the functionvariable if it is defined outside the function
Local variables – within a functionLocal variables – within a function Global variables – defined outside the Global variables – defined outside the
functionfunction
Logic and If statementsLogic and If statements
Boolean expressions give a result of Boolean expressions give a result of TRUE or FALSETRUE or FALSE
Created by George BooleCreated by George Boole If a certain condition is true execute the If a certain condition is true execute the
following codefollowing code
New JAVA commandsNew JAVA commands
mouseIsPressedmouseIsPressed
If (mouseIsPressed) {If (mouseIsPressed) {
ellipse (mouseX, position, 50, 50);ellipse (mouseX, position, 50, 50);
}}
Random (0 ,1) generates a number Random (0 ,1) generates a number between 0 and 1 to three decimal placesbetween 0 and 1 to three decimal places
New JAVA commandsNew JAVA commands
Round (0.2314) will round to 0Round (0.2314) will round to 0 Round (0.7341) will round to 1Round (0.7341) will round to 1
OperatorsOperators
OperatorOperator MeaningMeaning True True expressionsexpressions
====== Strict equalityStrict equality myAge === 53myAge === 53
!==!== Strict inequalityStrict inequality myAge !== 52myAge !== 52
>> Greater thanGreater than myAge > 21myAge > 21
>=>= Greater than or equalGreater than or equal myAge >= 53myAge >= 53
<< Less thanLess than myAge < 55myAge < 55
<=<= Less than or equalLess than or equal myAge <= 53myAge <= 53
Difference between = and ===Difference between = and ===
A single = assigns a value to a variableA single = assigns a value to a variablevar myAge = 56var myAge = 56
=== checks for equality === checks for equality If (myAge === 53){If (myAge === 53){
}}
Logical operatorsLogical operators
&& means AND&& means AND || means OR|| means OR
Sometimes called pipesSometimes called pipes Located below the backspace keyLocated below the backspace key If not on your keyboard, use shift +\If not on your keyboard, use shift +\
LoopingLooping
While loopsWhile loops
For loopsFor loops
Nested loopsNested loops
While loop exampleWhile loop example
fill(120, 9, 148);fill(120, 9, 148);var message = "Loops are REALLY var message = "Loops are REALLY
awesome!???";awesome!???";var y = 40;var y = 40;while (y < 400) { while (y < 400) { text(message, 30, y); text(message, 30, y); y += 20;y += 20;}}
Loop questionsLoop questions
1.1. What do I want to repeat?What do I want to repeat?The text function with the message!The text function with the message!
2.2. What do I want to change each time? -What do I want to change each time? -The y position, increasing by 20 each The y position, increasing by 20 each time. time.
3.3. How long should we repeat? How long should we repeat? 1.1. As long as y is less than 400As long as y is less than 400
Repetitive codeRepetitive code
Ask yourself if you can use a loop when you Ask yourself if you can use a loop when you see code that repeatssee code that repeats
Loops have built in code that tells it to repeat Loops have built in code that tells it to repeat the content of the loop until the condition is the content of the loop until the condition is satisfiedsatisfied
Balloon Hopper programBalloon Hopper program
The command to get the image of HopperThe command to get the image of Hopper
var hopper = getImage("creatures/Hopper-var hopper = getImage("creatures/Hopper-Jumping");Jumping");
image(hopper, 223, 232);image(hopper, 223, 232);
For loopsFor loops
More concise than While loopsMore concise than While loops
Trick used in the example is to comment out Trick used in the example is to comment out the code /* */the code /* */
Format – three parts only use two ;Format – three parts only use two ;// for (start; how long; change)// for (start; how long; change)for ( ; ; ) { }for ( ; ; ) { }
For loop exampleFor loop example
for (var i = 0; i < xPositions.length; i++) for (var i = 0; i < xPositions.length; i++)
{ {
drawWinston(xPositions[i], yPositions[i]);drawWinston(xPositions[i], yPositions[i]);
}}
Nested For loopsNested For loops
A loop within a loopA loop within a loop
Decide what loop controls whatDecide what loop controls what
Inner loop – number of gemsInner loop – number of gems
Outer loop – number of rowsOuter loop – number of rows
Think of any 2-d objects to convert to nested Think of any 2-d objects to convert to nested loopsloops
ArraysArrays
Variable is like a drawerVariable is like a drawer Arrays are like a chest of drawersArrays are like a chest of drawers
Pill case examplePill case example
Format of arrayFormat of array
To create an array, we declare a variable To create an array, we declare a variable like we always do, but then we surround like we always do, but then we surround our list of values with square our list of values with square bracketsbrackets and and separate each value with a comma: separate each value with a comma:
var houseFurniture = [‘chair’, ‘couch’, ‘table’];var houseFurniture = [‘chair’, ‘couch’, ‘table’];
Use Use bracketsbrackets, not parenthesis, not parenthesis
Defining arraysDefining arrays
var myTeachers = [“Cueni", “Mesh", var myTeachers = [“Cueni", “Mesh", “Hamilton"];“Hamilton"];
// myTeachers[1]// myTeachers[1]fill(255, 0, 0);fill(255, 0, 0);text( myFriends[1], 10, 30);text( myFriends[1], 10, 30);
This shows Mesh Why????This shows Mesh Why????Arrays start numbering at 0Arrays start numbering at 0
Length of the arrayLength of the array
myTeachers.length – keeps updating and myTeachers.length – keeps updating and returns the number of elements in the returns the number of elements in the arrayas you add elementsarrayas you add elements
Arrays and loopsArrays and loops
Arrays and loops work really well togetherArrays and loops work really well together
1.1. What do I want to repeat?What do I want to repeat?
2.2. What do I want to change each time? What do I want to change each time?
3.3. How long should we repeat? How long should we repeat?
Can use While or For loopsCan use While or For loops
Arrays and loopsArrays and loops
var myTeachers = [“Cueni", “Mesh", var myTeachers = [“Cueni", “Mesh", “Hamilton", “Vidmar", “Craigo", “Baird"];“Hamilton", “Vidmar", “Craigo", “Baird"];
var teacherNum = 0;var teacherNum = 0;
while(teacherNum < myTeachers.length) while(teacherNum < myTeachers.length) { text(myteachers[teacherNum], 10, { text(myteachers[teacherNum], 10, 30+teacherNum*30); 30+teacherNum*30);
teacherNum++;}teacherNum++;}
Adding values to an arrayAdding values to an array
var xPositions = [100, 200];var xPositions = [100, 200];var draw = function() { var draw = function() { if (mouseIsPressed) if (mouseIsPressed)
{ xPositions.push(mouseX); { xPositions.push(mouseX); }}
Where ever the mouse is clicked, that X Where ever the mouse is clicked, that X value is added or pushed onto the length value is added or pushed onto the length of the array. (Starts with two values)of the array. (Starts with two values)
ObjectsObjects
Create objects if you want to keep track of a Create objects if you want to keep track of a bunch of properties for a single variablebunch of properties for a single variable
var cueniAge = 53;var cueniAge = 53;
var cueniEyes = “brown”;var cueniEyes = “brown”;
var cueniLikes = [“walking”, “sewing”];var cueniLikes = [“walking”, “sewing”];
Identify objectsIdentify objects
var cueni = {var cueni = {age: 53,age: 53,eyes: “brown”,eyes: “brown”,likes: [“walking”, “sewing”],likes: [“walking”, “sewing”],isCool: “false”,isCool: “false”,
};};
Called properties of cueniCalled properties of cueniEach item is called a keyEach item is called a keyKey of age with a value of 53Key of age with a value of 53
To display object valuesTo display object values
text(“Mrs Cueni is “ + cueni.age + “ years text(“Mrs Cueni is “ + cueni.age + “ years old”, 10, 50);old”, 10, 50);
Text(“Mrs. Cueni has “ + cueni.eyes + “ Text(“Mrs. Cueni has “ + cueni.eyes + “ eyes”, 10, 70);eyes”, 10, 70);
Array of ObjectsArray of Objects
myCats is the name of the arraymyCats is the name of the array
The array has two objects: name and ageThe array has two objects: name and age
Cat example Array of objectsCat example Array of objects
var myCats = [ {name: "Lizzie", age: 18}, var myCats = [ {name: "Lizzie", age: 18}, {name: "Daemon", age: 1}];{name: "Daemon", age: 1}];
for (var i = 0; i < myCats.length; i++) for (var i = 0; i < myCats.length; i++)
{ {
var myCat = myCats[i]; var myCat = myCats[i]; println(myCat.name + ' is ' + myCat.age + ' println(myCat.name + ' is ' + myCat.age + ' years old.');years old.');
} }
Object Oriented ProgrammingObject Oriented Programming
Why is it useful?Why is it useful? Many items have the similar properties and object Many items have the similar properties and object
oriented programming allows you to pass and share oriented programming allows you to pass and share the propertiesthe properties
Object literalsObject literals Similar in nature with different propertiesSimilar in nature with different properties
• StudentsStudents NameName AgeAge HeightHeight Eye colorEye color Hair colorHair color
2 Object literals with 2 Object literals with properties and valuesproperties and values
var winstonTeen = { var winstonTeen = {
"nickname": "nickname": "Winsteen","Winsteen",
"age": 15, "age": 15,
"x": 20, "x": 20,
"y": 50"y": 50
};};
var winstonAdult = var winstonAdult = { "nickname": "Mr. { "nickname": "Mr. Winst-a-lot",Winst-a-lot",
"age": 30,"age": 30,
"x": 229,"x": 229,
"y": 50"y": 50
};};
Object types definedObject types defined
Object name starts with capital letter WinstonObject name starts with capital letter Winston
Constructive functionConstructive function
var Winston = function(nickname, age, x, y) var Winston = function(nickname, age, x, y) { this.nickname = nickname;{ this.nickname = nickname;
this.age = age;this.age = age;
this.x = x;this.x = x;
this.y = y;this.y = y;
};};
Object prototypeObject prototype
Property of an object and you can attach Property of an object and you can attach functions or behaviors.functions or behaviors.
Know as a MethodsKnow as a Methods
Programming is scary?Programming is scary?
https://www.youtube.com/watch?https://www.youtube.com/watch?v=wNbeXD2wF1gv=wNbeXD2wF1g