Page 1

Kids, Code, and Computer Science Lazing Around with Haskell

A Classic, Updated

The New Sphero Bolt

4 Free

Python Tools December 2018

$6.00 $6.00 USD

Wrap Your Head Around Minecraft Mods


beanz magazine December 2018: Volume 6 Issue 3 Issue 39 (online) & 24 (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

Publisher’s Note Look at the picture to your right: someone created a square Minecraft head to wear. I definitely want a Minecraft head! This issue is one of the busiest we’ve done in over 40 issues, with all kinds of stories. There’s an article about Google Dream, for example, about how you teach computers dog-ness. And a tutorial that lets you chase a small round robot with a flashlight, the same way you might play with a cat (dogs, of course, are too smart for that game). Plus articles about Scratch and Minecraft, secret code books, STEAM board games, more tutorials, and free Python resources. We also cover interesting computing problems: Can software write itself? If there’s money behind one of three doors, and one door you know is empty, how do you pick the right door? And when you use a credit card but type a wrong number, how does a computer know you’ve typed the wrong number? And, if that isn’t enough, we have an interesting article about how modern elevators decide which floor and group of people to transport. You type the floor number you want and the elevator tells you which car to get in. This issue also is our last for 2018. We hope you’ve had a fun year and look forward to more adventures in computing and science in the new year. Enjoy your family and friends over the holidays!

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: Amy S. Hansen, 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 Editor: Derek Lanuto Art Director: Kelley Lanuto Webmistress: Patricia Foster COVER IMAGE: THE STARRY NIGHT BY VINCENT VAN GOGH, PUBLIC DOMAIN IMAGE, ORIGINAL ART AT MOMA, NY, NY.

Tim Slavin Publisher beanz Magazine

beanzmagazine magazine(as (asKids, Kids,Code, Code,and andComputer Computer beanz Sciencemagazine, magazine,our ourearlier earliertitle) title)isisa awinner winner Science

Our Mission

Parents’Choice, Choice,Tillywig, Tillywig,and andAcademics’ Academics’ ofofParents’ Choiceawards: awards:http://beanzmag.com/awards http://beanzmag.com/awards Choice

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.


December 2018

2

Cover Story

Projects Catch Me If You Can!

Cover Story

17

5 6 7 8 10

Minecraft Wrap Your Head Around This!

11 12 14

Scratch Feeling Loopy? Secret Codes Secret Code Workbooks ProďŹ le Danit Peleg Creates 3D Printed Fashion Notebook "I Just Had the Strangest Dream . . ." Notebook STEAM Board Games

20 tidbitz

Robots Going Up!

25 5 Great Beginner 3D Design Programs 25 Be Internet Awesome 25 A Self-Solving Rubik's Cube

22 Cover Story

16 18

Best Practices Cover Story It's Not ssso Hard! SketchUp Creating a Tile Pattern Coding Can Software Write Itself? Concepts The Credit Card Algorithm Concepts What Exactly Is Memory?

Languages Haskell: Laziness Is a Virtue

23

History Anatomy of an Email Address

23

Best Practices Recycling Electronics

24

Puzzles Let's Make a Deal!

26

Electronics Steady,Now!

28

Parents and Teachers The Importance of Play in the CS Classroom

contents

advanced

intermediate

beginner

scribe b u s / m ag.co m z n a e b http://


Projects

2

BY TIM SLAVIN

Catch Me If You

Sphero’s newest app-enabled robot ball, named BOLT, makes it easy to have fun and learn. BOLT has an 8x8 matrix that displays messages along with a compass to track direction, an infrared sensor to gauge distance, an ambient light sensor, and much more. The robot also is easy to code with either a drag and drop Scratch-like interface or text programming. BOLT’s ambient light sensor lets you create programs that react to varying light levels. Try this project, which lets you chase BOLT around

A

the room with a flashlight. Use the pictures to help guide you through the steps. First, download the Sphero EDU app from the Apple App Store or Google Play. Open the app, then click the Activities link at the top right and select Create. A Fill out the Create an Activity page that appears. Next, click the Programs link at the top right and select Create. Fill out the Create a Program popup that appears. B Now to code the Sphero robot! Add a loop forever block to the

start of the program from the Controls palette at the bottom of the app. Now from the Controls palette drag and nest an if/else block inside of the loop forever block. Next, you need BOLT to measure the amount of light it senses. Add the luminosity sensor block to the left side of a basic

B


3

Can!

comparator block. Be sure to set it to > (greater than). The number on the right is the lux value for ambient light in the room. You will need to adjust this based on the amount of light in the room. C Now you need to set the conditions for the if/else statement. Under the if, place a matrix block over the default true setting from the Lights palette. Create or choose an animation to play when the

flashlight is shined on the BOLT. Add a speed block (set to -200) from the Movements palette, and a delay block (set to 1s) from the Controls palette. But what if BOLT doesn’t sense the flashlight? That’s what the else statement is for! First from the Movements palette, add a stop block under else. This will stop BOLT from rolling if it stops sensing the

flashlight. Add another matrix block and create a new animation. Add a spin block from the Movements palette. Set the degrees to 90 and the duration to 1s. Lastly, add one more delay block, from the Controls palette, and set it to something really short like 0.2s. D You’re all done! Place BOLT on the floor and hit START on your program. Grab a flashlight and start chasing BOLT around the room! Continued next page

C D


Languages

4

Continued from page 3

s ' t a Wh ? e d i s In

Sphero Heroes is a Sphero Edu ambassador program designed to recognize and celebrate teachers using Sphero robots to transform teaching and learning in their classrooms and beyond. The 2019 Sphero Heroes application launched on November 5, and selected teachers will be announced in January. To apply, visit: https://www.sphero.com/heroes. b


5

BY CLARISSA LITTLER

For info on Scratch go to https://scratch.mit.edu

If you've been making games in Scratch for even a little while, you've probably wondered how to do proper animation loops in your games. Let's discuss how to load animated GIFs into Scratch, how to cycle through frames of animation for moving around the screen, and how to have an idle animation that plays whenever you're not moving. Loading animated GIFs into Scratch is the easiest way to get animation loops into your game. You can just click on the button that creates a new sprite from an image and select the GIF! Scratch will create a new sprite that has a costume for each frame of the GIF. You can also add an animated GIF as a sequence of costumes by clicking on the button to add a new costume from an image. For a lot of Scratchers, this is how they get classic video game characters like Mario, Sonic, or Link into their games. For the purposes of this article, I'm going to be using the website Piskel to make my animated sprites (https://www.piskelapp.com/). I made a sprite that has both frames for an idle animation (A) and moving animation (B). Please don't be intimidated by the sheer artistic quality of my stick figures! There are a couple of concepts that are important for making the animations work. We need to first note which of the costumes constitute the loops we want. Each costume has a number associated with it that's in the upper-left corner of the costume. In this case, my idle-frames are numbers 1 through 3, and my walking animation frames are numbers 4 through 8. We're also going to make a variable to tell the game whether we're moving or standing still. In this case, I call the variable isMoving. We'll make sure that we only put the values 0 and 1 in isMoving, where 0 means "the sprite isn't moving" and 1 means "the sprite is currently moving". Here's what my code looks like: (C). There are two main blocks of code here. The first one is the movement loop. It detects key-presses and then moves the sprite, setting the isMoving variable to 1 if a key is pressed. If none of the keys are held down, then it sets isMoving to 0. The second block controls the animations. The code starts by checking whether the sprite is moving. If the sprite isn't moving, it starts the idle-animation loop. The idle-animation loop starts by moving to the next costume, and then checking whether the costume number is greater than 3 (has moved out of the idle animation frames), and if so, puts it back at the start of the idle loop. The "else" part of the "if-then-else" does the same thing but for the moving loop. Check out the link for this story on the back cover of this issue to learn more. b

Scratch

Feeling Loopy?

A B

C


Secret Codes

6

Secret Code Workbooks

BY SIMON BATT

Last issue, we covered a few gift ideas for code-lovers. We had so much packed into the issue, that we didn’t have the room to properly explore each one! This issue, we’re going to take a closer look at each of the workbooks we recommended, why we did so, and how they can help you out with your code sleuthing! Scientific Explorer Secret Codes Decoder Kit

If you’ve been a long-time reader of our cipher articles, you’ll remember the Pigpen cipher. This is where people make a key that looks like different pigpens, then designate shapes within those pens to specific letters. This kit comes with a premade Pigpen cipher code, so you can get creating right away! It also has a few other ciphers you can use, plus the traditional invisible ink for some extra sneaky messages. You can’t decode what you can’t see! Secret Decoder Deluxe Activity Set - ON the GO

This one is a little less focused on traditional ciphers that we’ve covered, but it provides plenty of codes in a miniature series with lots of fun tools you can use. It’s more to do with invisible ink and detective lenses than actual ciphers, but if you’ve always wanted to feel like a sleuth, this one makes code-busting fun! Telegraph Kit - The Science Cube DAVE MATOS, FLICKR

In a past issue, we covered the importance of Morse Code in

history. While it wasn’t a true cipher —it was designed to be easy to transmit, and not to fool or deceive people—it was still a good look into the creation of a code that saw a lot of use. This telegraph kit allows you to re-experience those moments by giving you a Morse Code machine ready to build. Put the pieces together and you, too, can talk in dots and dashes. Top Secret: A Handbook of Codes, Ciphers, and Secret Writing

If you prefer to skip the kits and tools and just want a solid book to read, this one is the perfect way to learn about ciphers. Don’t be fooled by its cover and title; it’s a great read for all ages and doesn’t get too complicated with its subject matter. It does recommend some ways to make your own spy tools if you want to practice them yourself, but it’s otherwise a great book for learning about ciphers. Cracking Codes with Python

If you want to get some practice done with programming, why not make some cipher-busting programs? This book teaches you how to make and break secret codes using the Python programming language. This makes for a fantastic way to learn how to code while also making something fun and practical you can use once you’re finished. A must for any programming enthusiasts! b Check out the link on the back cover of this issue for more info!


7

BY ERIN WINICK

Danit Peleg has pushed the bounds of 3D printed fashion for years. From her fashion collection made completely on home desktop printers in 2015, to her launch of the first 3D printed clothing available for purchase online this year, she continues to demonstrate 3D printing’s capabilities in fashion. Were you a “maker” growing up or did you find an interest in technology later on? Peleg: I think I have been a “maker” since a really young age. When I was 10, I attended an afterschool fashion course. My mother bought me a sewing machine and I started playing with it. I remember that it was mindblowing for me. I LOVED the idea that I could make my own outfits and costumes by myself. So I knew pretty early on that I would be doing creative things with my hands, especially creating clothes. Do you think 3D printing and fashion are a natural fit? Peleg: I think that there are many benefits when combining 3D printing and fashion and what we see today is only the beginning. I believe that we will see more and more 3D printed fashion, but it will look differently than today. I found it so interesting that by using this technology I was able to print 10 pieces of clothing by myself from the comfort of my house. The problem is that it took 2000 hours to accomplish. With the second collection — only a year and half later — the process became three times faster. Two things need to improve: the speed of the printers and better materials (filaments). The filaments PHOTOS BY DANIT PELEG

I produced are flexible, but they are not like cotton yet. I’m sure we will soon see innovative filaments and faster printers. What inspired you to create a line of jackets as your first consumer 3D printed items? Peleg: The first jacket came as part of the ‘Birth of Venus’ collection, which included a dress I made for the opening ceremony of the Paralympics in Rio 2016. The dress was worn by Amy Purdy, a Paralympics medalist and a dancer. I suppose the process of making this dress is what inspired me to be able to create this unique experience for more people. I didn’t meet the dancer in person but by using an app called Nettelo I was still able to customize it completely to her measurements. I was also able to send updated simulations for feedback, before even printing one piece of fabric, and the whole process produced zero waste. With my 3D printed designs I always try to do ready to wear looks, clothing that you can wear on the street, and I think I achieved it with the bomber jackets. Beyond making 3D printed fashion for the consumer, what innovation with 3D printing in fashion excites you most? What are you doing to push this forward? Peleg: We’re beginning by creating the possibility for a wider audience to own unique 3D printed garments. I want to solve all the challenges. I also plan to opensource some of the items from my first collection, so that people will be able to experiment with 3D printing themselves. I hope after reading this, you’ll be one them! b

Profile

Danit Peleg Creates 3D Printed Fashion

Peleg’s dress at the 2016 Paralympic opening ceremonies

The debut 3D printed fashion collection and ready to wear jacket


Notebook

8

e h t " d … a H m t a s e r u J D I t “ s e g n a Str

BY PATRICIA FOSTER

In 2015, a new milestone was achieved: an artificial intelligence creating its own art. Weird, nightmarish, surreal, full of eyeballs and psychedelic patterns. Google’s Deep Dream software was originally invented to visualize the inner workings of a Convolutional Neural Network, and scientists soon discovered that by tweaking a few equations they could make the algorithm create and modify images instead of just classifying them. The code for Deep Dream is now public, and several web apps exist that let you try it out on your own pictures. Two popular sites are Dreamscope (https://dreamscopeapp.com/) and Deep Dream Generator


(https://deepdreamgenerator. com/#gallery). Unfortunately, accessing the tools on either platform requires you to create a free account, but once logged in you can upload photos, choose your filter, and marvel at the results! (Remember: never upload photos of yourself to the internet. Use pictures of pets, landscapes, or images found on Google.) The Math Behind the Magic

How can you tell that the music on the radio is a rock song or a piece of classical music? The type of instruments, the speed of the song, and the patterns in the melody are all clues that your brain uses to differentiate between musical genres. Likewise, if you’re trying to recognize a piece of fruit, you’ll pay attention to things like color, size, shape, and weight. In a sense, neural networks work the same way as your brain. Using a series of linked statistical equations, neural networks take input data, crunch the numbers, and decide if the spherical orange object weighing 10 ounces is more likely a peach or an orange. To train a neural network, you show it the data from thousands of oranges and peaches, until it gets an intuitive sense ‘orange-ness’ and ‘peach-ness’.

Although not fully shown in the above diagram, every neuron is linked to every other neuron in the network. Each one does a simple equation on a piece of data and hands the output to the next layer of neurons. By adjusting equations over time, the network learns how to fire the correct “output neuron” when faced with a series of inputs.

Identifying an object inside a picture is extra hard because it’s not always clear what data you need to inspect. If you’re looking at a photo of a dog, the dog might fill the whole picture or it might be tucked away in a corner. You might see its full body or only its face, and the photo might be taken from the side or from above. So in order to classify the dog photo, we need a special variation of the neural network algorithm called a Convolutional Neural Network (CNN). Inside the CNN

You train a CNN by showing it hundreds of pictures of dogs until it gets an intuitive sense of ‘dog-ness’. While the algorithm still uses chains of statistical equations to make its decision, the process is a little less straightforward. First, the CNN slices up its input image up into squares. It then applies a series of different convolutions to each square in order to extract features. You can imagine a “convolution” as a type of filter. Only instead of making photos prettier we’re trying to make them simpler for computers to process. When applying a convolution, you adjust a pixel’s value based on the value of its neighbors. A blur is a simple type of convolution where colors and edges are blended together, which is useful because it obscures details and forces us to only consider essential shapes. There are many other types of convolutions, including sharpening and edge detection. Informally, “features” are “interesting parts” of an image. Things like lines, dots, and corners help us recognize that we’re looking at a drawing of a cat instead of a drawing of a dog: In this case, the shape of the snout, the ears, and the tail are the features that differentiate

between the two animals. By cutting up an image and applying convolutions, CNNs transform a complex photograph into a simpler series of features. Of course, the neural network has many layers, and each one breaks up the image into smaller squares and makes the features more abstract. In the final layers, it’s not obvious to humans what shapes the CNN is studying. The training process helps the CNN “learn” what types of features are common in the photos it’s trying to identify. This also means that each CNN is only to trained to recognize a specific thing, or maybe differentiate between a handful of objects. A CNN looking for dogs will classify an apple as a “not-dog” because the network has no concept of anything other than dogs and “not-dogs.” Deep Dream

Deep Dream is a type of CNN that uses its input picture as a springboard into bizarre dreamscapes. As the algorithm progresses it encounters feedback loops. At this point, the CNN returns to an earlier step and strengthens the features that it considered “interesting.” If the algorithm has been trained to detect dogs, it’ll fixate on the “dog-like” features of the picture and make them progressively more and more “dog-like” until dogs start to appear in clouds and trees! A CNN trained on eyeballs will make eyeballs sprout from walls and faces. Another neural network trained on impressionist art will transform its inputs into impressionist tributes. So is the algorithm really “creating?” The algorithm is just identifying and strengthening features in a mathematical, formulaic way. The neural network has no concept of “art” or anything beyond the shapes it’s trained to recognize. But CNNs are still amazing, and the creations of Deep Dream are interesting and fun. Happy dreaming! b

9


Notebook

10

BY SIMON BATT

Who says learning can’t be fun? There are plenty of ways you can learn essential STEAM-related skills while also making a game out of it. If you find yourself bored over the holidays and want something to keep you entertained, pick up some of these brain-ticking games and get thinking! Bloxels

Want to try making your own game, but can’t really code anything yet? Try Bloxels, the game within a game! Build levels using physical cubes on a grid, then scan it into the game’s app and watch as your level becomes a reality. This is a fantastic way to learn about grid-based game design without any of the code. Code & Go Robot

Maze games are fun, but what if you’re not directly controlling the character going through the maze? What if you had to pre-program the character with the directions and see if you got the solution correct? This is the concept behind the Code & Go

Robot. Build a maze, program the little mouse, and let it go. See if you can beat the maze with just your mental deduction alone. Roborally

If making a mouse go through a maze isn’t action-packed enough for you, why not pilot a battle bot instead? This board game has everyone take control of a battle droid, who has to make it out of the other side of a grueling obstacle course. The problem is, everyone has to pre-program their robots at the start of each turn, meaning everyone gets in each other’s way. The robots end up slamming each other into pits and firing at one another, whether the pilots meant it or not! Mastermind

Mastermind is a game all about logical deduction. One player secretly makes a code out of colored pegs, and the other player has to decipher

the code. The guesser's only input is a board where they can arrange their guess of what the code is. Once the player locks in their guess, the code setter lets the player know if their guess’ colors are in the correct spot, are the correct color but in the wrong place, or not in the code whatsoever. The guesser then keeps guessing until they work out the color code. Code Master

If you’d like to learn the logic behind programming before you jump into the real thing, try Code Master. This is a game that presents a world to you, which you have to beat to advance. The problem is, you interact with the game using a code-inspired movement system. Instead of moving the hero where you like, you have to create a string of instructions which is designed to be similar to how a computer reads code. Get all the gems and reach the portal using your code to win the level! b

M A E s T e S m a G d r a Bo Check out the links on the back cover of this issue for more info!

JJ MERELO, FLICKR


11

BY TIM SLAVIN

Python is a fun, (mostly) easy-tolearn programming language that also has powerful features. Here are a few places to go online to learn about Python. Repl.it

Practice your Python skills, from beginner to advanced, using this online service. Select Python 3 as your programming language then type your code in the left side of the interface, press the Run button, and see the output on the right. http://repl.it.

Learn Python the Hard Way

Well, not exactly the hard way. This online resource teaches Python step by step, project by project. It’s probably the most thorough way to learn the language. Click the Contents link top left to read the text online. A book version also is available for purchase. http:// learnpythonthehardway.org/book. Python Turtle

For beginners and younger kids who want to learn alongside a parent

Best Practices

It's Not sss o Hard!

or teacher, Python Turtle is a simple desktop computer software tool that teaches Python by typing code to move a turtle. The software is free and open source. http://pythonturtle.org/. Dan Bader Email Newsletter(s)

Dan is a Python expert who publishes helpful email newsletters with information about how Python works and is used in real life. https:// dbader.org/. b YU-CHAN CHEN, FLICKR


Creating a

BY BONNIE ROSKES

SketchUp

12

SketchUp is a free program for 3D modeling. Download SketchUp Make, at https://www.sketchup. com/download/all. There is also a web-based version called my.sketchup. Just go to www. my.sketchup.com. Now for the project, re-creating a Cordoba Tile pattern, from the famous Great Mosque in Spain. Go to the SketchUp page and launch your modeling session. You'll see Josh. The red and green axes are on the ground, blue is for the vertical direction. Click the Eraser icon to erase Josh. Switch to a bird’s eye view (looking straight down). On the right side, click the Views icon. 1 Then click the icon that looks like the top of a house. 2 You should now be looking straight down onto the redgreen plane. Press R for the Rectangle tool, and click to place the first corner anywhere. Don’t keep your mouse button pressed–no dragging. Then move your mouse in any diagonal direction until you see the “Square” popup, and click again for the

second corner. 3 Next, draw a circle centered in the square. Press C for the Circle tool. Then hover (don’t click) on any midpoint of any edge of the square. Then hover over any midpoint of an adjacent edge. 4 Move your mouse to the center of the square. When you’re in the right spot, you’ll see dotted lines from the two midpoints where you were hovering. Click to place the circle center. 5 For the second point of the circle, click on any midpoint of the square. 6 Now we can use the circle and square to construct the rest of the Cordoba Tile. Press L for the Line tool. Start the line at any rectangle corner, and end the line at the center of the circle. 7 Now add the two lines shown below, each starting at the point where the line and circle intersect, and ending where the circle meets the square. Click on intersection points and endpoints. 8 Extend these diagonal lines to meet the edges near the corner of the square. Start the line where

the diagonal line meets the circle, and move your mouse so that the preview line is magenta. This means the line will be following the same direction as one of the existing lines. End the line when it meets the correct edge of the square. 9 Do the same for the other diagonal line. Now rotate-copy what you’ve just made. Press Ctrl + A (PC) or Cmd + A (Mac) to select everything in the model. All edges and faces should be highlighted in blue. 10 Press Q to activate the Rotate tool. Place the protractor at the center of rotation (the center of the circle). 11 The next two clicks determine the rotation angle. But first, press the Ctrl key (PC) or Option key (Mac). This adds a plus sign to your cursor, meaning a copy will be created. Then click any corner of the square. 12 For the end of rotation, click any adjacent corner of the square. The Angle field in the lower right corner should say 90 degrees. 13 This created one rotated copy, but we need rotated copies in the

1

2

5

6

9

10

3

4

7

8

11

12

4

8


Tile Pattern other corners as well. In other words, we need three total copies, not just one. To get these copies, type 3x (which appears in the Angle field), then press Enter. Don’t place your cursor in the field, just type and the characters will appear. Now the square should have the same sets of lines in all four corners. Click anywhere in blank space to unselect everything. Next, erase the short lines in the four corners. 14 Then erase the lines that divide the eight diamond shapes that surround the center. 15 Finally, erase everything inside the 8-pointed star in the center, and erase all the parts of the circle as well. You might have some faces disappear, and some lines that should be thin may appear bold. 16 If you have any holes, or bold edges in the middle, activate Line and trace over any of these edges. You should have no holes and all thin lines in the middle. The only bold edges should be the outer edges of the square. This square and its lines make up the Cordoba Tile. 17 Now for the fun part: painting

and copying. Click this icon to open the Materials window. 18 To look through the options, click the Browse icon for colors and a variety of textures. 19 In my example, I used solid colors to get this: 20 To repeat the pattern, make the tile into a component. Press Ctrl + A or Cmd + A again to select everything. Right-click on any selected face and choose Make Component. Give the component any name, and click OK. Now this tile is a single object, rather than a set of loose edges and faces. This makes it much easier to make copies, changes, etc. Press M for the Move tool. Tap the Ctrl or Option key for Copy mode. Copying is done with two clicks: start and end. Click on the two endpoints shown to place the first copy. 21 Then type 2x (or 3x or whatever number you like) to make additional copies. 22 For copies in the other direction, do the same steps: Select everything, make the first copy in the vertical direction, then increase the copies.

13

We’ll now hide edges, to make the pattern easier to see. The beauty of using components is that if you make changes to any component, all other components get the same changes. Right-click on any tile and choose Edit Component. (You can also press the Spacebar for the Select tool and double-click a component to edit it.) The component that’s editable is now surrounded by a dotted-line box, and everything else is faded. Only what’s inside the component can be changed. Activate Eraser, press and hold the Shift key, and click all outside edges of the square to hide them. 23 When finished, right-click in blank space and choose Close Component. (Or press the Spacebar and click anywhere outside the component.) Here’s my new pattern, with all horizontal and vertical edges hidden. 24 You can continue making changes each time you edit a component. What patterns can you come up with? b

13

14

17

18

21

22

15

16

19

20

23

24


Coding

14

BY CLARISSA LITTLER

Can Software Write Itself? Can a computer ever be considered alive? Many researchers and thinkers have directed a lot of mental energy towards the question "can machines think like we do?" While that is an interesting question, we're going to step down—or up depending how you look at it—the evolutionary tree and ask a far more basic one: can machines, or at least software, reproduce? Douglas Hofstadter thought about this decades ago. In his book Goedel, Escher, Bach, he asked: can you write a program that, when run, prints out its own source code? Hofstadter called solutions to this problem Quines, after the philosopher Willard Van Orman Quine who wrote about selfreferential paradoxes. Things like "this statement is false" or "everything I say is a lie!" While you only need a single example of a Quine to show that, yes, software can reproduce itself, Quines are still interesting today as coding puzzles! Lots of people test themselves to write clever Quines in every language they can think of. It's a fun challenge that's a lot harder than it might seem. Let's try to write a simple Quine in Python to show why it’s tricky. I'm following a path towards a Quine very similar to the Python Quine on the Quine wiki page. Try the code out with https:// repl.it and use Python 3. To start you might want to try something like print("print(...)") where we need to figure out what to put in place of the ellipses. The problem? There isn't anything obvious to insert there! We easily get stuck in an infinite expansion: print("print(\"print(...)\")")

We're always printing one fewer layer of print statements than we need to replicate the source code! Let's put in a variable. What about something like str="str=...\nprint(str)" print(str) It may look like we've moved the problem to the definition of str instead of what goes inside the print statement. We need a way to insert data into the string that will tie the knot we're having trouble with. That's string interpolation, though! Finally, we can change our code to str="str=%r\nprint(str%%str)" print(str%str) So what we're doing here is making a "hole", so to speak, in the string with %r which we fill in the print statement with the string itself. That's the big punchline, here, that to make a Quine you need to be self-referential like the paradoxes Quine wrote about! As a technical note, we use %r instead of %s to make the hole we want to fill in because %r keeps the string looking exactly like it did originally, including quotation marks and escaped characters. We also use %% to escape the % symbol that we don't want to be a hole in str. You can try this out at https:// repl.it using Python 3. You should get the two lines of code that make up our software program. The program writes itself out. Also try removing and adding parts of the code, for example, print(str) instead of print(str%str). The online version of this article also has links to collections of Quines you can study, including a wiki at http://rosettacode.org/wiki/ Quine. Try writing them in in your favorite programming language! b


QUINN DOMBROWSKI, FLICKR

15


Concepts

16

BY JENNIFER NEWELL

The Credit Card Algorithm Imagine entering a credit card number into an online store and, midway through typing the number, one enters 72 instead of 27. With all the credit card numbers in the world, maybe the mistyped number belongs to one of your parent’s cards, and the person who typed it just accidentally charged $600.00 to their account. With all the online transactions that happen every day, accidents like this must happen all the time, right? Actually, there is a clever algorithm that prevents almost all such accidents. The algorithm is known as the Luhn algorithm. The Luhn algorithm is a checksum algorithm. A checksum is a relatively quick check involving the sum of the digits on the card. And this checksum was created by computer scientist and avid inventor Hans Peter Luhn in 1954 and patented in 1960. Imagine this scenario: A well-intentioned shopper has a credit card with the following number: 79927398713 (this number is made up: we wouldn’t want to publish a real credit card number!). However, the shopper gets distracted when entering the card number, and transposes the 2 and 7, typing the following incorrect

CONSUMERIST DOT COM, FLICKR

number: 79972398713. Thanks to the Luhn algorithm, the computer immediately gives the user an error message before asking for the expiration date and three digit card verification value. How does this algorithm work? First it takes every other digit that is entered and doubles it. The original number (typed incorrectly): 7

9

9

7

2

3

9

8

7

1

3

First becomes: 7

18

9

14

7

6

9

16

7

2

3

If the result of doubling a digit is a two digit number (such as 18, 14, and 16 above), replace the result with the sum of the digits (1 + 8, 1 + 4, and 1 + 6). 7

9

9

5

7

6

9

7

7

2

3

Now add up all the the single digit numbers: 7 + 9 + 9 + 5 + 7 + 6 + 9 + 7 + 7 + 2 + 3 = 71. In order for the computer to believe that the number entered could be valid, this sum must be divisible by ten (with a remainder of zero). However if we divide 71 by 10, the remainder is one. This alerts the computer that the number entered could not possibly be a valid card number. If we go through the same

algorithm with the correct card number we get the following result: Original Number: 7

9

9

2

7

3

9

8

7

1

3

9

16

7

2

3

7

2

3

Double Every Other Digit: 7

18

9

4

7

6

Add the Digits of Two-Digit Numbers: 7

9

9

4

7

6

9

7

Taking the sum of the digits in the bottom row, we get 7 + 9 +9+4+7 +6+9+7+7+2 + 3 = 70. Indeed, 70 ÷10 has a remainder of zero! Does a sum that is a multiple of ten guarantee that the user entered the correct number? No. There are a few possible errors that would still result in a sum that is divisible by ten. Transposing 90 to get 09, or typing 22 instead of 55 (known as a “twin error”) are two possible errors that would pass the test of the Luhn algorithm. Can you think of the other two twin errors that would slip though the test? Partly because the Luhn algorithm is not perfect, online stores also ask for the the card’s expiration date and the card verification number. However, using this quick checksum algorithm catches many unintentional errors that might lead to accidentally charging the wrong card. b


For info on Minecraft go to https://minecraft.net

Wrap Your Head Around This! For the past few issues, we’ve been focusing on mods that enhance exploration and add more base content to the game. Do you remember when we talked about redstone, and how it can be used in a computing way? Well, there are mods out there that take this one step further! Let’s take a look at some logic-based mods that are bound to have you thinking hard! Project Red

If the base redstone content has you bored, why not try Project Red? This deeply enhances redstone in the game, adding items such as circuit boards, coils, and plates. Project Red has a base ‘core’ mod that has all the basics, but

you can also pick and choose from other modules, with the ability to transmit redstone over long distances and use it to break and place blocks. ComputerCraft

If you want to try programming in Minecraft, this is the way to do it! ComputerCraft puts computers and programming into your game. You can use it to do some basic functions, or wire it up to other components to make logic-based contraptions. It’s a great way to learn how to code and have fun with it at the same time!

IndustrialCraft

If you aren't into building computers, but you enjoy the idea of making contraptions that perform your bidding, you may prefer IndustrialCraft instead. This doesn’t require programming, but it does introduce a lot of machinery which you have to build using your own logic. Furnaces are great for making ore, but how about making a conveyor system to pick up ore and automatically smelt it? How about automatically powering the furnace using solar energy, water power, or even lava? The choice is yours! Roboticraft

Did you ever wish you had your own programmable friend? Why not try Roboticraft, a mod that uses Python programming, to make your own worker companion? Build a small robot, then give it chips that allow it to attack, mine, build, and interact with redstone contraptions. It has its own inventory and is similar to a player character. All you need to do is tell it what it needs to do! It's a great way to learn Python with the end result being your own robot buddy.

MOOSHUU, FLICKR

BuildCraft

Playing Minecraft is a ton of fun, but what if you want to go exploring while also gathering ore for your base? If you want something else to do the hard work for you, try BuildCraft. This allows for superior automation when mining quarries, so you never have to lift a pick again! You can set up tubes and machinery to transport the freshly-mined ore right to your boxes, so you can watch the ore roll in after you’re back from your adventures. b

17

Minecraft

BY SIMON BATT


Concepts

18

BY PATRICIA FOSTER

What Exactly Is What happens behind the scenes when you hit the “run” button and your code springs to life? To develop a deeper understanding of computing, let’s take a look at an essential, if somewhat mysterious process: storing programs in memory. Breaking Down Into Binary

Every variable needs to saved somewhere. Otherwise, your program will forget values when it moves to the next line of code. At a base level, computers work with 0s and 1s. So before we store our data, we must transform numbers, letters, and complex audio-visual objects into simple 0s and 1s. Small integers (whole numbers) like “5” or “37” are stored as binary versions of themselves. “5” becomes “0101” and “37” is “100101”. For

DAWID ZAWILA, UNSPLASH

negative numbers, we use a clever system called “two’s complement”, which involves flipping each bit in the positive equivalent of the binary number and then adding one at the end. For example, “5” is flipped from “0101” to “1010”, and then finishes as “1011”. This representation makes it easy to add or subtract integers. To keep things simple, most operating systems store integers in standardized 32-bit blocks. Even tiny integers that only need 1 or 2 bits of space! Letters are stored using ASCII (American Standard Code for Information Interchange). ASCII is a not-so-secret code where every number from 0-265 corresponds to a particular letter or symbol. Capital “A”, for example, is 65. A question mark is 63, and the letter “1” becomes the number 49. ASCII codes are then stored using the same rules as integers. The string “Hello world” has 10

letters and 1 space, which requires 11 ASCII characters and therefore 11 bytes (88 bits) of space. Different types of data require different amounts of memory storage. In “typed” languages like Java or C, you specify the size and type of your variables when you write the code, which makes things simple for the compiler, but requires you to know the size of all your data in advance. Storing Variables

Let’s imagine values and variables as cats in boxes. The cat represents the actual value, like “5” or “Hello world”. The variable is just a convenient box where a cat can sit until it chooses to leave. During the runtime of a program, a single box might hold hundreds of different cats. This system is also a convenient way for the program to find a cat very quickly— just look inside the value’s box! In real life, each “box” is a tiny spec on a memory module deep inside the guts of your laptop (or phone, tablet, or hard drive). Each bit of data is stored as a 0 or 1 inside a special electronic circuit. With infinite patience and a very powerful microscope, you could crack open your laptop and locate the exact physical space where your variable is stored. In practical terms, this is impossible, because there are billions and billions of circuits inside each memory module!


PHOTOS FROM UNSPLASH, FROM TOP DOWN: GLENN CARSTENS-PETERS, RAWPIXEL771275, ANNIE SPRATT, FRANK WANG, COLE KEISTER

Memory? Each variable “box” has an address, the same way your house has an address. When a program is booted up, the operating system hands it a chunk of memory with a series of addresses it can use to store instructions and variables. All memory addresses are

hexadecimal numbers. So instead of looking for “123 Rainbow Rd” your program might search for “#0000 0340” or “#AF83 1E82” to find a particular integer or string. Stack and Heap

Depending on where you declare your variable, it’s either going to end up with an address on the stack or on the heap. Local variables—things declared inside functions—get put on the “function call stack” and stored together. So if you declare three integers in a row, they’ll probably be neighbors with continuous addresses. This makes it easy for

the program to find and manipulate data inside functions. The heap is for “dynamically allocated memory.” You don’t always know how much space your program needs, especially when you’re reading user input or manipulating big graphics files. In “low-level” languages, like C and C++, you can write code to ask the OS for a chunk of memory during the runtime of your program. The OS responds to your request with a hexadecimal value: the address of a new empty box to store your data! This value is also referred to as a pointer because it’s not a real piece of data, it’s just a sign post for a storage area. Practically speaking, the only difference between the stack and the heap is when and how the program stores variables inside them. They’re both just chunks of memory: electronic circuits used to store bits. Separating the two helps programmers stay organized, the same way you separate spoons and forks inside your cutlery cabinet to make things easier to find.

All of these actions happen inside a computer’s RAM, also known as “random-access memory.” RAM is “live” memory that requires electricity to keep values stored. If the power goes out—poof! The data is lost. For this reason RAM is also called “volatile” memory. On the plus side, it’s fast and easy to access. We've learned that all variables are stored as bits in different formats, and programs locate variables using their hexadecimal addresses. We've also learned that each address corresponds to a physical circuit inside your computer’s memory module, and inside a program, memory is separated between the stack and the heap. Each one stores different kinds of variables. And lastly, that programs are loaded inside RAM, which requires electricity to stay running. Managing memory is a tricky business. People who work in computer security or embedded systems deal with the nuts and bolts of storing bits and optimizing function calls. Improper memory management can cause “memory leaks,” which makes programs slow and buggy or become a gateway for hackers. For high-level programmers, it’s important to remember that things we do all the time—like writing code using words instead of bits, or importing graphics into our programs—are abstractions. There’s a whole world of details and processes happening behind even the simplest line! b

19


Going Up!

GILLES, FLICKR

ifa, D Khal Burj

In the past two issues of Beanz we have read about the robotics that goes into building simple elevators. We also created two elevator systems using a stepper motor and Arduino to transport items from the ground on up to the top of a mini treehouse, as well as up the prototype of a more standard elevator shaft. These projects involved a bit of mechanics, electronics, and code. Even though mechanics, electronics, and code are the main components of robotics, simple elevators are more electronics projects than robotic projects. They don’t involve sensors and the finished products require too much human involvement to run properly. Most elevators today still require a human to push a button telling it what floor to stop at. However, through the use of sensors and software code, elevators can decide when they have reached a specified floor. This makes them more robotlike than elevators that rely on humans who travel inside the car, pressing buttons to tell the elevator when to open and close its doors. Perhaps the most robotic elevators today are those that run on a system known as Destination Dispatch. For over half a century, the elevator industry lagged behind most others in terms of adopting new technologies. The increase in extremely tall buildings in the 21st century has created demand for more efficient people-transporting systems. From the Burj Khalifa in Dubai, to the Shanghai Tower in China, to the headquarters of Legg Mason in Baltimore, and on to the Marriott Marquis in Times Square, New York, people are now transported up and down much more efficiently than ever before. Destination Dispatch is an optimization technique used in today’s most modern buildings with multiple elevators. It uses an algorithm that groups passengers with similar destinations together in the same elevator. A person using this system types in the floor they wish to travel to before getting into the elevator. Destination Dispatch then quickly assigns the user to an elevator and tells them which elevator to board. Once inside, there are no buttons. The elevator already knows to stop at the floors corresponding to each passenger. Since it figures out which passengers to group together in advance without overcrowding the elevator, this system can increase elevator capacity by approximately 30%, which translates to much shorter wait times. Our homemade elevator prototypes are still a far cry from the most robotic of elevator systems. And Destination Dispatch is a patented algorithm that we would not be able to replicate even if we had the parts and the technical skill. But those at home interested in designing a slick system to transport figurines up and down the mini-buildings that they reside in might consider adding a distance sensor to a ropehobby motor-Arduino setup such as those described in the August and October issues of Beanz. If you’re interested, check out the online version of this article for details. b

ubai

BY JENNIFER NEWELL

The

Robots

20

JAVI LORBADA, UNSPLASH


21

The

r, C Towe ghai Shan

hina

Y

,N

k Yor ew

,N uis arq tM iot arr eM Th

KOICHI ILJIMA, FLICKR

CHRIS PARKER, FLICKR


Z

Z

Z

Haskell: Laziness Is a Virtue BY CLARISSA LITTLER

Z

ZZZZ

Z

Z

Z

Z

Z

Z

Z

Z

Z

Z

Languages

ZZZZZZ

Z

22

ZZ

Z

Z

ZZ ZZZZZ

Haskell code: 1 messOfTwos = 2:messOfTwos

ZZ

2 main = print (take 10 messOfTwos) Let's break down the syntax quickly: messOfTwos is a Z definition of a list. Lists in Haskell are pretty standard for most programming languages and are built out of two operators, : (pronounced "cons") and [] (pronounced nil). You can either build a list with these operators or with a convenient syntax like [1,2,3]. This is the same as the list 1:2:3:[] built step-by-step with cons. The second line of this program says that main, the function that runs when you execute the whole program, is going to print out the first ten elements of the list messOfTwos. Let's talk about what's so weird about this code: we can do this by looking at the definition of messOfTwos = 2:messOfTwos. We can read this aloud as "messOfTwos is a 2 followed by messOfTwos." In Haskell, we can treat the equals sign like a real equals in mathematics— which means that we can substitute in the definition of the left-hand side into the right-hand side. So messOfTwos = 2:messOfTwos can be unrolled into messOfTwos = 2:2:messOfTwos and then further into 2:2:2:messOfTwos and arbitrarily far into something like ZZ

Z

In the last issue, we talked about the oldest thing you could even call a programming language. Now we're going to talk about one of its most interesting descendents: Haskell! Haskell is sort of a language for programming-language-design nerds. It was originally developed in the ’90s as a test-bed by language design researchers, but now it's a mainstream programming language. Today it’s used for all sorts of applications and website building, in addition to its more highbrow roles in compiler writing or developing projects for the Department of Defense. I think one of the cooler Haskell projects I’ve come across is called Tidal (https:// tidalcycles.org/), which was used in the development of the No Man’s Sky soundtrack (https://slab. org/65dos-on-tidalcycles/). Haskell is a language with a lot of interesting features, some of them still unique after over 20 years! Let's focus on one of the weirder features about Haskell: programming with infinite loops. First, the best way to get started with Haskell is The Haskell Platform (https://www.haskell. org/platform/). It comes with the main Haskell compiler, GHC (The Glorious Glasgow Haskell Compiler), as well as a number of useful libraries and tools. You can run the GHCi executable to get an interactive command line like in Ruby or Python. Here's a really simple example of

2:2:2:2:2:2:2:2:2:2:messOfTwos. I think it's clear at this point that messOfTwos is an infinite list of twos. So why doesn't this infinite list cause Haskell to hiccup and go into an infinite loop trying to print the first ten elements? Because Haskell is a lazy language. That's not an insult! It's a style of computation! A lazy language leaves all its definitions rolled-up, uncomputed, until they're needed. Then it computes just enough to finish the program. That process of unrolling the definition that we did by hand up above? That's actually what Haskell programs do when they run! Since the program needs to know the first ten elements of the list messOfTwos, it only unrolls until it knows what the first ten elements are and prints them out! Hopefully this gives a little teeny taste of the fact that Haskell is unusual and interesting. We haven't even gotten into some of the other interesting features like its neat type system. It’s one of my favorite languages and I hope you check it out! b


@ Anatomy of an Email Address

If you have an email address, it's likely you've barely thought about how the address works. For example, can you use odd characters like a period or an underscore or an asterisk in an email address? Email addresses have two parts separated by the @ (called ‘at’) symbol: a local part and a domain, as in jane.doe@anytown.com. jane.doe is the local part and anytown.com is the domain. Mail servers are software that use the domain to find the server that handles your email. Once your email arrives at your email server, the local part is used to deliver email to your mailbox. Even more interesting are the rules around email addresses. The local part can be up to 64 characters while the domain part can be up to 255 characters. And there’s only one @ symbol allowed, between the local and domain parts. The local part can be uppercase and lowercase Latin letters, A to Z and a to z, as well as digits 0 to 9, special characters !#$%&’*+-/=?^_`{|}~, and a dot or period in some cases. jane..doe@anytown.com is not allowed but ‘jane..doe’@anytown.com works. The domain part has stricter rules. Only letters, digits, and hyphens are allowed. What actually works, however, ultimately depends on your mail server. It’s a good idea not to get too crazy or complicated the next time you create an email address. b

@

@

History

23

BY TIM SLAVIN

@

Recycling Electronics With the holidays almost upon us, chances are you will get some brand-new electronics. Maybe a computer, or a Switch, or some other game system. But what do you do with your old electronics? Or maybe you don’t need the latest electronics, and you're wondering where you can find reliable used equipment. Electronics recycling centers are both a place to recycle your electronics safely and, in some cases, repair technology for sale. Many will erase your hard drives to protect your privacy. In the US, start with the EPA website (https://www.epa.gov/ recycle/electronics-donation-and-recycling) to find locations and search online with the phrase electronic recycling centers. Other countries have similar websites. Staples, Gamestop, and other stores also recycle. So do Apple and Dell. Look around and make a few phone calls. Recycling electronics also is a great way to conserve energy and resources, as well as reduce pollution. For example, the EPA says recycling a million laptops would save the energy equivalent to the electricity used by 3500 homes. b RYAN BODENSTEIN, FLICKR

Best Practices

BY TIM SLAVIN


Puzzles

24

e k a M s ' t e L ! l a e D a

BY PATRICIA FOSTER

For decades, “Let’s Make a Deal” was a popular TV game show. The rules were simple: there are three doors, one that hides a prize, and two that conceal “zonks” (joke prizes). Imagine that you’re the contestant picked from the audience. To begin, the host, Monty Hall, asks you to randomly pick one of the three doors, each with an equal chance of being your ticket to the big prize. Let’s say you pick door #1. Unlike you, Monty Hall knows where the car is hidden. He walks over to the two unpicked doors and opens #2 to reveal a zonk. The audience gasps! Now Monty gives you another choice: do you keep the door you’ve chosen, or would you like to switch to door #3? What should you do? To figure out the best strategy for the Monty Hall problem, we need to learn a few basic rules of statistics. Basic Rules of Probability

Let’s say you toss a coin; that’s an event. There are two possible outcomes: heads or tails. In this case, each of them are equally likely. Rule #1: Total Probability = 100%

If heads and tails are the only two possible results of a coin toss, then the probability of getting heads—P(H)—must be 50% and the probability of getting tails—P(T)— must also be 50%. Rule #2: The Law of Large Numbers

If you flip a coin 10,000 times, you can expect to see about 5000

heads and 5000 tails. In practice, maybe you have 5024 heads (50.24%) and 4976 tails (49.76%). But if you flip coins, over and over and over, these numbers will slowly morph into 50% and 50%. In other words, probability and statistics are accurate over long periods of time. Stay or Switch?

Going back to the Monty Hall problem, the answer is that you should always switch doors. In this scenario, there are only three outcomes: Door #1, Door #2, and Door #3. Since total probability always sums to 100%, and all doors are equal, the chance of winning with Door #1 is 33%. (Technically, 33.33333333 . . . We can round this down to make things easier). Therefore, the chance of winning with a different

door is 67%. To put it another way: The chance of winning with either Door #2 or Door #3 is 67%. When Monty opens Door #2 to reveal a zonk, the probability doesn’t rebalance itself into 50% for Door #1 and 50% for Door #3. Instead, take the previous statement and remove the words “either Door #2 or” from the sentence. What does it say now? It says: The chance of winning with Door #3 is 67%. When Door #2 was eliminated, the cloud of probability hovering over Doors #2 and #3 “pools” into Door #3. Switching doors makes you twice as likely to win! Don’t throw a party just yet, though! Remember, a higher probability isn’t a guarantee of winning. If you played “Let’s Make a Deal” 10,000 times with your math-savvy strategy, you could expect to win 6667 cars and 3333 zonks. But if all you have is one shot, the dice might not fall in your favor. Sometimes the law of large numbers is just a bummer. The Monty Hall problem illustrates that it’s important to think twice about our first assumptions— especially in math! b SIMPLE

INSOMN

IA, FLICK

R


tidbitz

5 Great Beginner 3D Design Programs

Shapeways is one of several online services that will print your 3D models. The hard part is finding software that’s easy to use to create your models. This article describes five tools to explore and try out. From SketchUp (which we write a lot about) and TinkerCAD to Sculptris and 3D Slash. https://www.shapeways. com/blog/archives/381375-awesome-beginners-3ddesign-programs.html. b

ZOMBIE WOLVERINE BY KAZUYA MATSUMURA ON ARTSTATION, CREATED IN SCULPTRIS

Be Internet Awesome

25

A SelfSolving Rubik's Cube A Japanese inventor Takashi Kaburagi figured out how to use Arduino electronic boards to create a Rubik’s cube that solves itself. Having created a big version in 2017, in 2018 he made a new one that’s much smaller. The Arduino boards control rotating parts attached to each cube in a Rubik’s cube with software doing the math to find the ideal solution without stopping. Watch this self-solving Rubik’s cube march its way across a table: https:// techcrunch.com/2018/09/24/ watch-this-self-solving-rubikscube-march-its-way-across-atable/. b

IMAGE FROM HTTPS://BEINTERNETAWESOME.WITHGOOGLE.COM/EN

IMAGE FROM HTTPS://MEDIA. DMM-MAKE.COM/ITEM/4462/

Google has a fun program, Be Internet Awesome,, and game called Interland to teach kids how to be safe online. The program includes a curriculum for teachers and parents. Overall it’s an excellent way for adults to engage kids about how to be safe online. https:// beinternetawesome.withgoogle.com/en. b


Electronics

26

y N d a , ! e w t o S

BY LES POUNDER

You'll Need: A micro:bit, An Adafruit Circuit Playground Express, 2 x Crocodile clips, A box, 1 x Piece of long wire (a coat hanger will do), 1 x short piece of wire (to make a wand), Masking tape Do you have steady hands? Could you complete this challenging course? The player must navigate a twisty course made of conductive wire. The wire is connected to one side of a circuit. If the player's wand touches the course, then the circuit is closed and completed, allowing power to flow to a buzzer or LED signaling that the player has failed. To build this project we need the items above. We'll use Circuit Python, a version especially for Adafruit’s boards. Audio

We need a 16bit 22050Hz Mono audio file. A Google search will find lots of audio files to use, but abide by its terms and conditions of use. Edit using Audacity (https://www. audacityteam.org/), a free audio editing tool for Windows, Mac, and Linux. Save it as “buzzer.wav”.

A1 using a crocodile clip. On the underside of the box, connect the course to 3V3 using the other crocodile clip. Now, the code. Software

Flip the box. Bend the wire so that it cannot get out. Flip the box right side up and create another hole in a corner diagonal from the first, and feed the wire through the hole, and bend it to hold in place. We now have the start and end of the course. Bend the remaining wire into a course.

At the start and end of the course, use a little masking or electrical tape to create a safe zone, where the player can rest the wand. Now make a wand, using a thinner, shorter piece of wire.

To code with the Adafruit Circuit Playground Express, we need to follow the steps to install drivers for our board (Windows only) (https:// learn.adafruit.com/adafruit-circuitplayground-express/adafruit2windows-driver-installation), and then we update our board to the latest software (https://learn. adafruit.com/adafruit-circuitplayground-express/circuitpythonquickstart). Now we move to installing the Mu editor, which we'll use to write the code. Mu is an beginner-focused Python editor. Download Mu from https://codewith.mu/ and install it. Connect your Circuit Playground Express to the computer using a micro USB lead. Start Mu. It will detect the board and ask if you'd like to start in Adafruit Circuit Playground

Building the Hardware

First, connect crocodile clips to pins A1 and 3V3. Take a cardboard box, and make a small hole in one corner. Take a length of wire (a coat hanger is great for this) and insert it into the box.

Form an open hook at one end of the wire, and then place the hook over the wire of the course. Close the hook so that the wand cannot be removed from the course, but keep the wand wide enough so that players can have a chance! Now connect the course and wand to the Circuit Playground Express. Connect the wand to

For info on Micro:bit go to https://microbit.org/resellers


Mode. Say Yes. First, import a few Python libraries. Time will enable us to pace the speed of the game. Board enables us to interface with the Circuit Playground Express board, DigitalIO (DigitalInOut, Direction and Pull) enables us to control and read the state of the GPIO, audioio is used to play audio via the board. import time import board from digitalio import DigitalInOut, Direction, Pull import audioio The next step is to enable the onboard speaker and set it as an output (so we can hear it). spkrenable = DigitalInOut(board SPEAKER_ENABLE) spkrenable.direction = Direction OUTPUT spkrenable.value = True The Circuit Playground Express also has a built-in LED connected to pin 13, which we'll use as a visual indicator that the player has touched the wire. So tell the code where the LED is and that it is an output. led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT Now let's set up the code for our wand. The wand is connected to pin A1 on the board, and it's an open

switch. It's ready to receive current as an input device and the pin is pulled low, so that when we touch the metal wire of the course (which is at 3.3V), the pin is temporarily pulled high. This completes the circuit and triggers the game over. wand = DigitalInOut(board.A1) wand.direction = Direction.INPUT wand.pull = Pull.DOWN When the player touches the course with the wand, we want the Circuit Playground Express to play an audio file. Let's write a function that we can call when this happens. Functions are blocks of code that, when called, will run many lines of code at once. Our function is called “play_file” and it has a parameter in ( ) that is the name of the file that we wish to play. def play_file(filename): The next section of code is indented to show that it belongs to the function. We first print the name of the file to Python shell (REPL) for debug purposes, and then we create a variable called “wave_file” that will contain the raw data from the file, read (r) by opening the file as a binary file (b) and storing it to the variable. print("Playing file: " + filename) wave_file = open(filename, "rb") Use that file to play the audio. So

Ta-dah All don ! e!

27 we call a function from the audioio library that will play a wave (WAV) file, and play this via pin A0 (which by default is the built-in speaker). We then use the raw file data to play the file, and using the “playing” function we check that the audio is still playing. If so, we “pass” the code to keep it going to the end. with audioio.WaveFile(wave_file) as wave: with audioio.AudioOut(board. A0) as audio: audio.play(wave) while audio.playing: pass When the audio is finished, we print “Finished” to the Python shell. print("Finished") The code for the function is complete. Next, we move on to the main loop. This is a while True loop, and it will constantly run a test to check if the wand is touching the metal wire. If it does, then the value will change and trigger the code to run, in this case the LED (D13) will light up, we print “True” to the Python shell, and we play the audio file “buzzer.wav”, before pausing for half a second. while True: if wand.value: # button is pushed led.value = True print(True) play_file("buzzer.wav") time.sleep(0.5) If the wand doesn't touch the course, our “else” condition will be activated, so nothing will happen. The LED will be turned off. Then the loop pauses for 0.01 seconds before the entire process repeats. Save the code as main.py on to the CIRCUITPY drive (the Adafruit Circuit Playground Express plugged in to our computer). The board will automatically reboot, then copy the audio file “buzzer.wav” that we created earlier to the CIRCUITPY drive, and play can start. Now play the game and try your hand! b


Parents and Teachers

28

BY TIM McGUIGAN

The Importance of Play A parent of a prospective student visited my school recently and walked into my hallway to see students lying on the floor. Surrounded by Solo cups, sprawled out on the carpet, and jumping around in anticipation. As I approached, she gave me a bit of a bemused look and asked what was going on. I responded, “We’re playing.” Now I don’t know what the takeaway was for this parent, but my answer wasn’t meant to be glib. I take play very seriously in my classroom. During this lesson, students use Sphero robots to knock down solo cup towers. As I hear the cheers and groans coming from all corners of the hallway, serious play is making my students more confident and resilient. Play-based learning is nothing new in the education world, however in my experience it is still under-appreciated. Powerful

in subtle ways, play is one of the creative literacies that can quietly empower students and expand their imaginative scope. While firmly at home in physical education or art classes, I have found that it is also a natural fit for Computer Science and innovation curriculums. What makes play serious, then? By nature, play is low stakes and has a low barrier to entry. As a final crescendo to my robotics unit, students build a miniature golf course out of cardboard and recycling bin castoffs. Not only are the materials familiar, modular, and easy to manipulate, but the Kindergarten-esque vibe in the room puts many at ease. This low stakes environment of play can disproportionately benefit anxietyprone students or students with learning differences. As they work through what is possible with paper towel rolls

and duct tape, without knowing it, students are reducing their affective filter. Research has shown that affective variables such as anxiety, self-confidence, and boredom can really affect intake of new information. When students are in playful learning mode, these variables are lessened, and they are more open to processing new ideas. During my lesson, if their program doesn’t put the robot where students are intending, due to the low stakes environment they feel freer to begin again from


ROBERT COLLINS, UNSPLASH

in the CS Classroom square one. Serious play can also be a valuable introduction to iterative processes like the engineering design cycle. One influential supporter of play-based learning is Mitch Resnick, founder of the Lifelong Kindergarten research group at MIT. From consulting LEGO on the development of their Mindstorms robotics platform to creating the Scratch programming language, Resnick has been a champion of the cognitive benefits of kindergarten for all. In a 2007 paper, he introduced the Kindergarten approach cycle. The approach is a cycle that asks students to imagine, create, and play. The cycle then moves on to sharing, reflecting, and back to imagining. I have a poster of this cycle on the wall in my room and it informs many aspects of my curriculum. Recently, we were working on learning computational abstraction, which can be tricky for 7th graders. Before moving on to

more traditional instruction, I first asked students to create digital paintings that were an abstraction of an original. As students shared out their designs, I encouraged everyone to continue altering their paintings based on the feedback. After the class came to an end, some students told me they wanted to continue working on their paintings at home, which is always great to hear. Throughout our unit, I’ll return to this activity frequently when they are trying to wrap their heads around writing JavaScript programs with functions and parameters. While pioneers like Mitch Resnick have advanced the importance of play in the Computer Science classroom, aspects of play

are powerful in many contexts. When an English teacher at my school began using a game called Socratic Smackdown to teach a Socratic Seminar, she found that student participation increased— especially from boys. Another Elementary Science teacher uses a unit on Rube Goldberg devices to teach an introduction to physics in an elementary classroom. While there is a constant pressure in education to remain faithful to content and standards, the time spent imagining and playing is certainly not a waste of time. As the pace of technology increases, these creative literacies could enable students to be flexible while navigating platforms not yet invented. It is certainly possible that play may turn out to be one of the best teachers students have. b

29


“The science of today is the technology of tomorrow.” —Edward Teller 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. Catch Me If You Can! http://beanzmag.com/ sphero-light-chaser

Creating a Tile Pattern http://beanzmag.com/ sketchup-cordoba-tile

Anatomy of an Email Address http://beanzmag.com/ email-address-anatomy

Feeling Loopy? http://beanzmag.com/ scratch-animations

Can Software Write Itself? http://beanzmag.com/quines

Recycling Electronics http://beanzmag.com/ recycle-electronics

Secret Code Workbooks http://beanzmag.com/ secret-code-workbooks Danit Peleg Creates 3D Printed Fashion http://beanzmag.com/ danit-pelege "I Just Had the Strangest Dream . . ." http://beanzmag.com/ google-dream STEAM Board Games http://beanzmag.com/ steam-board-games It's Not ssso Hard! http://beanzmag.com/ free-python-tools

The Credit Card Algorithm http://beanzmag.com/ luhn-algorithm Wrap Your Head Around This! http://beanzmag.com/ minecraft-redust-gates What Exactly Is Memory? http://beanzmag.com/ computer-memory-411 Going Up! http://beanzmag.com/ robot-elevators Haskell: Laziness Is a Virtue http://beanzmag.com/haskelllanguage

Let's Make a Deal! http://beanzmag.com/ monty-hall-problem tidbitz http://beanzmag.com/ december-2018-news-wire Steady, Now! http://beanzmag.com/ adafruit-test-nerves The Importance of Play in the CS Classroom http://beanzmag.com/ playing-computer

http://beanzmag.com/subscribe

ribe! Subsc

Profile for beanz Magazine

beanz Magazine December 2018  

Got old electronics? Learn how to recycle them to make room for holiday gifts. Also learn about Minecraft mods, the history of email, secret...

beanz Magazine December 2018  

Got old electronics? Learn how to recycle them to make room for holiday gifts. Also learn about Minecraft mods, the history of email, secret...

Profile for beanzmag