How to use audio in P5JS skripts – Part I

Uncategorized

190122 ImageAnimP5.jpg

https://editor.p5js.org/mikefromd/embed/qSTMuQNjs

How to delay the execution of something in Javascript?

In order to delay the execution of a code snippet in Javascript, use the setTimeout() method.

Its syntax is as follows:

setTimeout(functionName, delay)

FunctionName is a call back function that will be executed after the time fixed in the parameter delay has passed. In this video you get more details on how to use this function:

General remark before starting with the audio libraries:

The following tutorials are from Daniel Shiffman and can all be found on his Youtube channel “Codetrain”. I have selected some basic ones for you to get started with audio. Please remember that you have to download your audio file first into the editor, only then the player can access them and you can get your code running.

Please remember that you need to log in with P5JS to be able to upload your audio files. You can then drag and drop them into the field opening when you select Sketch/Add File.

Sound with p5.js

Load and play a sound file

Here is again a video about how to load and play an audio file. Again like with image files, you should use the preload function to make sure that the whole file is loaded before you start to play it.

Besides the basics you see how to change the volume, the rate or speed of the playback as well as the pan (left and right side effect).

This is the code for the basic audio playback

Adding control buttons to your audio player

The following video shows how to add a button playing and stopping the audio.

Here is the finished code for the playing and pausing of the audio track.

Put it all together …

The image and the link to the p5js script at the beginning of this blog show you what you can do while combining audio, images and small animations in P5JS. Give it a try!

 

 

 

More coding with p5.js, about conditionals

Game, GetToKnow, p5js, Uncategorized

Here is a cheat sheet summarizing the most important methods P5JS provides to create graphics.

The following video introduces you to the concept of conditionals. They allow a program to branch, to do different things depending of the evaluation of the condition. Example:

If an object reaches the border of the canvas, then reverse its moving direction.

In Javascript they are of the form

if ( Boolean Expression ) { do something }.

A Boolean Expression is an expression that returns either True or False. If the expression gives true, the part following inside the curly brackets is executed, otherwise the program continues aftere the curly bracket.

In order to get True or False, you can apply different types of operators, normally on a combination of fixed values and variables. Today we will use relational operators.

A relational operator is of the form <, >, <=, >=, ==, ===, !=. They compare two values of same type, if the result is correct, the operator returns True, otherwise False. Here are two examples for relational operators:

(5 < 10) gives True. Another example: (5 > 1000) gives False.

Conditionals are used with variables. These can contain different values, and depending on their actual value and another fixed or also variable value, the operator returns True or False.

Here is the video:

There is another family of operators used frequently, logical operators. They work on boolean values. The most common operators are AND (in JS “&&”) and OR (in JS “||”).

Example for a logical expression within a conditional:

IF the ball is touching the upper border of the canvas AND at the same time touching the right border of the canvas, THEN do something.

This would express in Javascript as follows assuming that you have defined a vector object ball with the coordinates x and y. You can get its x coordinate with ball.x, the y coordinate with ball.y. Furthermore you need to know that the upper border has the y value 0 and the right border the x value width. Then you could write:

if (ball.x > width && ball.y < 0) {do something}

You can describe the result of a logical AND operator depending on two input values in a table as follows:

Value 1  Value 2   Result

True     True      True

True     False     False

False    True      False

False    False     False

The other important logical operator is the OR operator. It can be described with the following table:

Value 1  Value 2   Result 

True     True      True 

True     False     True 

False    True      True 

False    False     False

Following are some exercises you can open, modify and then save in your account. You will need to manipulate colours, the website below allows you to determine the three integer numbers to choose a colour:

https://htmlcolorcodes.com/color-chart/

 

Now you can apply your knowledge about conditionals, Here is a code snippet you can work on and some tasks you can try out:

CodeSnippet Conditional 1

The tasks:

  • Draw a vertical line at x=150, give the line a thickness of 10 units and then make the colour of the background change when you pass the line from left to right.
  • Change the background colour when you go beyond the bottom of the canvas.
  • Change the the background colour when you reach the top right corner. You will need to use a logical operator together with two relational operators.
  • Change the colour of the background to the left of the vertical line x=150 to red when you move the mouse beyond the line. You may need to use a big rectangle to achieve this.
  • Copy the code and make a new project with it. Create a rectangle in the middle of the canvas. When the mouse is hovering over the rectangle, it should change its colour.

Revisit the Snake Game

Here is another full implementation of the snake game. Once you have opened the editor, you need to click on the small flash on the top left of the editor to open the file menu. The full code for the game is in the files script.js and snake.js.

Snake Game V2

Do the following modifications to the game:

  • Change the size of the canvas and see what happens.
  • Change the colour of the food
  • Change the size of the food in order to get a bigger playground.
  • Change the speed of the game
  • Reassign different keys for moving the snake.
  • Use the mouse to control the snake, not the keyboard.

Once you have opened the link, make sure that you have logged into your account. Once you have made changes to the code, you can save them as your own under “File”, “Save”. Don’t forget to give the project a suitable name.

Modify a clock

Here is a video showing how to create a “analog” dial clock with P5JS.

You may look in the References section of http://www.p5js.org to learn more about the methods transform(), rotate, push(), pop() as well as arc(…).

The “%” operator gives the remainder of a division on an integer number. Ex.: 23 % 12 = 11, 4 % 2 = 0, 5 % 2 = 1.

the map() function is defined in the p5js reference as follows:

Re-maps a number from one range to another.

In the example given in the reference, the number 25 is converted from a value in the range of 0 to 100 into a value that ranges from the left edge of the window (0) to the right edge (width). So you do not need to do the calculation yourself.

Here is the code for this clock:

p5js Clock

 

Have a look and modify the clock. Here are some ideas:

  • Change the colours of the indexes.
  • Change the way the time is shown (no index, maybe coloured arcs? Have a look in the video.
  • Create a 24 hour clock.

p5.js – Create, Move and Interact with Sprites

Animation, p5js, Uncategorized

Here are some additional exercises, they prepare you for the game we will do in the following lessons, step by step.

Create a smiley

181105 Smiley oho

https://www.openprocessing.org/sketch/598332/embed/?plusEmbedHash=NjBhNzY4OGI5ZmRhYmQ1ZDA4Yzk0OTY4NGIxNzFjOWQyYzI1MjBhYmJkZmQxYzFiMTUyNWE3Zjc0YzJiZDI3MTJkY2I1ZWZiYTE4MTdiNThiNzUzNDdhZDc1YjcxZmQ2YmU5Y2YzYzEyMGQ2YjE1NWVjMjI4Yzk3Njg5ZGZlOWQwZ01XOUpsbjlHK0t0WmwrNU5BSTZNbjhBbk90OFhpaWhCK2R1ZWV6azZUVzNZTzV5RURWZ1VDWDdhYW95SVRpdWF5QUMvN3JCS1h6eUVRNGxUL1VHQT09&plusEmbedTitle=true” target=”_blank” rel=”noopener”>Smiley on Openprocessing

As a first step only create the lower lip, then you have a “classical” smiley.

Create a Packman sprite

pacman-151558_640.png

Hint: There is a shape function “arc(…)” that allows you to create the body of the Packman with one line. Have a look in the documentation and play around with the parameters inside the parenthesis.

Don’t forget that angles are entered in radians. 0 degree is 0 radian, 180 degrees are PI radians and 360 degrees are 2*PI radians. PI is a constant in p5js, its actual value is 3.14… You only need to generate the Packman, the three small circles we do not need for now.

Control the movements of your sprite with the mouse

How to interact with your program? How can you control what is happening on the canvas?

P5JS gives you access to the mouse and the keyboard.

The mouseX and mouseY variables return you the current position of the mouse cursor. You can use it to make a rectangle follow your mouse on the canvas:

181106 mouseX.jpg

Here is a video p5js mouse position that shows you more about this mouse variables and some related variables.

Your program can also recognize when the mouse is pressed and then do something. Here is a code snippet, you add your action between the curly brackets.

A shorter way for the if statement is simply “if (mousePressed) { … .”


if (mouseIsPressed == true) {
// do something
}

 

Control the movements of your sprite with the keyboard

You can also use the keyboard to control what is happening on the canvas. Here is a code snippet that uses four different keys. You find more information about the subject of keycodes in the reference documentation.

181106 p5js_KeyEvents.jpg

Make a rectangle change its colour depending on mouse or keyboard events

Now you have all the tools you need to create a small project that changes colour and or position of a rectangle. Here is a nice example

Next Step for the Packman game

With the examples given before, you can now make the Packman follow a horizontal line along the x axes.  The tricky part consists in making him turn and then also turning his face. Think about a solution before you have a look https://editor.p5js.org/mikefromd/embed/Skn51kA3m“>here and this is the code

 

 

 

Micro:bit – Catch Game Part II

Uncategorized

The game should now look as follows, it is already fully playable:

181008_CatchGameFull1

Replacing the buttons with the accelerometer

An important remark first, do it like a pro …

When developming the program, do it like a pro. Professionals develop and test their software on simulators and with special test software. We do not have the later, but we have a simulator. You can check your changes immediatly when you launch your program on the simulator at the left. Do it!

First we want to replace the buttons with values supplied by the accelerometer. Then we only need to tilt the micro:bit from left to right or bottom to top so to control the movement of our sprite. This is much more convenient. Have a look again at the code we implemented last week. We need to replace the two blocks with “on button A/B pressed” by something new comprising out of a block to change the position of the sprite, getting the values of the accelerometer and these two embedded in a “forever” loop.

The values provided by the accelerometer vary between -1023 and +1023. That’s a lot, we only have 5 x 5 LEDS on our micro:bit. So if we do nothing, an even so small movement will always make our sprite move from one border to the other. So we need to transform this big range down to something feasable for our display. We do this by dividing the value coming from the accelerometer by a big number, matching the single moves we need to. Try to find a suitable value.

Another problem is the forever loop we will embed our acceleration block into. It is providing values many times per second, so when we move our micro:bit even a tiny bit, it will record many movements and each of them will relocate our sprite again to the border of the display. We can avoid this if we place a pause block after taking a value from the accelerometer. Find a suitable value again.

Try this out by yourself before looking at the solution. Then compare your solution with the one below.

181008 CatchGameAccelerometerBasis

Completing the Game

Now we can finish the game. What is still missing to get a real game?

Here are my suggestions:

  1. We need to allow the player to do the game many times. So each time we need to delete the old target and create a new target.
  2. Get a timer that counts down, so we have a fixed time to play.
  3. We need to count the points and at the end show the score.

The following program does that all. but I suggest that you try to figure out yourself what to do first. Most of the blocks you need, you can find in the category “Games”

181009_CatchGameFinal1

TIPP: This game may work great on the simulator, but depending on your choice of values for the pauses and the transformation of values coming from the accelerator, it may not run properly on the micro:bit. In case you have problems, adjust the values for pauses, and more important for the acceleratior. Then you will get the game running on the micro:bit.

micro:bit Curriculum: Variables

  • Why do we use data, in particular in science and mathematics?
  • What type of data do we have around us?
  • How do we track those data in real live? Which operations do we use in CS?
  • Difference between a constant and a variable
  • Which data types can constants and variable hold in Javascript? (numbers, booleans, text, objects and functions)
  • What operations do we have available to calculate with those variables? They are different depending on their type!

Let’s make a scorekeeper and then see how we can use variables to count values coming from our sensors on board of the micro:bit

Make a scorekeeper

Everything counts

Micro:bit – Accelerometer, the Game Blocks and a Catch Game Part I

Blocks, Game, micro:bit, Uncategorized

For this game we need to use the accelerometer to sense the orientation of the micro:bit. This sensor is comprehensively described in the documentation. You find it under “Reference”.

mb_Accelero

Let’s have a look at one sensor, we choose the accelerometer. It measures acceleration, caused by gravity and sudden movements. Here is a sketch explaing about the three coordinates it uses to put the acceleration into numbers. You can measure the acceleration in on direction (x, y, z) at a time. The values change between -1023 and 1023.

mb_coordSys

Here is the link accelerometer so that you can have a look.

The documentation is interactive, so you can also upload a sketch to the IDE and run it there. Furthermore, you find examples that you can also easily transfer to the editor, no need to rebuild the projects.

Get to know sensors and how to program them.

Get the examples running on the simulator and your micro:bit. As a next step find the documentation for the magnetic sensor and implement a compass.

Game module

In the micro:bit editor under Advanced you find the category “Game”. It contains blocks to make small games.

The small display of the micro:bit contains 5 x 5 LEDs. In the game module you can address each LED with its coordinates (x, y). You may know coordinate systems from school, they have their origin (0,0) always at the lower left corner. In computer science we normally put the origin at the upper left corner.

mb_coordSysLED

Create your first game

Following you find the beginnings of a small game. At the beginning of the game a LED will light up at a random location. Then the player needs to move the other LED to that location using the buttons A and B. When he reaches the final position, the display shows “Win!”. The button A is already coded, try to understand what is happening when you press the button. Then finish the game by coding the functionality for button B.

181002_Catch1


let dir_x = 0
let sprite2: game.LedSprite = null
let sprite1: game.LedSprite = null

sprite1 = game.createSprite(2, 2)
sprite2 = game.createSprite(Math.random(5), Math.random(5))
dir_x = 1

basic.forever(() => {
if (sprite1.isTouching(sprite2)) {
basic.showString("Win!")
}
})

input.onButtonPressed(Button.A, () => {
if (sprite1.isTouchingEdge()) {
dir_x = dir_x * -1
}
sprite1.change(LedSpriteProperty.X, dir_x)
})

input.onButtonPressed(Button.B, () => {
})

Above is the code in Javascript, open the micro:bit Javascript editor, select “{}Javascript” and then copy and paste the code into the editor. Next, select “Blocks” and the code will be converted into the Block language. Here you can now

  • try out the program,
  • figure out what is happening when you press  Button A and
  • then add the missing functionality for button B.

Games, Animation and Arts – Introduction of the Tools

Uncategorized

When running my Games, Animation and Arts class, I am using three programming tools:

  1. P5.js, this is a Javascript library based on the Processing language.
  2. Alice 3, a program to tell stories and make small games in 3D, using a block based programming languag. You can also code Alice in Java, but this is not covered here.
  3. Micro:bit controller using external hardware as LEDs, Neopixel bands as well as other sensors and actors, programmed in Blockly, Python or C.

P5.js

P5.js is a library for the programming language Javascript. Javascript is very popular for web programming. We will use this language to learn the basics of coding. P5.js provides a lot of functions that allow us to create artwork. Here is one example:

P_4_3_1_02-150x150

Have a look at generative-gestaltung and look at the section “Sketches”. By clicking on the portfolio images, you can use them. When you are interested to see how they are working, click on the “Open in P5.js Editor” link. This coding environment is the primary tool in the activity.

Furthermore, you find a nice introduction to Javascript based on a derivative of p5.js called processing.js on Khanacadamy.

Alice 3

Alice is a platform that lets you to tell a story with animated 3D figures and sound. A scene editor provides you with plenty of characters and props to set up the scenes of your story.

181002 AliceUfoSpot1

A code editor allows you to control the flow of the story by selecting, arranging and configuring blocks. It’s a bit like Scratch, but you can do more things. The program when started controls the flow of your story.

181002 AliceIntroCode1

A nice introduction is following an Hour of Code activity described here.

Alice 3 is not available on the web browser, but you can freely download the program here and install it on your computer. If you want to transfer your projects between school and class, just load them on your Google Drive or on an USB stick. For more advanced coders, you can also program. Alice scenes with Java. A description can be found on the Alice homepage.

The micro:bit

The micro:bit microcontroller is a simple to use platform that allows you to control many different devices as LEDs, Neopixel bands, level meters, basically all sorts of sensors and activators. The program needs to be written on a PC, some tools run on a browser others require you to install an application on your computer. Once you have finished your program, you compile and download it on the micro:bit, either by USB cable or by Bluetooth. This depends on the tool. Here is an example of a program controlling a Neopixel band.

Here is the setup of the hardware.

IMG_1373

Code sample

The following code is written in Python and uses an editor and compiler you can access with the web browser. The browser will compile you an executable file, a program, that you can upload to the micro:bit with a USB cable.

This first example changes the colour of the Neopixels one after another and leaves each pixel on until it is refreshed in a different colour.

"""
Repeatedly displays random colours onto the Neopixels.
Works for Neopixel strips of 30.
"""

from microbit import *
from neopixel import NeoPixel
from random import randint

# Setup the Neopixel strip on pin0 with a length of 30 pixels
np = NeoPixel(pin0, 30)
while True:
#Iterate over each LED in the strip
for pixel_id in range(0, len(np)):
red = randint(0, 60)
green = randint(0, 60)
blue = randint(0, 60)
# Assign the current LED a random red, green and blue value between 0 and 60
np[pixel_id] = (red, green, blue)
# Display the current pixel data on the Neopixel strip
np.show()
sleep(100)

Here is another example with a different lighting pattern:


"""
Adafruit example, modified to run with 30 LED strip.
see at
https://learn.adafruit.com/pages/11472/elements/2981640/download
for the basic version with one running neopixel
180815 Modified the original version, but not yet debugged.
181001 Debugged and running!
"""

from microbit import *
from neopixel import NeoPixel

num_pixels = 30
foreground = [255, 0, 0] # Int color - red, green and blue
foreground2 = [0, 255, 0]
background = [16, 16, 16]

ring = NeoPixel(pin0, num_pixels)

while True:
# red/green dot circles around a white background (for 30 neopixel strip)
for i in range(0, num_pixels-1):
ring[i] = foreground # set pixel i to foreground
ring[i+1] = foreground2
ring.show() # actually display it
sleep(50) # milliseconds
ring[i] = background # set pixel to background before moving on
ring[i+1] = background
ring.show()
# implement the closing of the circle for last and first element.
ring[num_pixels-1] = foreground
ring[0] = foreground2
sleep(50)
ring[num_pixels-1] = background
ring[0] = background

With the micro:bit you can create interactive artefacts, that’s what we are aiming for in this course.

More Experiments with the micro:bit II

Uncategorized

If you have completed all activities from the previous week, you can implement the following two projects as well:

Temperature Activity

180925 mcShowTemp

The micro:bit has many sensors on board, also a temperature sensor. Here you will use it to measure the environmental temperature. Click on the attached link to go the page with the instructions on how to program your activity.

Temperature Activity

Some background: Computational Concepts I

Once you have done one or two projects, it may be time to get to know some key computational ideas that will help you to modify exisiting projects and also create your own. Have a look here

Die Roll Activity

180925mcRollDice

This small project allows you to build an electronic die. When shaking the micro:bit, it will show you a number, like on a real physical die. This small program contains a variable and a series of if conditions. When implementing the program, focus on the use of variables and the if conditions. You find some more information about these two concepts on the following page.

Click on the attached link to go the page with the instructions on how to program your activity.

Die Roll Activity

The best textual programming language for learners

Uncategorized

When starting to teach computer programming there is no doubt that visual programming languages are best suited for young learners. But once the students have reached a certain mastery, there are a lot of languages to choose from. “8,512 different programming languages” (Alfred Thompson) have been created so far while the first computer was only made 70 years back. You can apply various criteria to figure out which of those languages are most suitable for students to learn coding. Python is the best choice to learn coding with a textual programming language. It is best suited for a beginner when considering the ease of use, support, and the complexity of the language.

Python has an easy to install and use integrated development environment (IDE), suitable for beginners. All the tools you need can be downloaded in one package free of charge from the internet. There are packages available for all popular operating systems, so the beginner does not need to tweak installation files. He just needs to install and get going. All tools needed, interpreter, editor, debugger are available out of the box. The user interface is easy, there is no need to set parameters or other values the beginner may not be familiar with. The editor offers as default syntax highlighting, so the keywords of the programming language are highlighted in colour. This makes it easier for the beginner to find errors and see the structure. Debugging is further facilitated by comprehensive error messages. For all those reasons Python is very suitable for beginners to learn coding.

The programming language Python is very popular. It has a huge community of helpful coders that offers help. In addition, you find many useful online tutorials to help you getting started. There are many forums on the Internet where people working with Python are sharing their experiences and helping each other, www.python-forum.org is one example. Then you have open source projects promoting learning about computing and programming, for example the Raspberry Pi. On this platform, Python is the preferred programming language. The foundation offers a lot of examples and tutorials to help the beginner. In general the big community of “Pythoneers” has created over the years many libraries to make writing code for graphical output, simulations, games, etc. easier. You just need to import and use those libraries in your program. With that help you can write programs that would require you a lot of additional coding in other languages. These are three reasons why the Python community is really powerful and helps a “newbie” to start with this language.

The Python language has an easy and versatile syntax and semantics. It is not a typed language, so you do not need to declare variables as integers or text strings, the interpreter will figure this out by himself based on defaults and clues you give. While this may sometimes cause confusion, it saves time for typing and out of experience the beginning programmers learn to deal with this rather fast and prefer the saved time for declaring variables. The language is rather compact and uses indents to define blocks of code that belong together. This saves a lot of time for typing code, other languages use various forms of brackets to define blocks. This approach also forces the beginner to pay attention to the style of his coding from the first day, that is useful when he needs to understand his code later of find errors. Furthermore the language offers features for three programming paradigms, the procedural, the object oriented and the functional. This makes the language very versatile for the advanced programmer. These are some examples, why Python is easy and versatile.

JAVA is another well-known programming language, it is used for commercial projects (i.e. Android OS) and at universities. Compared to JAVA, Python has several key advantages. The easier syntax has just been talked about in the previous paragraph. This is a major advantage for the beginner. The availability of libraries is another criteria. While Python is supported by a lot of freely available libraries, there are much less available for Java. Another reason to favour Python over Java is the licensing. Python is known for a very open licensing policy. So the FAQ page of the Python foundation states that “the PSF [Python Software foundation] License allows Python to be included in non-open applications, either in unmodified or modified form“ (Paul Boddie). So there is no problem in bundling your code together with Python and package it for easier installation by a third party. This is not the case for Java where the Java Runtime Environment (jre) cannot be bundled together with your program due to license constraints by its owner, the Oracle Corporation. This is a restriction that makes people move away from Java in some areas.

The Open Roberta project is an initiative by the Fraunhofer Institute FhI (Germany) and is developing and maintaining an IDE to teach children robot programming. They have traditionally been using Java for their project, also due to a missing alternative. Nevertheless they see as one of its shortcomings that “[they] can’t ship ready to use sd-card images, since [they] cannot redistribute the oracle jre” (Stefan Sauer). So the institute is now working on migrating their code to Python so to overcome the shortcomings of the existing solution with Java. This is one example of why Python is better suited for applications in the educational sector.

Summarizing, Python has a lot to offer for the beginner with coding. It has an easy to install and manage programming interface with all the tools a beginner needs to start coding. There is a huge community behind Python developing new libraries and offering help when needed. The language in itself is easy to learn and work with. So it is better suited than Java, another well knows programming language. For all those reasons Python is the best suited textual programming language for learners.

Works Cited

Thomson, Alfred. “HOPL: an interactive Roster of Programming Languages.“ Microsoft Education Blogger, Jan 15th, 2007. Web. Nov. 29th, 2015

Sauer, Stefan. “Open Roberta on ev3dev.” Open Roberta, Oct. 20th, 2015, Web Nov. 29th, 2015 https://mp-devel.iais.fraunhofer.de/wiki/display/ORDevel/Open+Roberta+on+ev3dev

Boddie, Paul. “”. March 29th, 2014,, Web Nov. 30th, 2015. “Python Software Foundation License FAQ, ” https://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq

Why am I here?

Uncategorized

Welcome to my new website, it is all about learning and teaching computer science and the impact of the related technology to our world. I share with you opinions, material and reviews that are useful on your very personal way to discover the beauty and relevance of computer science. While getting directly involved in it was out of reach for many of us a few years back, all of us can get hands-on nowadays.

There is a lot of new material available for all age groups and irrespective of prior knowledge. This blog aims to show you some material with concrete examples you can follow. Create your very own CODE2RUN.

Going on this discovery is most enjoyable if you do it together with someone else. Either you can join one of the many online or courses, these have very helpful communities. More interactive is to take the first steps together with someone face to face, maybe your child? Computer Science is now being taught for young children as early as 5 years, maybe even for younger ones, so again, it is possible and a lot of fun!

This website will provide you with material to try out, with news from the world of computer science and technology, as well as with reviews about some of the tools that can facilitate your journey.

I hope that CODE2RUN is informative for you. Please feel free to leave your comments and share your opinion as well as suggest new topics to investigate and talk about if you like.

Enjoy browsing, reading and making!
Michael Braehler