Kids, Code, and Computer Science Build a City From Scratch!
o t n w a r D r e h c s E her t e g o ome T C t r and A e c n tchUp e k S Scie With
Get Your Jedi On With Micro:bit How Bots Learn From Nature June 2018
$6.00$6.00 USD
beanz magazine June 2018 : Volume 5 Issue 6 Issue 36 (online) & 21 (print) ISSN: 2573-3966 (online) ISSN: 2573-3958 (print) beanz Magazine© is published bi-monthly, six times a year, online at http://beanzmag.com and in print. A print + online magazine subscription includes online access to all articles, with links to let you explore topics in more detail. SUBSCRIBE: visit http://beanzmag. com/subscribe or email us for checks/ invoices. We’re also available through EBSCO, Discount Magazine, WT Cox, Magazine PTP, and many other subscription services. ONLINE MAGAZINE ACCESS: send your email address to hello@beanzmag.com and we’ll set you up. Published by Owl Hill Media, LLC 378 Eastwood Rd, Woodmere, NY 11598 Email: hello@beanzmag.com Phone: (646) 553-3390 POSTMASTER: Send address changes to Owl Hill Media, LLC, 378 Eastwood Rd, Woodmere, NY 11598. Periodicals postage paid at Woodmere, NY and other mailing offices. Copyright Owl Hill Media, LLC with all rights reserved except as noted. Flickr images are copyright their creators, as noted with each story both online and in print. Publisher/Editor/Webmaster: Tim Slavin Staff Writers: Simon Batt, Patricia Foster, Bonnie Roskes, Clarissa Littler, Jennifer Newell, Les Pounder, Paul Seal, Erin Winnick, Tim Slavin Contributors: David Dodge, Jay Silver, Jeremy Kubica, Colleen Graves, Daniel Fenjves, Ali Hagen, Emeline Swanson, Jean-Francois Nguyen, Madeleine Slavin, Tim McGuigan Back Office Magic: Wendy Garrison Copy Editors: Madeleine Slavin, Derek Lanuto Art Director: Kelley Lanuto Webmistress: Patricia Foster
Publisher’s Note Is it June already? The start of summer? If it is summer and you’re bored already, we have a lot of hands on projects and ideas to explore. There’s Godot, an open source (free!) game engine to create and play games. There’s also Botnik, an online community that used predictive software to write Harry Potter and the Portrait of What Looked Like a Large Pile of Ash. We also have the first in a series about command line interfaces, also called CLI. It’s fun to control your computer by typing commands instead of dragging and dropping files, making copies of files, and performing other tasks. CLI is a great way to learn about computing. And if you’re serious about programming, CLI is a must have skill. But I’ll also be honest: CLI is scary at times, for me at least. What if you type the wrong command? It’s easy to learn, however, and you’ll make fewer mistakes as you learn. If you’re like us and into Escher's artwork, definitely check out this issue’s SketchUp article. It shows how to create Escher-like images. If you don’t know, SketchUp is a free 3D software tool that makes it easy to create objects and, in this case, patterns. You don’t need a 3D printer to create neat things. Also be sure to look at our other articles about secret codes, Scratch, Minecraft, robots, 3D printing (in metal!), and more. We hope this issue provides a lot of fun. And be sure to enjoy your summer. School will be here again way too quickly!
beanz magazine (as Kids, Code, and Computer Science magazine, our earlier
Tim Slavin Publisher beanz Magazine
title) is a winner of Parents’ Choice, Tillywig, and Academics’ Choice awards: http://beanzmag.com/awards
Our Mission
beanz magazine is a bi-monthly online and print magazine about learning to code, computer science, and how we use technology in our daily lives. The magazine includes hard-to-find information, for example, a list of 40+ programming languages for education, coding schools, summer tech camps, and more. While the magazine is written to help kids ages 8 and older learn about programming and computer science, many readers and subscribers are parents, teachers, and librarians who use the articles to learn alongside their young kids, students, or library patrons. The magazine strives to provide easy to understand how-to information, with a bit of quirky fun. Subscribers support the magazine. There is no advertising to distract readers. The magazine explores these topics: Basics of programming and where to learn more, Problem solving and collaboration, Mathematical foundations of computing and computer science, Computational thinking, Recognizing and selecting computer devices, and the Community, global, and ethical impacts of technology. COVER IMAGES ALL FROM FLICKR: BACKGROUND: KERSTIN; TOP: ALVARO IBANEZ; CENTER ROW LEFT: FDECOMITE; CENTER ROW MIDDLE: ROBERT VAN DER STEEG; CENTER ROW RIGHT: FDECOMITE; BOTTOM: PETER, FROM A PHOTOGRAPH OF AN IMAGE BY M.C. ESCHER AT THE ESCHER MUSEUM
June 2018
18
Notebook The Command Line Interface
ď‚Ż
all ow I'm "You kn rface, te 'bout in t 'face..." a 'bout th ď‚Ż
2 4
Robotics Cover Story Biobots: Biomimicry in Robots Show and Tell Predictive Keyboards: A Work in Progress
9 10
Make It Heavy Metal
12
Projects A Game Engine for All
Secret Codes Breaking the Code and Winning the War
6
Cover Story
SketchUp Escher Sketch(Up)
15 16 20 24 25
14
Minecraft Redstone Languages Elm: A Language for Making Webpages Electronics Cover Story Curses! Foiled Again! Coding Visualizing Randomness Show and Tell Older Tech That's No Dinosaur
23
Scratch Build a City From Scratch!
Puzzles aMAZEing!
Cover Story
Archives Seeing the Invisible
26
28
Parent-Teacher Corner Making the Leap With Coding Challenges
contents
advanced
intermediate
beginner
scribe b u s / m ag.co m z n a e b http://
Robotics
2
Biobots: Biomimicry BY JENNIFER NEWELL
You , e d Du ar! i l i m Fa k o o L
LISA COX, PACIFIC SOUTHWEST REGION USFWS, FLICKR
eanz! cool b
How does a mosquito fly in the rain? And how does this relate to robotics? A raindrop has about 50 times as much mass as a mosquito and travels at up to 22 miles per hour. So a mosquito getting hit by a raindrop is analogous to a person getting hit by a truck. The human would not survive, but the mosquito keeps right on flying. David Hu, at Georgia Tech University, found it's likely the mosquito's small mass combined with its strong exoskeleton that helps it fly in the rain. Engineers are applying such discoveries to developing biologyinspired robots, from micro air vehicles to a nano-hummingbird. Snake motion is also inspiring robotic design. Snakes move by contracting and relaxing their muscles. They're able to travel through sand, up trees, and through water. A robot able to navigate such a range of terrain could help perform search and rescue operations and investigate difficultto-access locations. The "snakebot" is being developed at the biorobotics lab at Carnegie Mellon University. Connecting any number of pieces, or modules, creates a snake whose length is ideal for its intended purpose. Each module is an elastic actuator (a motor with a spring). The spring helps measure both the amount of force the robot exerts, as well as how much force is exerted upon it. It can be programmed to respond appropriately to changes in force and pressure. Prototypes were deployed in Mexico City as part of the search and rescue effort following the 2017 earthquake. The snakebot has also been tested at Zwentendorf nuclear power plant
3
in Robotics in Austria, where it was able to travel through confined spaces that neither humans nor other robots could safely explore. The octopus is also studied. The octopus has no bones or internal skeleton. Given its unique structure, it makes use of two main modes of locomotion. To crawl along the ocean floor the octopus shortens and elongates its tentacles, choosing which tentacles to move in order to travel in a desired direction. When the octopus needs to speed up, it draws water into a cavity within its body and squirts it out to push it along. A soft-bodied robot with nearly infinite degrees of freedom for movement like the octopus could open the doors to many new robot applications. Scientists and engineers at Harvard’s Wyss Institute for Biologically Inspired Engineering have created, with 3D printing, a soft-bodied "octobot" made of silicon. Even the “brains”, or circuitry, of the robot are soft. This is made possible using liquid-filled logic gates and pneumatics to control motion. Basically, small amounts of liquid hydrogen peroxide undergo a chemical reaction, turning into a much larger volume of gas. The gas is then distributed into the octobot's tentacles, inflating and deflating them something like a balloon, to control their motion. Because the robot's movements are controlled by liquids and gases, rigid components such as batteries and circuit boards are not necessary. A perfected octobot can be useful in both internal medicine as well as search and rescue missions, when more rigid bots are not up for the job. b
OREGON STATE UNIVERSITY ROBOTICS, FLICKR
Show and Tell
4
Predictive Keyboards: BY PATRICIA FOSTER
Almost ten years after the release of the seventh Harry Potter book, the magical story of a boy who discovered he was a wizard has finally been updated with a new chapter. This text, however, wasn’t written by J. K. Rowling, but by an artificial intelligence. It starts like this: “The castle grounds snarled with a wave of magically magnified wind.” Not bad, right? Then it gets weird: “Ron was standing there and doing a kind of frenzied tap dance. He saw Harry and immediately began to eat Hermione’s family.” The great minds behind Harry Potter and the Portrait of What Looked Like a Large Pile of Ash are from Botnik, an online community of writers and developers who combine art and tech to “create strange new things.” To write this text, the authors used a predictive keyboard trained using all seven Harry Potter novels. You can read the
full masterpiece here: http://botnik. org/content/harry-potter.html The Magic of Statistics
When texting on a smartphone, you’ve probably seen “word suggestions” pop up above the tiny digital keyboard. If you clicked on the first suggestion, and kept clicking until you had a full sentence, you’d be following the same process as the writers at Botnik. Except while phones analyze a person’s text messages, Botnik’s algorithm studied a specific author's style. Predictive keyboards are built using a mathematical system called Hidden Markov Models (HMMs). The term may be fancy, but the logic boils down to this: every word in a sentence depends upon the previous word. Or, more accurately, upon several previous words. Let’s say you’re reading a book and the last word on the page is
“cold”. What do you think comes next? “Feet”, “wind”, “snow”, and “night” are good candidates, whereas “sun”, “fire”, “cookies”, and “stegosaurus” are less likely, although not impossible. Now, what if the last two words on the page are “a cold” versus “several cold”? You’d probably tweak your guess by suggesting “foot” in the first case and “feet” in the second. In short, the more words we analyze, the more accurate our guess can be. But how many words is the right number? Too many words make long, slow programs, and too few words create algorithms that get stuck: “I want a pony because I want a pony because I want a pony…” Some very smart scientists tackled this problem and decided that the magic number was 3. Next problem: while both “wind” and “snow” are great candidates,
A Work in Progress how does the predictive keyboard know which is the absolute best? The first step in creating your HMM is to chop up the training text into chunks. The sentence “unicorns have magical healing powers” becomes “unicorns have magical”, “have magical healing”, and “magical healing powers”. Next, you group identical segments together and count which words commonly follow them. If the segment “unicorns have magical” appears in your training text 2,000 times, you might get results like this: And: 320 / 2000 (16%) Friends: 100 / 2000 (5%) Horns: 1000 / 2000 (50%) Healing: 580 / 2000 (29%) When this predictive keyboard sees the phrase “unicorns have magical”, it’ll choose “horns” as the next word in the sentence. Simple statistics! Of course, real texts have more varied answers. Plus, the Harry Potter books contain over 1 million words—that’s a lot of segments to analyze! Machine Learning to the Rescue
Artificial Neural Networks (ANNs) are all the current hype in computer science. They can recognize complex patterns like stop signs, individual human faces, or signs of cancer in a patient. They can also be used to create approximations for complex systems like Hidden Markov Models, often much faster than calculating the models directly. Imagine that you’re trying to explain the concept of an elephant to someone that’s never seen one before, like an alien, or a toddler. You could try listing characteristics: elephants are big and grey, they have floppy ears, four legs, and they
live in Africa and Asia. This would be the “traditional” approach to pattern recognition, and it often runs into trouble. For starters, baby elephants aren’t big. Plastic toy elephants can be pink and blue and green, and many elephants live in zoos all over North America and Europe. So now our definition looks like this: Elephants are big (but sometimes small) and grey (but not necessarily), they have floppy ears, four legs (most of the time), and they live in Africa or Asia (but not always). That's sure to confuse any alien! ANNs approach the problem using examples. They’d show picture after picture of elephants in different scenarios until the concept is crystal clear: elephants eating food, elephants sleeping, old elephants and baby elephants, elephants at zoos, cartoon elephants, elephants with riders. The bigger and more varied this “training set” of pictures, the more likely that the alien can recognize an elephant under any conditions. Fun fact: this is similar to the way humans learn! What makes ANNs powerful is that they work well with “unstructured” data like pictures, videos, or text, and they’re faster and more accurate than other types of algorithms, especially ones that tackle the difficult math head-on. Using neural networks also ensures that your model can handle inputs it’s never seen before. If the phrase “rocket spaceship cookies” doesn’t appear in the training data, but pops up in a real-life scenario, our program won’t fall to pieces! An Imperfect Model
After studying 10,000 sentences, the predictive keyboard knows that “several” should be followed
by “puppies” and not “puppy”. But does it understand, deep down, the concept of plurals? Does it know what a puppy is? Of course not! HMMs and ANNs are simply clever tools to help computers imitate the ability to recognize objects or write sentences. Harry Potter and the Portrait of What Looked Like a Large Pile of Ash wasn’t 100% computergenerated. The plot may be nonsensical, but the grammar is perfect; words were ultimately chosen by humans. Still, using an AI to guide their writing helped the creators at Botnik think outside the box. Way, way outside the box! Current work in machine learning is hoping to improve text prediction by adding grammar to the model. For example, since words like “dog” and “cat” have similar roles, the sentence “dogs are cuddly” could be used train a model to create “cats are cuddly”, as well as “dogs are cute” and “dogs were cuddly”. One of the biggest challenges in Natural Language Processing (NLP) —the branch of AI that’s tackling the transformation of human language into computer language—is the fact that grammar doesn’t follow clear, mathematical rules. Even the smartest algorithms make rookie mistakes that a four-year old could recognize. How many years until robot writers can pass for humans? Some scientists estimate that AIs will produce best-selling novels as early as 2040. Until then, we can enjoy their less refined work: complete with Ron turning into spiders and Hermione being dipped in hot sauce. b PUBLIC DOMAIN DEDICATION, UNSPLASH
5
SketchUp
6
Escher Sketch BY BONNIE ROSKES
Creating Escher Tiles, in my.sketchup
SketchUp is a free and fun program for 3D modeling. You can use SketchUp to design just about anything, from furniture to a dream bedroom to an entire city. There is a downloadable version called SketchUp Make, which you can get at https://www.sketchup. com/download/all. But there is also a web-based version which works right in your internet browser. This version is called my.sketchup, and to use it just go to www.my.sketchup. com. If you haven’t heard of M. C. Escher, look him up on Google (and Google Images) right now. He came up with all sorts of crazy tessellations, which means shapes that tile; they repeat infinitely to fill a plane, with no empty spaces. You know that this can be done easily with squares, rectangles, triangles, even hexagons. But Escher came up with lizards and birds as well, and so can you. All you need are some basic SketchUp tools and a little creativity. I’ll demonstrate this project with my.sketchup. Once you see how it’s done you can go wild and create your own crazy Escher tiles. When you open SketchUp, you’ll see Josh standing on the ground. Josh isn’t needed for this project, so from the toolbar on the left side, click the Eraser (or press E). Click anywhere on Josh (click on an edge, not on a face) to erase him. We want to create
our shapes on the ground, in Plan view (also called bird’s-eye view). To switch views, click the Views icon from the toolbar on the right side. Then click the Top View icon.
For our basic shape, we’ll start with a rectangle. From the Shapes flyout toolbar, click the Rectangle icon (or press R). Click once to place the first corner, then click for the second corner. Your rectangle can be any size.
Now we’ll make some changes to this rectangle. Activate the Line tool (or press L). Starting at the top left corner of the rectangle, draw a few zig-zaggy lines. Be sure to end at the top right corner.
This has created a few new faces, and these faces need to copied from top to bottom of the rectangle. But before they can be copied, they need to be selected. Activate the Select tool (or press the Spacebar). To select multiple objects at once, press and hold the Shift key. Then click all of the faces created from the lines along the top.
Copying is done with the Move tool (shortcut: M). Press the Ctrl key (PC) or the Option key (Mac), which puts you in Copy mode. Don’t keep the key pressed, just tap it once. You should see a little “plus” sign next to your cursor. For the first move point, click either top corner of the rectangle. Then for the second point, move straight down and click the bottom corner.
Now we’ll do the same to the left
(Up) and right edges. Add a few lines along the left edge. Then select the new faces, activate Move and press Ctrl or Option, and copy these faces from left to right. If your new faces overlap with other faces, use Undo (Ctrl +Z or Cmd + Z) and start over with a different set of lines.
Now we have all we need for our Escher shape. With the Eraser, remove all horizontal and vertical edges of the original rectangle.
With Move active and Ctrl or Option pressed, make one copy of this shape anywhere in empty space. Space them so that the shapes aren’t touching.
Now some creativity is needed. Decide what your shapes should be: birds or lizards, strange furniture, even human (or alien?) faces. Then use the SketchUp drawing tools to fill in the shapes. Press C to make circles, A to draw arcs, L for lines. Any closed shape you make will form a new, separate face.
Adding color makes this even more interesting. From the toolbar along the right side, click Materials. There are lots of material categories from which to choose. To see the list, click the Browse icon. You can use solid colors, or some of the various patterns provided. Here’s my example after painting:
Before connecting these shapes to one another, it’s important to make each one a component. This does two things. First, it prevents shapes from “sticking” to one another. Second, components make it easy to make copies, and also make changes to those copies. To make the first component, activate Select and drag a selection CONTINUED, PAGE 8
Who is M.C. Escher?
Self Portrait by M.C. Escher Born in the Netherlands in 1898, Maurits Cornelis Escher was a famous graphic artist. You’ve probably seen some of his zanier work, like his two hands drawing each other. But he was also a brilliant mathematician, and brought many math concepts into his drawings. Maurits entered college to study architecture. His interest in building and construction probably came from his civil engineer father. (Although his drawings of impossible staircases and waterfalls that go both up and down would confound any builder.) But in his first week of college, he decided to switch to graphic art, and the rest became history. Maurits was also fascinated by geometry, specifically tessellations: shapes that repeat infinitely in all directions. And he didn’t just stick with simple rectangles or triangles. He came up with crazy repeating shapes that he turned into stars, fish, birds, and lizards. After producing hundreds of lithographs and woodcuts, and over 2000 drawings and sketches, M. C. Escher died in 1972, at the age of 74.
7
8
Do the same for the other shape.
CONTINUED FROM PAGE 7
window that encloses one complete shape. This selects everything inside that shape: faces and edges. Right-click on any selected face and choose Make Component. Name this component whatever you like, then click OK. Repeat for the second shape. Each component is now a separate object—a set of edges and faces that acts as a single object.
Now let’s start tiling these shapes. Activate Move once again, and on one of the shapes, click a corner that you know meets a corner of the other shape.
But these two shapes aren’t enough—we need more copies. And it’s always a good habit to select in advance the object you’re going to copy. Make sure one of the shapes is selected. Activate Move and press Ctrl/ Option, and click a corner you want to meet the other shape.
Click to complete the copy.
Move that point to where it meets the other shape.
The Title Pun, Explained The title of this article, "Escher Sketch (Up)," is actually a pun that refers to a hugely popular toy dating back to the 1960's called an Etch-a Sketch. Your parents, or maybe your grandparents too, spent lots of time with these old-timey versions of a digital tablet with a drawing app. Vertical and horizontal lines were easy to draw, but diagonal lines were tricky! Perhaps you had an Etch-a Sketch? They're still around! Hours of analog fun for the whole family.
Keep going until you have as many copies as you like. You could go on forever, these will tile infinitely! And here’s the beauty of components: change one and you change them all. Right-click on any shape and choose Edit Component. The component you’re editing appears in a dotted-line box, and everything else appears faded. The only things you can change now are what are in the component itself. Everything else is off-limits. In this example, I erased the yellow stripes and replaced them with some dots.
When your editing is finished, right-click anywhere outside the component and choose Close Component. (Or you can activate Select and click once anywhere outside the component.)
The rest of the components come back into full view, and all identical components show the same change. What crazy shapes can you come up with? b Check out the link on the back cover of this issue for more info!
Did you know 3D printing is so much more than just plastic? While you can make some awesome toys and art projects using brightly colored plastics, 3D printing is so much more than that. You can use it to 3D print everything from metal parts for rocket engines to jewelry! However, metal printing is a bit more complicated than plastic printing. It's much more dangerous to 3D print a metal creation in your home than a plastic one. Metals are very hard and require much more heat to form them into the shape you want. Therefore, to 3D print with metal, engineers developed different methods than those used for plastic printing. The primary difference is the metal usually starts as a powder. Then, heat is applied to the powder, melting it into a solid piece. This heat can be applied with very hot ovens called kilns or even with a laser! Other precious metals like gold and silver are poured into a mold that was 3D printed from wax, rather than printing with the metals directly. Did you know you can get your creations easily made out of metal? Although you won’t be able to do it on your own in a library or in your house, there are people out there who will print your creations in metal for you. I’d recommend printing your design in plastic first to make sure you like it and don’t want to make any changes. It’s a lot cheaper and faster to keep printing varieties of
9
Make It
y v a e H l a t e M
BY ERIN WINICK
your design in plastic than in metal. Keep in mind, some things that can be printed in plastic cannot be printed in metal, so be ready to adjust your design after consulting with a metal 3D printing service. Parts could be too small, too big, or even too thin to create in metal. Don’t be disheartened though! Making changes to your design is part of the engineering design process. By practicing this, you are on your way to becoming an engineer. Once you are happy with your creation, it's time to send it off to be created in metal. A few places that offer metal printing services are Shapeways, Sculpteo, and i.materialise. I personally recommend Shapeways as they often have the cheaper price and have a user-friendly website. There you will go through a final check to make sure your model works, select the metal you want to print in, and send off your order. You can pick from metals ranging from steel all the way up to platinum. Then, a few days to weeks later (it depends on which material you picked) a box with your design created from metal will arrive at your door. Since I use metal 3D printing to create science and engineering jewelry designs for my business, Sci Chic, I have gotten hundreds of these boxes delivered to my door, but it's still exciting every time! So, don’t be afraid to test out different materials when you are 3D printing. It’s a fun world of making out there! b Necklaces 3D printed from bronze and stainless steel
Secret Codes
Breaking the Code and BY SIMON BATT
anticipate this and therefore will encrypt their messages in a form of code. The code used by the Germans in World War II was called the Enigma Code, and cracking it was a huge feat of computing at the time. The Enigma Code was invented by Arthur Scherbius in 1918. The Germans used the very complicated Engima Machine in order to encrypt their messages. A group of Poles managed to figure out how to decrypt the messages, but the Germans then Londoners celebrating the end of World War II. began changing the cipher every day. This meant that the Allies had to re-crack the code every day in order to stay on top! It was a daunting task, but an Englishman named Alan Turing stepped up to the challenge. enemy. The idea being that if you He, along with fellow codebreaker know what your enemy is doing, you Gordon Welchman, worked with can use your army more efficiently. his colleagues in Bletchley Park, in One way of getting this England. They created a decryption information is to listen in on what machine called the Bombe, which the enemy is saying. This is usually had the task American Military Police of decrypting reading about the the Enigma German surrender. messages as quickly as possible. Additionally, they would try to work out how to decrypt the Enigma Code every time it changed. There were a few clues done by finding the communications they discovered. For one, the Enigma channels being used and secretly Machine was built in a way where a listening in. A good military will In the past few issues, we’ve covered a wide range of different ciphers and codes. This issue, we’re going to be looking at one of the most famous codes in wartime history: the Enigma code. When you think of wars, you may initially think of soldiers, tanks and boats. But there’s another, hidden layer to warfare. When two countries fight, they usually engage in operations with the goal of extracting important information from the
PHOTO OF CHURCHILL, FACING PAGE, AND BOTH PHOTOS ON THIS PAGE FROM GOODFREEPHOTOS.COM
letter could not be encrypted into itself (for example, the letter ‘A’ would never be encrypted into an ‘A’, a ‘B’ into a ‘B’, and so on.) This cut out a lot of coding possibilities, as any solution where a letter was encrypted into itself could be ruled out. The Germans were very confident in their code, using it for ground, sea, and air communications. This meant that, when Alan Turing and his Bombe managed to begin busting the code, the Allies had access to a lot of the Germans' information. Turing’s contribution to the war effort was huge; so much so that the prime minister of the time, Winston Churchill, personally commended Turing and said the war would have been much harder were it not for Turing’s efforts. Not every war hero is a soldier, after all! Today we know how the Enigma code worked. There are even sites on the internet that allow you to encode and decode messages like the Germans did during World War II. Go to http://www.counton.org/ explorer/codebreaking/enigmacipher.php, then scroll down until you see the encoder and decoder. Set the positions to ‘B’, ‘C’, ‘A’, and ‘D’, then type w$6)v.d/cwg into the ‘Encrypted Text’ box and click ‘Decrypt’ to find out what it says: If you want to send a reply, what message would you send back? To work this out, type your message into the ‘Inputted text’ box and click ‘Encrypt’. To test it, try typing ‘Let’s meet up today’ into the box and clicking ‘Encrypt’, then check your result to the answers below. For more about the Enigma machine, Alan Turing, and the Bombe machine, check out the beanz August 2017 issue. b
ANSWERS: w$6)v.d/cwg = ‘Hello There’ Let’s meet up today = $$b@s.+bch,$b!o3u6l
10
American Navy women using the Bombe codebreaking machine in Washington, D.C..
Winning the War
11
J BREW, FLICKR
ELLIOTT BROWN, FLICKR
A codebreaking hut at Bletchley Park
Bletchley Park House
Winston Churchill flashes the "V for Victory" sign to a huge crowd in London celebrating the end of the war. BOB JENKIN, FLICKR
A German Enigma Code document
CHRISTIAN LENDL, FLICKR
Projects
12
A Game Engine BY CLARISSA LITTLER
In previous issues, we've talked about how to make games with different frameworks: Scratch, WoofJS, and PyGame. Today we'll talk about an up-and-coming system for making games: Godot. Godot is a lot like Unity. Unity is a system that's becoming popular with developers because it lets them code both 2D and 3D games quickly without having to custom write a graphics and physics engine. Unlike Unity, Godot is free, open source, and runs on Linux. Those are all big wins in my book! To get started, you can find the Godot engine at https:// godotengine.org/download. It's available pre-compiled for all three of the major operating systems: Windows, OS X, and Linux. The source code is also available for download on GitHub (https:// github.com/godotengine/godot). You probably won't have a reason to download the source code if you're just getting started, but if you find that you really enjoy coding in Godot and have ideas for features then you could take a crack at adding them. Now, once you have Godot installed you'll see something like this, though with fewer things listed.
If you click on the Templates tab, you should see a number of examples that people have created that you can use as a starting point. This is going to be a great place to learn once you get the basics down. The Godot site also has a really comprehensive first-game tutorial at http://docs.godotengine.org/ en/3.0/getting_started/step_by_ step/your_first_game.html. We're going to do something even smaller than their first tutorial just to give you a feel for what Godot is about, taking some inspiration from HeartBeast's video tutorials linked below. First, open Godot if you haven’t already. Select New Project, give it a name, and make a folder for the project to live in. You should then be looking at a screen like
Next, click on the 2D selector to tell Godot you want to make a twodimensional scene. We're starting with two-dimensional just because it's simpler and involves fewer concepts to get started. Now you'll be looking at a blank screen. On it we're going to create our first node. Nodes in Godot are like the basic building blocks that you connect together to make
things in the game. Click on the + symbol under the tab on the right hand side that says Scene. Search for kinematic and choose the node type of KinematicBody2D. In Godot's parlance, a "kinematic body" is an entity that can move and interact with other objects but that isn't subject to all the rules of Godot's built-in physics engine; rather, you have to manually write the code for its movement. You'll see a little square orange outline but nothing else. This happens because the kinematic body doesn't have anything visible inside it. We need to do two things to make it solid and visible: we'll give the kinematic body a sprite sub-node and a collision shape so that it'll be solid. If you're coming from Scratch this use of "sprite" might seem weird. In Scratch, a sprite is the whole bundle of properties and code that makes up an object in the game. Here, a sprite is just the visual component: more like a "costume" in Scratch's language. Now, if you right click on the kinematic body node in the nodelist you can add a child node of Sprite. Still nothing appears yet! Now we need to give a texture to the sprite. Click on the sprite node in the Scene tab. Then, if you look in the inspector tab in the lower-right part of the screen you should see
13
for All an entry called texture. You can add an image to the resources for the project by dragging an image file into the left-hand panel under the icon.png file. You should choose an image just like you would in scratch: you want a transparent image and pngs are generally a good choice. When you have the image added to your resources you can drag the image from the resources list into the texture field in the inspector. I chose my favorite marsupial: Already we can make our character move! Go ahead and right-click on the kinematic body node in the scene tab, choose the Attach Script option, and then just click create on the pop-up that appears. Replace the code you see in the editor with the following:
Now, hit the play button in the upper right and your code should run: you'll have the picture you loaded moving in the direction you press with the arrow keys. There's one last thing I want you to try: go to the Scene menu in the left hand corner and select New Scene. Now make a generic Node, right-click on it, then select Instance child scene. From here, you'll select the kinematic body you saved earlier. This is the “child scene” that we’re inserting into our new, empty, scene. It might seem weird to call this a "scene". In Godot, a scene is basically a collection of nodes and code that you can re-use later. For good measure, add another instance of the scene you already made and use your mouse to drag it somewhere else on the screen. If you hit the play scene button, the one with the clapperboard like on a movie set, you should see a couple extends KinematicBody2D of instances of your image moving around when you hit the var motion = Vector2() arrow keys. The way you can func _physics_process(delta): nest scenes inside if Input.is_action_pressed("ui_right"): each other is one motion.x += 1 of the things I like about Godot: it's easy if Input.is_action_pressed("ui_left"): to create individual motion.x -= 1 building blocks of if Input.is_action_pressed("ui_up"): game that you can stick together just like motion.y -= 1 you would with the if Input.is_action_pressed("ui_down"): built in node types. motion.y += 1 Check out Godot and try making some move_and_slide(motion) games! b
it a w e “Th r... is ove t is Godo " here!
Scratch
14
BY CLARISSA LITTLER
For info on Scratch go to https://scratch.mit.edu
Build a City From Scratch! We've explored a few different Scratch games over the last year, but now we're going to do something different and a bit more complex: a city-builder/idle game. Find this game at the following link: https://scratch.mit.edu/ projects/209530385/#player. You may have seen idle games. They're a kind of "casual" game where you let the game sit and work for stretches of time, usually accumulating levels or money. This game is a sort of a cross between the original Sim City and a tapheavy idle phone game. Let's start by learning some basics of the game mechanics and then some hints for implementing them. You don't have to make this exact game, but you can use it as an example for making your own simulation or idle-style games. The basic idea is that you're trying to build a city of ten million people. You can build three basic kinds of districts: housing, shopping, and offices. You'll need housing; the more housing you have the faster your population can grow. However, in order for people to move to your city you'll need to have jobs for them. Building offices gives businesses a place to go and create jobs. Shopping centers also add some jobs, but they mostly help your city make money with that sweet, sweet sales tax. You'll also get money from your citizens paying taxes once a second. You set the tax rate, but be careful. TIM TRAD, UNSPLASH
If taxes are too high, people won't want to move to your city! The game is about finding a balance between building different kinds of properties and finding the tax rate sweet spot. You can speed things up by repeatedly clicking on the BOOST button to triple your growth rate, or by buying special properties like libraries or parks. My "I'm totally going to add graphics…someday" version of the game looks like:
The three buttons on the left are the districts you can build. Green is residential, blue is shopping, and pink means office buildings. You can click on any of them and, if you have the money, you can drop a district down on the map on an unoccupied space. (You can't overlap them.) Once you've placed a district, if you click on it and you have 10x the money it initially cost, you can upgrade it. Upgrading will have varied, but big, effects. There are a lot of comments in the code itself on how the game is implemented, but here are some important points: First, the buttons for building are implemented with a little "in-this-
sprite-only" variable that keeps track of whether they're the original or a clone. Clicking on it to build only works if it's the original. Second, the menu is implemented just by sending messages for "Show" menu and "Exit" menu that show or hide the respective sprites. This means, though, that the game is still technically running even when you're in the menu. Third, a lot of the game is organized by having visible-toeveryone variables that control what upgrades are in place and what the tick speed should be. So it's pretty easy to add new upgrades and control the core functionality. These visible-to-everyone variables are all given their initial values in code that runs on the stage and not any particular sprite. You can now look at the project, read the comments, and be ready to remix it or add features. If you want to try adding some features here are some ideas: • change the game so that there's a lose condition, like your population hitting zero or going bankrupt. • change the rules so that if your city is too unbalanced or taxes are too high your population goes down. • add more buyable upgrades that give you different advantages. • add a transportation system where you have to buy roads and you can build only there. For more info on this and other Scratch games in this genre, check out the link on the back cover. b
During your Minecraft adventures, you may have found a strange red powder called ‘redstone’ that can be mined out. They come in ore that looks like this:
You’ll quickly find out this is nothing like other resources you can mine. For one, it doesn’t make any armor or weapons like other ores. When you try to place raw redstone on the ground, it will appear as a red line instead of a block. What’s going on here?
Redstone works differently than other blocks. You use redstone like you would an electrical wire. You can send charges down redstone pathways to activate machinery, which then allows you to automate simple tasks. To get a feel for how redstone works, you can set it so that the charge is ‘always on’. You can do this by attaching some redstone to the end of a wooden stick, which then creates a redstone torch. If you lay out some redstone in a line, and then place a redstone torch adjacent to it, you’ll see that the line of redstone will light up. This means that the redstone
For info on Scratch go to https://minecraft.net
is receiving a charge and will activate any machinery that it’s connected to. You can use the torch to test out your redstone network before you place down an activator for it. One thing you can automate are doors. Iron doors can only be opened by redstone charges, meaning you can set up a secure way to keep the baddies out of your fortress. Set up your redstone so that the charge reaches the bottom of the door, like this: Now when you apply the torch to the redstone,the door will open. You can even use redstone to dispense items you’ve stocked beforehand. Create a dispenser, load it full of items, and then send a redstone charge to it to make it spit out an item. Remember that you need to have the redstone going toward the block, like this:
Even better, if you load the dispenser with arrows, it will shoot out a deadly shot every time it detects a redstone charge for an automated defense mechanism! If you use TNT in your mining
but don’t like to get too close, TNT can also be triggered with redstone. Simply ‘wire it up’ and then activate the redstone line to set off the explosives from a safe distance. No more running away as fast as you can! This is all well and good, but having to manually place a redstone torch when you want to activate things kind of makes the ‘automatic’ part redundant, doesn’t it? Let’s make it so we can do things with the touch of a button —literally! Buttons can transmit redstone signals when they’re pushed. Place one on a block, then lead the redstone line into the block like you did the blocks before. Now when you push the button, you’ll send a redstone charge down the line and activate whatever is at the end. Similarly, pressure plates can act like buttons on the floor. Stone pressure plates only trigger when a monster or human stands on them, while wooden ones will trigger if an item is placed atop of them. You can use these to activate redstone contraptions; perhaps to open a door while you walk, or to unleash a volley of arrows on any monster that steps on it! We’ve talked a lot about redstone, but in truth, we’ve only just scratched the surface. There are still repeaters, logic gates, pistons, and even powered minecart rails for you to explore. Make some great inventions of your own! b the link on ut the o e k u s c e is Ch f this over o ft and a r c e back c Min re on for mo as! e id e n Redsto
15
Minecraft
Redstone BY SIMON BATT
Languages
16
Elm BY CLARISSA LITTLER
A Language for Making Webpages
How do you make a web page? Normally, you have to write code in a combination of languages: HTML, CSS, and JavaScript. The HTML you write determines what elements appear in the page. The CSS determines how the HTML looks. The JavaScript gives the whole page life and interactivity. Elm, though, is a single programming language designed to compile to actual, functional web pages! You write Elm code and the Elm compiler turns it into the CSS, HTML, and JavaScript that makes up the final page. Elm is a relatively new functional programming language. It both looks and feels a lot like if JavaScript and Haskell had a baby: A particularly feisty baby that immediately gave the React framework some competition. I always like learning new programming languages, but Elm in particular, though, was probably the most fun I've had with a new language in a very long time. I won't say it's easy, particularly if you haven't done much functional programming before, but it's very satisfying. To get started with Elm, you can go to the language's homepage (http:// elm-lang.org/) and follow our examples by clicking the Try Online button. There are some examples in the online Elm editor, but here's our example: a super tiny Elm program that lets you enter strings into an input and then it makes a little palindrome out of what you typed. import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onInput) main = Html.beginnerProgram {model = "", view = viewFunction, update = updater} type Msg = TextChanged String viewFunction s = div [] [input [onInput TextChanged] [], text (s ++ (String.reverse s))] updater : Msg -> String -> String updater msg s = case msg of TextChanged s2 -> s2 For this tiny program, it compiles to the webpage shown below:
PERMACULTURED, FLICKR
Here I've used the developer tools in Chrome so we can simultaneously see the web page on the left and the structure of the HTML on the right. Try matching up the HTML you see in the picture with what's in the viewFunction in the Elm code. The div, input, and text all appear in the final page. This function creates the HTML of the page from special data called the model. In our little program, the model is just a string. We call the function that builds the HTML the view. The view is also called to update the HTML every time the model changes. What part of the code above changes the model? It's the updater function.
The updater has a very important job. It receives messages that represent something happening in the user interface—you clicked a button, typed in an input field, or moved the mouse—and uses the message to decide how to update the model. Messages in Elm aren't that much different than messages in Twine except that • you define them yourself • they can carry data, like in our case the TextChanged message holds the new string from the input field We come to the final piece of the puzzle: who sends the message to the update function? The view does. Up above we have this snippet of code: input [onInput TextChanged] [] The function input creates the HTML of the input but it also creates the JavaScript code for an event handler. In this case, Elm is registering an event handler for the oninput event that fires in your browser whenever you type in an input field. This event handling code is going to send the message TextChanged to the function updater. Now we've tied the loop together: the view reads the model and renders HTML that the user can interact with, the event handlers created by the view send messages to the update function when the page is used, the update function reads the message and changes the model, and when the model changes the view re-renders the page. The Html.beginnerProgram is the Elm function that does this loop-tying. You give it the starting model, the view function, and the update function, and it builds the code that connects all those pieces together. Now that we've gotten a feel for a complete Elm program, I want to bring up its type system. Unlike something like JavaScript, Python, Ruby, Clojure, etc. there's a typechecker that goes through the program and makes sure that the program doesn't misuse data. If you're familiar with a language like Haskell, Purescript, ML, or the like then you might be used to the kind of type system that Elm has. If your only exposure to typechecked languages is something like C or Java then, well, this is going to be a little different. First, instead of writing types of functions like int mySillyFunction(int arg1, int arg2){ ... } in something like Elm you'd just write mySillyFunction : Int -> Int -> Int mySillyFunction arg1 arg2 = ... where the type signature and the actual definition are on different lines. The type signatures in Elm are largely optional though. You can write them when you need to clarify things for yourself, but like in our example above you can leave them out and Elm will first infer types before checking them. This is a really cool feature that languages like Haskell, ML, and Elm have: it lets you write code that looks like an unchecked language but with higher assurance that the code is correct. Now, we've only scratched the surface of Elm but hopefully it's enough get you interested. Check out the link on the back cover of this issue to both my own examples and to other tutorials and interesting things about Elm! Happy hacking! b
17
Notebook
18
BY CLARISSA LITTLER
The Raspberry Pi is a really cool piece of hardware, a tiny low-power $35 computer that's roughly as capable as a desktop computer from the ‘00s. It's so small it might not be connected to a mouse, keyboard, or a monitor. I have one connected to my tv, my router, and my external harddrive where I keep all my music and movies. When I need to operate the pi, I could attach a keyboard and mouse, but an easier way to run programs on my Pi is to connect to it remotely from my laptop and control it from the command line. That's my awkward introduction to this article about using the command line in Linux, with a special emphasis on the things you'd need to know to administer a Raspberry Pi. For this article, you'll need
a computer running Linux or Apple's OSX. (Windows has its own command line interface that's different enough from Linux or OSX that a lot of things we'll be talking about don't apply.) Further, this article is mostly focused on Linux because that's almost always what's installed on the Raspberry Pi. (OSX is closely enough related to Linux that its command line is basically the same.) First, open a terminal. On both Linux and Mac there should be a program called "terminal" or possibly "terminal emulator": Open it and you'll see:
command line and hit enter. You should see a list of files in the current directory:
Here's a little note of terminology (more like terminal-ogy, eh??): If you're used to using a graphical interface on a computer you might think of the containers that hold all your files as "folders". When you read
d n a m m o C e h T Now what? Well, for your very first command type ls at this
ith her w t o b t ' . You “Don , Fred d r o c mand that e Com h t e s ect to can u conn o t e y Pi Lin pberr s a R your tely!" remo
Check out the link on the back cover of this issue for more!
ANDY MORFFEW, FLICKR
documentation about command-line interfaces you'll see them called directories instead, which is the terminology I'll use in this series of articles. The next command is cd, which stands for change directory. This is the first command that needs to be given an extra piece of data, called an argument. On the command line, commands are separated from their arguments by a space. So if I want to move into the directory called Documents then I would type cd Documents Here's a shortcut: the tab key functions as an autocomplete at the command line. So all you type is cd Do and hit tab. It turns into cd Documents/. More shortcuts: the tilde, which is the ~ character, stands for your home directory. So you can type cd ~/projects and the computer understands it as cd/ home/clarissa/projects. In order to go up one level in the directory
structure, type cd... That's two periods with no space between them. In general when dealing with directories in Unix/Linux/OSX the .. means "the directory that contains the directory I'm in". Try moving between directories and looking at what's in them with the ls command, getting a feel for navigation at the command line. Next, let's learn about optional arguments to commands. I can type ls to see a basic view of all the files in a directory, but I can also type ls -s to
19
“So, like, a Pi in the Sky?"
e c a f r e t n I e n i L see not just the names of the files but their size, or ls -a to see all the files, even the hidden files and directories that contain extra data and configuration for the programs on your system. For example, if I type ls -a in my home directory I see this:
Most commands have these optional arguments, and the general rule is • optional arguments start with a dash and one or two letters or • optional arguments start with two dashes (--) and are followed by a word. Often there's both a shorter and a longer way of specifying optional arguments. For example, ls --all and ls -a do the same thing. Here are three more commands to round out your file system skills:
rm to remove files, mv to move files, and cp to copy files. The rm command is both straightforward and dangerous. You can delete a file or directory permanently with it. I recommend that while you're new to the command line you should always call rm with the -i argument for "interactive". This will ask you about each file before deleting it. If I have a file called OMGTerribleFanFic. txt then I can delete it with rm -i OMGTerribleFanFic.txt. If I want to delete a directory, like a directory called TerriblePhotos, then I'd type rm -i -r TerriblePhotos: the -r stands for recursive and is needed to get rid of entire directories. The cp and mv commands copy and move files, respectively. You can say cp thisFile to copy a file or mv thisFile to move it instead. You can reference the entire directory structure in these commands, like mv ~/Videos/cats_being_weird. mp4 ~/Dropbox/bestcatever. mp4. You don't have to do anything special in order to move a directory, but to copy a directory you have to say cp -r just like removing a directory. Finally, here's a little trick
FILIP MALJKOVIĆ, FLICKR
to let you handle a bunch of files or directories at the same time: wildcards. At the command line you can reference a bunch of files at once by typing an asterisk, which is the * symbol. If you type mv Videos/*.mp4 Dropbox/. you'll move every file that ends with .mp4 from the Videos directory to the Dropbox directory with the same file name. That wraps up the intro to using the command line. Now you know enough to handle basic file management. Next issue we'll talk about calling other programs from the command line, editing files from the command line, and doing some more system administration. b
KURT BAUSCHARDT, FLICKR
“I KNEW you'd go for t he pun, Fred."
:bit Micro s i h hT n Wit O i d e ct! our J Proje Get Y r o t c Dete Sith
BY LES POUNDER
Electronics
20
! s e s r Cu d e l i Fo n! i a Ag
Building the Hardware
Building the project requires some electronics and plenty of cardboard. (Ask your local grocery store for extra boxes.) First we'll concentrate on the electronics. We need to know that they are working before we install them into the cardboard frame. To make these connections we need to use the Kitronik breakout board which will break out all of the GPIO pins present on the micro:bit ready for use with a breadboard. Insert the micro:bit into the breakout board so that it is firmly in place.
JD HANCOCK, FLICKR
Use some female to male jumper wire to connect the Ground (GND) of the micro:bit to the GND (-) rail of the breadboard. Now connect the battery back GND (Black) wire to the same rail. Then connect the Red 5V wire to the (+) rail. We now have a common ground, which means our devices will all exist in the same circuit. The next component to connect is the piezo buzzer. The red wire of the buzzer should be inserted into a spare place in the breadboard, and then a male to female jumper wire used to connect the red wire to pin 0 of the micro:bit breakout board. The black wire of the buzzer can be connected to the (-) rail of the breadboard.
For more info on Micro:bit go to https:// microbit.org/resellers
The next connection is made to the neopixels, and they have three pins. Vcc is connected to the (+)
rail of the breadboard via two male to female jumper wires connected together. The GND pin connects to the (-) rail using two more male to female jumper wires. The DIN pin, which means Data In, connects to pin 1 on the breakout board using one male to female wire and one female to female wire.
21
You'll Need:
• A micro:bit • Micro USB lead to connect micro:bit to computer • A Kitronik breakout board (https://www.kitronik.co.uk/5601b-edge connector-breakout-board-for-bbc-microbit-pre-built.html) • Breadboard • A Servo • Neopixels (we used an 8 pixel strip) • Screw Terminals (optional but handy) • Lots of cardboard • Piezo Buzzer • Arcade button or push button • Lots of male to female jumper wires • 2 x Female to female jumper wires • 4 x AA battery box and batteries You'll Learn:
• How to code with JavaScript blocks • How to connect components to the micro:bit • How a servo works • How to generate sound • How a loop works • How a conditional statement works • How neopixels work Our servo connects to the breadboard (+) and (-) but the color of its wires is different. Here, red connects to (+) and brown to (-). The yellow pin connects to pin 2 of the breakout board using one male to female wire and one female to female wire.
The final connection to make is the button used to trigger the device to life. This is an arcade push button, but you can also use a standard push button on the breadboard. The button connects to pin 13 of the breakout board and to the 3V pin. The button does not have a polarity so either pin can be used. Writing the code
We'll code this project using the JavaScript Blocks editor. Go to the microbit.org website and look for “Let’s code.” Click on the link, then look for the JavaScript Blocks option and click “Let’s code”. The JavaScript Blocks editor is in three sections. The first is the simulator, here we can interact with a virtual micro:bit. The second section holds our blocks which we use to write the code. The final section is where we drop the blocks to create the project.
Start the code by creating a link in the code to our neopixels. Go to Variables, create a new variable called “pixels” then drag “set item to” and place it inside the “on start” loop. Change the “item” option to “pixels” (we need to keep an eye on this). Next, tell the micro:bit where the neopixels are connected; you'll need the neopixel blocks. These are not installed as standard and require us to go to the “Add Package” option and install the Neopixels library.
Now we need the “Neopixel at pin… with ...leds as” block from Neopixel. Attach this to the previous block and configure the block to say that our neopixels are on pin 1 and that we have eight of them (change this to match the number you have).
Let's start coding the functionality that will be triggered at the press of the button. Inside the “forever” loop we need to place a conditional test called “if”. This will test if our button has been pressed. The "if" block is in the “Logic” menu (top option). Drag it inside the forever loop. From the Logic menu drag the “0 = 0” block and connect it to the “if” block. This will form our test. When it is pressed, the button connects the 3V pin of the
micro:bit to pin 13, and it turns that pin on (otherwise known as high) and returns a value of “1” telling us the pin is on. To check, go to the Pins menu and drag “digital read pin P0” in to the first “0” of the “0 = 0” block, next manually change the second 0 to 1.
The button press is ready. Next, tell the micro:bit that we want the following code to run three times. So we use the “repeat 3 times” block from the Loops menu, and place this inside the “if” condition test. To use the servo, tell the micro:bit how far it needs to turn. The Servo blocks are located in the Pins menu. We need the “servo write pin P0 to 180” block. Drag this and place it inside the repeat 3 times loop. Change the P0 to P2 as our servo is on Pin 2. Go to the Basic menu and drag the “pause (ms) 100” block and place it under the servo block still inside the if condition. Change the value to 1000 (1 second).
Your servo will now move 180 degrees and wait for 1 second, but in CONTINUED, PAGE 22
22
CONTINUED FROM PAGE 21
the next step we shall ignite Luke’s lightsaber! Go to the Neopixel menu and select “item show color red” and place it under the previous blocks, all still in the if conditional. Change the “item” option to our variable called “pixels” and change red to another color (Jedi have blue, green, purple, or white lightsabers). Still in the Neopixel menu, drag the “item show” block and place it under the previous neopixel block. Remember to change “item” to “pixels.” Our neopixels must be told to show a color change otherwise they won’t do it.
Luke is ready for battle. Sound the alarm (our piezo buzzer)! From the music blocks drag the “play tone” block and place it under the previous blocks, but still inside the repeat 3 times loop. Change the tone to any note you like. We also changed the tempo of the note. Use another “servo write pin” block from Pins to tell our servo on Pin 2 to rotate to 0 degrees, causing Luke’s head to spin around, we then pause for a further 1 second using the “pause (ms)” block from Basic.
to change “item” to “pixels”. These blocks will clear the neopixels and turn off Luke’s lightsaber.
We're now outside the “repeat 3 times” loop, but still inside the “if" conditional. Use another “servo write pin” to tell the servo connected to Pin 2 to return to 90 degrees, returning Luke’s head to its normal position. Then, use another “pause (ms)” from the Basic menu to change the value to 1000 for a one second pause. With the code completed, name the file “Sith-Alarm” in the box at the Congratulations! You've learned how to interface your micro:bit with a servo, button, and neopixels, and defended us all from the Sith. Today you used a button as a trigger, but if you want to automate the alarm you could use an infrared sensor to detect movement in the vicinity. There are also doppler radar sensors that work like infrared but use radio waves to detect movement… even through walls! b
The circuit for this project
The last two blocks inside the repeat 3 times loop are from the Neopixel menu and they are “item clear” and “Item show”, drag them both into the code and remember
bottom center of the screen. Then click on Download to download the code to your computer. Insert your micro:bit via the USB port. It will appear as a USB flash drive. Drag and drop the code we downloaded onto the micro:bit, and it will write the code to the micro:bit. After a few seconds it will be ready for use. Make sure your battery pack is switched on and there are batteries in it. Now press the button and watch as Luke jumps to our rescue!
Check out the link on the back cover of this issue for more, as well as this YouTube link: https://youtu.be/ yNrB_UNDWiA
Wall Follower Algorithm
The most basic technique is the “right hand rule”. Simply touch the wall to the right and keep your hand glued to it as you wander along. When you hit a junction, pick the option that keeps your hand connected to the wall. If the maze’s inner walls are all connected, you can picture them as a single piece of string looping back and forth, occasionally doubling over itself. Unravelling the string creates a circle. So when you follow the wall with your hand it may feel like a strange squiggly route, but it turns out that you’re heading in a straight line. Would the “wall follower” technique work with your left hand? Why might you choose one direction over the other? You need to put your hand on the wall the moment you enter the maze. The right hand rule can fail if you start in the center, or if the maze has bridges and crossovers. The biggest danger is getting stuck on an island: an isolated section of wall disconnected from the rest of the labyrinth. To deal with these features, we need a more advanced solution.
a MAZE ing! BY PATRICIA FOSTER
Trémaux to the Rescue
A simple algorithm developed by the French author Charles Pierre Trémaux is guaranteed to solve all mazes, no matter how bewildering. To make it work you need to remember which passages you’ve already visited. The rules are: 1. If you visit a junction with new paths, pick one at random. “Cross it out” as you explore. 2. If you get to a junction that’s been visited before, choose new paths over crossed-out paths. Likewise, choose paths that have been explored only once instead of paths that have been explored twice. 3. Never take a path that’s been visited twice! If you have to, turn around and go back the way you came. What if you don’t have chalk, string, breadcrumbs, or any other way of remembering where you’ve been? You can always try the ‘random mouse’ algorithm: picking a direction at random and crossing your fingers that it was the right choice. It’s not the most efficient method, but it should get you out—eventually. The Computer Version
Trémaux’s algorithm is just a human-friendly version of depth-first search (DFS), a common algorithm used in everything from GPS systems to artificial intelligence. To apply DFS we first transform our maze into a graph. Individual paths become edges and junctions become nodes. Now imagine that the nodes are beads connected by pieces of string. If you pinch the start node (the red circle) with your fingers and lift the whole maze into the air, the result will look something like this: To run the DFS, start at the top node and work our way down until you find the exit node (in bright yellow). Whenever you're faced with a choice, go to the left. If you run into a dead end—like that first orange node— backtrack up until a new path opens up to the right. Ideally, our exit node is at the bottom left. In the worst case, the node is at the bottom right and we end up visiting the entire graph. While DFS rarely finds the shortest route to the exit, it’s a simple algorithm and it doesn’t take up a lot of space in memory.
The colored circles represent junctions (nodes) connected to various paths (edges).
Puzzles
Print out some mazes and try solving them with depth-first search. When does it work well? When could it be improved? Can you think of any changes you could make to the algorithm that would make it faster? b XAVI, FLICKR
This type of graph is called a tree.
23
Puzzles
There are walls on every side. Passages twist and turn—you’re stuck in a maze and can’t get out! Don’t panic: math may have the solution you need.
Coding
24
BY PATRICIA FOSTER
Visualizing Randomness If we put the numbers 1-100 in a hat and draw them out one by one, what kind of sequence could we get? What if we shuffle the numbers back in once they’ve been picked? Randomness is a tricky concept that pops up in computer science. It seems simple, but gets convoluted as you get into it. To see what randomness looks like, we’re going to use Python and Turtle! Navigate to www.repl.it. In the ‘Search for a Language' bar, type ‘python’ and select the option ‘Python (with Turtle)’. Make sure that Turtle is included! In the code editor on the left-hand side, write: from turtle import Turtle, Screen from random import randint These two lines allow us to access modules of code written by professionals. Complicated tasks can now be done in one line instead of 100! Functions and Objects
The goal of functions is to hide pesky programming details and leave developers free to focus on the logic of their code. Imagine chatting with your best friend. Are you thinking about the movement of your tongue, lips, or throat? Probably not; that stuff happens automatically! Your brain is essentially passing chosen words to a ‘talk’ function that takes care of coordinating your body into saying the words correctly. In Python, you can recognize functions because they end with brackets: (). Inside those brackets are the function parameters that direct the behavior of the function. An object is a collection of data and functions that can be accessed through a single variable. Picture this: a person is a collection of arms, legs,
thoughts, and feelings; and each one is referenced by a unique name. Objects make it easier to organize and understand code. For example, it’s a lot nicer to say ‘Katie’s arm’ than ‘Arm #345567’. An object is created using a constructor, a special function whose name starts with a capital letter. In this program, we have two objects: a Screen and a Turtle. The Screen
Add the following code to your left-hand editor: playground = Screen() playground.setup(500, 500) playground.setworldcoordinates(0, 0, 500, 500) This code sets up a square digital playground that our turtle can explore. Imagine that the screen object is separated into a grid, like a chess board. Each square is defined by two numbers: a row and a column. If we pick two numbers, we can use them to pinpoint a specific square on the grid. This method of “mapping” numbers to squares is called a coordinate system, like this:
The bottom-left corner is (0, 0). The higher the first number gets, the more we travel to the right. The higher the second number gets, the
more we travel upwards, all the way to the top-right corner, which maxes out at (500, 500). The Turtle
Add the following code to your left-hand editor: thomas = Turtle() thomas.shape(‘turtle’) thomas.stamp() The first line creates our turtle object, and the second changes its image from a small arrow to a picture of a turtle. The “stamp” function in the third line leaves an impression of the turtle image on the screen, allowing us to tell exactly where Thomas has been. Now, finish off the program with the following: while True: num1 = randint(0, 500) num2 = randint(0, 500) thomas.goto(num1, num2) thomas.stamp() A while loop keeps running the code inside until its condition becomes false. For example, the statement ‘while cake not eaten’ loops until there’s no cake left, and ‘while skittles < 10’ continues until the program has 10 or more skittles. In our program, we want the loop to run forever, so our chosen condition is ‘True’. This is normally a big no-no in programming. It works in this scenario because we have a button that can stop the program by hand. Still—don’t tell the coding police! Inside the while loop, the program chooses two random numbers between 0 and 500. Next, it tells Thomas to head for these coordinates. When he arrives, he leaves a stamp. These actions are repeated until we end the program. Make sure that each open bracket has a closing bracket. Check that
‘True’, ‘Turtle()’, and ‘Screen()’ all start with capital letters. Make sure that you’ve imported your packages. Check that the four lines inside the while loop all start with a tab or two spaces. Don’t mix tabs and spaces or you’ll get an error! You’re all ready to go! Hit the ‘run’ button at the top of the screen!
As Thomas zooms around, we get an exact record of the all the random numbers “picked out of a hat”. Do a few trial runs, then leave the program running for 10-15 minutes. What do you see?
The picture tells us which numbers were picked, but it doesn’t tell us anything about the order. Can you think of a way to add this into b the code? What if you added colors? out Check on the k n the li f over o back c r fo e u this iss more!
Dinosaurs once walked the grounds of NASA in Maryland. Some left footprints in sandstone. In 2012, Ray Stanford, an amateur paleontologist, was visiting NASA in Greenbelt, MD. He noticed an outcropping of rock and found a nodosaur footprint! “Think of them as a four-footed tank,” Stanford said. The rock was important, but it was in a construction zone! Enter Dr. Stephen Godfrey, Curator of Paleontology at the Calvert Marine Museum in Solomons, MD. His job was to preserve the rock. While crews dug up the huge rock, it was decided that an exact copy of the stone needed to be made in case the original was damaged. Dr. Godfrey could scan the rock and print it using the then fairly new technology of large 3-D printing, or he could make a mold the old-fashioned way and pour an exact replica of the rock. He decided 3-D printing wouldn’t work as well as molding and casting. Scientists needed as much tactile detail as possible. 3-D printing couldn't do the high resolution work. First the team poured a thin layer of melted petroleum jelly onto the rock. This would release the mold easily. Then they mixed silicon rubber into a thick liquid form. They poured on many thin layers until their mold was half an inch thick. When the mold was pulled off of the original stone, they used it to make the plaster copy (a cast) of the rock. Dr. Godfrey’s son Michael painted the copy to resemble the original stone. Mr. Stanford moved the painted plaster copy of the rock to his basement. He and other paleontologists spent many hours examining the indentations, thinking about how they could have gotten there. They found footprints of a dinosaur parent and baby, three-toed meat-eating dinosaurs that are closely related to birds, and most surprisingly, they found mammal footprints. “This is the mother lode of Cretaceous mammal tracks,” said Martin Lockley, paleontologist with the University of Colorado, Denver. “We’re looking at the largest known slab that has mammal tracks on it. I know of four or five sites in the whole age of dinosaurs and some of them have one or two, and here we have approximately 100 footprints.” Dr. Godfrey’s detailed work paid off. For this level of research, he says that casts are still the best. However, he sees other uses for 3-D printers. His museum wanted to have an exhibit on Maryland Dinosaurs. They didn’t have the budget for molds, but they had digital files of scanned dinosaur heads and a maker-bot. His team was able to print and display skulls of the plant-eating Tenontosaurus, the bird-like Ornithomimus, and the meat-eater Deinonychus. “You can get a lot of very accurate information from these,” he said. “Just not as much detail.” b
25
Show and Tell
Older Tech That's No Dinosaur
BY AMY HANSEN
Archives
26
g n i e e S e h t e l b i s i v n I
BY TIM SLAVIN
27 When you pull out your phone or tablet (or desktop computer, if you’re a dinosaur) and call up a web page in a web browser, or use a social app, it’s magic, right? Somehow your device displays data on your computer screen without wires. The same happens if your car has a dashboard map device. How does this happen? You might logically know how the internet and broadcast work. However, if it’s all invisible, does it really exist? There is an invisible world, part of an infosphere, which includes devices that broadcast data to our computers. In the same way the biosphere has many different animals, plants, and other elements, the devices in the infosphere have many different pieces. Satellites, for example, broadcast signals
computers use to fix your location as you drive or walk down the road. Wi-Fi boxes broadcast data to and from the internet to and from your computer. Cell towers transmit your mobile phone calls. The Architecture of Radio app shows this amazing digital infosphere. You can see how your Wi-Fi box, for example, broadcasts huge circles of radio waves. These waves undulate and mix like ocean waves as they bounce off walls and pass through doorways. Your location in the wi-fi circle determines whether your connection is strong or weak. Or you can see and learn about GLONASS, INTEGRAL, FORMOSAT, and other satellites flying above your head in space, broadcasting signals down. The Architecture of Radio app is easy to use: point your phone or tablet anywhere around you. To identify a source, place it in the center of your screen and hold
your device long enough for the identifying information to appear. Described as a “field guide to the hidden world of digital networks,” the app was created by a Dutch artist, Richard Vijgen. His design studio explores stories within massive data sets, always looking for a connection to the physical world and social space people inhabit. The data set used to visualize the hidden world of radio waves around us includes 7 million cell towers, 19 million Wi-Fi routers, and hundreds of satellites. These signals are acquired and identified using the OpenCellID open source data set for cell towers, as well other open source data sets to identify Wi-Fi router and satellite signals. The app works on iOS (Apple devices) and Android devices. It costs $2.99 which is not much for such an educational and fun app. Especially since it is an unusual way to see and explore a vital but hidden part of our daily lives. It’s perfect for teachers to explain how the internet works with mobile devices, as well as how cell phones and other technology we take for granted work. b
IMAGE FROM WWW.ARCHITECTUREOFRADIO.COM
BY TIM MCGUIGAN
Making the Leap With Coding Challenges Each spring, my 7th grade classes make a sizeable leap. They transition from programming in graphical languages like Scratch or Blockly to the text-based languages, JavaScript and Python. Some students are eager and adept with the new languages, but for others this transition can be a bit bumpy. Text-based languages are more unforgiving with both syntax and structure than graphical ones. An omitted semicolon or misspelled parameter can bring their whole program to a standstill. However, I have found that short programming challenges are one indispensable tool in helping students navigate the world of consoles and compilers. While observing my 7th grade students during a recent JavaScript coding challenge, I noticed that some students were loners, focused solely on their own screens, while
WAYNE SILVER, FLICKR
Parents and Teachers
28
others peered at their friends’ code, quickly grabbing ideas. One savvy student consulted Stack Overflow. One made an excuse to wander and glimpse at answers. A few, with exasperation, gave up entirely. I learned a lot watching information flow around the room and solutions and frustrations bubble up. One of the factors that make puzzle-like challenges effective is consistent and predictable feedback. In his seminal book on decision making, Thinking Fast and Slow, Nobel Laureate Daniel Kahneman makes the case that people who seem to have mastered a skill and operate seemingly on intuition got there through repetition. However, Kahneman also states that an important factor in developing intuition is consistently predictable feedback. Fast and consistent feedback can better nudge a student towards mastery. Unlike a typo in an essay, which can take days to be returned to a
student, an error message thrown by a programming language gives swift feedback. However, if a program gets too large, a student can find themselves well into the weeds before learning basic skills. Short online challenges are the right fit for my young learners because they don’t allow the student to get too far ahead before providing feedback. I have to also be cautious in how I deal with students who begin to feel defeated. The goal is to have them struggle, but also feel that the task is not outside their capability. This is where the students guiding each other comes in. As students begin to pool information, I remind them that I encourage helping, but not plagiarizing. If they are helping a friend through writing a tough function, they have to explain why the answer works. I also frequently find myself sitting with a student asking some very leading questions, but always stopping short of solving it for them. If a student tried but came up short, they often return the next day more determined. While building up to a large web application is the goal of our JavaScript unit, the daily puzzles consistently make students better at programming the syntax and logic of the language. Over time, the commands become easier to recall and the cries of “I don’t get this” become less frequent. The students who this week are struggling with top-down design haven’t noticed that they are now effortlessly writing functions with multiple parameters. By giving them small but manageable challenges, they have moved something that used to be frustrating into second nature without really noticing. b
29
Coding Challenges I use: • Code.org CS Principles course
(https://studio.code.org/courses/csp) • Codingbat.com • codewars.com Tim McGuigan teaches middle school Computer Science and Robotics and is the Farrell Chair for Innovation at Shady Side Academy.
“Play is our brain’s favorite way of learning.” —Diane Ackerman Thank you for reading this issue of beanz ! Check out the links below to read stories from this issue online with links to learn more. Biobots: Biomimicry in Robots http://beanzmag.com/ bio-robots Predictive Keyboards: A Work in Progress http://beanzmag.com/ harry-potter-keyboard Escher Sketch(Up) http://beanzmag.com/ sketchup-escher-tiles Heavy Metal http://beanzmag.com/ 3d-printing-metal Breaking the Code and Winning the War http://beanzmag.com/ the-enigma-code
A Game Engine for All http://beanzmag.com/ godot
aMAZEing! http://beanzmag.com/ maze-solving-algorithms
Build a City From Scratch! http://beanzmag.com/ scratch-citybuilding
Visualizing Randomness http://beanzmag.com/ turtle-stamps
Redstone http://beanzmag.com/ minecraft-redstone
Older Tech That's No Dinosaur http://beanzmag.com/ dinosaur-footprints
Elm: A Language for Making Webpages http://beanzmag.com/elm The Command Line Interface http://beanzmag.com/cliintroduction Curses! Foiled Again! http://beanzmag.com/ microbit-sith-detector
Seeing the Invisible http://beanzmag.com/ architecture-of-radio Making the Leap With Coding Challenges http://beanzmag.com/ coding-challenges
ribe! Subsc
http://beanzmag.com/subscribe