Build a Space Shooter with Phaser3 and JavaScript(Tutorial2)

In this blog post series, I want to unpack building a 2D shooter game using Phaser3.js. Phaser3 provides a robust and fast game framework for early-stage JavaScript developers. In this post, we’ll focus on enabling our ship to fire lasers.

Space shooter

Please make sure to check out Tutorial 1 to get started with this project. You’ll need to build upon the code and ideas from the previous blog post.

Let’s start by creating a game object to represent a laser. (see code below) We’ll model this object using the ShipLaser class that extends Phaser.GameObjects.Sprite. In general, a class connects data stuff and related functions(or methods) in a nice little package. In this case, the laser has data properties like location(x,y), a texture, speed, and a scene. This code snippet has two methods: constructor and preUpdate.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class ShipLaser extends Phaser.GameObjects.Sprite {

    constructor(scene, x, y) {
        super(scene, x, y);
        this.setTexture('laser');
        this.setPosition(x, y);
        this.speed = 10;
        this.scene = scene;
        scene.physics.world.enable(this);
    }

    preUpdate(time, delta) {
        if(this.active == false){return;}
        super.preUpdate(time, delta);
        this.y -= this.speed;
    }
}

The constructor method enables us to set up the ShipLaser class. We’ll initialize properties like texture, position, speed, and physics.
In Phaser 3, the preUpdate method of a sprite enables us to describe behavior or movement of the sprite. The framework requires that we call “super.preUpdate.” On the next line, we move the sprite upward on the screen by subtracting from the y property.

Let’s make some edits to our Ship class. We’re going to store a reference of the scene. To describe how fast the ship moves over the game space, we initial deltaX and deltaY to 5. In this current design, we’re going to store the list of lasers from the ship in an array. We also need to store some information related to when the last shot was executed.


1
2
3
4
5
6
7
8
9
10
11
12
class Ship extends Phaser.GameObjects.Sprite  {

    constructor(scene, x , y) {
        // ... other setup stuff

        this.scene = scene;
        this.deltaX = 5;
        this.deltaY = 5;
        this.lasers = new Array();
        this.lastShot = new Date().getTime();
        this.shotFrequency = 250;
    }

It’s time to shoot stuff! Let’s define a method to fireLasers from the ship. When my kids play this game, they just keep their fingers down on the space bar the whole time. 🙂 By design, we want to control how often the laser gets shot. We start by checking the current time. The quantity of currentTime – lastShot returns the number of milliseconds since the last shot. If this value is greater than 250, we allow the ship to fire.

When we fire, we create an instance of the ShipLaser we defined. Notice that the ship laser will be created with the same scene and location as the ship. Once we have an instance, we add the laser instance to the scene. We finish up by storing the laser in our lasers list and updating the “lastShot” time.


1
2
3
4
5
6
7
8
9
    fireLasers() {
        var currentTime = new Date().getTime();
        if (currentTime - this.lastShot > this.shotFrequency) {
            var shipLaser = new ShipLaser(this.scene, this.x, this.y);
            this.scene.add.existing(shipLaser);
            this.lasers.push(shipLaser);
            this.lastShot = currentTime;
        }
    }

We have to make one more edit to our Ship class to make the lasers function properly. The “preUpdate” javascript function enables us to describe behavior associated with our sprite. The game framework calls this function on every game tick. In the following code snippet, we’re going to remove laser objects that have reached the top of the screen. We start by building an array of lasers to remove from the scene. In the first loop, we search for lasers that have reached the top of the screen. (i.e. lasers[i].y <= 0) In the second loop, we remove the laser objects from the ship and destroy them. If you create game objects, it’s important to clean them up if you’re not using them.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    preUpdate(time, delta) {
        super.preUpdate(time, delta);

        var i = 0;
        var j = 0;
        var lasersToRemove = new Array();

        for (i = 0; i &lt; this.lasers.length; i++) {
            if (this.lasers[i].y &lt;= 0) {
                lasersToRemove.push(this.lasers[i]);
            }
        }

        for (j = 0; j &lt; lasersToRemove.length; j++) {
            var laserIndex = this.lasers.indexOf(lasersToRemove[j]);
            this.lasers.splice(laserIndex, 1);
            lasersToRemove[j].destroy();
        }
    }

In the scene1 class, we need to add one more detail. The laser should fire when the user presses the space bar. Let’s edit the update method to fire the lasers.


1
2
3
4
5
6
7
```javascript
    update() {
        if (this.cursors.space.isDown) {
            this.myShip.fireLasers();
        }
       
```

If you’re interested in reviewing the completed code tutorial, feel free to visit my GitHub tutorial link.

In the next post, we’ll add some alien targets for our game. We’ll see you next time!

Space shooter graphic

If you’re really excited to learn more, I have found the learning from the examples very helpful.

Phaser Labs Examples

JavaScript Posts from InspiredToEducate.NET



Posted in technology | Leave a comment

Combating Summertime Boredom

As a college professor I have the option to take off about 8 weeks during the summer. I look forward every year to spending this time with my kiddos. During the school year we are constantly running from one activity to the next. It is so nice to be able to relax and have some space in our schedule. That said, I get bored easily. By this point in the summer my kiddos are really starting to pick at each other. This is often a recipe for disaster. In this post I want to share some of my strategies to combat summer boredom and to keep those young minds nimble.

If it were up to my kids, they would watch TV/play video games all day long. Honestly, that would make my life so easy! I could get so much done while they were complete zombies. However, I don’t want to melt their little brains so we try to limit the screen time in our house to two hours per day. The american average is greater than 7 hours.

Activity Books

A couple of the workbooks we use.

When I get up in the morning I need time to drink my coffee and get myself psyched up for the day. The kids often get up and immediately want to turn on the devices. One way that I manage to limit screen time is that I require my kids to eat breakfast, get dressed and spend sometime completing activities in summer bridge workbooks before they turn anything on. These can be found at your local bookstore or on Amazon. There are lots of options. I have one from Kumon, another from Sylvan Learning Centers and one from Brain Quest. I picked ones that corresponded to grade level and offered a variety of activities.

Visit the Local Library
I must admit, I do not use the library much at all during the school year. It is just too much for me to keep track of all the books checked out and stay on top of due dates. In the summer, on the other hand, I make a point to visit the library at least once a week. Most public libraries offer free summer activities for kids and my kids love to bring home new books to read. The variety helps us to keep reading all through the summer! One way to stay on top of the chaos is to have a designated place in the house for the library books. We have a crate where we keep all of our books so it is easy to grab on the way out of the house on library day.

Our library crate.

Play to Your Strengths!
I am a microbiologist and I teach general biology classes. I purchased a small digital microscope that we have been playing with this summer, exploring stuff that we can find in/around our homes. I have also adapted some of the labs that I use with my college kids for home use. I’ll save the details of those experiments for a later blog post, but here are some of the things we found in the backyard yesterday.

Check out the Local Attractions
We are very fortunate to live in Central Florida. We have lots of things that we can do outside the house. Some are free and others are incredibly expensive (I’m looking at you Mickey). We have memberships to the local zoo and to the science center. We also try to visit some of the lesser known attractions. Last summer we went to Gatorland. That place is so awesome! It is a look into what we would call “Old Florida” complete with gator wrestling!

Gator wrestling

Documentaries/Online Learning Programs
21st century kids are constantly exposed to electronic media. I try to be intentional about the type of media that my kids consume. Sometimes I let them choose a cartoon or show from the offerings on Netflix or Amazon Prime Video, but there is so much crap out there! I prefer that they choose shows/activities that are learning centered. For my pre-Kindergartner I like StoryBots (Netflix). She has learned so much from it! The older kids will even watch it wither her.

My fifth grader loves Jonathan Bird. He makes documentaries about sea life that are freely available through his website or through YouTube. Here is our favorite episode:

We also subscribe to the Smithsonian Channel and there are tons of great documentaries available for streaming through Netflix, Amazon and YouTube.

For learning games my kids enjoy the Prodigy math game and learning to program using Scratch ( https://scratch.mit.edu/ )

What sort of activities do you do in the summertime? I would love to know!

-Sarah

Posted in technology | Leave a comment

Build a Space Shooter with Phaser3 and JavaScript(Tutorial1)

Like many computer enthusiasts, I grew up playing video games on the classic Nintendo entertainment system. Some of my favorite games included Super Mario brothers, Legend of Zelda, Tetris, and Star Force. It’s been fun to share these game classics with my kids. They still find them fun. In this blog post series, I want to unpack building a 2D shooter game using Phaser3.js. Phaser3 provides a robust and fast game framework for early stage JavaScript developers.

From exploring the options in 2D game creation using Javascript, Phaser has grown an impressive community of game makers. Here are a few game samples that you would want to explore.

Space shooter assets from www.kenney.nl

In this post series, I wanted to collect a few resources, tools, and links to help you get started building a space shooter game with Phaser 3. We’ll be drawing from the inspiration of classic games like Space Invaders.

In terms of JavaScript writing style, we’re going to keep the code samples as simple as possible to express core concepts. If you need to get started with JavaScript, I recommend checking out the free sources at CodeAcademy to start exploring the language. We’ll be drawing inspiration from classic games like Galaga and Star Force. Even though I’m trying to unpack these ideas for early stage JavaScript coders, I also want to provide examples that leverage ES6 coding structures. The Phaser3 documentation does not focus on this style of code organization. In general, I want to explore programming concepts that provide nice encapsulation and readability. We also want to make sure we can extend these coding patterns well.

The game we’re building may feel similar to this work here:
http://users.aber.ac.uk/eds/CS252_games/mwg2/JSGame/

In this tutorial, we want to encourage you to setup your work environment with Visual Studio code. You can also inspect the tutorial code in the following glitch sample.

https://glitch.com/edit/#!/awg-tutorial?path=shooter.js:1:0

Setting up Visual Studio Code

In this series, I recommend setting up Visual Studio Code on your computer. It’s a robust tool for web development and works well for JavaScript projects. You can find instructions to install VS Code using this link. I also recommend using the Visual Studio Code Live server extension to make it easier to hot re-load your code changes. Please refer to the following video for details.

Downloading some boilerplate code

To save some time, I have organized a ZIP file with a collection of code and graphics that you can leverage in building your own shooter game. You’re encouraged to play and build with these assets, sounds, and code samples to elaborate on your own game. For this first exercise, we just want to get a ship displayed to the screen and move it around using arrow keys.

  • Download the boilerplate code from here.
  • Extract the ZIP file to a location on your computer. We’ll call this your working directory. For me, I might store my files in “c:\alienWarGame-tutorial1.”

Let’s explore the contents of this boilerplate code

  • shooter.js: This JavaScript file will contain our game objects and behavior code.
  • shooter.html: This HTML file provides a home for our JavaScript game code. (see the code below) Please note that we’re downloading phaser.js (version 3.11) from a content delivery network. In the body of the HTML file, we import our shooter.js. Remember to install “Live server” extension for Visual Studio. You will be able to right click on the code HTML file and select “open with Live server.” This will load the file on a small HTTP server on your computer. All phaser games need to be hosted on a web server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
&lt;!doctype html>
&lt;html lang="en">
&lt;head>
    &lt;meta charset="UTF-8" />
    &lt;title>Space Shooter Tutorial 1&lt;/title>
    &lt;script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js">&lt;/script>    
    &lt;style type="text/css">
        body {
            margin: 0;
        }
    &lt;/style>
&lt;/head>
&lt;body>
    &lt;script src="shooter.js">&lt;/script>    
&lt;/body>
&lt;/html>

Breaking Down Shooter.js

All Phaser games start with a little bit of configuration. In this “config” object below, we establish a screen size of 800 pixels by 600 pixels. This will be our drawing surface for the game. To help detect if objects bump into each other, we will be leveraging the ‘arcade’ physics engine included in Phaser3.


1
2
3
4
5
6
7
8
9
10
var SCREEN_WIDTH = 800;
var SCREEN_HEIGHT = 600;
var config = {
    type: Phaser.AUTO,
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
    physics: {
        default: 'arcade'
    }
};

Ok. Let’s build our Space ship player object. In Phaser 3, they have been working to improve the framework to leverage modern JavaScript features like Es6 classes. The class will help us store the properties of the ship. Properties will include stuff like the location of the ship on the screen, object state, and texture. The class will also include several methods for moving the ship around. In the constructor method, we accept a scene object and location on the screen. (x,y). The call to “super” and “setPosition” helps associate the sprite with the parent scene and location. We call “setTexture” using the parameter of ‘ship’ to associate the ship graphic with the sprite. Finally, we set some variables(deltaX, deltaY) to configure how much the ship will move when we press keys.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Ship extends Phaser.GameObjects.Sprite  {

    constructor(scene, x , y) {
        super(scene, x, y);
        this.setTexture('ship');
        this.setPosition(x, y);
        this.deltaX = 5;
        this.deltaY = 5;
    }

    moveLeft() {
        if (this.x > 0) {
            this.x -= this.deltaX;
        }
    }

    moveRight() {
        if (this.x &lt; SCREEN_WIDTH) {
            this.x += this.deltaX;
        }
    }

    moveUp() {
        if (this.y > 0) {
            this.y -= this.deltaY;
        }
    }

    moveDown() {

        if (this.y &lt; SCREEN_HEIGHT) {
            this.y += this.deltaY;
        }
    }

    preUpdate(time, delta) {
        super.preUpdate(time, delta);
    }
}

In the following method called ‘moveLeft’, we implement the math to move the sprite to the left. Since we’re moving left, we subtract 5 pixels from the current x position. We only execute this code if x is greater than zero. Most of the other movement methods operate in a similar manner.


1
2
3
4
5
    moveLeft() {
        if (this.x > 0) {
            this.x -= this.deltaX;
        }
    }

Let’s make a scene!

In the following class, we have to establish a Phaser scene object. It has a few simple tasks. In the “preload” method, need we load the ship sprite graphic from our assets folder.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Scene1 extends Phaser.Scene {

    constructor(config) {
        super(config);
    }

    preload() {
        this.load.image('ship', 'assets/SpaceShooterRedux/PNG/playerShip1_orange.png');
    }

    create() {
        this.cursors = this.input.keyboard.createCursorKeys();
        this.myShip = new Ship(this, 400, 500);
        this.add.existing(this.myShip);
    }

    update() {
        if (this.cursors.left.isDown) {
            this.myShip.moveLeft();
        }

        if (this.cursors.right.isDown) {
            this.myShip.moveRight();
        }

        if (this.cursors.up.isDown) {
            this.myShip.moveUp();
        }

        if (this.cursors.down.isDown) {
            this.myShip.moveDown();
        }

        if (this.cursors.space.isDown) {
            // shooting guns goes here
        }
    }
}

The create method has does additional setup for our scene. We establish a property called cursors that will be used for detecting keyboard input like the arrow keys. We also create a ship instance at (400,500) and add it to the scene.


1
2
3
4
5
    create() {
        this.cursors = this.input.keyboard.createCursorKeys();
        this.myShip = new Ship(this, 400, 500);
        this.add.existing(this.myShip);
    }

We now can start moving the ship around using the update method. The if statements in update help us detect the various arrow keys. We call the appropriate method on the ship. In other words, if we press the LEFT button, we should call this.myShip.moveLeft().


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    update() {
        if (this.cursors.left.isDown) {
            this.myShip.moveLeft();
        }

        if (this.cursors.right.isDown) {
            this.myShip.moveRight();
        }

        if (this.cursors.up.isDown) {
            this.myShip.moveUp();
        }

        if (this.cursors.down.isDown) {
            this.myShip.moveDown();
        }

        if (this.cursors.space.isDown) {
            // shooting guns goes here
        }
    }

Here’s the final step, we associate our game configuration information to a new game. We then add our scene.


1
2
var game = new Phaser.Game(config);
game.scene.add('scene1', Scene1, true, { x: 400, y: 300 });

If you’re really excited to learn more, I have found the learning from the examples very helpful.

Phaser Labs Examples

Posted in technology | Leave a comment

Recording Music and Audio with the Kids using Audacity

As a young person, my mom and dad invested a great deal in my growth as a musician. Looking back, I’m thankful that I’ve been able to use my gift of music to foster various ministries in our church. My wife and I love making music together by singing and playing the guitar. It’s honestly one of my favorite ways to re-charge and relax.

I wanted to give a shout out to a free tool that I have enjoyed using for basic music recording and talks. Audacity, a free and open source music recording software, has the ability to do a multi-track recording and has lots of basic effects. Audacity runs on Linux, Mac, and Windows. In contrast with other audio recording tools, I appreciate the simplicity of the user experience.

As a Dad, I’m excited to share the gift of music with my kids. My little girl has become very interested in singing lately. To help motivate her, I have started recording some of our jam sessions with Audacity. She loves showing off our work to mom. When my wife and I record music, I do use some professional mic equipment. For the recording sessions that I’m doing with my daughter, the laptop mic works just fine.

If you’re interested in starting a podcast, you might consider starting with Audacity. You can always advance to a more complex tool later. I found a comprehensive post on starting podcasts here. I do like their recommendation for purchasing a higher quality mic. In my experience, I’ve never had any issues with Audacity with advanced recording gear.

Here’s some of the key features that I appreciate from Audacity

  1. Multi-track recording: Let’s say that you want to record many singers or instrumentalists individually, Audacity enables you to layer individual tracks for each recording session. This enables you to edit, mute, solo and apply effects on an individual basis.
  2. Metronome: For some music recording situations, it’s helpful to have a metronome to help you align your tracks across sessions. You can add a metronome track by clicking “Generate > Rhythm track.” Audacity will enable you to set the tempo and generate a click track.
  3. Export to major audio formats: Out of the box, you can export your work to most popular audio formats like Wav, Ogg, and mp3. It’s pretty easy to share your work on services like SoundCloud.
  4. Effects: Audacity has many helpful effects for the entry-level sound engineer. You can amplify sound, apply compression, and apply reverb. When I’m playing with the kids in a silly manner, we sometimes enjoy becoming chipmunks by increasing the speed of tracks or adding lots of echoes.
  5. Editing audio: Audacity has a basic set of tools for editing audio. Once you’ve installed Audacity, you might check out David Taylor’s complete guide to Audacity. He provides a detailed introduction to the tool and many advanced features.

In researching this post, I found a pretty cool Edutopia article talking about the benefits of audio recording for writing. I like the idea of using an audio recording as a brainstorming tool. I also like the idea of reflecting on work by recording it and playing it back. I might try this idea as I’m teaching the kids piano.

Related Posts

Posted in creativity, music, open source, parenting, stem, technology | Leave a comment

Inspiring Curiosity

We initially started this blog in 2012. I was a brand new college professor and this platform became an opportunity for my husband and I to share our thoughts and ideas on education and technology. We took the conversations that we had at the dinner table and put them into this public forum. It was a project that we could share. The last time I posted was in 2014, I had just finished my first year in a tenure track position and was getting ready for the arrival of our third baby. It’s true what they say, three is the hardest number of kids. The long and the short of it is that life has been incredibly busy over the last five years. While Michael has continued to maintain the blog, I have struggled with juggling parenting and full time teaching. Throw in an interstate move, a new job, and some extra teaching jobs on the side, and I just did not have the bandwidth to write.

Things are beginning to settle down a bit (I hope) and I feel the need to start contributing again. Two years ago I started my current position at an awesome institution dedicated to high quality education. They invest heavily in faculty development and provide plenty of opportunities for me to hone my craft as a teacher. I have learned so much and I want to share those ideas with others, so here I am, back in the blogosphere.

Michael got super excited the other day when I told him that I wanted to start writing again. For him, this blog has been a labor of love. We sat down over breakfast, before the kids got up, and talked about the directions we wanted to take things. I am a biology professor and he is a computer programmer. We both naturally lean towards topics in STEM, but we don’t want to limit ourselves to that. We tossed around some ideas, and came up with our new catch phrase:

Inspiring Curiosity through Creative Projects and Exploration

As both a teacher and a parent, it is my hope that I can inspire people to get excited about learning. One of my biggest frustrations is when I encounter a student that sees my class as an obligation for getting a degree and not an opportunity to learn new things. I want to tap in to people’s natural curiosity.  With curiosity comes joy in learning and discovery. I want to help people to find awe and wonder in the world around them. I want to use this blog and social media channels to this end. In this world of fear, suspicion and tribalism, I want to encourage others to think outside of themselves and open themselves up to new ideas and perspectives.

I am not sure where this all will lead, but I will leave you with this video that encompasses what I am hoping to achieve. It is of a student seeing Euglena (a microscopic, single celled creature) under the microscope for the first time. The first voice you will hear will be mine, followed by my student’s. I love that I captured this moment, because you can just hear her joy in her laughter. It is more moments like these that I seek.

Posted in technology | Leave a comment

Music Maker: Using NodeJS to Create Songs




Music maker screen shot

In my graduate school career, I had the opportunity with our evolutionary complexity lab to study creating music using neural networks and interactive genetic algorithms. It’s fun to study these two topics together since I enjoy crafting code and music. If you enjoy this too, you might enjoy Music maker, a library I created to explore generating music with code. Sonic Pi by Sam Aaron, a popular tool to teach music theory and Ruby code, inspired me to build this tool. My team from InspiredToEducate.NET enjoyed teaching a coding workshop on music using Sonic Pi. We, however, encountered a challenge of installing Sonic-Pi on a lab of computers. The workshop targets 5th-grade to 8th-grade students who have good typing skills. It would be cool if something like Sonic-Pi supported features like Blockly coding too.

In terms of musical motivations, I wanted to provide features like the following:

  • Like Sonic-Pi, the tool should make it easy to generate chords and scales.
  • I want it to feel simple like Sonic-Pi. I, however, don’t think I’ve achieved this yet.
  • I wanted the tool to have a concept of players who can generate music over a chord progression. I believe it would be cool to grow an ecosystem of players for various time signatures and musical types.
    I wanted to support the MIDI file format for output making it possible to blend music from this tool in sequencers broadly available on the market. This also enables us to print out sheet music using the MIDI files.
  • Building drum patterns can be tedious at times, I wanted to create a way to express rhythm simply.
  • We desired to have a browser-based interface that a teacher could install on a Raspberry Pi or some other computer. This was a key idea from one of my teachers.  I’m focusing on building a tool that works on a local area network.  (not the broad internet)
  • From a coding perspective, we need to build a tool that could interface with Blockly coding someday. JavaScript became a logical choice. I’ve wanted to explore a project the used TypeScript, NodeJS and Express too. I especially enjoyed using TypeScript for enums, classes, abstract classes, etc.

Here’s a sample MIDI file for your enjoyment:  jazz midi test

I do want to give a shout out to David Ingram of Google for putting together jsmidgen. David’s library handled all the low-level concerns for generating MIDI files, adding tracks, and notes. Please keep in mind that MIDI is a music protocol and file format that focuses on the idea of turning notes and off like switches over time. Make sure to check out his work. It’s great NodeJS library.

Here’s a quick tour of the API. It’s a work in progress.

Where do I get the code?

https://github.com/michaelprosario/music_maker

  • run app.js to load the browser application.   Once the application is running, you should find it running on http://localhost:3000 .
  • Make sure to check out the demo type scripts and music_maker.ts for sample code.

JSMIDGen reference

To learn more JSMIDGEN,
please visit https://github.com/dingram/jsmidgen

Hello world


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var fs = require('fs');
var Midi = require('jsmidgen');
var Util = require('jsmidgen').Util;
import mm = require('./MusicMaker')

var beat=25;
var file = new Midi.File();

// Build a track
var track = new Midi.Track();
track.setTempo(80);
file.addTrack(track);

// Play a scale
var scale = mm.MakeScale("c4", mm.ScaleType.MajorPentatonic,2)

for(var i=0; i&lt;scale.length; i++){
    track.addNote(0,scale[i],beat*2);
}

// Write a MIDI file
fs.writeFileSync('test.mid', file.toBytes(), 'binary');

Creating a new file and track


1
2
3
4
5
6
var file = new Midi.File();
var track = new Midi.Track();
track.setTempo(80);
file.addTrack(track);

// Play cool music here ...

Play three notes


1
2
3
track.addNote(0, mm.GetNoteNumber("c4"), beat);
track.addNote(0, mm.GetNoteNumber("d4"), beat);
track.addNote(0, mm.GetNoteNumber("e4"), beat);

Saving file to MIDI


1
fs.writeFileSync('test.mid', file.toBytes(), 'binary');

Playing a scale


1
2
3
4
5
var scale = mm.MakeScale("c4", mm.ScaleType.MajorPentatonic,2)

for(var i=0; i&lt;scale.length; i++){
    track.addNote(0,scale[i],beat*2);
}

Playing drum patterns


1
2
3
var DrumNotes = mm.DrumNotes;
var addRhythmPattern = mm.AddRhythmPattern;
addRhythmPattern(track, "x-x-|x-x-|xxx-|x-xx",DrumNotes.ClosedHighHat);

Setup chord progression


1
2
3
4
5
var chordList = new Array();
chordList.push(new mm.ChordChange(mm.MakeChord("e4", mm.ChordType.Minor),4));
chordList.push(new mm.ChordChange(mm.MakeChord("c4", mm.ChordType.Major),4));
chordList.push(new mm.ChordChange(mm.MakeChord("d4", mm.ChordType.Major),4));
chordList.push(new mm.ChordChange(mm.MakeChord("c4", mm.ChordType.Major),4));

Play random notes from chord progression


1
2
var p = new mm.RandomPlayer
p.PlayFromChordChanges(track, chordList, 0);

Play root of chord every measure


1
2
var p = new mm.SimplePlayer
p.PlayFromChordChanges(track, chordList, 0);

Tour of chord players


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var chordList = new Array();

// setup chord progression
chordList.push(new mm.ChordChange(mm.MakeChord("e4", mm.ChordType.Minor),4));
chordList.push(new mm.ChordChange(mm.MakeChord("c4", mm.ChordType.Major),4));
chordList.push(new mm.ChordChange(mm.MakeChord("d4", mm.ChordType.Major),4));
chordList.push(new mm.ChordChange(mm.MakeChord("c4", mm.ChordType.Major),4));

var chordPlayer = new mm.SimplePlayer
chordPlayer.PlayFromChordChanges(track, chordList, 0);

chordPlayer = new mm.Arpeggio1
chordPlayer.PlayFromChordChanges(track, chordList, 0);

chordPlayer = new mm.RandomPlayer
chordPlayer.PlayFromChordChanges(track, chordList, 0);

chordPlayer = new mm.BassPLayer1
chordPlayer.PlayFromChordChanges(track, chordList, 0);

chordPlayer = new mm.BassPLayer2
chordPlayer.PlayFromChordChanges(track, chordList, 0);

chordPlayer = new mm.BassPLayer3
chordPlayer.PlayFromChordChanges(track, chordList, 0);

chordPlayer = new mm.OffBeatPlayer
chordPlayer.PlayFromChordChanges(track, chordList, 0);

 

If you write music using Music Maker, got ideas for features, or you’d like to contribute to the project, drop me a line in the comments or contact me through GitHub!  Hope you have a great one!

 


Posted in creativity, music, open source, programming | Leave a comment

4 Orlando Makerspaces You Don’t Want to Miss #makerspace #orlando




Atlanta Maker Faire 2016

When my family lived in Macon, GA, our Macon makers community helped start one of the first makerspaces in Middle, GA: SparkMacon.com. A makerspace is a community oriented and operated workshop with tools to support a broad range of art and technology projects. At SparkMacon, we had tools for woodworking, physical computing, music recording, laser cutting, 3D printing, and art projects. In this season of life, I had the opportunity to witness the awesome benefits of a makerspace community. SparkMacon was founded to support local technology startups and inspire the growth of makers young and old. In general, makerspaces encourage grass-roots learning environments where makers learn from each other. I love the cross-functional nature of makerspaces too. It’s amazing the things you learn when you have different types of engineering, business minds, science, computer geeks and art people in the same room. Many makerspaces also support the mission of seeding the startup ecosystem of a city.

I’m looking forward to engaging in a makerspace community in Orlando at some point. I wanted to share a few makerspaces that you might enjoy exploring.

FamiLAB: As we were building SparkMacon, I gained a lot of inspiration from this makerspace community. I believe that this makerspace was the first makerspace community for Orlando. They consistently have diverse set of events and learning experiences. I’ve enjoyed taking my kids to their Raspberry Pi Jam sessions. The scale and variety of tools is amazing. (laser cutting, 3D printing, metal working, DIY biology and more). I specially find the DIY biology sub-community interesting since my wife teaches microbiology. ( very similar to http://biocurious.org)

Website: https://familab.org/

Melrose Center: I love seeing the makerspace movement move into other community and education organizations. If you live in Orange county in Orlando, you have a really nice benefit: Melrose Center. The Melrose Center, associated with the Orlando downtown library, provides makerspace services for the cost of a library card. If you don’t live Orange county, you can access many of the services for a nominal cost. The Melrose Center provides a nice spectrum of professional development workshops, family STEAM workshops, and community meetups. Some of my favorite meetups including ONETUG, Google Developers of Central Florida, and the Data Science and Machine Learning group of Orlando meet there. The makerspace offers tools like 3D printers, podcasting recording studios, music recording space, Adobe products lab, virtual reality lab, and more.

Website: https://www.ocls.info/locations-hours/melrose-center

MakerFX: The MakerFX makerspace, located in South Orlando, have an impressive community of makers. Like all makerspaces, they offer an impressive range of tools and educational programming. If you’re interested in visiting this makerspace, they offer an “open house” every Friday. You can “drop in” and sample the community and tools. While this makerspace has equipment to serve advanced makers, they seem to have a cool collection of beginner content including Arduino workshops, 3D printing, laser cutting, electronics, and more. On the more advanced end, you can learn about beekeeping, parametric design, PCB layout with Eagle, and combat robotics. This makerspace is the home of the Maker Effect foundation. ( http://www.themakereffect.org/ ) This foundation support STEAM education efforts in the city, connecting the makerspaces of Orlando, and coordination of the Orlando MakerFaire. (one of my favorite events every year!)

Website: http://www.makerfx.org/

Factur: I wanted to give a quick shout out to the makers at Factur too. While attending Orlando MakerFaire in 2017, I saw some impressive projects from this community. This makerspace community has entrepreneurial tone since the makerspace also serves as a co-working space in downtown Orlando. They seem to have a great buzz. You can learn more about their culture, tools, and events here: http://factur.org/

To our readers, make sure to mark your calendars for Nov 10 and 11 for Orlando Maker Faire. It truly is the greatest “show and tell” of the city. The art, projects and creativity will blow you away! And you get to see all of these makerspaces in action! 🙂  It’s a great event for the family.  Make sure to check it out!

 

 


Posted in technology | Leave a comment

Remotely Control IoT devices using NodeJs, Firebase, and Johnny5




Hello, makers!  In our blog post today, I wanted to share a simple way to remotely control IoT devices using NodeJs and Google Firebase.  Let’s say you’re trying to remotely control a small lego crane like this.  You’ll notice there are two servo motors connected to an Arduino.  You can learn more about how you can build this in our post on Arduino and Lego motor control.   For the scope of this blog post, let’s say we wanted to remotely control the servo motor at the bottom from any place in the world.  How would we do that?

Lego Crane

Firstly, check out Johnny 5,  a very nice NodeJs library for controlling IoT devices like Arduino’s, Raspberry Pi, and more.  I really appreciate the clarity of their documentation and API.  You can do a lot with a small amount of javascript.

I started to wonder if we could connect Johnny 5 to the real-time database of Firebase.   What’s a real-time database?  In a traditional relational database like MySQL, you need to declare database tables and structures.  You can make a database table to store a list of persons and their addresses (see sample code here).   After doing that, you can insert data into that table.  In this traditional database world, you can’t listen for inserts into a database table and easily write code to reach to that event.

The Firebase real-time database organizes information in a tree structure.  You can store information in that tree any way that you want.  Other users who have access to the database can listen for data changes at various locations in the tree and write code to react to that event.  Check out the following video to learn how the Firebase Real-time database works. Especially listen to how the value change event works.

This link review the details of getting started with FireBase on the web or NodeJS: https://firebase.google.com/docs/database/web/start

So, let’s explore the code for moving a single servo motor using Johnny 5 and Firebase.

At the top of the JavaScript file, we import johnny-five and firebase-admin. We start our firebase
database session by calling “initializeApp.”

On line 9, we create a “Board” object. I have my Arduino connected to my computer by a serial cable. Johnny5 handles this situation by default.

Once the board enters “ready” state, we create an instance of a servo motor connected to pin 10.

On line 14 and 15, we connect to a storage location called ‘servo_angle.’ Using the servo_angle “on value” event, we listen for changes to this location and
set the angle of the servo. And that’s it!

To write values into “servo_angle”, check out the following code.

In this script, we connect to the Firebase database in the same way. On line 10, we accept an angle from command line arguments. On line 16, we write that angle to ‘servo_angle’.

It’s a very simple pattern for making internet connected robots or home automation.

We love to hear from our readers. Leave a comment below if you get other ideas for internet connected robots, toys or devices.

Related Blog Posts



Posted in making, programming, technology | Leave a comment

Building Chat Bot Apps with Google Actions




r2d2

In science fiction, we have dreamed about the days when we’ll talk to our computers to make things happen. In Star Trek, crew members can talk to the Holodeck computer to “program” and explore amazing virtual experiences. Tony Stark(aka. Ironman) constantly gets situation awareness from Jarvis during battle by simply talking to his device. We’re still a long way away from Holodecks, R2D2, and Ironman. As developers and makers, we can explore the potential of voice interactions with mobile devices today.

The Google Actions toolkit enables you to integrate your services into the voice command interface of a Google assistant. This technology touches millions of devices including phones, cars, and assistant devices. You can also integrate into services provided by Google or third party services.

This past weekend, our local Google developer group of Central Florida organized a hackathon to explore applications of voice user interfaces and Google Actions. We enjoy getting to organize community workshops like this. Love seeing our community come together. It’s always a great opportunity to learn, meet people, and generate new ideas.

Google Actions Hackathon

In general, Google actions work well in three major use cases. Users on the go. People starting their day. People relaxing at the end of the day.   For my Google Actions app, I tried to think of an application of Google Actions that would support our leadership team for our GDG. We recently adopted a Trello board to help us organize tasks for our club. If you’re not familiar with Trello, it’s simple a task management system popular with Agile teams. ( see a screenshot below )  As a busy Dad and professional, I typically think of stuff that needs to be accomplished for the GDG while I’m driving.

Trello board

I decided to create a simple Google Action to enable me to collect a task and share it on our leadership Trello board. I tried to explore this task in three phases.

1. Get to know the Google Actions API: I used a variety of resources to get to know the Google Actions interface. I, however, found this code lab very helpful.  After doing this code lab, I was able to slightly elaborate on the tutorial to create my own stuff.

https://codelabs.developers.google.com/codelabs/actions-1

2. Build Trello integration code to add a task to a list: On my local laptop, I started playing around with a few options for adding task information to a list.  I found the “node-trello” package for NodeJs worked really well.

https://github.com/adunkman/node-trello

3. Integrate the Google Actions API and the NodeJS code together

Here’s a quick tour of the Google Actions conversation setup. Using Dialogflow, it’s really cool that you can create conversational interface actions with almost no code.  JavaScript code becomes necessary if you need to integrate services or databases together.   Let’s focus on one intent: adding a task.   In general, intents enable you to accomplish a focused interaction on your Google assistant.   In my case, the user calls my action by doing the following:

  • Ok, Google.  Let me talk to GDG tasks
    • The system replies with a greeting and a prompt for a command
  • The user can reply “add task.”

In this intent, we can configure the system to respond to similar phrases to “add task.”

Add task

At this point, the intent collects two pieces of information.  (task name and task details).  We configure the intent to fulfill the conclusion of the intent with custom code.

Hope this code sample helps you understand the experience of building a Google Actions application.

Here’s a few more resources and ideas to help you write your own Google Actions app.

Related content

Please know that we’d love to see you at GDG Central Florida!  Hope to see you there!

Google Developer Group Central Florida

Orlando, FL
552 Members

Welcome to Google Developer Group (GDG) Central Florida.We are a technology user group for developers, designers and entrepreneurs interested in learning about mobile, web, i…

Next Meetup

I/O Extended 2019 Orlando

Thursday, Jun 13, 2019, 7:00 PM
19 Attending

Check out this Meetup Group →

 


Posted in making, mobile, programming | Leave a comment

The Importance of Reading To Foster Empathy




Girl with books

In my view, one of the best educational and community hacks of all times is the library.  Why?  They are organizations devoted to growing minds through books.   Books have the ability to send us to new worlds of adventure, help us consider diverse perspectives, and exercise our imagination.  Today, I wanted to introduce you to one of my best friends from church and expert homeschool teacher, Lisa Twardowski.  She has amazing, thoughtful and talented kids.   We enjoy getting our families together to do maker education projects.   I really appreciated her post on the empathy you learn from books.   Hope you enjoy it.

===

As I sit sipping my hot tea after I have tucked my children into bed, I ponder the questions they asked during our nightly read aloud.  While the youngest, our daughter, was still brushing her teeth, I began reading, “The Dangerous Book of Heroes” to our boys. They opted for an entry entitled, “The Abolition of Slavery in England”.  As soon as we started the story, the boys said we would need to stop before their sister joined us, but it was too late. She was already in tears in the other room, asking how one person could possibly feel like they had the right to own or sell another person – a human being!?  One of her brothers explained that that is just the way the world is, while the other brother tried to explain that it is not okay and no one should do it.

We all opted to move on to our family read aloud, “Little House on the Prairie”.  Safe, I mistakenly thought. The title of the chapter we were reading, “The Tall Indian”.  In this chapter, Laura describes her mother’s disgust at the Indians who are using the well-worn trail that is near their new home in Missouri.  Pa mentions that if he had known that trail was the Indian highroad, he never would have built his home so close to it. Laura asks question after question about the Indians: why will they have to move west (because the government will make them) and isn’t this their territory (yes, but white men are moving here now).

The topics, so unfamiliar to us today – at least to my young children – were upsetting, thought-provoking, and cause for pause and reflection.  They felt empathic; they have the ability to imagine or share the feelings of another.

Empathy is something that cannot be taught, it must be understood, lived, experienced.  One person cannot live in every situation, so how do we “learn” empathy? TV isn’t working; computer games aren’t working; apps – as great as they are, aren’t getting the job done.  What is a mom or dad to do – our future generation is at stake! Empathy is now one of the Top 10 Skills employers are looking for in their new hires. Why? Because so many of our young people today are not able to put themselves in a situation outside of the one they are living.

So, how do we solve this problem of learning to be empathic?  It’s as simple as words in print: Books. Do you remember those?  A stack of bound paper with words and sometimes pictures printed in ink, some with a funny smell.  It’s the words printed on those pages that are the important part of this story. Sure, now you can read the printed word on a screen, and even get the sounds effects of turning a page – which works just fine too, but it is those words.  It’s the words that tell the stories of lives and journeys and events that the reader can never live, but can experience through those written words. The reader can become familiar with characters, and practices, and locations that they may never get to visit – or that no longer exist except through that written word.

Reading is a big deal these days.  Sometimes we think reading is the magic key that will unlock any door.  And while I am certainly a believer that reading can fix many of our problems, I do think it is VERY important to choose what we, and our children, are reading carefully.  Captain Crazy Cape is not going elicit more than crass humor from our children. Diary of Anyone is probably not worth our time. What goes in will come out – it works in the stomach and the brain.

There are some great book recommendations online – and what you will find after reading enough of those lists is that as that they contain a lot of the same books.  Not all the books are old, but those tend to be the ones most often turned to. Some of the books I have read recently that really stirred me are middle-grade novels, many written in the 1950s.  The following is not a complete list, as I don’t believe such a thing can exist, but any of these books are a good place to begin.

  • Stuart Little
  • Charlotte’s Web
  • Little House on the Prairie Series
  • Sarah, Plain, and Tall
  • The 100 Dresses
  • Number the Stars
  • Heidi
  • Amos Fortune, Free Man
  • The Secret Garden
  • Tuck Everlasting
  • Carry On, Mr. Bowditch
  • Where the Red Fern Grows
  • Island of the Blue Dolphin
  • Shipwreck at the Bottom of the World: The Extrodinary True Story of Shackleton and the Endurance
  • Johnny Tremain
  • Roll of Thunder, Hear My Cry
  • Men of Iron
  • The Bronze Bow
  • The Giver (Upper Middle School, High School, and Adult)
  • Silas Marner (Upper Middle School, High School, and Adult)
  • The Strange Case of Dr. Jekyll and Mr. Hyde (High School and Adult)
  • The Hiding Place (a must read for ALL High School students and Adults)

There is no magic fix all in any of these books.  Some are true accounts of the authors’ lives, some are historical fiction, and still, others are fiction outright.  All tell the story of humankind: the hardship and failures, the successes and joys. Each will allow the reader to walk a mile in another person’s shoes.  These stories span historical times, locations, race, and socio-economic classes, but they all deal with characters who struggle with one issue or another, but find hope to continue on.  

Most of these situations are not things we can even offer our children, nor would we want to: to become an orphan, or a slave, or a science experiment.  But they can see life through another’s eyes and learn what it may have been like to have those struggles, and think those thoughts, and possibly make different choices – or at least ponder, “what would I have done?”  To be empathic to another’s struggles and life. To gain the ability to imagine or share in the feelings of another, all from the safety of the sofa.

As LeVar Burton of Reading Rainbow so often reminded us, “But you don’t have to take my word for it…”  

Lisa Twardowski

 

Other posts from InspiredToEducate.NET

Photo credit: https://www.flickr.com/photos/yannickcarer


Posted in parenting, teaching | Leave a comment