Once you have tried the intro courses you can move to our level 1 courses or jump into our "Intergrated Development Environments" or IDEs, where you can make your own custom games and websites.
Coordinates use a grid system and numbers to find locations easily. Usually, they use a group of numbers that indicate the horizontal and vertical position of a point.
Coordinates are pairs of numbers, like (3,4). They help you find places on a grid.
The first number tells you the horizontal position of a point, it tells to you go across the x axis until you hit the number 3.
The second number tells you the vertical position of a point, it tells to you go down the y axis until you hit the number 4.
Coordinates are used in both mathematics and computer science, (as well as in geography, archeology, criminology, the army, and many other areas). But they are used in different ways.
Math uses an axis with 0, 0 in the middle, and counts across and up. Up from 0 are positive numbers on the y axis and when you count down from 0 you have negative numbers. The same is true for left and right. Left of 0 are negative numbers and right of 0 are positive numbers. The coordinates (0,0) or (3,4) give the location of a point. (shown in the image as the points where 2 lines cross)
Computergrids model a computer screen, which is made up of thousands of little squares called pixels.
You can't have negative pixels, so 0,0 starts in the top left corner of your screen.
When given computer coordinates you count across the x axis from left to right, just like reading a book and then down the y axis. The coordinates (0,0) or (3,4) point to a specific pixel. (shown in the image above as a square)
Imagine the above example is very [[zoomed in- pixels are tiny]]
The CA course Food Frenzy→ uses a grid to place game objects. You can change the numbers in the coordinates to change the location of the object.
We usually label the horizontalaxisx and the verticalaxisy but it can really be called anything, those are just the traditional labels
Concepts
1.2: Uses for coordinates
5 min
Coordinates on a grid are really useful for mapping. It makes it easy to share directions, find out the distance of one place to another and decide how to use space.
GPS
A really large scale use of coordinates is the G.P.S, or global positioning system. GPS uses a triangulation of satellites to find your location and then overlays it onto a world-wide grid using longitude and latitude coordinates.
The world is broken into 360 slices vertically (north to south pole) and 180 rings horizontally (equator).
Each degree can be broken into 60 minutes ('). Each minute can be divided into 60 seconds (''). The Code Avengers head-quarters in New Zealand has the coordinates (37° 47' 39.60'' S, 175° 13' 59.08'' E), which is 37 degrees, 47 minutes and 39.60 seconds south of the equator and 175 degrees, 13 minutes and 59.08 seconds east of Greenwich, England. These coordinates are long and complicated, lets look at an easier example on a smaller scale.
Treasure hunt
On a much smaller scale, treasure hunts and scientific digs use grids and coordinates to track their findings.
You create your own grid of squares over a section of land .
We have a treasure hunt for buried coins on the beach.
We have a map with the treasure marked but we can't be sure where we have it buried. If we make a grid on the beach out of string and draw a matching grid on our map. Suddenly, it becomes much easier to use our map to find the hidden coins.
Activity
1.3: Drawing graphics back to back activity
20 min
This is a drawing activity on paper that is done in pairs. Learn about coordinates, grids, and being how those techniques help you to be precise. This activity is suitable for 8 year olds and up.
Objective
This pair-activity helps students to learn to give and follow precise instructions in order to draw simple graphics and demonstrate the precision of coordinates.
Background
All complex computer graphics start with instructing the computer to draw basic shapes at precise locations.
Coordinates
Learners should use coordinates to help them explain how to draw the pictures.
Coordinates are pairs of numbers, like (3,4). They help you find places on a grid.
The first number tells you the horizontal position of a point, it tells to you go across the x axis until you hit the number 3.
The second number tells you the vertical position of a point, it tells to you go down the y axis until you hit the number 4.
Below you can see the position of the coordinates (3,4).
Preparation
Print off enough worksheets for each pair to have a copy.
You can print 2 A4 pages or, to save paper, you can print of 1 A4 page that you will need to cut in half.
All learners, either on a blank piece of paper (with no grids) or online on this blank drawing canvas, will try to draw a simple picture that the instructor will make up and call out.
Example dialog:
In the top left of the page draw a circle,
In the middle of your page draw two squares stacked on top of each other.
Add a bigger triangle on top.
Add a small circle inside the top square, in the top right corner.
Draw a long rectangle inside the bottom square, attached to the bottom.
Add two lines to the bottom of the bottom square, going off the page.
The instructions create a very simple house
Get learners to compare their results- are they identical? Is everything the same size and in the same place?
If not discuss why not.
Activity:
Players will be in pairs, sitting back to back. They are designated as Player 1 and Player 2.
The instructor begins by explaining that the players are drawing images from instructions and these images have to be accurate.
There will be two rounds.
Round 1: Player 1 will call instructions and Player 2 will draw.
Round 2
Then, Player 2 will call instructions and Player 1 will draw.
Give each pair the two printed templates, a page to each person, making sure that Player 1 and Player 2do not see each others page.
To start, those with "Instruct 1" in the first grid are Player 1 and they will give clear instructions to Player 2 to draw image one.
Example of an instruction...Player 2, in the draw 1 grid, draw shape A in the square (4,0). Draw shape F against the right side of (1,3).'"
Once the pair completes the 1st shape, they can swap roles. (Don't look yet!)
Player 2 describing "Instruct 2" and Player 1 drawing in "Draw 2".
Compare drawings.
Ask questions about what happened and what worked/didn't work.
Was it more accurate than the house drawing in the intro?
Versions:
Easy:Player 1 can tell Player 2 what the picture is of.
Medium: Students can only give instructions, not say what the image is.
Hard: Cut off the shape directory at the bottom of the page and players must describe the shapes along with their sizes and orientations.
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
A tangram is a puzzle that uses small, often brightly colored, wooden blocks to form different shapes. Here we will use coordinates to draw those small block shapes and create a picture.
This worksheet may be completed individually or in pairs and is suitable for ages 9 and up.
Objective
Draw, individually or in pairs, basic shapes by connecting points described by coordinates.
Background
Computers can draw shapes by using coordinates to select the correct pixels to turn off and on.
Coordinates
Coordinates are pairs of numbers, like (5,1). They help you find places on a grid.
The first number tells you the horizontal position of a point, it tells to you go across the x axis until you hit the number 5.
The second number tells you the vertical position of a point, it tells to you go down the y axis until you hit the number 1. (across, down)
In the image you can see the position of the coordinates (1,1),(5,1),(5,5) that have been joined together to form a triangle.
Preparation
These puzzles are available in a print version or online.
Requirements: Worksheet, pencil and ruler or a computer with Internet access
Optional: Colored pencils
This can be an individual or pair exercise.
Instructions
Read the coordinates, mark them on the grid and then join them.
The coordinates will connect to form shapes on the grids.
Read the first coordinate and find it on the grid.
Mark the first coordinate on the first grid with a small dot or x and then do the same to the second coordinate.
Use the ruler to draw line between them.
Mark the next coordinate
Using a ruler, again connect that coordinate to the last one.
Repeat for all coordinates in one shape.
To complete the shape, connect the final coordinate with the first coordinate with a ruled line.
Optional: Draw lightly in pencil and when all shapes are drawn, color the shapes in.
Dialog of first few steps
"Go across the grid to number 5, then go downline 5 until you hit line 1. Make a mark.
Go across the grid to number 9, then go downline 9 until you hit line 5. Make a mark.
Rule a line between the two marks.
Go across the grid to number 5, then go downline 5 until you hit line 9. Make a mark.
Rule a line between the (9,5) and (5,9)."
Variation
Easy: Let players refer to the answer sheet
Medium: Tell players the rough shapes they are drawing, or let them see the answers before drawing.
Hard: Give no hint to the answer as players work through the instructions
Note: Only teachers have access to the answers so make your own copy to share with the class to give them access.
Here is a practice project to prepare for the next lesson on sequences.
Extension: Activity
1.7: Battleships
10 min
If you have done everything else and want to practice using coordinates, here is a battleships game you could play. Battleship game
The game, Battleships uses coordinates to communicate where players are firing their shells. See the battleship game here.
You can see how the ships align to the grid. To play you call a set of coordinates to check if your opponent has ships there. (D,5) means you go across to the column D and then down to row 5.
60 min
2: Sequences
Sequences are lists that are in order. Things in a sequence have to be done one before the other in steps. Recipes are a good example of sequence.
vocabalertcommentnewlinesequence
prerequisitescoordinates
Activity
2.1: Robot Cup Stacking
20 min
This is a fun physical team activity. This is suitable for ages 5 to 15 and is best in groups of 2 to 4.
Objective
Learn how to give precise instructions to make a robot/computer complete a task.
Background
Computers require clear exact instructions in the correct sequence to complete even simple tasks.
Sequences
A sequence is just a fancy name for a list that must be followed in order.
The computer needs to be told what to do in precise order.
Every step needs to be carefully written and in the proper order.
The most common example of sequence is writing a recipe.
In a recipe you complete each instruction before moving onto the next one and changing the order may change the results.
For example, you will have a very different cake if you added egg to the cake after baking it, instead of before baking it.
Preparation
Split your group into two or more teams.
Each team needs two or more people in it (max 8 but less is better)
Each team will need:
10 or 15 plastic or paper cups,
a flat surface (table is good) and
a blindfold
Instructions
Split your group into two or more teams.
Each team needs two or more people in it (max 8 but less is better).
Place the cups face down on the table.
A blindfolded team member takes the role of the robot.
The other team members take turns to instruct the "robot" to move one cup at a time, with the goal of stacking all 10 or 15 cups in a pyramid.
Versions:
Easy: Stack 10 cups
Medium: Stack 15 cups
Hard: Stack 15 cups and have one person in the team give good advice and others give bad advice. This makes it more of a trust exercise than an algorithmic one.
With a few teams it can become a challenging race.
Stack 10 cupsStack 15 cups!
Variation- Maze
This is an more active version of the game, and can be turned into a trust exercise if you wish.
Use furniture and objects around you to create a maze that the blind folded robots have to navigate.
The team members could write the code (instructions) before hand, test the code (run the robot through the maze) and then debug (fix anything that didn't work well)
The learning intention here is that basic code is run in a sequence and that you need to test and correct your code for it to work properly.
Concepts
2.2: Sequences
5 min
A sequence is just a fancy name for a list of instructions that must be followed in order.
Sequence is one of the three basic logic structures in computer programming. The other two logic structures are selection and loop.
Here is a very basic rundown of the three, you will learn more about each logic structure later:
sequences happen in order; each line of code is executed in order, starting at the top of the page and ending at the bottom.
selections will run one bit of code if it meets the required conditions (For example, while driving if the traffic light is green you go, otherwise you stop)
loops (or iterations) repeat their code over and over again
Activity
2.3: Write a sequence list
5 min
Let's practice writing a sequence.
How did you get ready for your day today?
Write a list that covers your first few hours of a standard morning for you.
Start with waking up and use about 8 steps
Example list of my morning sequence
Woke up
Got out of bed
Made bed
Had a shower
Put on clothes
Made breakfast
Ate breakfast
Made lunch
Packed bag
Walked to work.
The most basic way to do things in coding is in sequence, one thing after the other, however the order is important. You can't skip steps or mix them up and still get the same result. If you want to message someone and say hello with their name, we have to first ask their name, store it and send it out. You can't send out a message with their name if you don't have the name stored.
2.4: Alert—alert(''), new-line—\n and commenting—//
5 min
Alert
An alert is a JavaScript command that pops open a box with a message in it.
alert('Hello everyone')
It is usually used to give the user a reply or some information.
Messages always need to be in quote marks to make them strings of text.
" " or ' '
Commenting
//, two of these forward-slashes will create a comment in the code that won't show on your webpage. The computer will ignore them so use them to label and leave messages for yourself and for other coders who might use your code, or to block out (hide) code you don't want the computer to run but that you don't want to delete either. You can use /* and */ together to comment out (hide) code as well. /*hidden code*///This is a comment, used to explain code to other programmers //a pop up to greet people alert("Hello everyone,") /*Don't delete, I will add this code in later var time = 5 alert('The time is' + time)*/ alert("Welcome to the zone.")
Text on multiple lines \nnewline
When we are writing in code hitting ENTER does not make text start on a new line.
So if you want to start a new line you have to use \n (backslash not forward-slash).
Keyboards
There are two types of keyboards with the Latin Alphabet that you might have; a US (American) keyboard or a UK (British) keyboard.
They have similar characters and symbols but they have a slightly different layout.
Below we have highlights where to find the forward / and backward
\
slashes.
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Computers needs to be told what to do with clear, step-by-step instructions.
In JavaScript, we give our instructions sensible names like MoveForward() instead of something like DoTheThing(), which would confuse anyone else looking at your code.
We are trying to move a robot down a path. It will only move one slab at a time. We have created some commands for it, it can move forward() and move backward() and turn 90 degrees right() or turn 90 degrees left().
We have to tell the robot we want it to move by calling it by name. We say "robot, move forward" or robot.forward()
In the brackets we can repeat the instructions.
So if we want to go forward 3 squares we can write:
MoveForward() MoveForward() MoveForward()
OR, more simply, we can write:
MoveForward(3)
We have a robot challenge below that is a lot of fun. The objective is to write instructions to the robot to move it to the red square. The more efficient the code the better, that means try to take the best path.
My code won't work elsewhere?
You can't just jump on any code editor and type in robot.forward() and expect a robot to appear and move forward.
We have a bit of code in the background that sets the robot up for us so that you can learn the fun basics first.
We will explain more about how you can make the code yourself in the later courses, when you have learned a little more.
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Variables are items in your code that hold information.
Think of a variable as a box that can store information.
Your computer can store millions of these boxes, or variables, in it's memory.
Each box can store lots of different types of information, such as text and numbers. This information, or
data
, can be changed/updated/deleted and this makes variables very flexible.
Declaring and assigning variables
To make or declare a variable, it needs a name (a label on the box) and it is assigned (=) a value (what is in the box).
You also need to use the keywordvar the first time you use the variable.
//We declare that the variable named "age" exists var age; //We assign it the number 14 var age =14; //Let's declare a second variable named "name" and assign it the string of text "Fred" var name ="Fred";
Reusing variables
Once a variable has been declared and assigned we can use the name over and over again.
var age =3;
alert("My age is "+ age);
alert (age + age + age);
age +=2;
alert("In two years my age will be "+ age);
var doubleAge = age + age;
alert(doubleAge);
In our code above we have written only two numbers but here are the alerts we have made:
Alert 1: My age is 3
Alert 2: 9
Alert 3: In two years my age will be 5
Alert 4: 10
What has happened?
The above code creates a variable called age and assigns it the number 3.
Then it pops up an alert displaying the variable, "My age is 3".
Another alert shows the added up the value of the three ages, 9.
We change the variable to the variable + 2
And display the new value that is in the variable, (age is holding the number 5 now).
Finally, we have declared a new variable, which is double the variable age
(doubleAge is holding the number 10).
But what do we use variables for?
We use variables to make our program easy to modify in the future.
(Especially when the same number is used to mean different things.)
It makes your program easier to read than having numbers everywhere.
Here are some examples of how we use variables:
We use them to store answers to questions we ask our users.
var age = prompt("How old are you?");
We use them in equations,
age*2;
We can use them as counters that go up by one each time the program is run (more on this and loops in JavaScript level 1)
age ++;
We can even use them to write interactive poetry and stories
var red = prompt('Name something red, (in plural)'); var blue = prompt('Name something blue, (in plural)'); alert(red +" are red, \n" blue +" are blue,\n you wrote this poem,\n just for you");
An example of easy modification;
It is better to write equations using variables because you can easily change them. For example, if you are writing a program to find the area of a rectangle it would be better to write:
var width =40 var length =56 var area = width * length alert("The area is "+ area +"m sq")
than
var area =40*56 alert("The area is "+ area +"m sq")
It may seem like more work but it is much tidier. Also, as your code becomes more complex you might use width in a lot of places. When you use a value instead of a variable, that is called hard-coding and can be a lot of work. If you use a number like 40 in all the places you are using width instead of using a variable, it can be very annoying to go back and change when you find out that the width was actually 36.9, or you want to use the same program for finding the area of a different rectangle and you have to change your whole program. In the first example you can just change the number once and it will work fine.
Concepts
3.3: Naming variables
5 min
Each programming language you learn will have it's own conventions for naming variables. All variables should be long enough to be descriptive and not have any spaces. Most languages do not let you start with numbers or symbols, except $ and _. There are some words that you can't use because they are reserved, like the keywords that we use in JavaScript.
Some examples of illegal names in JavaScript:
varvar
var#time
var alert
var91210
var*hi*
JavaScript uses lowerCamelCase to name variables. This means that the first word is in lowercase, then if you have more words you capitalize the following words to make it easy to read, (remember you are not allowed spaces). lowerCamelCase is called that because the capitalization looks like a camel's humped back.
Here are some examples of lowerCamelCase
(Sometimes just called camelCase or mixedCase)
var lastName =
var thisIsTheRealLife =
var gameOfThrones =
var codeAvengers =
There are many other ways of writing names but below are three other common ways.
UpperCamelCamel, where all the words are run together and capitalised:
(LastNameThisIsTheRealLifeGameOfThronesCodeAvengers)
lower_case_with_underscores, where everything is lower case and words are separated with underscores instead of spaces:
(last_namethis_is_the_real_lifegame_of_thronescode_avengers)
Python conventionally prefers this way for writing basic variable names.
Python conventions: Variable names can use letters, digits (0-9), underscore (_) and $. The 1st character in a variable name can't be a digit. Also variable names can't contain spaces.
ALL_UPPER_CASE_WITH_UNDERSCORES, where all letters are capitalized and the words broken up by underscore.
(PIADULT_AGEFINGERS_ON_2_HANDS)
Constants are written like this.
Note
You can actually name your variable anyway you want.
But you should start it with a letter or underscore, _, not a number or symbol. Avoid using lowercase o,l, (oh, el), numbers zero, one, (0,1), or uppercase I (iy) to start names, as they are easily confused.
You don't have to use all lowercase or CamelCase. But it is good practice to follow the conventions of the programming language you are learning.
A
convention
is "the way it is done." For example, grading students work at school is conventionally done in red or green pen.
Be consistent, pick one way of naming variables and use only that way.
Concepts
3.4: Datatypes and how to convert them (extra content)
5 min
Variables can hold a lot of different types of data.
In programming, data types is an important concept.
To be able to use variables properly, it is important to know something about the type of data that is inside the variable.
datatype
The type of data (string, int, float etc.) that is stored in a variable e.g. for name ="Tomais" the datatype of name is string.
Common types of data
Explanation
Example
string
This represents text (including spaces, symbols and even numbers). Strings are enclosed in quotation marks " " or ' '
var text ="Strings4life" or var text ='Strings for the masses, #2all'
boolean
A boolean variable can only have two value: true or false
var lightOn =true; or var lightOn =false;
number
These are numbers, (surprise!), they can be written with or without decimals.
var year =1920 or var money =32.00
There are other datatypes that you will learn about later.
In Python, a decimal is called a
floating point
datatype (float), 3.00, and a whole number is called an integer (int),3.
When you ask for an input, they are automatically strings.
We can see that by testing the output var test = prompt('Enter a number')//2 console.log(test +3)//will output 23 console.log(2+3)// will output 5
You can practise this with JavaScript 1.9 Joining Strings And Numbers With +
String to number
To make sure we have the number datatype we add Number() around the prompt (or around variable we want to use as a number)
var test =Number(prompt('Enter a number'));//2 console.log(test +3);// will output 5 console.log(2+3);// will output 5
If you run a prompt and the user clicks cancel the variable is set to null: a special value that means nothing or no value.
The code if (variable == null) checks if the user clicked cancel. No quotes are needed around null.
var test = prompt("What is your favourite number?") if(test ==null){//Don't want to use while so that people can escape the program when they click cancel. test = prompt("Please answer: What is your favourite number?") if(test ==null){ console.log("You cancelled the question")//Display a error message } }
If the user enters a string that can't be a number- "one", "tree", "$2" etc it will output NaN (Not a number)
var test =Number(prompt('Enter a number'));//$2 console.log(test +3);// will output NaN console.log(2+3);// will output 5
How to loop isNan() to stop non-numbers coming through
In a program when you want a number inputted you can create a loop to repeat the question until a valid number is put in.
var test =Number(prompt('Enter a number'))//Two while(isNaN(test)){//while loop will keep going until test is a number and not a "NaN" test =Number(prompt('Sorry that was not a number\n Please enter a number'))//Will repeat until a number is added, I.E. 2 } console.log(test +3)//will output 5 console.log(2+3)//will output 5
Remember that isNaN(null) and isNaN('') are all false, because null and '' are automatically converted to the number 0.
Boolean to number
Booleans can also be turned into numbers
var boolean =Number(true); console.log(boolean)//will output 1var boolean =false; console.log(Number(boolean));//will output 0
Number to string
Adding a number to a string will turn it into a string.
var test = prompt('Enter a number')//2 (string) console.log(test +3)//will output 23 (string) console.log(2+3)// will output 5 (number)
The toString() also method converts a number to a string. You can even choose the counting system you want (choose between 2 and 36).
var test =13; console.log(test.toString());//"13" in decimal (default) console.log(test.toString(2));//"1101" in binary console.log(test.toString(16));//d in hexadecimal
Number Systems: 10, 2 and 16
The number systems we often use are 10, 2 and 16.
Decimal (10) is the counting system you learned at school.
You can count up to ten numbers before adding a new digit.
Nine has 1 digit (9).
Ten has 2 digits (1 and 0).
One hundred and thirty four has 3 digits (1, 3 and 4)
binary
From the base 2 number system this uses only 0 and 1 to represent data.
Zero has 1 digit (0),
One has 1 digit (1),
Two and 2 digits (1 and 0),
Three has 2 digits (1 and 2)
Four has 3 digits (100)
One hundred and thirty four has 8 digits (1,0,0,0,0,1,1, and 0)
hexadecimal
A number system that counts to 16 in one digit- 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f.
We can use this to set colors. The parameters are #RRGGBB, with each letter being replaced by a 0-F.
For example color:#FFFFFF is white, #FF0000 is red and turquoise is #40E0D0
Two has 1 digit (2)
Nine has 1 digit (9)
Thirteen has 1 digit (d)
Sixteen has 2 digits (1 and 0)
One hundred and thirty four has 2 digits (8 and 6)
Table of examples
Number
Binary
Decimal
Hexadecimal
base 2 - 01
base 10 - 0123456789
base 16 0123456789abcdef
Zero
0
0
0
One
1
1
1
Two
10
2
2
Three
11
3
3
Four
100
4
4
Nine
1001
9
9
Ten
1010
10
a
Thirteen
1101
13
d
Fifteen
1111
15
f
Sixteen
10000
16
10
Twenty three
10111
23
17
One hundred and thirty four
10000110
134
86
Concepts
3.5: Constants
5 min
Constant variables are variables that we label differently to show that they don't change, their value is constant.
Some real world examples of constants are Pi (ratio of a circle), C (the speed of light) , or the Golden Ratio (a 'perfect' way to divide things).
Here, constants are just variables that won't change in our program.
Let's say we are writing a program to calculate how much money a person has to spend on things. There are lots of variables: food costs will vary, fuel costs will vary, power costs will vary. But BASE_INCOME and RENT will be constant week to week.
We often show this by naming it differently to normal variables. We use UPPERCASE_UNDERSCORE traditionally to name constants.
var HOURS_IN_A_DAY =24
var MONTHS_IN_A_YEAR =12
var SECOND_IN_A_MINUTE =60
var DOZEN =12
var PAIR =2
var PI =3.14159265359
Example of constants in a program
Let's use our money example from above, written as code.
//all variables are in dollars per week
var BASE_INCOME =300;
var extraIncome =15;
var fuel =70;
var food =50;
//keyword name = value
var RENT =100;
var income = BASE_INCOME + extraIncome;
var costs = RENT + fuel + food;
var spendingMoney = income - costs;
alert("You have $"+ spendingMoney);
Concepts
3.6: Substitution age = whatever
5 min
#piano-f-sharpVariables use what is called [[substitution], i.e., we can substitute a short name in the place of a really long number or message.
You have seen some examples above of how variables work but if you are still not sure how the variable age could hold different information at different times like, the age of a person or the lyrics to "Somewhere over the Rainbow" or even a complex equation. Remember that age is just the name or label of our variable box, and we can put anything we want into the box.
We actually use variables and substitution all the time in real life.
Lets look at this symbol #, called a hash or pound key.
This symbol can stand for a few things. See if you can read the sentences below aloud:
"We're #1, We're #1"
"When writing pounds, some USA businesses use 300lb and some use 300#."
"The next note we play on the piano is an F#"
"Have you seen Twitter? #viralwaytowritethis"
How many did you know?
Here we can see that the hash symbol can be substituted for the words number, pounds, sharp or used to mark a hash-tag.
//# is actually an illegal symbol to use in a name in JavaScript, but just pretend.
var#="number";
alert("We're "+#+" 1, We're "+#+" 1");
#="pounds";
alert("When writing down weights, some USA businesses use 300lb and some use 300"+#);
#="sharp";
alert("The next note we play on the piano is an F"+#);
#="hash-tag:";
alert("Have you seen Twitter? "+#+"viralwaytowritethis"
In exactly the same way as the # can mean a different thing in each context, a variable named age can mean whatever we assign to it.
var age =12; alert("You are"+ age); age ="cheese"; alert("Old milk is"+ age); age ="bronze"; alert("The"+ age +"age began when humans started to mix tin and copper together.");
Activity
3.7: Silent Varia-ball
20 min
This is a physical game played in a group and is a variation on the game Silent Ball.
Objective
The aim of this physical activity is to practice the concept that variables are simply named boxes that hold information, and that this information can be changed.
Background
Variable are great, they make it very easy to personalize messages, change calculations and they are a big part of what makes a program work and be interactive.
We can ask the user for an input, save their answer in a variable, and then print the variable, giving a personalized message output.
In the examples below we have created a variable by writing a name. We have assigned, (=), it the answer to the question "What is your favorite color?". Then we add the answer variable to our own string, creating a message that the user can see.
In JavaScript a variable looks like this:
In Python a variable looks like this:
var favColor = prompt("What is your favorite color?") alert(faveColor +"? Oh, that's cool")
fave_color = input("What is your favorite color?") print("{} ? Oh, that's cool".format(fave_color))
User input = Blue → output: "Blue? Oh, that's cool"
Preparation
Requires:
A ball (or other throw-able object i.e. pencil case)
Sturdy chairs for standing on. (If no sturdy chairs are available have players stand in an unbalanced way i.e. on one foot.)
Basic Game Instructions
Silent ball is a game where players stand on their chairs (NOT swivel computer chairs!) and silently pass a ball to each other.
The game should naturally get faster as they proceed.
Each individual plays until they are out, then they sit down and watch the others compete.
Players are out of the game if they:
Miss catching a throw (Drop the ball),
Lose their balance,
Fail to follow commands,
Speak (unless that is part the challenge).
The leader adds in commands to make the game more difficult. Players must follow that command until another command is given.
Example commands:
"Catch the ball one-handed"
"Raise one hand above your head"
"Stand on one foot"
"Call the name if the person you are throwing to"
"Stand on one foot, close one eye and when you catch the ball say 'arrr'"
The winner is the last one standing.
Varia-ball Variation:
All leader commands are written as variables on the board.
Ideas:
x = clap before catching the ball,
b = stand on one leg,
a = keep one eye closed
c = hot potato (you have to throw the ball as soon as you catch it because it is 'hot!')
Example commands:
"Do X." -players must clap before catching the ball,
"Now you have to do x and b.", -players clap and stand on one leg
"Now try only c."- players must throw the ball as soon as they catch it.
Change the variables occasionally to show that they can change.
x = click fingers before catching the ball.
You want the game to go quickly so that people can join back in.
Concepts
3.8: Concatenation—joining messages
5 min
As you can see from our previous examples, you can join numbers and sentences and variables. We use a + to join them. This is called concatenating, a technical word for linking together in a chain or series.
Below let's link, or concatenate, two lines of a poem
var line1 ="Roses are red, "
var line2 ="Violets are blue, "
alert (line1 + line2)
Roses are red,Violets are blue,
Adding +"\n" will break up the lines (remember newline works in a string).
alert (line1 +"\n"+ line2)
The best part of concatenating variables is that we can change the message easily, without changing the whole programme.
var line1 ="Carrots are orange, "
var line2 ="Spinach is green, "
alert (line1 +"\n"+ line2)
Concepts
3.9: Prompt
5 min
Example of prompt code: prompt('What is your age?')
The prompt code opens a box similar to an alert, the difference is that a prompt asks for input from the user (it has a place that users can write in).
We can use prompt code to ask questions for the quiz.
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
If statements are sections of code that run only when certain conditions are met.
vocabconditionelsefalsetrue
prerequisitespromptsvariables
Activity
4.1: Ada Says
20 min
This is a group activity that is a variation on the game Simon Says→.
All the code below is pseudocode unless otherwise stated.
This is appropriate for ages 5+ and up.
Who is Ada?
Ada Lovelace was born over 200 years ago into the nobility of England. Her father, Lord Byron, was a famous celebrity poet with an unstable lifestyle and her mother raised her as a mathematician to try to make sure Ada would not be like her father. Her life is a very interesting one, involving scandals, successes and a sharp intelligence. She is most famous for her friendship and collaborations with Charles Babbage. She died young at the age of 36 of cancer.
Image: The plans for Babbage's Difference Engine
In 1822, a man named Charles Babbage created the plan for a calculator, a very clever and complicated machine called the Difference Engine→.
Despite being a very valuable tool for a range of disciplines that used hand written mathematical tables, it was never complete. This was because it cost too much, the technology of the current materials were not precise enough and Babbage lost focus and began to work on the Analytical Engine, which also didn't get built.
But his plans have made him hailed as the "Father of computers".
He gave a seminar, which was recorded in French. A friend of Babbage asked Ada to translate the recording. She did and added her own notes to the paper that was later published. In her notes she theorised that computers could do more than just calculate numbers and wrote the first algorithm for Babbages' Analytical Engine to calculate a sequence of Bernoulli numbers→
If you want to know a little more read our CA blog→ about Ada
You can also celebrate the women in STEM whose work you admire or discuss research into equality and diversity on Ada Lovelace day.
Ada Lovelace Day is held every year on the second Tuesday of October. If you want to know more check out http://findingada.com/→
Objective
The aim of this activity is to practice if statements and encourage activity and movement.
The goal of the game is to correctly act out what the robots would do when instructions are given
Background
Basic code is run one line after the other in a sequence.
But sometimes we don't want a line of code to run all the time, only at certain times.
We can use if statements to easily do this by saying "only if this is true run this code".
A brief rundown on if statements
If statements are an example of conditional coding.
if(the condition written in here is true){ run this code; }
The statements written inside the curly braces are only selected to run if the condition (the bit in the brackets) is true. If the condition is false we don't run the code.
The program checks if the condition is true or false. If it is true then the program will run the code.
if(light is off and it is dark){ turn on light; }
Here is a real code example for part of a simple guessing game:
JavaScript
Python
var guess = prompt('Can you guess the number from 1 to 5?:');
if(guess ==3){ alert('You guessed right!'); }
guess =int(input("Can you guess the number from 1 to 5?:"))
if guess ==3: print ("You guessed right")
else if and else:
elif and else:
var guess = prompt('Can you guess the number from 1 to 5?:');
if(guess ==3){ alert('You guessed right!'); }elseif(guess <3){ alert('Sorry, it is a higher number!'); }else{ alert('Sorry, it is a lower number!'); }
guess =int(input("Can you guess the number from 1 to 5?:"))
if guess ==3: print ("You guessed right") elif guess <3: print ("Sorry, it is a higher number!") else: print("Sorry, it's a lower number!")
Above you can see that you can add else if to add more conditions and add else to run something if the conditions are false.
Preparation
You will need:
A writing place that all participants can see, like a whiteboard, to write instructions.
Marker pen and eraser.
A little bit of space around the players for them to move.
Write on board:
if("Ada Says" is said){ then follow the instructions } else{ stay still }
Instructions
The group stands up with a little space for each to move around. The players are robots that have if statements in their programming.
The instructor is Ada Lovelace, the author of the first computer program.
Ada gives spoken commands for the robots to follow.
A command starting with the phrase: "Ada says", must be followed.
A command without the phrase: "Ada says", should not be performed.
Anyone who breaks one of these two rules is out of the game.
Ada can issue her commands faster or be repetitive to make the game harder.
Example Dialouge
Ada: "Ada says Arms up."
#Robots put arms up
Ada: "Ada says Arms down."
#Robots puts arms down
Ada: "Arms up."
#Robots remain still-Arms should remain down
Anyone who moves to put their arms up is out, because "Ada says" was not said.
Easy: Play this basic version of the game.
Medium: Add one of the following variations: "Else if statements" or "Embedded if statements" or ""Ada invariably says"
Hard: Add ALL the variations together in a Spaghetti Code
Elimination recap:
Do the new action when "Ada says" was not said,
Do not do the new action when "Ada says" was said,
If they get the action wrong E.G. "Ada says: raise your right hand" and they raise their left.
The winner is the last robot standing or Ada, if all players are out.
Variations:
1. Else if statements
You can add more if statements or else if statements to make this harder.
if(Ada says){ follow instruction; }
elseif(Turing says){ do the opposite of the instruction (raise left hand, crouch rather than jump, spin in opposite direction); } else{ stay still; }
Alan Turing (23 June 1912 – 7 June 1954)
Alan Turing was a genius mathematician and theoretical computer scientist also born in England, his work was published in 1938 over 100 years after Ada's. He is most famous for his work decrypting the Enigma Code as an intelligence agent in WW2, for being persecuted as a homosexual and for creating the simple but effective
Turing Test
to gauge AI intelligence. "He was highly influential in the development of theoretical computer science, providing a formalisation of the concepts of algorithm and computation with the Turing machine, which can be considered a model of a general purpose computer. Turing is widely considered to be the father of theoretical computer science and artificial intelligence." Read more about his life on wikipedia→
2. Embedded if statements
Add conditions based on the people playing
if(Ada says){ if(you are condition){ dothis; }else{ spin clockwise; } } else{ stay still }
So "Ada say" is said and based on your condition follow either direction.
Ada: "Ada says if you are a boy jump"
#Boys jump Others spin clockwise
Ada:"Ada says wave hand"
#Robots spin clockwise
Ada: "Ada says if your elbows are showing clap"
#Elbow baring robots clap, Other robots spin clockwise"
Ada:Spinclock wise
#Robots stay still
People who are out can help call out others.
3. "Ada invariably says"
Write some variables on the board.
For example:
var x = clap
var b = stand on one foot
var 1 = jump
var 2 = crouch
and play "Ada Says"
Ada will call out variables rather than (or as well as) full instructions:
Ada: "Ada says x"
#Robots clap
Ada:"Ada says wave hand"
#Robots wave
Ada: "Change to B"
#One robot stands on one foot and is out because Ada didn't say "Ada says."
Spaghetti Code Variation (HARDCORE MODE)
Spaghetti code:
Spaghetti code is a phrase for awful source code that has a complex and tangled structure, like a bowl of spaghetti. The code below is not really spaghetti code...but it is confusing so concentrate hard!
Throw together all the variations written above to create the most complicated game of "Simon says" ever played!
Write this (or something like this) on the board:
var a = jump (opposite is crouch) var b = clap (opposite is stomp) var c = raise right hand (opposite is raise left hand)
var1= right foot (stand on right foot only (opposite stand on left foot only)) var2= spin clockwise (opposite spin anticlockwise) var3= pat head, rub circles on stomach (opposite rub circles on head pat stomach)
if(Ada says a letter){ if(you are wearing glasses){ do variable letterCalled; }else{ "b"; } } elseif(Turing says { do opposite of action; } else{ remain still; }
Whoa, that is a lot. And you can change it up as you like by replacing variables. You can even change the final else from "remain still" to clap or something.
Ada: "Turing says stand on right foot"
#Robots stand on left leg"
Ada: "Turada says jump"
#Robots remain still
Concepts
4.2: If statements—if(true){}
5 min
Every day we make decisions right from the moment our alarm goes off... for example one of the first decisions you make might look like this:
wake up get out of bed
if(i am hungry){ eat breakfast }
have a shower
An if statement is a bit of code that has the following format (syntax):
if(condition){ statements; }
Let's break down the syntax:
A statement is a just a line of code. Here are 3 examples of statements that you have used;
var tree ="Oak";
alert(4+3);
var day = prompt{"What day of the month is it?";
.
If we have the statements written normally in code, they will be run in sequence, one line after the other. But the statements written inside the curly braces are only selected to run if the condition (the bit in the brackets) is true. If the condition is false we don't run the code.
The rule is
if(this condition) is truedo{the stuff in curly braces}
A condition is a fancy word for what thing is the program checking. The program checks if the condition is
true
or
false
. If it is true then the program will run the code.
if(light is off and it is dark){ turn on light; }
Conditions—a computing example
Let's use an example of guess a number game.
var guess = prompt('I have a number in my head between 1 and 5, Can you guess it?');
if(guess ==4){
alert('Correct, you are amazing!');
}
alert('Have a nice day.');
Simple Guess A Number Between Program
This code will run in sequence from Line 1 to Line 5.
A prompt (Line 1) will appear for the user to input their answer (either 2, 3 or 4) and this will be stored in guess.
Unknown to the user, the correct answer is "4" (Line 2).
Based on the inputted answer, the computer proceeds to the if statement to determine whether the code in the curly-braces (encompassing Line 3) should run or not.
If it is TRUE, (which means "4" was inputted), the congratulatory Line 3 alert statement will run followed by the Line 5 alert.
If "4" was not inputted, the computer determines it is FALSE and ignores the Line 3 alert but the Line 5 alert still works because it is outside the if statement.
Concepts
4.3: True and False
5 min
Computers function in a binary or 2 numbered system: 0 or 1, yes or no, true or false, on or off.
Be careful to use conditions that the computer can check as being true or false.
This is because, while humans can deal with conditions that are unclear, robots and computers can only check conditions that are clearly true or false.
Here are some examples of vagueconditions that humans can deal with but a robot would need more information for.
If your hair is too long, cut it. (What is too long?! How much do we cut?)
if(hair more than or equal to 7cm){cut hair to 4cm;} is more specific.
If car is running low on fuel then add more fuel. (How much is low? How much is more? Noo!?)
if(fuel in car is less than 1/16 full){fill to full tank}
If it is bad weather then take a coat. (Er, define bad weather?)
A robot would need something like this: if(it is raining){wear a raincoat}. That is clear, a robot can check if it is raining or it is not.
A typical human would have enough world knowledge to know what sort of bad weather requires a coat.
Robots would need all the forms of bad weather listed in a measurable way.
Bad weather measurements
It is raining
True/False
The wind is above 30 knots
True/False
It below 10° celsius
True/False
In order to give this instruction to a robot you would need to give a precise definition of "bad weather."
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Variables do not always stay as one thing. They can be changed. You can change it by just writing the same variable name with different information.
For example:
You can change the value of a variable.
var tree ="3m tall"; tree ="4m tall";
You can set the value of variable to another variable
var donut =1.40; var totalCost = donut; //totalCost is now storing the value 1.40
You can increase and decrease the value of a variable
var countDown =5; //decrement (decrease by one) countDown --; //decrement (decrease by one) countDown --; //countDown is now storing the value 3var countUp =5; //increment (increase by one) countUp ++; //increment (increase by one) countUp ++; //countUp is now storing the value 7var count =5; count +=4; //(count = count + 4) //count is now storing the value 9
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Warning:There might be a few words below that are new to you. Don't be confused, you probably know exactly what we are talking about. We are just adding some new vocabulary to describe it.
In the simplest terms an
operation
is doing something to a number with another number. (Or other values, see below)
The following arithmetic expression shows an example of operators and
operands
:
4+5=9 //operand operator operand solves to value
In the above example, '+' is the symbol for the
operation
called
addition
.
You need two operand inputs for an addition operation 4 + is not a complete operation.
An operand, then, is also referred to as "one of the inputs for an operation".
Here are the basic arithmeticoperators (or as you may know them, "basic math symbols")
It is important to know how to solve an expression/equation because computers only work with values. A value is a something that can not be solved or simplified further. 4/8 is not a value because it can be simplified to 1/2. 4 - 2 is solved by the computer to give the value of the number 2. Values can be boolean statements like true or false, numbers such as 2.09330, -8 or 4 and single strings, so "The end" could be simplified from "The "+"end"
Multiple operations
The above example has one operation, 4 + 5, you can often have many operations in one expression.
4+5+2+1=12 //3 operations here
In this example we solve the first operation, 4+5, and that answer (the value 9) is then input as the first operand of the second operation
4+5=9...9+2=10...10+1=11
When mathematical and computing
equations
(or expressions) become longer and use different operators, +,/,*,..., we need to know what order we
solve
the operations in
5**6+(4-3)/2*2-2=???
The order in which we solve operations
BEDMAS/PEMDAS/BODMAS/BIDMAS
These famous acronyms are taught in a wide range of schools across the world to remember the order of operations of our basic math equations.
PEMDAS - "Please Excuse My Dear Aunt Sally" [parenthesis, exponents, multiplication, division, addition, subtraction] is one of the memory tricks that are used to remember the order in which we solve operations.
If the order level is the same we solve from left to right, for example, subtract and addition are in the same order so we solve the four operations in 4-3+2+1+5 from left to right. 4-3=1,1+2=3,3+1=4,4+5=9.
But when there are operations that have different orders of importance you have to solve the highest order first. Look at the six operations here 5+4-2*3/2+(4-3), they are in 3 different orders of importance. We first solve the brackets, then the multiplications and divisions, then the additions and subtractions..
//Maths expression full of operators 5+4-2*3/2+(4-3) //operation 1 (4-3)=1 //operation 2 2*3=6 //operation 3 6/2=3 //operation 4 5+4=9 //operation 5, second input is from operation 2 9-3=6 //operation 6, first input is from operation 1 and the second input is from operation 5 6+1=7
Symbol
Name
Example
PEMDAS or BEDMAS
The order in which you do basic mathematical operations:
()
Brackets/Parentheses: Do all operations inside the brackets first
(3+4) x 2=7 x 2=14
x**p
Exponents: Evaluate all powers/orders/indices/exponents (whichever you call them) next
43=4 x 4 x 4=8 x 4=32
/ *
Division / Multiply (from left to right)
3*4/2=12/2=6
- +
Addition/Subtraction (from left to right)
3 + 4 - 2 = 7 - 2 = 5
Remember to perform divisions and multiplication from left to right and then perform addition and subtraction from left to right.
5**3+(4-3)/10*2-2=123.2 5**3+1/10*2-2=123.2 125+1/10*2-2=123.2 125+0.1*2-2=123.2 //left to right 125.2-2=123.2 123.2=123.2
Comparative operators: These are some common operators that compare equations.
Symbol
Name
Example
<
less than
1 < 2
>
greater than
2 > 1
<=
Less than or equal to
1<=2,2<=2
>=
Greater than or equal to
3>=2,2>=2
Complete Computer Science order of operations
Order
Symbols
Names
1
() [] -> . ::
Function call, scope, array/member access
2
! - + * & sizeof type cast ++ --
(most) unary operators, sizeof and type casts (right to left)
Want to build your own apps and games? Start here! With Code Avengers' comprehensive JavaScript courses you'll learn one of the most widely used languages, and build lots of fun apps and games along the way.
Creating games can be really fun and challenging. Many people have a big interest in making and playing games and a lot of money can be made from the gaming industry.
So what is a computer game?
A computer game is interactive. It could be a choose your-own-adventure story, puzzle, quiz or competition (or something else). It might be text-based or have lots of graphics, but what makes a game a game is that it requires input from the player. With computer games this usually is with a keyboard, mouse or controller.
Most video games are made up of objects, background art, audio and sprites. Let's explain those terms by looking at a simple video game, like Pacman.
Here is a link to a Pacman level→ made by Google.
Pacman—a case study in basic game play
Pacman is a game.
Game play description
In this game, the player controls the character Pacman with arrow keys on the keyboard. Pacman eats dots in a maze. Four ghosts wander around the maze and if a ghost hits Pacman then Pacman dies.
Pacman has 3 'lives'. If you eat all the dots you win and move onto a new level, if you die 3 times you lose and the game ends. There are PowerDots that super-charge Pacman turning him into Hunter Pacman. He can destroy the ghosts for a short amount of time, they turn into scared ghosts.
This is a description of how a player might experience the game. But as a game developer you have to learn to break down what you see happening, or want to see happen, to write the code you need to create.
For example "Pacman eating dots" actually has many steps to it.
You have to add code to trigger when a dot and Pacman occupy the same coordinates. That particular Instance of the dot has to vanish, without affecting the other dots. Points have to be added and Pacman must continue moving and animate eating.
Writing code for games requires a shift of thinking from what you see happen to what is actually happening.
"Gravity" is not falling- it is an object moving along vertical coordinates.
Stopping when an object hits something isn't colliding with a mass so they stop- these objects don't have mass (unless you give it to them), it is detecting a collision and setting movement speed to 0.
There is no such thing as ground in games- just code that stops the player object vertically moving at a certain coordinate.
Guns are not shooting. There is code saying when 'space' is hit by the user. Create a object next to gun, moving at this speed in that direction.
Bullets don't kill enemies. The code detects a collision. Destroys the bullet sprite, adds a explosion sprite animation for a few seconds, destroys the explosion sprite. Removes points from health, checks if the enemy is dead (Now enemies are not dead of course- the code checks if the number stored in the variable health is >= 0 and if so it destroys the enemy sprite)
Planning and working out these steps is important, so is testing each bit as you make it as you make it to see that it is working.
The objects are the parts of the game that interact. Their behaviour is run by code.The background image is black with wall objects over top, the audio changes based on what is happening and the sprites are the images you can see of the walls ghosts and pacman. By cycling through the images simple animation can be created.
Concepts
5.2: Spritesheets
5 min
A sprite is a single image. A static object has a single sprite, like a blue line for a wall. An animated object has many sprites attached to it. You cycle through these images very quickly (many times per second) so it looks like Pacman is moving his mouth or the ghosts are wiggling their feet.
A simple animation like Pacman, might have 5 sprites for moving in one direction. We usually use several sprites and change the sprite that gets displayed several times per second.
So remember objects do things(events) and they can "wear" sprites, (so that you can see them on the screen). You put an instance of the object on the screen.
You can save all your sprites onto one sheet that you upload and use at once.
Why don't we split up each image into a single file and load it when we need it?
Because it saves memory and space when you put all the images on one sheet.
It is easier to load a single image file that has all the game sprites that you will be using for a character and only selectively "draw" out the sprites that you require.
Here is an example of the character Zanpto's sprite sheet, created by LSWBeast.
Concepts
5.3: Raster and bitmap images versus vector graphics
5 min
There are two ways to make computer graphics, using bitmap (raster) or vector methods.
Bitmap or raster
The first way to draw an image on the computer is called
bitmap
, this is the one your camera uses. A dense grid of colored dots, called pixels, are created to make a picture.
The result, if you have a lot of pixels in a small grid, is a high quality image with a huge variety in colors.
Always save images to the size that you need them. Very detailed image files are often very large in size and take up a lot of space and memory in your computer. If you have a small image and try to make it big then
pixelation
can occur. Pixelation is when your image gets large blocky outlines and look blurry. This happens because the pixels copy their neighbor's color, making big chunky blocks of color. A good way to remember what bitmap is, is that it is a "map of bits." There are a lot of images with bitmap file types. Some of the most common include: JPEG, PNG, GIF, BMP, and TIFF. We will learn more about file types in the HTML section of this course.
Let's look at a jpeg of our CA icon that is 64x64 pixels
Actual size}
Those numbers mean that the bitmap grid is 64 pixels across and 64 pixels wide and the logo image is made up of 4096 pixels (64*64).
50% of the screen
Now here is it blown up to 50% of the screen.
Do you see the difference in quality? The image is blurring because the new pixels being used by the image are just copying their neighbours color, becoming chunky jagged squares. These squares of color confuse your eyes and destroy the smooth line you expect to see, making it look unfocused.
100 times bigger
We have stretched the icon to 6400X6400 pixels, and it was a bit too big to show you (we saw a lot of black corner). So we cut out the left edge of the C to show you a part of it. Remember, this is a part of an image that has been stretched out 100 times bigger than the original size. Here you can see the squares of color in the bitmap grid. Actually, each square you see is made from 10,000 pixels and is generated from that one pixel of color in the original 64X64 picture.
Vector
The second type of graphic image is called Vector. It uses mathematical equations to
render
(draw) pictures.
It also can be resized without losing quality. But it is not used often for things like screen savers and photographs. Vector images use more processing power than bitmap to render (load/ draw the image), which is only really noticeable when the file size is big, because each image element must be drawn individually and in sequence.
Concepts
5.4: Game design videos
5 min
Your game should be designed around what you can already do, what is fun and challenging for a player and how the game looks and feels to play.
Below are a list of videos from the amazing youtube channel "Extra Credits→".
We could explain what good game designing looks like but they can do it much better. If you want to learn more they have a lot more videos on game design here→
Don't make your SCOPE too big
Make something based on code you mostly already know
Design around your strengths
GOAl: build something playable. Don't worry about the graphics being amazing or the every part being 100% amazing.
Build a SIMPLE game. Text games are easier than Maze games, which are easier than platform games, which are easier than 3rd person shooters.
Build the very basic part of your game before adding in more stuff. For example, The first code you write for Pacman should be to move him, stop him going through walls, collect the dots and end the game when all the dots are collected. The ghosts and the power-up-balls should come after the basics work.
Learn a bit then make from mostly what you have learnt rather then try to build from a concept where you don't know how to do any of the code.
Are you interested in making video games? Learning a programming language is essential. Why don’t you learn while making a game at the same time? Use JavaScript to build a simple 2 player 2D top-down game, where players race to collect coins while avoiding obstacles and enemies!
Depending on time, we recommend working on the first 4 tasks of this project and then completing it later.
Concepts
5.6: JavaScript syntax
5 min
Remember that syntax is not a scary word, it just means the rules we have to use to use a language properly, to make sure it is structured in the right way. How we structure our sentences matters: "dis rreed KAnt i ahs (I can't read this as)... easily as I can read this half of the sentence." because when you learn a language you learn to follow rules that make you understandably to others. Statements in programming are the same. You need to spell keywords correctly, use the correct punctuation and have the word and item order correct for your code to work.
Here is some new big vocab for you:
//Keyword Identifier Operator Value Terminator var lastName ="Khan";
Keywords
Keywords are specific words that trigger code in the program, hopefully the editor will often color them blue.
Some keywords used in the previous sections were alarm, prompt, var and if
Identifiers
Identifiers are the names we give variables (and that we give other things like functions and classes, that you can learn about in the later courses JS level 1 and JS level 2). As we have said above, identifiers (names), must begin with a letter, a $ or an _. No numbers or other symbols are allowed and you can't use reserved words like keywords.
These are all valid identifiers (with the var keyword)
var tim =
var _hi_ =
var $ave =
var a1233 =
var tree =
var thisIsAnIdentifier =
Here are a few invalid or illegal identifiers:
varvar=
var5666=
var#=
varif=
var a&=
var a#=
Operator
Operator is a fancy word for the signs and symbols you use in maths, like +-*/. These work the same in computing as they do in maths, except for =. That is used to assign values to identifiers, == means equals. There are many other operators but you will learn them as you go.
5*2-3+1/2**2+(2+3)==12.25 //"5 times 2 minus 3 plus one divided by 2 to the powers of 2 plus (2 plus 3) equals 12.25" //"5 multiplied by 2 subtracted by 3 increased by 1 divided by 2 to the powers of 2 increase by (2 increase by 3) equals 12.25"
Value
A value is "an expression which cannot be
evaluated
any further". For example, the 1 + 2 is not a value as it can be reduced to 3. Our datatypes are all values, even the string is a value.
But wait, can't we have maths equations assigned to identifiers?
//Keyword Identifier Operator Expression (contains values and operators) Terminator var number =(2+3)*6+(1+8);
What a thoughtful question, well happens here is how the computer SOLVES the expression, turns it into a value and that is what is saved in our variable box.
if it can't solve the equations, like var a =4+, then the code will break.
PaperScript lesson plans (Draw the flags of the world)
Editor
Use the editor to plan your first room.
To find the editor go to the JavaScript IDE (place where you write your own projects). Follow this URL: https://codeavengers.com/javascript/7 or follow these steps:
Here are the tools you need to know:
Open a new file and name it, add .js on the end. eg throwing_game.js
Go to the editor
This is the place to plan your work.
Click and drag the type of object you want onto the grid. Don't worry if they are not the sprites you want for the objects, we can change that later.
After you have made your layout of your first room click show code.
Make a game
After you have made your layout of your first room click show code.
The code for the objects will appear. If you hit run and click inside the pop up box, you can bring up the game and play it as you create it.
Use the reference to find some cool code to add, or if you have forgotten some code.
You can do things like add a score, unlock doors, shoot guns and change sprites.
Reference for Game Making
Click the Reference button in the JavaScript IDE to find example code for different things.
A catalog of images and a small reference list of objects can be found in the activities section in this book.
Play others games
When you are ready to share your game hit the deploy button. Give your game a name and write some instructions or a small introduction on what your game is about.
The game will pop-up so make sure your browser allows pop-ups from Code Avengers
Message someone your code and play theirs.
PaperScript
You can use our JavaScript IDE→ to make, save and share your own digital designs.
Make sure you have //paper 600 600 at the top of your page if you want a nice big canvas to work on.
You can change the size of the canvas by changing the numbers //paper 200 500 for example makes a 200 wide by 500 high box to create on.
Adding 2D graphics to a webpage
If you want to add your images to a normal web page outside of Code Avengers, it will require a little set up.
Code to add images
We have made a Path module'' that is based off the2D JavaScript graphics module'''.
The Code Avengers' code is easier to use because we do all of the set up for you but it only works on code saved on our website.
If you are ready to make graphics in your own website then read the content below.
You first need to learn about HTML <canvas> and linking JS, HTML and the 2D context library.
Then you need to learn how the functions work for 2D, we have some notes and links below that can help you.
<canvasid="drawing"width="250"height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var shape1 = drawing.getContext('2d'); /*Write your drawing code here*/ shape1.fillStyle ='lightBlue'; shape1.strokeStyle='navy'; shape1.fillRect(25,25,50,50); shape1.strokeRect(25,25,50,50); </script>
The tags and JS covered here are <canvas></canvas> and .getContext('2d')
You can draw images and shapes onto a webpage using code instead of uploading an image.
Canvas tag —<canvas></canvas>
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, shapes, text or even do simple (and not so simple) animations.
To get canvas to work is a little tricker than the other tags. The <canvas> element places the drawing window on the page. We added a border in CS so you can see it. But the drawing is written in JavaScript.
<style> #drawing{ border: lightGrey dashed 1px; } </style> <p>The grey border shows the canvas, the red rectangle is created with JavaScript. <canvasid="drawing"width="150"height="100"> HTML5 Canvas isn't working if you see this text. </canvas> <p>Did you know this is a live example? Click on the HTML code box and try your own code. <script> var drawing =document.getElementById('drawing'); var codeForDrawing =drawing.getContext('2d'); codeForDrawing.fillStyle ='lightBlue'; codeForDrawing.fillRect(25,25,50,50); </script>
Adding JavaScript
The 2dinterface is used for drawing circles, rectangles, text and more inside a canvas element. The library called '2d' has all the code context to draw the shapes (written in JavaScript) on the canvas.
So in the code above we have a canvas in HTML but the important stuff is happening in the script element.
Firstly we make a variable that links our canvas to the JavaScript, var drawing = document.getElementById('drawing');.
Then we create a variable to link our JavaScript to the already existing code inside the file called 2d, var codeForDrawing = drawing.getContext('2d');.
Now with those 3 things linked you can draw a lot of different shapes.
All the browsers have access to 2d so you only have to ask for the browser to find it and pull the context out of it. Read a good explanation of context on StackOverFlow by Brian Kelly from 2011.
The canvas/2d/JavaScript linking is all done for you in our intro lessons. Like our fun drawing challenge: CA Flag Drawing Challenge
Drawing shapes
You can draw many things, the basics are lines, rectangles, circles, triangles, half circles and stars. The drawing code is slightly different to what you have learned here at Code Avengers.
See a range of options at W3schools
Rectangle
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvasid="drawing"width="200"height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var rectangle = drawing.getContext('2d'); rectangle.rect(25,25,50,50); rectangle.stroke(); </script>
Lines
Begin a path, move to position 0,0. Create a line to position 300,150:
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvasid="drawing"width="200"height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var line = drawing.getContext('2d');
line.beginPath(); line.lineWidth="5"; line.strokeStyle="navy";/*Draw path*/ line.moveTo(0,45); line.lineTo(150,45); line.stroke();/* Needs stroke function to show drawing*/
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvasid="drawing"width="200"height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var line = drawing.getContext('2d');
line.beginPath(); line.lineWidth="5"; line.strokeStyle="navy";/*Draw path*/ line.moveTo(10,45); line.lineTo(150,45); line.lineTo(150,10); line.lineTo(10,45); line.stroke();/* Needs stroke function to show drawing*/ </script>
Circle
Use arc to make a full circle
(name.arc(x,y coordinates of center, radius, start angle(0 is on right side of screen), end angle, clockwise?)
The angles are not degrees but radians. 2PI is a whole circle so 1*Math.PI will draw half a circle etc.
arcTohere is more of a rounded corner function
Use arc instead and brush up on your
radians
and PI. You can use PI in your equation- you just have to call it from the Math library, Math.PI.
name.arc(x-of center,y-of center,radius,sAngle,eAngle,counterclockwise (optional)); name.arc(40,40,20,1*Math.PI,2*Math.PI,true);
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvasid="drawing"width="200"height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var arc = drawing.getContext('2d');
The beginPath() method begins a path, or resets the current path.
Color
You can draw a wide range of shapes and change their colors. There are two parts of a shape that you can control the color of the fill and the stroke:
fill
'Color in', the color that fills up the inside area of a letter or shape
stroke
The lines that make up the outline of a letter or shape
There are a couple of ways you can change the color of your graphic.
You can use 'symbolic names' like 'red', 'chartreuse' 'OrangeRed', or, if you know about RGB or Hex colors, these work too.
rect.fillColor = '#5889D2'; //hex rect.fillColor = 'rgb(88,137,210)';//RGB rect.fillColor = 'stelBlue';//nameshape1.fillStyle = 'red'; shape1.strokeStyle= 'blue';
<canvas id="drawing" width="150" height="100"> HTML5 Canvas isn't working if you see this text. </canvas>
Click the REFERENCE button in the JavaScript IDE to find example code for different things.
Here is a list of terms to search:
Audio.play
Game.BadItem
Game.Bar
Game.Button
Game.clearCharacters
Game.clearItems
Game.clearTimerEvents
Game.Door
Game.Enemy
Game.fadeOut
Game.FadingLabel
Game.Goal
Game.GoodItem
Game.Gun
Game.Item
Game.Moveable
Game.nextLevel
Game.Obstacle
Image Catalog
These are images available on the Code Avengers website for games. Simply replace the file paths of your characters and objects.
new Game.Player(50, 50, '/image/game/player1.png')
Disclaimer:It is not a complete list and some image files could be moved or renamed post publication.
Are you interested in making video games? Learning a programming language is essential. Why don’t you learn while making a game at the same time? Use JavaScript to build a simple 2 player 2D top-down game, where players race to collect coins while avoiding obstacles and enemies!
If there is time try to complete this second Game Development project.
5.9: Build your own game
You can use our editor and the JavaScript IDE to make some pretty cool basic games.
But in the end Code Avengers is here to teach you coding and computer science.
If you want to start to really challenge yourself there are a lot of amazing game engines out there that can help you make something amazing
These are ranked from simplest to most complex
Scratch
Gamemaker
Unreal Engine
6: Drawing flags—an introduction to JavaScript graphics
Make pictures using coordinates.
This is a 3 hour lesson plan on 2d graphics.
There are two courses on drawing flags that each take an hour to complete and an unplugged Shapes Activity.
This lesson plan covers all you need to know about starting to draw graphics with JavaScript.
Firstly, it takes you through concepts and activities that will help enhance your understanding then it lists the Turtle lessons found on Code Avengers.
There is some more in depth information listed as extension concepts.
This is an in-depth break down of the content to enhance learning and help teachers unfamiliar with these concepts to be able to teach them.
Key to lesson icons
There are 3 types of lesson segments
Concepts - are notes to expand on learning in lessons
Activities - are off-line and online games and activities to help your learning.
CA Lessons - are online lessons, projects and quizzes created by Code Avengers.
Extension: - These are additional segments for fast learners (or homework)
Concepts
6.2: Coordinates
5 min
Coordinates are pairs of numbers, like (3,4). They help you find places on a grid.
The first number tells you the horizontal position of a point, it tells to you go across the x axis until you hit the number 3.
The second number tells you the vertical position of a point, it tells to you go down the y axis until you hit the number 4.
Coordinates are used in both mathematics and computer science, (as well as in geography, archeology, criminology, the army, and many other areas). But they are used in different ways.
Math uses an axis with 0, 0 in the middle, and counts across and up. Up from 0 are positive numbers on the y axis and when you count down from 0 you have negative numbers. The same is true for left and right. Left of 0 are negative numbers and right of 0 are positive numbers. The coordinates (0,0) or (3,4) give the location of a point. (shown in the image as the points where 2 lines cross)
Computergrids model a computer screen, which is made up of thousands of little squares called pixels.
You can't have negative pixels, so 0,0 starts in the top left corner of your screen.
When given computer coordinates you count across the x axis from left to right, just like reading a book and then down the y axis. The coordinates (0,0) or (3,4) point to a specific pixel. (shown in the image above as a square)
Imagine the above example is very [[zoomed in- pixels are tiny]]
The CA course Food Frenzy→ uses a grid to place game objects. You can change the numbers in the coordinates to change the location of the object.
We usually label the horizontalaxisx and the verticalaxisy but it can really be called anything, those are just the traditional labels
Activity
6.3: Drawing shapes with functions
30 min
This is activity can be completed in pairs or individually. Learn about coordinates, shapes and functions
Objective
Create an image by translating the coded instructions to the grid.
Background
Computers can create graphics from very simple instructions, using code from pre-made JavaScript libraries like 2D.
You write the name of the shape and then add some numbers to draw it. This is calling a function named after the shape in the
2d
library and plugs in the numbers you add.
For example, to draw a 3 by 5 rectangle at the top left of your screen you would write Rectangle(0,0,3,5).
The function Rectangle is only allowed numbers in the brackets, those are the parameters, and the order those numbers decides where and how large to draw the shape.
Rectangle( x, y, width, height ).
function
A function is a named reusable section of a program that performs a specific task and may return a value.
Reference sheet
This printable sheet is a handy reference when drawing 2d/paperjs shapes on a computer (or by hand).
Helpful for the flags challenges 1 and 2 or the unplugged shape activity.
The first two numbers are the coordinates for the starting point of the shape, the top left corner of the rectangle will be at this point.
The width of the rectangle is counted across in pixels.
The height of the rectangle is counted down in pixels.
Circle
Circle(x,y,radius)
The circles' coordinates set the center of the circle, not the top left like the rectangle.
The radius is then drawn from that point.
Star/Polygon
Set Coordinates
Set Outer and Inner Radius
Star(x,y,points,outerRadius,innerRadius)
Stars are fun, and a little tricky.
The outer and inner radii can be adjusted to make some pretty cool shapes.
//1.The inner radius is bigger than the outer radius var inner = new Path.Star(40, 40, 6, 20, 40); inner.fillColor = 'black'; //2.The outer radius is bigger than the inner radius var outer = new Path.Star(120, 40, 6, 40, 20); outer.fillColor = 'black'; //3.The outer and inner radii are equal var equal = new Path.Star(200, 40, 6, 30, 30); outer.fillColor = 'black';
You can make any regular shape by adding half the number of points you want (Because a 5 pointed star really has 10 points and 10 sides) and setting the outer and inner radii to the same number.
var shape = new Path.Star(40, 40, 1.5, 30, 30);
Triangle = 1.5
Diamond = 2
Pentagon = 2.5
Hexagon = 3
Heptagon = 3.5
Play around with all the different values and see what fantastic shapes you can create!
Irregular shapes—path
Irregular shapes are drawn by naming (with coordinates) every corner of the shape:
Point
Lines,
Triangles,
Weird-sided shapes,
Semi-circles—arcTo
Paths
Line
Triangle
Quadrilateral
Paths can make any shape, you simply have to give the coordinates of each point and it join them all together.
Path(x,y)(x,y)(x,y) for three different points will draw a triangle.
As with all coordinates, the first number is across from the top left of the screen and the second number is down from the top left of the screen.
Semi circle
Path(x,y)arcTo(x,y)
Semi-circles use the keyword arcTo between the coordinates of a line. This adds a curve between the two points as well as a line.
Preparation
Print off the blank "Grid Exercise" worksheet and the "Grid Challenge Example" sheet below, which is a cheat-sheet of the shape functions and their parameters.
In this activity you draw out a scene by completing 10 shapes.
These ten shapes are written in as functions for 2d drawing.
Your job is to use the "Grid Challenge Example cheat-sheet" to work out what the numbers in the brackets mean.
Then draw the shapes from those numbers.
Level of difficulty:
Easy: Let learners constantly refer to the answer imageas they draw.
Medium: Tell the learners what they are drawing or show them the answer imagebefore they begin.
Note: Only teachers can access the answers file so please follow the link and make your own copy to share with your class.
First steps
Go through the first two steps with students.
"For shape 1, the function is Rectangle (4, 6, 12, 6).
We have to draw a rectangle that starts at the coordinates(4,6),
we go across to line 4 and then ''down''' to line 6 and add a mark where (4,6) meet.
The rectangle is 12 squares wide so count 12 across and add a mark to (16,6).
The rectangle is 6 squares high so count 6 squares ''down''' and add a mark at (16,12).
Rectangles are equal in height and equal in width, so mark (4,12) as well.
Connect the dots to form a rectangle."
"For shape 5, we are also drawing a four-sided shape but because the shape is not "equal in height and equal in width" we just use a path."
"Path (3, 6) (17, 6) (15, 2) (5, 2)
Answer
Answer image Note: Only teachers can access the answers file so please follow the link and make your own copy to share with your class.
js7.1
My own project
Make your own shapes with our JavaScript I.D.E, to have the canvas working use //paper at the top of the page.
Read our IDE guide to learn more about the I.D.E's
Adding 2D graphics to a webpage
If you want to add your images to a normal web page outside of Code Avengers, it will require a little set up.
Code to add images
We have made a Path module'' that is based off the2D JavaScript graphics module'''.
The Code Avengers' code is easier to use because we do all of the set up for you but it only works on code saved on our website.
If you are ready to make graphics in your own website then read the content below.
You first need to learn about HTML <canvas> and linking JS, HTML and the 2D context library.
Then you need to learn how the functions work for 2D, we have some notes and links below that can help you.
<canvas id="drawing" width="250" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var shape1 = drawing.getContext('2d'); /*Write your drawing code here*/ shape1.fillStyle = 'lightBlue'; shape1.strokeStyle= 'navy'; shape1.fillRect(25, 25, 50, 50); shape1.strokeRect(25, 25, 50, 50); </script>
The tags and JS covered here are <canvas></canvas> and .getContext('2d')
You can draw images and shapes onto a webpage using code instead of uploading an image.
Canvas tag —<canvas></canvas>
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, shapes, text or even do simple (and not so simple) animations.
To get canvas to work is a little tricker than the other tags. The <canvas> element places the drawing window on the page. We added a border in CS so you can see it. But the drawing is written in JavaScript.
<style> #drawing{ border: lightGrey dashed 1px; } </style> <p>The grey border shows the canvas, the red rectangle is created with JavaScript. <canvas id="drawing" width="150" height="100"> HTML5 Canvas isn't working if you see this text. </canvas> <p>Did you know this is a live example? Click on the HTML code box and try your own code. <script> var drawing = document.getElementById('drawing'); var codeForDrawing = drawing.getContext('2d'); codeForDrawing.fillStyle = 'lightBlue'; codeForDrawing.fillRect(25, 25, 50, 50); </script>
Adding JavaScript
The 2dinterface is used for drawing circles, rectangles, text and more inside a canvas element. The library called '2d' has all the code context to draw the shapes (written in JavaScript) on the canvas.
So in the code above we have a canvas in HTML but the important stuff is happening in the script element.
Firstly we make a variable that links our canvas to the JavaScript, var drawing = document.getElementById('drawing');.
Then we create a variable to link our JavaScript to the already existing code inside the file called 2d, var codeForDrawing = drawing.getContext('2d');.
Now with those 3 things linked you can draw a lot of different shapes.
All the browsers have access to 2d so you only have to ask for the browser to find it and pull the context out of it. Read a good explanation of context on StackOverFlow by Brian Kelly from 2011.
The canvas/2d/JavaScript linking is all done for you in our intro lessons. Like our fun drawing challenge: CA Flag Drawing Challenge
Drawing shapes
You can draw many things, the basics are lines, rectangles, circles, triangles, half circles and stars. The drawing code is slightly different to what you have learned here at Code Avengers.
See a range of options at W3schools
Rectangle
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var rectangle = drawing.getContext('2d'); rectangle.rect(25,25,50,50); rectangle.stroke(); </script>
Lines
Begin a path, move to position 0,0. Create a line to position 300,150:
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var line = drawing.getContext('2d');
line.beginPath(); line.lineWidth="5"; line.strokeStyle="navy";/*Draw path*/ line.moveTo(0,45); line.lineTo(150,45); line.stroke();/* Needs stroke function to show drawing*/
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var line = drawing.getContext('2d');
line.beginPath(); line.lineWidth="5"; line.strokeStyle="navy";/*Draw path*/ line.moveTo(10,45); line.lineTo(150,45); line.lineTo(150,10); line.lineTo(10,45); line.stroke();/* Needs stroke function to show drawing*/ </script>
Circle
Use arc to make a full circle
(name.arc(x,y coordinates of center, radius, start angle(0 is on right side of screen), end angle, clockwise?)
The angles are not degrees but radians. 2PI is a whole circle so 1*Math.PI will draw half a circle etc.
arcTohere is more of a rounded corner function
Use arc instead and brush up on your
radians
and PI. You can use PI in your equation- you just have to call it from the Math library, Math.PI.
name.arc(x-of center,y-of center,radius,sAngle,eAngle,counterclockwise (optional)); name.arc(40,40,20, 1*Math.PI,2*Math.PI,true);
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var arc = drawing.getContext('2d');
The beginPath() method begins a path, or resets the current path.
Color
You can draw a wide range of shapes and change their colors. There are two parts of a shape that you can control the color of the fill and the stroke:
fill
'Color in', the color that fills up the inside area of a letter or shape
stroke
The lines that make up the outline of a letter or shape
There are a couple of ways you can change the color of your graphic.
You can use 'symbolic names' like 'red', 'chartreuse' 'OrangeRed', or, if you know about RGB or Hex colors, these work too.
rect.fillColor = '#5889D2'; //hex rect.fillColor = 'rgb(88,137,210)';//RGB rect.fillColor = 'stelBlue';//nameshape1.fillStyle = 'red'; shape1.strokeStyle= 'blue';
<canvas id="drawing" width="150" height="100"> HTML5 Canvas isn't working if you see this text. </canvas>
Drawing with JavaScript is easier than you might think. Learn more about the flags of the world as each level increases in complexity. Learn about shapes, coordinates, colors as well as the importance of sequence in coding.
Learn a little more about
paperJS
, practice using coordinates to make shapes on our canvas and then practice by recreating some of the world's flags as each level increases in complexity. Learn about shapes, coordinates, colors as well as the importance of sequence in coding.
The first two numbers are the coordinates for the starting point of the shape, the top left corner of the rectangle will be at this point.
The width of the rectangle is counted across in pixels.
The height of the rectangle is counted down in pixels.
Circle
Circle(x,y,radius)
The circles' coordinates set the center of the circle, not the top left like the rectangle.
The radius is then drawn from that point.
Star/Polygon
Set Coordinates
Set Outer and Inner Radius
Star(x,y,points,outerRadius,innerRadius)
Stars are fun, and a little tricky.
The outer and inner radii can be adjusted to make some pretty cool shapes.
//1.The inner radius is bigger than the outer radius var inner = new Path.Star(40, 40, 6, 20, 40); inner.fillColor = 'black'; //2.The outer radius is bigger than the inner radius var outer = new Path.Star(120, 40, 6, 40, 20); outer.fillColor = 'black'; //3.The outer and inner radii are equal var equal = new Path.Star(200, 40, 6, 30, 30); outer.fillColor = 'black';
You can make any regular shape by adding half the number of points you want (Because a 5 pointed star really has 10 points and 10 sides) and setting the outer and inner radii to the same number.
var shape = new Path.Star(40, 40, 1.5, 30, 30);
Triangle = 1.5
Diamond = 2
Pentagon = 2.5
Hexagon = 3
Heptagon = 3.5
Play around with all the different values and see what fantastic shapes you can create!
Concepts
6.7: Irregular shapes—path
5 min
Irregular shapes are drawn by naming (with coordinates) every corner of the shape:
Lines,
Triangles,
Weird-sided shapes,
Semi-circles
Paths
Line
Triangle
Quadrilateral
Paths can make any shape, you simply have to give the coordinates of each point and it join them all together.
Path(x,y)(x,y)(x,y) for three different points will draw a triangle.
As with all coordinates, the first number is across from the top left of the screen and the second number is down from the top left of the screen.
Semi circle
Path(x,y)arcTo(x,y)
Semi-circles use the keyword arcTo between the coordinates of a line. This adds a curve between the two points as well as a line.
Concepts
6.8: Color
5 min
You can draw a wide range of shapes and change their colors. There are two parts of a shape that you can control the color of, the fill and the stroke:
var rect = new Path.Rectangle(10, 40, 100, 200); rect.strokeColor = 'navy'; rect.strokeWidth = 5;
fill
'Color in', the color that fills up the inside area of a letter or shape
stroke
The lines that make up the outline of a letter or shape
There are a couple of ways you can change the color of your graphic.
You can use 'symbolic names' like 'red', 'chartreuse' 'OrangeRed', or, if you know about RGB or Hex colors, these work too.
rect.fillColor = '#5889D2'; //hex rect.fillColor = 'rgb(88,137,210)';//RGB rect.fillColor = 'stelBlue';//name
Make it a team challenge.
Students work in teams of 2-8 with two or three computers per team. They can choose to jump to any flag from the white index in the top left of the lessons.
As they complete the flags they earn points for their team.
As a team they can only earn the points for each flag once- so two computers completing the same flag would be a waste of time.
Poland
Italy
Benin
Sweden
Japan
Bahamas
Seychelles
Puerto Rico
Saint Vincent and the Grenadines
South Africa
Extension: Concepts
6.10: Draw your own shapes on Code Avengers
5 min
You can use our JavaScript IDE→ to make, save and share your own digital designs.
Make sure you have //paper 600 600 at the top of your page if you want a nice big canvas to work on.
Adding 2D graphics to a webpage
If you want to add your images to a normal web page outside of Code Avengers, it will require a little set up.
Code to add images
We have made a Path module'' that is based off the2D JavaScript graphics module'''.
The Code Avengers' code is easier to use because we do all of the set up for you but it only works on code saved on our website.
If you are ready to make graphics in your own website then read the content below.
You first need to learn about HTML <canvas> and linking JS, HTML and the 2D context library.
Then you need to learn how the functions work for 2D, we have some notes and links below that can help you.
<canvas id="drawing" width="250" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var shape1 = drawing.getContext('2d'); /*Write your drawing code here*/ shape1.fillStyle = 'lightBlue'; shape1.strokeStyle= 'navy'; shape1.fillRect(25, 25, 50, 50); shape1.strokeRect(25, 25, 50, 50); </script>
The tags and JS covered here are <canvas></canvas> and .getContext('2d')
You can draw images and shapes onto a webpage using code instead of uploading an image.
Canvas tag —<canvas></canvas>
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, shapes, text or even do simple (and not so simple) animations.
To get canvas to work is a little tricker than the other tags. The <canvas> element places the drawing window on the page. We added a border in CS so you can see it. But the drawing is written in JavaScript.
<style> #drawing{ border: lightGrey dashed 1px; } </style> <p>The grey border shows the canvas, the red rectangle is created with JavaScript. <canvas id="drawing" width="150" height="100"> HTML5 Canvas isn't working if you see this text. </canvas> <p>Did you know this is a live example? Click on the HTML code box and try your own code. <script> var drawing = document.getElementById('drawing'); var codeForDrawing = drawing.getContext('2d'); codeForDrawing.fillStyle = 'lightBlue'; codeForDrawing.fillRect(25, 25, 50, 50); </script>
Adding JavaScript
The 2dinterface is used for drawing circles, rectangles, text and more inside a canvas element. The library called '2d' has all the code context to draw the shapes (written in JavaScript) on the canvas.
So in the code above we have a canvas in HTML but the important stuff is happening in the script element.
Firstly we make a variable that links our canvas to the JavaScript, var drawing = document.getElementById('drawing');.
Then we create a variable to link our JavaScript to the already existing code inside the file called 2d, var codeForDrawing = drawing.getContext('2d');.
Now with those 3 things linked you can draw a lot of different shapes.
All the browsers have access to 2d so you only have to ask for the browser to find it and pull the context out of it. Read a good explanation of context on StackOverFlow by Brian Kelly from 2011.
The canvas/2d/JavaScript linking is all done for you in our intro lessons. Like our fun drawing challenge: CA Flag Drawing Challenge
Drawing shapes
You can draw many things, the basics are lines, rectangles, circles, triangles, half circles and stars. The drawing code is slightly different to what you have learned here at Code Avengers.
See a range of options at W3schools
Rectangle
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var rectangle = drawing.getContext('2d'); rectangle.rect(25,25,50,50); rectangle.stroke(); </script>
Lines
Begin a path, move to position 0,0. Create a line to position 300,150:
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var line = drawing.getContext('2d');
line.beginPath(); line.lineWidth="5"; line.strokeStyle="navy";/*Draw path*/ line.moveTo(0,45); line.lineTo(150,45); line.stroke();/* Needs stroke function to show drawing*/
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var line = drawing.getContext('2d');
line.beginPath(); line.lineWidth="5"; line.strokeStyle="navy";/*Draw path*/ line.moveTo(10,45); line.lineTo(150,45); line.lineTo(150,10); line.lineTo(10,45); line.stroke();/* Needs stroke function to show drawing*/ </script>
Circle
Use arc to make a full circle
(name.arc(x,y coordinates of center, radius, start angle(0 is on right side of screen), end angle, clockwise?)
The angles are not degrees but radians. 2PI is a whole circle so 1*Math.PI will draw half a circle etc.
arcTohere is more of a rounded corner function
Use arc instead and brush up on your
radians
and PI. You can use PI in your equation- you just have to call it from the Math library, Math.PI.
name.arc(x-of center,y-of center,radius,sAngle,eAngle,counterclockwise (optional)); name.arc(40,40,20, 1*Math.PI,2*Math.PI,true);
<style> html{ background-color:lightGrey;} #drawing{ background-color:aliceBlue; border: slateGrey dashed 1px; } </style> <canvas id="drawing" width="200" height="200"> HTML5 Canvas isn't working if you see this text. </canvas>
<script> var drawing = document.getElementById('drawing'); var arc = drawing.getContext('2d');
The beginPath() method begins a path, or resets the current path.
Color
You can draw a wide range of shapes and change their colors. There are two parts of a shape that you can control the color of the fill and the stroke:
fill
'Color in', the color that fills up the inside area of a letter or shape
stroke
The lines that make up the outline of a letter or shape
There are a couple of ways you can change the color of your graphic.
You can use 'symbolic names' like 'red', 'chartreuse' 'OrangeRed', or, if you know about RGB or Hex colors, these work too.
rect.fillColor = '#5889D2'; //hex rect.fillColor = 'rgb(88,137,210)';//RGB rect.fillColor = 'stelBlue';//nameshape1.fillStyle = 'red'; shape1.strokeStyle= 'blue';
<canvas id="drawing" width="150" height="100"> HTML5 Canvas isn't working if you see this text. </canvas>
This is the lesson plan for the HTML Intro course and is suitable for Junior High students and above.
Prior Learning
7.1: Outcomes
5 min
Create a basic webpage for Wiki Jr
The HTML Intro Course contains 5 Code Avengers' online
lessons with 5 tasks each.
Just doing the Code Avengers Lessons will take about
1 - 1 1/2 hours depending upon the person.
The content here stretches those lessons over roughly 3 hours and gives suggested lesson plans with added notes and activities to expand understanding.
60 min
8: HTML, head and body tags
Hyper text Mark-up Language, HTML, uses tags to structure a webpage.
Starting to learn HTML and CSS is easy and fun with this digital postcard. Learn about adding headings, paragraphs, images and links to create a holiday card or birthday celebration to share with friends and family.
Firstly, create a quick postcard using HTML and CSS.
100%
Concepts
8.2: The bones of a web page are HTML, CSS and JavaScript
5 min
Coding webpages
There lots ways to build websites. For example, you can find a template and use a website builder like Weebly to quickly and easily create a professional looking website, without writing a any computer code.
However, if you want to build something unique and have full control over how your webpages look and work, you need to know 3 computer languages: HTML, CSS and JavaScript.
HTML
HTML (HyperText Markup Language) is used to write the content (text, images, video etc.) and structure of webpages.
The example image shows what Google looks like with only HTML code.
CSS
CSS (Cascading Style Sheets) is the language used to add colors, fonts and layout to webpages.
Combine HTML and CSS with some good design sense and you'll nice and pretty webpages like Google.
JavaScript 50%
JavaScript is a programming language that is used to make things click-able and more interactive.
For example, Google search uses JavaScript to automatically suggest search keywords as you type, and to display the search results when you press ENTER.
Server-side programming
In addition to HTML, CSS and JavaScript, websites may have another programming language that reads and writes data to and from a database and inserts that data into the HTML and CSS code that gets sent to your web browser.
If you want to learn more about servers and server-side programming, you can start by doing our Intro to the Internet course.
Some neat tricks
View the HTML code for any webpage: Press CTRL+U in Windows, or CMD+U in Mac.
To turn off CSS code for any website drag the following bookmarklet to your bookmarks toolbar, and click the bookmark to turn off CSS code: <a href="javascript: var el = document.querySelectorAll('style,link');for (var i=0; i<el.length; i++) {el[i].parentNode.removeChild(el[i]); };">Remove Styles</a>
The Web Developer plugin for Firefox and Chrome is able to do this
Concepts
8.3: Start and end tags, and self closing tags
5 min
HTML uses tags to format things. It add spaces, creates paragraphs and headings.
All the code for web pages are lines of text and symbols. This code transforms into beautiful web pages when opened in a browser.
<h1>This is a heading</h1> <p>This is a paragraph of normal text
The spelling and the characters you use are important when they are inside the tags <>.
They have to be correct in spelling (for the CSS, in American English (Color not colour)) and correct in punctuation, (for example, all brackets and quote marks have partner).
Most of the tags are easy to remember, some are full words like <strong>, some are abbreviations like image, <img>, or emphasize, <em>.
A few might look strange but you will learn them as we go. Good Luck.
Start and end tags
Tags typically come in pairs; an opening start tag and a closing end tag with a forward slash: <tag>Words</tag> and the actual content to display goes between them, like this:
An HTML element is made up of a start tag, end tag, and the content in between.
Here you can see different sections of our HTML create different parts of our webpage
So these are both elements:
<br> and
<h1>Hi Sis</h1>
You can also have elements inside of elements
2 elements, one inside the other
<a href="add a hyperlink"> <img src="add an image"> </a>
3 elements inside each other
' <ul>Bullet point list <li>point 1</li> <li>point 2</li> </ul> </body>'''
Concepts
8.5: Formatting white space
5 min
Formatting your HTML code makes it much easier to read.
If an element is inside another element it should be moved to the right a bit on a new line (this is called indenting).
This leaves white space on the left so that it is really easy to see what elements are inside others and it makes your code tidy.
How much do we indent by?
The internet rages with conversations about whether to use 2 spaces, 4 spaces, or 8 spaces when indenting. We are a 2 space company because we follow the Google Style Guide.
A lot of it has to do with using the TAB key to indent. In some editors the default space of TAB is 4 spaces and so people grow up learning and loving that, if you use tab characters some languages and editors, like Python, assume you are using 8 spaces.
So what should you use?
Well, we recommend 2 spaces, but it is ok to follow personal preference. If you wish to have 4 or 8 spaces then add those. Just make sure you use indentation to add space to the left margin.
You can use empty lines (hitting ENTER) for formatting as well, this has no effect on your webpage but it makes the HTML code easier to read.
Later on, you might also notice how the automatic color coding in your code editor helps a lot too. This is called "syntax highlighting".
Tab characters versus spaces
Tab is a very useful key to use for indentation when you are coding. Depending on your editor settings, hitting TAB will either add a tab character (which is one long space covering 2 or 4 or 8 normal spaces) or normal spaces. Editors all have a different setting to their tab character length. This means your code will look different when you open your file in the CodeAvengers IDE, having made it in notepad++. It is better to change your TAB key to just add your favourite number of spaces instead of the tab character (do this in the settings) so that when your code is opened by different editors it will look the same.
How can you tell if TAB is using tab character or inserting spaces? Hit TAB in an editor and hit your left arrow key once. Do you go back one space or do you go back 2 or 4 spaces at once (one tab character).
Using Wordpress or Weebly you can create basic websites without writing any code. However, if you want to build the next YouTube, Google, Twitter or Facebook, the first computer languages you need to learn are HTML and CSS!
Our HTML tags can be as simple as a <p>, to create a paragraph, or they can have more information inside them.
Anchor tags for example need an attribute called href (hypertext-referencing), href holds the to link to another webpage. href="" is an example of an attribute.
Below we have a color-coded example of parts of an HTML element.
<tag attribute="value">Text node inside element</tag> <a href="www.codeavenger.com"> This is a (hyperlink) link to CA!</a>
Tags structure your webpage, they add spaces and headings and images. Some of these tags use attributes these add more functionality a
tag.
Attributes have a specific name, like width=' ' or href=" " and have a value inside quote marks, like width='300px'. You can have more than one attribute in a tag. Some attributes must be used with a tag and some are optional, you will learn them as you go.
Confused? It will make more sense as you write the code yourself.
The src attribute is not optional, it tells the browser where to find the image. In this case the value, "http://gathergather.co.nz/grumpy-cat.png takes you to a grumpycat image.
The height attribute is optional has a value of 100 pixels.
This will make the imageimage100 pixelstall. The width can also be set with a width attribute, if it is not added the width of the image will automatically resize to keep the same height to width
ratio
of the image.
Concepts
8.9: Head elements—title, link, meta | doctype
5 min
There are some tags that we add to the head or top part of our webpage. These are usually for linking to special files (not normal webpages!), or giving the computer information about your webpage and they do not appear on the webpage.
Example: Look at the output of this code- what actually shows up for viewers?
Only the h1 text is in the body section, the rest are in the head of the webpage and are not seen by the webpage user.
Doctype tag–<!doctype html>
<!doctype html>, or <!DOCTYPE HTML>, is an element that tells the browser that this document is written in html 5.
Required attributes
None
Tag placement
Place on Line 1
Tag type
Self closing
Line 1 should always have the <!doctype html> tag to tell the browser that this document is written in html 5.
Your web page should also always be saved with the .html file path ending, home.html
Notice that it is actually outside of the html and head elements.
<!doctype> <html> <head></head> <body></body> </html>
Title tag—<title> </title>
The title element is important, it defines the title of a document. Title elements are often used on search engine results pages (SERPs) to show a section of your webpage. Title elements are useful for SEO (Helping people to find your website) and social sharing (The info that can show up when you share a link with people). They also show up in your browser tab.
Required attributes
None
Tag placement
Top of page (head)
Tag type
Start and end
The title element of a web page should give a lot of information of a page's content clearly and should use not very many words. It is often the name of the webpage.
<head> <title>Introduction to Coding Lesson Notes: Code Avengers</title> </head>
Link tag <link href="" rel="">
The link tag links the CSS style sheet to our web page, it is used for other files as well but CSS is the most common file you link to. We will learn more about how to add CSS in our later lessons.
Required attributes
href= The hyper reference links to the file rel= This says the relationship of the new file to the web page
<meta name="..." content="..."> elements are used by the browser, robots and search engines to find out information about your webpage. Use it to add descriptions, make your site accessible to different screen sizes and more.
(Often) required attributes
name= Name of meta tag ie author, description, keywords content= Description and information
Tag placement
Top of page (head)
Tag type
Self-closing
<head> <meta charset="UTF-8"> <meta name="description" content="Lesson notes for the introduction course on HTML 5 with Code Avengers."> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head>
Keyword
<meta name="keyword" content="lessons, code, programming, html"> The words you type into a search engine become the keywords it searches webpages for.
This meta element will help those search engines find your site...except it is not always that useful as Google Search ignores your keyword meta element. There are other search engines out there that do use keywords.
Using Wordpress or Weebly you can create basic websites without writing any code. However, if you want to build the next YouTube, Google, Twitter or Facebook, the first computer languages you need to learn are HTML and CSS!
src= The source attribute tells the browser where to "source" (find) the image. It is usually the URL of where the image is. alt= is text to describe the image. It is not required but you should use it.
Tag placement
Middle of page (body)
Tag type
Self-closing
<body>
<img src="http://gathergather.co.nz/grumpy-cat.png" alt="A cartoon of a grumpy cat.">
<p>img src="http://gathergather.co.nz/grumpy-cat.png" alt="A cartoon of a grumpy cat." <br>will get you this grumpy cat picture on your webpage. </body>
Concepts
9.3: Image src attribute
1 min
The image element will not work without the src attribute to link to the image file.
The source attribute tells the browser where to "source" (find) the image. It is usually the URL of where the image is.
If you set only one of the two attributes, say width, the height of the image will automatically scale up or down so that the picture is has the same
ratio
of height to width.
3 ways to resize an image.
It is good to know that you can use HTML to set your image sizes.
When you have learned more about HTML and CSS you should use CSS to resize your images.
If you learn about image manipulation (eg Photoshop) you should digitally resize your images correctly so that you won't need to use CSS or HTML and save on memory.
Concepts
9.5: Image with title attribute
5 min
The title attribute is used to add tooltips to images. A tooltip is a message that is shown when the mouse pointer
hovers
over an item on a web page.
Hover over the picture in the webpage output below and then look at the HTML code. You can change the text in the HTML code and see what happens.
title="Yay, you hovered. Look a message appears!">
Concepts
9.6: Image with alt attribute
5 min
alt is another image attribute.
alt is the alternative text that screen readers use to explain images to people who are visually impaired. It also shows up when there is a "broken image", when the computer can't find a picture because of typos or moved files.
Seach Engines (like Google) use this information, along with the title of the image, and the title tag to find your page and images.
You should always include the alt attribute in your image code.
Think about the words you use:
Describing the meaning of the image is far more useful than describing what it looks like.
For example:
"Logo of Code Avengers" is far more useful than "Red letters"
Below we have an a broken image with alt text.
Here is the code:
<img src="example" width="160" height="131" alt="A cartoon of a grumpy cat." title="Yay, you hovered again.">
Do you see how both alt and title have text but they are used differently?
Concepts
9.7: Iframe tag <iframe>
5 min
iframe is a body section element, with a self-closing tag (it doesn't use a closing tag).
Required attributes:
The iframe tag embeds (or puts) an HTML web page inside another HTML web page.
Common things that you can embed are Youtube videos, google maps and ...
In this case you are using a special web page provided by YouTube that makes the video fill the whole screen.
Concepts
9.8: Copyright and Creative Commons
5 min
Think about copyright
You must learn to not use copyrighted material.
Intellectual property is important to recognize and you can easily fail assessments or get in trouble at work for stealing images from people- especially if you make money from it.
What constitutes intellectual property? They are ideas, and the creations or products made from those ideas. Intellectual property belongs to the person who thought them, (or the company that person works for).
Facebook
A famous example of a fight over intellectual property is depicted in the movie The Social Network (2010), which talks about the beginning of Facebook and a real-life lawsuit filed against it's creator Mark Zuckerburg for stealing the Winklevoss twin's social media idea. Zuckerburg was hired to make a facebook-like website for them and instead made his own. Other lawsuits were involved, but in February 2008 they settled in an agreement reportedly valued at US$65 million.
Creative Commons
There are a lot of creators who are happy for you to use their images for free.
An easy way to find them is using
Create Commons Image Search
It gives access to search services that find content you can use, share and remix.
Using Wordpress or Weebly you can create basic websites without writing any code. However, if you want to build the next YouTube, Google, Twitter or Facebook, the first computer languages you need to learn are HTML and CSS!
The target attribute controls how the link is open, the default way it works (when you don't include it) is target="_self" and the link will open in your current window. you can use target="_blank" to open the link in a new tab.
<a href="http://www.codeavengers.com" target="_self"> Code Avengers Home- Click here </a> <a href="http://www.codeavengers.com" target="_blank"> Code Avengers Home - Click here </a>
Title attribute title=""
The title attribute works with both the image tag and anchor tag.
It creates a tooltip message that pops out when you hover over the link.
<a title="with no href attribute clicking this text will not take you anywhere"> Hover here </a>
All three attributes together
Here is an example of all three attributes inside the anchor start tag. The code below links the text to the home page, adds a tooltip to explain and when clicked, the link will open in a new tab.
<a href="http://www.codeavengers.com" target="_blank" title="Go to the homepage"> Code Avengers Home </a>
Nesting (or how to make an image clickable)
You can also make an image a link using nesting.
Nesting is simply when we place a tag within another tag.
For example:
<a href="#"> <img src= "#"> </a>
This relationship is often referred to using the terms "parent" node and "child" nodes or parent element and child element.
A node is a word used to describe where our code branches and is part of the vocabulary we use when talking about nesting.
Let's try linking our Code Avengers logo to our webpage using an anchor element.
Take our link from the previous example. By replacing the text with an image element, which links to our logo, we will have created a linked image.
For example:
Click here → <a href="http://codeavengers.com"> <img src="/images/logo.png"></a> ← to go to Code Avengers.com
Extension: Concepts
9.12: Linking file paths
5 min
File paths can be written in different ways and so it is important to know where and how you save your files on the computer.
The file path we have been using in our work mostly has been the absolute file path to files on the web, the URL (Uniform Resource Locator), https://www.google.com
They are based on how your files are saved in folders
Let's do a quick count of the 4 types of links used in this course.
Links to pages on other websites use the full URL.
<a href="http://wikipedia.org"> Wikipedia </a>
Links to pages in the same folder use the file name only.
<a href="page2.html"> Mario </a>
Links to pages in a different folder start with / followed by the folder and file path.
<a href="/wiki/index.html"> Wiki Jr Home </a>
To link to a website home page set href to /.
<a href="/"> Website Home Page </a>
Click here for more information about using file paths.
Using Wordpress or Weebly you can create basic websites without writing any code. However, if you want to build the next YouTube, Google, Twitter or Facebook, the first computer languages you need to learn are HTML and CSS!
Businesses all over the world are competing to create websites, apps and games that Users want to buy.
So what gets Users interested?
It needs to function but it also must look and feel good to use.
Visual appeal is really important.
"But, isn't all art and stuff subjective?"
Yes, but there are fundamental rules to learn in good design that you have to master before you break them.
There is a lot of psychology, and trial and error of artists that has developed into a guide of principles and elements of good design.
For example people like repetition, it makes them feel comfortable to be able to predict their world. How anxious would you feel and annoying would it be if the exit icon moved to a different spot every time you went to a new web page? Or a website had a completely different layout for each webpage?
These posters have been adapted from Patrick Butler. His original posters can be found on http://splitcomplementary.blogspot.com.
They are a great resource for the classroom.
Concepts
10.2: CSS
10 min
Cascading Style Sheets
Cascading means the styles of outer elements often apply to the styles of inner elements.
So all the h1 headings in the text will change color from black to blue.
CSS rule
HTML selector
Property
Value
Declaration
Concepts
10.4: Formatting CSS
5 min
A declaration has one property and should be on a new line. We end a property with a colon : and we end a declaration after the value/s with a semicolon ;.
Like HTML, you need to use extra whitespace and add line breaks to make it more readable.
body is a selector that applies styles to the entire page, and all of its content.
All the elements in the page will change to match your style properties.
body { font-family: sans-serif; }
Our first style background-color:
background-color is a property that can be applied to any tag, such as the body.
<style> body { background-color: blue; } </style> All the text on a web page is in the body section.
Changing font color color:
Now the text is a bit hard to read on the blue background. Because the <body> tag is the highest possible visible HTML tag, the body selector will also allow us to target the font color on the entire page.
<style> body { background-color: blue; color: white; } </style> All the text on a web page is in the body section.
You can also add background images to your web page (background-image: url(/images/textures/light2.png);)
with the property background-image: and the value url(link to image file);
For example:
<style> body { background-image: url(/images/textures/light5.png); color: green; } </style>
All the text on a web page is in the body section.
Using Wordpress or Weebly you can create basic websites without writing any code. However, if you want to build the next YouTube, Google, Twitter or Facebook, the first computer languages you need to learn are HTML and CSS!