CS4ALL Computer Science For All Of Us
  • Home
  • Community
  • Workshop
    • Workshop Info
    • Schedule
    • Location
    • Sponsors
  • Resources
    • Scratch Resources
CS4ALL
  • Home
  • Community
  • Workshop
    • Workshop Info
    • Schedule
    • Location
    • Sponsors
  • Resources
    • Scratch Resources
  • Home
  • Scratch Resources

Scratch Resources

In Drawing a square we used the commands “move 50 steps” and “turn clockwise 90 degrees” four times each. To shorten this task we can use the repeat command. Wrapping blocks in a repeat allows us to reuse the logic. Draw a Circle A computer can only draw straight lines, but we can create the […]Command Action Start a sequence of commands running when the flag above the stage is clicked. Go forward a number of steps (or backward for negative steps) Rotate pen to right Rotate pen to left Clear the drawing Return pen to the middle of screen Do not draw a line as sprite moves Draw a […]This tutorial is based off an excerpt from The Absolute Beginner’s Guide to Coding Using Scratch hard copies and digital copies can be purchased on Amazon Drawing in Scratch is a lot like drawing with a pen and paper, except in order to draw something in Scratch, you have to tell the computer in which […]This tutorial is based off an excerpt from The Absolute Beginner’s Guide to Coding Using Scratch hard copies and digital copies can be purchased on Amazon On the Scratch website, click the Create menu item at the top of the web page. When you first open Scratch you will see something similar to the sketch […]If we wanted to keep track of the score in a game, we stored the current score in a variable. But what if we had a game with 100 levels and we wanted to keep track of the score that the player got at each level? Unfortunately, variables can only store ONE thing at time, […]Adding images is a great way to add to a program. But there are some things to keep in mind: Your project must be saved! Your image must be saved in the same directory as your project Your image must be saved as one of the following formats: GIF, JPG, TGA, or PNG If we […]Processing has several functions like ellipse(), rect(), and fill() Those functions are provided by the makers of Processing to make our life easier when drawing and coloring shapes. We can also make our own functions! Functions are great for making reusable code. If we perform the same task over and over again, we can simply […]For loops do the exact same thing as while loops except they are formatted differently. Just like while loops, we use for loops to make the boring, repetitive tasks of programming a lot easier. Some programmers like for loops better than while loops because they are more readable, while other programmers like while loops better […]If you wanted to draw 10 identical ellipses in a row, you could write 10 ellipse functions like so: Writing out 10 ellipse functions is not very hard, but what if you wanted to draw 200 ellipses or 1000 ellipses? It would be a lot of work to write all those ellipse functions (and even […]We are going to create a program in which a ball bounces off the four walls of the screen. Each time the ball hits a wall, it changes color. When programmers write large programs, they first write a tiny chunk of the program and then check to see if it is working before they move […]

Repeat

In Drawing a square we used the commands “move 50 steps” and “turn clockwise 90 degrees” four times each. To shorten this task we can use the repeat command. Wrapping blocks in a repeat allows us to reuse the logic.

Draw a Circle

A computer can only draw straight lines, but we can create the appearance of a curved line by drawing a bunch of of tiny lines that, when connected together, look like a circle

Since a circle has 360 degrees, we can create a circle by making 360 tiny lines, each one pixel long. After each line is drawn, we turn the pen 1 degree to the right.

What if you wanted to draw a circle to the left? You could repeat the same commands except change the command “right” to the command “left.”

To make the circle bigger we can change the length of line (For example: move 3).
Drawing a Triangle

We can also use the repeat command to easily make an equilateral triangle (a triangle in which the length of all three sides are equal). Since each of the internal angles must also be equal we can create a triangle by rotating the pen 120 degrees after each line is drawn.

Common Tasks

Command Action
Start a sequence of commands running when the flag above the stage is clicked.
Go forward a number of steps (or backward for negative steps)
Rotate pen to right
Rotate pen to left
Clear the drawing
Return pen to the middle of screen
Do not draw a line as sprite moves
Draw a line as sprite moves
Make the sprite say something in a speech bubble.

Drawing a Square

This tutorial is based off an excerpt from The Absolute Beginner’s Guide to Coding Using Scratch hard copies and digital copies can be purchased on Amazon

Drawing in Scratch is a lot like drawing with a pen and paper, except in order to draw something in Scratch, you have to tell the computer in which direction to draw the line and how far to draw the line.

By convention, we will use a sprite that looks like a green triangle when drawing as an aid to visibility. You can think of this triangle as a pen. Whichever direction the pen is pointing is the direction the line will be drawn. It is ok to continue using the cat sprite or you can pick your own shape.

Step 1

The first thing we need to do is draw a straight line. To do this, we will need to put the pen down. Pen down is a command block in the Pen section of the block palette. Then we will need to move the sprite. Move is a command in the Motion section. Set move to 50 steps.

Step 2

When you click on the flag above the stage, the pen will move across the screen and there will be a line from where the pen started to where the pen ended.

Step 3

Now we want to draw the side of the rectangle. To change the direction of pen use the turn clockwise block. Set the turn to 90 degrees. This tells the program to rotate the pen 90 degrees to the right. The pen will change direction and will now be facing down.

Next, draw the side if the square by connecting another move 50 steps block. Your program should look like this.

And when your program runs, it should draw two sides of a square like so:

Step 4

You can see where this is going. Snap together a couple more turn and move command blocks to complete your program.

We manage to create a square! In futures chapters we will learn how to draw triangles and circles

Scratch – Basic Program

This tutorial is based off an excerpt from The Absolute Beginner’s Guide to Coding Using Scratch hard copies and digital copies can be purchased on Amazon

On the Scratch website, click the Create menu item at the top of the web page. When you first open Scratch you will see something similar to the sketch below.

One of the first thing you will notice is that there is a picture of a cat in the middle of the stage area. The cat is called a

sprite
. A sprite is an object that performs actions in the program. You can change your sprite’s image by clicking on the Costumes Tab in the Block Palette.

Making a program in Scratch is a snap because everything we want to tell the computer to do can be made by fitting together the command blocks. For our first program we will make the cat say “Hello World.”

Step 1

The first thing we need is a way to start the program running. Click on

Events
in the block palette.

This will reveal a the event command blocks. We would like the program to start running whenever the green flag above the stage area is clicked. Drag the when flag clicked block into the script area.

Step 2

Next, click on

Looks
in the block palette. Drag the
say
block into the script area, connecting it to the when flag clicked block.

Step 3

Double click the world “Hello!” and change it to “Hello World”

That’s it. You have written your first program in Scratch.

Running your program
To run your program, click on the green flag above the stage area. You should see your sprite say “Hello World.”

Arrays

If we wanted to keep track of the score in a game, we stored the current score in a variable. But what if we had a game with 100 levels and we wanted to keep track of the score that the player got at each level?

Unfortunately, variables can only store ONE thing at time, which means we would have to declare and initialize 100 variables in our program. Doing all that writing is very tedious, which is why we use arrays to initialize a lot of variables at one time. An array is like a list of variables.

How Arrays Work

Every item in the array must be the same data type, which means that an array can only store all integers or all data type array name we are initializing the array with 5 elements the brackets mean that we are declaring an array booleans or all strings.

An array has a fixed size. This means that when you declare the array, you must tell Processing how many items you are going to store in the array. So if you tell Processing you want 5 items in your array you can not increase the array size to 6 or decrease the array size to 2 later in your program.

Adding or Changing Values in an Array
Now that we’ve instantiated an array, we need to learn how to add a value or change a value in an array. We can think of arrays as a bunch of boxes lined up in a row, the first box is labeled with 0, the second with 1, the third with 2, and so on, for all the boxes in the array. These numbers are called
index positions
and they are the same for every array.

We assign a value to the array by writing the array name and the index position of of the value between brackets.

int[] scores = new int[5];
scores[0] = 3;
scores[1] = 2;
scores[2] = 3;
scores[3] = 5;
scores[4] = 1;

int[] scores = new int[5]; scores[0] = 3; scores[1] = 2; scores[2] = 3; scores[3] = 5; scores[4] = 1; for (int i = 0; i < scores.length; i++) { println(“Score ” + i + “ is ” + scores[i]); }

Finding the size of an Array
To quickly find the size of the array, we can append the .length function to the array name. In the following example, Processing will print to the console: “The size of times is: 6.”

int[] times = {12, 34, 56, 14, 39, 13};
println(“The size of times is: “ + times.length);

Images

Adding images is a great way to add to a program. But there are some things to keep in mind:

  • Your project must be saved!
  • Your image must be saved in the same directory as your project
  • Your image must be saved as one of the following formats: GIF, JPG, TGA, or PNG

If we wanted to use an image called turtle.jpg in a program called TurtleImage, we would save it into the same directory as the program.

Make sure your images are saved to the right place! You can quickly find the directory your project is saved in by going to Sketch > Show sketch folder.

When we use an image in a program, we must first load the image into a variable with the datatype of PImage. We load the image inside the setup() function because loading the image elsewhere will reduce the speed of the program.

Bouncing Image

To add an image to your project you must first save your project somewhere on your computer. Then you must save the images you want to use to the same directory as the project the image is being used in

int xPos = 100;
int yPos = 100;
int xSpeed = 2;
int ySpeed = 3;
PImage turtle;
int turtleImageHeight = 80;
int turtleImageWidth = 125;
void setup() {
 size(500, 300); turtle = loadImage(“turtle.jpg”);
}
void draw() {
 background(255, 255, 255); 
// Check if turtle hit right wall 
if (xPos > width - (turtleImageWidth / 2)) { 
xSpeed *= -1; 
} 
// Check if turtle hit left wall 
if (xPos < 0 + (turtleImageWidth / 2)) { 
xSpeed *= -1; 
}
 // Check if turtle hit bottom wall 
if (yPos > height - (turtleImageHeight / 2)) {
 ySpeed *= -1; 
} 
// Check if turtle hit top wall
 if (yPos < 0 + (turtleImageHeight / 2)) {
 ySpeed *= -1; 
} 
/* Adjust the x and y-coordinates of the center of the circle */
 xPos += xSpeed;
 yPos += ySpeed;
 imageMode(CENTER);
 image(turtle, xPos, yPos);
} 
If your image is not showing up in your project, check to make sure that you spelled the name of the image exactly as it appears in the file directory (including the format of the image, like .jpg or .png)

Functions

Processing has several functions like ellipse(), rect(), and fill() Those functions are provided by the makers of Processing to make our life easier when drawing and coloring shapes.

We can also make our own functions! Functions are great for making reusable code. If we perform the same task over and over again, we can simply call the function rather than rewriting the same block of code over and over again.

Why use functions?
We also use functions to break up our code into small, easily read parts. So far, we have only made small programs with one big chunk of code, but when you create a program with 200 or more lines, breaking your code up into functions will help you not only read your code but also fix errors in your code

Syntax
Sometimes we use functions to calculate a value and then return that value to the main program. It is important to note that a function can only return ONE value. However, we can pass as many parameters as we want to the function.

The

function name
is the name we call whenever we want to use a function in our program

The

return type
is the data type that the function will return A function that returns a value must use the return keyword in the program. The
return
keyword tells Processing to return a particular value from the program.

Parameters
are the values inside the parenthesis. A function can have as many parameters as you want. Each parameter must have a data type associated with it.

Using a Function:
In order to use a function, we must call it from our main body of code. To call a function we simply write the function’s name followed by the parameters expected by the function. For example, we would call the above program like so:

multiplyTwoNumbers(4, 5); 

Since the function is expecting two integers as parameters, you MUST call the function with two integers. An error will occur if you pass the wrong data type or if you pass too many or too little parameters.

Function Example
int multiplyByFive(int n) {
 return n * 5;
}
void setup() {
 println(“Multiply 3 by 5: “ + multiplyByFive(3));
}

Sometimes we do not want to return anything from a function. When that happens the return type is called

void
. When the return type is void we do not use the return keyword.

The setup() and draw() Functions
Two functions, setup() and draw() are special functions offered by Processing. These two functions are never called by us, rather Processing calls them automatically.

For Loops

For loops do the exact same thing as while loops except they are formatted differently. Just like while loops, we use for loops to make the boring, repetitive tasks of programming a lot easier. Some programmers like for loops better than while loops because they are more readable, while other programmers like while loops better because they are easier to understand.

We are using the variable “count” to count the number of times we will repeat the block of code. There are three parts to the for loop, the first part,

int count = 0
, tells the computer to start with the value 0 for count. The second part of the loop,
count < 4
, tells Processing to keeping running the loop while the count is less than 4. The third part of the loop,
count++
, tells Processing to increment the count variable by 1 every time the loop finishes.So, in the example above, if we start at 0 and end at 4 we will loop a total of 4 times (count = 0, count = 1, count = 2, count = 3) .

Example

Lets say we want to sum all the integers from 1 to 10 (e.g. 1 + 2 + 3 +… + 9 + 10). An easy way to do this would be to use a for loop.

int sum = 0;
for (int count = 1; count <= 10; count++) {
sum += count;
}
println(“The sum of all integers from 1 to 10 is: “ +
sum);

Lets examine what is happening in this loop. We start at 1 (count = 1), and end at 11 (count <= 10). First, Processing checks to see if 1 is less than or equal to 11. Since it is, Processing executes the code in the loop body. In the loop body we do a simple math operation, which is adding the current count to the sum. When the loop is finished, which means that it reaches the closing curly bracket ( } ), the count is incremented by 1. Processing then checks to see if the count is less than or equal to 10, if so, it executes the code in the loop body. It will keep looping until the count is greater than 10.

When the loop is finished, Processing will print:

The sum of all integers from 1 to 10 is: 55

While Loops

If you wanted to draw 10 identical ellipses in a row, you could write 10 ellipse functions like so:

size(500, 300);
//Declare and initialize variables
int xPos = 30;
int yPos = 150;
int diameter = 40;
int space = 49;
// Draw 10 circles
ellipse(xPos, yPos, diameter, diameter);
ellipse(xPos + space, yPos, diameter, diameter);
ellipse(xPos + 2 * space, yPos, diameter, diameter);
ellipse(xPos + 3 * space, yPos, diameter, diameter);
ellipse(xPos + 4 * space, yPos, diameter, diameter);
ellipse(xPos + 5 * space, yPos, diameter, diameter);
ellipse(xPos + 6 * space, yPos, diameter, diameter);
ellipse(xPos + 7 * space, yPos, diameter, diameter);
ellipse(xPos + 8 * space, yPos, diameter, diameter);
ellipse(xPos + 9 * space, yPos, diameter, diameter);

Writing out 10 ellipse functions is not very hard, but what if you wanted to draw 200 ellipses or 1000 ellipses? It would be a lot of work to write all those ellipse functions (and even more work if you make a mistake in your calculations and have to correct every ellipse function).

Luckily, there is something called a while loop that allows us to draw as many ellipses as we want in just a few lines of code.

The text between the parentheses is called the

loop condition
. The loop condition must always be a boolean, which means that the loop condition must be true or false. The code between the curly brackets ( { } ) is called the loop body. The loop body is what gets executed if the loop condition is true.
int counter = 0;
int i = 0;
while(counter < 10) {
 i += 5;
 counter++;
}

When Processing gets to a while loop in a program, it first checks the loop conditional (in the example above, the loop conditional is counter < 10) to see if the statement is true. If it is true, it executes all the code in the loop body.

When Processing reaches the end bracket, it checks again to see if the conditional (counter < 10) is still true. If it is, Processing jumps back to the beginning bracket and processes all the code in the loop body.

As long as the conditional is true, Processing will continue to execute the code in the loop body. Processing can not exit the loop until the conditional is false.

While loops can be difficult to understand at first.
It can be very helpful to walk through the code yourself line by line in order to understand what Processing is doing when it executes a while loop
int counter = 8;
while (counter < 12) {
println(“counter is: ” + counter);
counter++;
}
println(“counter is greater than or equal to 12, exit the
 while loop”);
counter is: 8
counter is: 9
counter is: 10
counter is: 11
counter is greater than or equal to 12, exit the while loop
Drawing Circles
size(500, 300);
// Declare and initialize variables
int counter = 0;
int xPos = 30;
// Draw 10 identical circles in a row
while (counter < 10) {
// Draw the ellipse
ellipse(xPos, 150, 40, 40);
// Shift the x-coordinate of the center of the circle // over by 49 pixels
xPos += 49;
// Increment the counter by 1
counter++;

Bouncing Circle

We are going to create a program in which a ball bounces off the four walls of the screen. Each time the ball hits a wall, it changes color.
When programmers write large programs, they first write a tiny chunk of the program and then check to see if it is working before they move onto writing the next section of the program. Fixing errors in a small part of the program is much easier than trying to fix multiple errors in a huge program.
1
In the first section of the program, we want to be able to adjust both the x and y-coordinates of the center of the circle so the circle can move at a diagonal and not just in a straight line.
int xPos = 50;
int yPos = 50;
void setup() {
&emsp;size(500, 300);
}
void draw() {
&emsp;background(255, 255, 255); fill(39, 58, 150); ellipse(xPos, yPos, 100, 100); xPos += 1; yPos += 1;
}
2
We manage to get the circle moving at a diagonal, but it disappears off the screen. In this program, we want to have the ball bounce off the screen. The easiest way to get the ball to bounce is to have two more variables for the speed of the x and y-coordinates of circle. We will add the speed to the x and y-coordinates of the circle in order to get the circle to move. The reason we want to have separate variables for the speed is because it will let us not only add the speed to the x and y-coordinates it will also allow us to subtract the speed. There is a little trick that will allow us to two switch between adding and subtracting the speed: every time the ball hits the wall, we will multiply the speed by negative one (-1). Why does this work? If the speed is positive, multiplying by -1 will make the speed negative. When you add the speed to the x and y-coordinates, you are actually subtracting the speed. On the other hand, if the speed is negative, multiplying by -1 will make the speed positive, because multiplying two negatives makes a positive.
int xPos = 50;
int yPos = 50;
int xSpeed = 2;
int ySpeed = 3;
void setup() {
size(500, 300);
}
void draw() {
background(255, 255, 255);
fill(39, 58, 150);
// Check if ball hit right wall
if (xPos &gt; width) {
xSpeed *= -1;
}
// Check to see if ball hit left wall if (xPos &lt; 0) { xSpeed *= -1; }
// Check to see if ball hit bottom wall if (yPos &gt; height) { ySpeed *= -1; }
// Check to see if ball hit top wall
if (yPos &lt; 0) { ySpeed *= -1; }
/* Adjust the x and y-coordinates of the center of the circle */
xPos += xSpeed; yPos += ySpeed;
ellipse(xPos, yPos, 100, 100);
}
3
The ball bounces off the wall, but half of the circle disappears off the screen before the ball bounces. Let’s adjust the program so the ball bounces whenever an edge of of the circle comes into contact with a wall. In order to do this we will have to adjust the if statements to account for the fact the the xPos and yPos variables keep track of the center of the ellipse.
int yPos = 50;
int xSpeed = 2;
int ySpeed = 3;
void setup() {
size(500, 300);
}
void draw() {
background(255, 255, 255);
fill(39, 58, 150);
// Check if ball hit right wall
//subtract 1/2 of the width of the ball from the width of the screen
if (xPos &gt; width - (100 / 2)) {
xSpeed *= -1;
}
// Check if ball hit left wall
if (xPos &lt; 0 + (100 / 2)) { xSpeed *= -1; }
// Check if ball hit bottom wall
if (yPos &gt; height - (100 / 2)) { ySpeed *= -1; }
// Check if ball hit top wall if (yPos &lt; 0 + (100 / 2)) { ySpeed *= -1; }
/* Adjust the x and y-coordinates of the
center of the circle */ xPos += xSpeed; yPos += ySpeed; ellipse(xPos, yPos, 100, 100);
}</div>
<img src="http://cs4all.cs.mtu.edu/wordpress/wp-content/uploads/2016/07/double-back-circles.jpg" />
<div class="divide">4</div>
Finally, we want to change the color of the ball whenever it bounces off a wall. In order to do this we will need to store the color of the ellipse in a variable. To store a color we will need to use a data type that we haven’t seen before called “color.” To change the color when the ball bounces off the wall we will use the random function to generate a random number between 0 and 255 (Remember that each part of a RGB value must be a value between 0 and 255).
<div class="code">int xPos = 50;
int yPos = 50;
int xSpeed = 2;
int ySpeed = 3;
color circleColor = color(39, 58, 150);
void setup() {
size(500, 300);
}
void draw() {
background(255, 255, 255); // Check if ball hit right wall if (xPos &gt; width - (100 / 2)) {
xSpeed *= -1;
circleColor = color(random(255), random(255), random(255));
}
// Check if ball hit left wall
if (xPos &lt; 0 + (100 / 2)) {
xSpeed *= -1; circleColor = color(random(255), random(255), random(255));
}
// Check if ball hit bottom wall
if (yPos &gt; height - (100 / 2)) {
ySpeed *= -1;
circleColor = color(random(255), random(255), random(255));
} // Check if ball hit top wall if (yPos &lt; 0 + (100 / 2)) { ySpeed *= -1;
circleColor = color(random(255), random(255), random(255));
}
/* Adjust the x and y-coordinates of the center of the circle */
xPos += xSpeed;
yPos += ySpeed;
fill(circleColor);
noStroke();
ellipse(xPos, yPos, 100, 100);
}