Learn to Code in 30 Days with MiniScript and Mini Micro Joe Strout MiniScript Press Copyright © 2020 by Joseph Strout All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission to use material from this text or product, submit all requests via email to [email protected] Project consultation, production and manufacturing under the direction of Dane Cornel Petersen at Petersen Books. For details, send e-mail to [email protected] Printed in the United States of America First Edition 10 9 8 7 6 5 4 3 2 1 Dedicated to Michelle, for her steadfast support and encouragement in all my endeavors Acknowledgments Writing a book is a big task. I couldn’t have done it without the patience and support of my wife, Michelle Strout, who also served as a very capable copy editor. The book is much better than it would have been without her help. I’m also grateful for the support of Dane Petersen at Petersen Books, whose assistance was invaluable in turning a raw manuscript into the beautiful book before you. About the Cover The word CODE on the front cover is a magnified view of the “large” font in Mini Micro, with pixels separated for visibility. The large swaths of color represent the red, green, and blue components of any color in computer graphics. That adorable animal gracing the cover is a chinchilla, the official MiniScript mascot. Like MiniScript, the chinchilla is not yet widely known, but is universally loved by all who have had the pleasure of discovering its existence. Introduction Congratulations! By selecting this book, you have chosen an unusually good way to learn computer programming. Whether this is the start of a professional career, or just a new and rewarding hobby, you will look back on this day as a pivotal moment. Computers today are everywhere — not only on our desks and in our pockets, but in our televisions, cars, kitchen appliances, game consoles, VR headsets, and on and on. Every one of those computers does the amazing things it can do because programmers wrote some code. It’s no exaggeration to say that our entire civilization runs on computers, and the computers do the bidding of their programmers. For all their amazing, almost magical power, what a computer does is fundamentally simple: it follows instructions, step by step. Programming is the process of writing out these instructions in a way a computer can understand. Computers can’t (yet) really understand human languages, such as English. Human languages have all sorts of ambiguities and things that are left unsaid. Attempts to make them more precise end up with the sort of complex, long-winded text you find in end-user license agreements and other legal documents. So engineers have developed various computer languages that are designed to be brief but precise, and those are the languages we use to write computer programs. Here’s an example: 1c = input("Enter temperature in Celsius: ").val 2f = c * 5/9 + 32 3print "That's " + round(f) + " F." 4if c < 2 then print "BRR!" A small program in MiniScript. If you’ve never done any programming before, this may not make much sense to you yet. Don’t worry — it will, by the end of the book! For now, just notice that a computer language looks a little bit like English, with recognizable words like input, print, if, and then. And it also looks a bit like grade-school math, with symbols like + and =. You already know English and you already know grade-school math, so once a few basic rules are explained to you (covered in the first few chapters of this book), you’ll have no trouble reading and writing this sort of computer code. The code shown above is in a computer language called MiniScript, which you will learn over the next few weeks. MiniScript is just one of many computer languages. There are literally hundreds of languages in common use; some of the most famous ones are JavaScript, Python, C# (pronounced “C sharp”), and C++ (pronounced “C plus plus”). However, MiniScript is a particularly good choice for a beginning programmer. It was very carefully designed to be as simple as possible, while still being powerful enough to use in real, nontrivial programs. It is inspired by the best features of other languages, but lacks the baggage they all bring along. MiniScript is free, and can be used in a variety of ways, including to create your own games, simulations, and data analysis software. Other languages can do similar things, but they are generally not quite as simple or easy to learn as MiniScript. New programmers often struggle learning the syntax of a language, that is, the rules about exactly how to write what you’re trying to say. MiniScript is “syntax-light” — it uses only the bare minimum of extra punctuation and odd symbols. Other languages tend to have more. For example, here’s the same program in C++: 1 #include <iostream> 2 #include <string> 3 #include <cmath> 4 5 int main() 6 { 7 int c; 8 std::cout << "Enter temperature in Celsius: "; 9 std::cin >> c; 10 float f = (float)c * 5/9 + 32; 11 std::cout << "That's " << round(f) << " F.\n"; 12 if (c < 2) std::cout << "BRR!"; 13} The same program, but written in C++. This does the same thing as the MiniScript code above, but as you can see, there are a lot more extras required: semicolons at the end of most lines, curly braces, several #include lines at the top, and odd symbols like << and >>. All that extra stuff gets in the way of learning the real core of programming, which is figuring out what you want to happen, step by step. How to use this book The book is divided into 30 chapters, designed to be done at about one chapter per day. Each chapter is about 10 pages long, and shouldn’t take too long to do. However, in every chapter, you will find code examples. The best way to learn is to try these examples on your own machine! To do that, you will need a desktop computer. Almost any kind of desktop computer will do: it can run Windows, Mac, or Linux, and it doesn’t have to be particularly new or powerful. But you do need something, or you’ll be missing out on most of the fun of the book, which is the joy of typing in some code and making things happen. To give you an example of the sort of thing you’ll be learning to do, and also make sure your computer is right for this, here is your first task! Open a web browser, and go to this address: ⚙ https://miniscript.org/MiniMicro You should see, right in your web browser, something that looks like one of those computers you might see in movies from the 80s. Welcome to Mini Micro. Don’t let the old-fashioned appearance fool you! This is a virtual but modern computer, capable of creating sophisticated games and simulations. Want to try some? Type in the following commands, precisely as shown — be careful to match the punctuation and capitalization exactly. 1]load "/sys/demo/flappyBat" 2]run (Don’t type the ] character; that’s called the prompt and is supplied by Mini Micro. You just type the rest.) When you press the Return key after typing run, the screen should clear, and a game of “flappy bat” begins! Press the space bar to make your bat fly as long as you can. When you see GAME OVER, you can type run and press Return again to give it another try. Or how about this one? 1]load "/sys/demo/theMatrix" 2]run This one is not a game, but just a little “demo” — short for demonstration — which makes characters fall down from the top of the screen. You may notice that these draw on top of the pipes still present from the flappyBat game. Mini Micro has a multi-layered display, which you will learn to use to your advantage. This demo runs forever until you stop it by pressing the Esc key, or by holding the Control key and pressing C. In the mood for something more active? Here’s another demo, but one you can control using the arrow keys and the spacebar: 1]load "/sys/demo/platformer" 2]run This one is a cute little Nintendo-style platformer. I wouldn’t call it a “game” because there are no enemies or objective; you just run and jump around a small level. (And no, you can’t actually pick up the key either.) It’s here to demonstrate that you could make such a game, and to help you get started. By the end of this book, you’ll be equipped to finish it! If by this point you have only read the words above, and not actually tried these commands for yourself, please put the book down a moment, go find a computer, and give them a try. You will learn more quickly, understand more deeply, and retain it all much longer if you actually do these experiments on your own machine, and now’s a great time to form that habit. Don’t worry that you don’t really understand what you’re doing yet; you will, soon enough. Let’s begin! Whether you want to uncover the secrets of the universe, or you just want to pursue a career in the 21st century, basic computer programming is an essential skill to learn. — Stephen Hawking (theoretical physicist) Chapter Objectives Learn how to run MiniScript code on the web. Use the print command to make MiniScript display something on the screen. Learn about numbers and strings. There are many ways to run MiniScript. You may even find MiniScript within some commercial or open-source game or software tool. But in this book we are going to cover just three. The last of these will be Mini Micro, of which you got a glimpse in the Introduction. In the middle will be command-line MiniScript. But first, starting today, we begin with the simplest: running MiniScript right within your web browser. The home of MiniScript on the web is https://miniscript.org/, and you will find all sorts of useful resources there. Today, follow the “Try-It!” link, or just go directly to: ⚙ https://miniscript.org/tryit/ This should bring up a page that looks something like the figure below. MiniScript Try-It web page The standard layout has a code editor (with a white background) on the left, and an input/output area (with a black background) on the right. If you find that they are instead stacked vertically, try stretching out your browser window until they appear side-by-side. This should work equally well on Mac, Windows, and Linux. If you are using a tablet or mobile phone, you may not be able to accomplish this; that’s OK. You can still use it when they’re stacked vertically. ✎code editor: a text editor specialized for writing program code Down below the editor and input/output area, you’ll find a “Help & Information” area that is chock full of useful stuff. By clicking on the items on the left, you can make explanations and reference material appear to the right. Many of the items on the left are folders; you can twist those open by clicking the little triangle next to them, to drill down into more detailed topics within. Explore this a bit; you are likely to use this information in the future when writing your own code. The code editor contains some sample MiniScript code to get you started. As it’s only Day 1, this code probably doesn’t make much sense to you yet. That’s OK too. You’ll understand everything there in a couple of weeks. For now, just select all the code in that code editor, and delete it. The code editor works just like any other text editor, word processor, or comment form you’ve ever used; the main difference is that it will automatically color your text as you type. Don’t worry about what the colors mean for now; they’re mostly there to make your code look pretty! Now it’s time to write your very first MiniScript program — and for many readers, your first program of any sort. We’ll begin with the classic greeting program. After clearing out the sample code, type this into the code editor on the Try-It! page: print "Hello world!" Greetings program Type it exactly as shown here. Notice that print is all lowercase; that’s important. Like most computer languages, MiniScript is case-sensitive, which means that if you get the capitalization wrong, it will not work. ✎case-sensitive: a language or system where upper- and lower-case letters are considered different ✎case-insensitive: a language or system where upper- and lower-case letters are considered the same After entering the above code, click the Run Script button. You should see the words “Hello world!” appear in green text in the input-output area. If you do, congratulations! You just wrote your first program! If you don’t see that, then you probably have a typo. Congratulations to you as well, as you have discovered what happens when you make a mistake! Go back and check your work carefully — spelling and punctuation must match exactly. Computers work fast, but they are very picky about the details. If you weren’t so fortunate as to make a mistake on your first attempt, then please do so now. It’s important not to be afraid of making a mistake. It is impossible to hurt the computer by anything you type on the Try-It! page. When the computer can’t understand what you want, it never gets upset or impatient. It just calmly points out where it got confused, and waits patiently for you to fix it. So, with that in mind, please try this version of the program: Print "Hello world!" Incorrect greetings program Can you spot the difference between this program and the first one? We’ve used a capital “P” here. Go ahead and enter this code, then click that Run Script button again! You will get no output in the input/output area, and instead, an error message will appear below, along the lines of: Runtime Error: Undefined Identifier: 'Print' is unknown in this context [line 1] This is MiniScript’s way of telling you that it doesn’t know what Print means — even though it does know what print means, these are considered completely different words, because (again) MiniScript is case-sensitive. ✎Runtime Error: an error that occurs after the program starts running ✎Compiler Error: an error that happens even before the program starts running, when MiniScript is studying the code ✎Undefined Identifier: a type of runtime error that occurs when you use a word MiniScript does not know Now you may be wondering, what about the words Hello and world? Are these words that MiniScript knows? The answer is no, and it doesn’t need to, because we have enclosed them inside of quotation marks. This is something like giving an actor lines in a language he doesn’t speak. A skillful actor can parrot the words exactly as written in the script, without having any idea what they mean. Computers are the same way: anything you put inside quotation marks gets parrotted back without having any meaning to the computer. On the other hand, words that tell the computer to do something — like print — must not be in quotation marks, and they must be among the words the computer already knows. Today, print is the only such word you’re going to learn, but starting tomorrow you’ll learn more, and by the end of the book you’ll know all sorts of such words, and even how to add more. A pair of quotation marks surrounding some words is called a string. This is because the characters (letters, numbers, etc.) are strung together in a certain order, like beads on a string. ✎string: some letters, numbers, or punctuation surrounded by quotation marks The string in our program above was “Hello world!” But it can be anything. Try these: 1print "Greetings, program!" 2print "My name is 101001." 3print "@*#$!! I spilled bits on my chips!" 4print "Later alligator!" More greetings You can try out those lines one at a time if you like. Or, you can type them all in at once, with each print statement on a new line in the code editor, as shown above. In that case each message will appear in the output area, one after the other. Notice how the strings can contain any combination of letters, numbers, and punctuation. They can even contain foreign characters or emoji; if you know how to type any of these, go ahead and give it a try. It’s all just strings to MiniScript. There is one exception, however. What if you wanted to put quotation marks inside your string? That’s problematic, since the quotation marks are how MiniScript knows where the string ends. If you stick some in the middle, it will think your string is done, and won’t know what to do with the rest of it, resulting in an error. The solution is to enter the quotation marks twice if they occur within a string. To include quotation marks in a string, enter them twice in a row. Here’s an example: print "Hello, ""Bob,"" if that is your real name." Quotation marks within a string Try that. You should see in the output window that the doubled quotation marks have magically transformed into ordinary quotation marks. This is just a trick to work around the problem of MiniScript knowing where your strings end, and it is the only character that is special in this way. You now know just about everything there is to know about defining a string. Strings are one of the four basic types of data in MiniScript. Before calling it a day, let’s learn about one other type: numbers. Numbers are easy. They are exactly what you think they are. Here’s an example: print 42 The ultimate answer Here, 42 is a number. Nothing to it, right? Numbers can be any size, and can include a decimal point or not. They can also be written in exponential notation, which is sometimes convenient for very large or very tiny numbers. exponential notation: a way of writing numbers like 2.5E10, where the number after the “E” ✎ means to shift the decimal point that many places to the right (or to the left, if the number is negative) So 2.5E6 is 2.5 times a million (i.e., a 1 followed by 6 zeros), or 2.5 million. 2.5E-6 would be 2.5 times a millionth. You won’t need this form of numbers very often, but now you know it exists. Many regions of the world write their numbers differently, for example, with a comma instead of a period to separate decimals. MiniScript, like most other computer languages, always uses a period as the decimal point, no matter where you are. Also, you may be used to writing large numbers with some grouping character before the thousands, millions, and so on. That makes it easier for humans to read, but it only confuses computers. So even a big number like 7,603,985,818 (the population of Earth at the time of this writing) must be written 7603985818. We’ll end the chapter with one last little sample program. This prints a variety of strings and numbers. If you’ve just been reading and nodding at the examples above, you should be sure to type in this one. Typing in code trains your fingers and your brain, and will make learning to code that much easier. 1print "The answer to the Ultimate Question..." 2print "of life, the universe, and everything..." 3print "is..." 4print 3.14157 5print "...wait, no, it's actually:" 6print -2.5E6 7print "...no, I'm sorry, the answer is:" 8print 42 Printing strings and numbers Were you surprised by how one of those numbers came out? Strings appear exactly as you type them — except for doubled quotation marks — but numbers come out in a standardized format, which may be different from how they appear in your code. And that wraps up day 1! You have taken your first steps down an incredibly rewarding path. Let’s review what you learned today: Chapter Review You can run MiniScript code on the web at https://miniscript.org/. You know how to use print to display strings and numbers. You learned that MiniScript is case-sensitive, and how to recognize and correct mistakes in your programs.