Upload data files
Browse files- data/MiniScript-Manual.md +1049 -0
- data/QuickRef.md +209 -0
- data/day1.txt +169 -0
- data/day10.txt +205 -0
- data/day11.txt +319 -0
- data/day12.txt +223 -0
- data/day13.txt +321 -0
- data/day14.txt +439 -0
- data/day15.txt +248 -0
- data/day16.txt +311 -0
- data/day17.txt +258 -0
- data/day18.txt +282 -0
- data/day19.txt +346 -0
- data/day2.txt +301 -0
- data/day20.txt +303 -0
- data/day21.txt +333 -0
- data/day22.txt +365 -0
- data/day23.txt +364 -0
- data/day24.txt +270 -0
- data/day25.txt +307 -0
- data/day26.txt +429 -0
- data/day27.txt +316 -0
- data/day28.txt +348 -0
- data/day29.txt +109 -0
- data/day3.txt +158 -0
- data/day30.txt +106 -0
- data/day4.txt +137 -0
- data/day5.txt +235 -0
- data/day6.txt +245 -0
- data/day7.txt +276 -0
- data/day8.txt +372 -0
- data/day9.txt +249 -0
data/MiniScript-Manual.md
ADDED
|
@@ -0,0 +1,1049 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MiniScript Manual
|
| 2 |
+
|
| 3 |
+
*Learn to read, write, and speak the world's easiest computer language*
|
| 4 |
+
|
| 5 |
+
Joe Strout
|
| 6 |
+
MiniScript Maker
|
| 7 |
+
|
| 8 |
+
Version 1.6.2
|
| 9 |
+
Monday, July 22, 2024
|
| 10 |
+
|
| 11 |
+
# Welcome to MiniScript
|
| 12 |
+
|
| 13 |
+
*a high-level, object-oriented language that is easy to read and write*
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
MiniScript is a modern scripting language designed to be clean, simple, and easy to learn. It was designed from the ground up by borrowing only the best ideas from other languages such as Python, Lua, Basic, and C#. If you know pretty much any other programming language, you’ll pick up MiniScript almost immediately.
|
| 17 |
+
|
| 18 |
+
And if you’ve never written a line of code in your life, don’t panic! MiniScript is the friendliest and most fun way to get started. It’s much easier than you probably expect.
|
| 19 |
+
|
| 20 |
+
Important: MiniScript is designed as an embedded programming language. That means you will usually use it inside some other program, such as a video game. You should find another document that describes how to access and use MiniScript within that other program. This document only describes the MiniScript language itself, and the intrinsic functions that are common to most MiniScript applications.
|
| 21 |
+
|
| 22 |
+
## Clean, Clear Syntax
|
| 23 |
+
|
| 24 |
+
Let’s jump right in with an example, to see what MiniScript code looks like.
|
| 25 |
+
|
| 26 |
+
```miniscript
|
| 27 |
+
s = "Spam"
|
| 28 |
+
while s.len < 50
|
| 29 |
+
s = s + ", spam"
|
| 30 |
+
end while
|
| 31 |
+
print s + " and spam!"
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Each statement in MiniScript normally occurs on a single line by itself. Notice that there are no semicolons, curly braces, or other markers at the end of a line.
|
| 35 |
+
|
| 36 |
+
However, there is one exception: if you want to join multiple statements on one line, just to make your code more compact, you can do this by separating the statements with a semicolon. The following code is ugly, but legal.
|
| 37 |
+
|
| 38 |
+
```miniscript
|
| 39 |
+
s = "Spam"; while s.len < 50; s = s + ", spam"; end while
|
| 40 |
+
|
| 41 |
+
print s + " and spam!"
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
In practice this feature is rarely used, but it's there if you need it.
|
| 45 |
+
|
| 46 |
+
## Code Blocks
|
| 47 |
+
|
| 48 |
+
If you’re used to C-derived languages (such as C, C++, C#, etc.), then you’re used to seeing curly braces around blocks of code. MiniScript doesn’t roll that way; code blocks always begin with a keyword (if, for, while, or function) and end with a matching end statement (end if, end for, end while, or end function).
|
| 49 |
+
|
| 50 |
+
## Whitespace and Indentation
|
| 51 |
+
|
| 52 |
+
You can insert spaces and tabs into your code pretty much wherever you want. You can’t break up an identifier or keyword (pr int is not the same as print), nor omit a space between two identifiers or keywords (end if is correct, but endif would not work). And of course spaces within quotation marks go into your string exactly as you would expect. But between numbers, operators, etc., you can include extra spaces however you like. The following two lines are exactly the same, as far as MiniScript is concerned.
|
| 53 |
+
|
| 54 |
+
```miniscript
|
| 55 |
+
x=4*10+2
|
| 56 |
+
x = 4 * 10 + 2
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
To make the structure of code more readable, it’s traditional to indent the lines within a code block by either a tab or two spaces. But it’s not required. MiniScript doesn’t care how or whether you indent your code, so do whatever works best for you.
|
| 60 |
+
|
| 61 |
+
## Breaking Long Lines
|
| 62 |
+
|
| 63 |
+
Unlike C-derived languages, there are no semicolons or other funny punctuation at the end of each line to let the computer know that the statement is over. Instead, the line break alone is enough to signal that. But what if you need to enter a statement longer than one line?
|
| 64 |
+
|
| 65 |
+
MiniScript will recognize that a statement is incomplete, and continues on the next line, if the last token (before any comment — see below) is an open parenthesis, square bracket, or brace; or a comma, or any binary operator (such as +, *, and so on). So, for example, you could do:
|
| 66 |
+
|
| 67 |
+
```miniscript
|
| 68 |
+
speech = ["Four score and seven years ago our fathers",
|
| 69 |
+
"brought forth on this continent, a new nation, conceived",
|
| 70 |
+
"in Liberty, and dedicated to the proposition that all",
|
| 71 |
+
"men are created equal."]
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
That's four lines, but only one statement as far as MiniScript is concerned. That's because the first three lines each ends with a comma, which tells MiniScript that more is coming.
|
| 75 |
+
|
| 76 |
+
## Comments
|
| 77 |
+
|
| 78 |
+
Comments are little notes you leave for yourself, or other humans reading your code. They are completely ignored by MiniScript. Comments begin with two slashes, and extend to the end of a line. So you can put a comment either on a line by itself, or after a statement.
|
| 79 |
+
|
| 80 |
+
```miniscript
|
| 81 |
+
// How many roads must a man walk down?
|
| 82 |
+
x = 6*7 // forty-two
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
Just like indentation, comments are never required… but they’re probably a good idea!
|
| 86 |
+
|
| 87 |
+
## Use of Parentheses
|
| 88 |
+
|
| 89 |
+
Parentheses in MiniScript have only three uses:
|
| 90 |
+
|
| 91 |
+
Use them to group math operations in the order you want them, just as in algebra.
|
| 92 |
+
|
| 93 |
+
```miniscript
|
| 94 |
+
x = (2+4)*7 // this is different from 2+4*7
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
Use them around the arguments in a function call, except when the function call is the entire statement.
|
| 98 |
+
|
| 99 |
+
```miniscript
|
| 100 |
+
print cos(0) // parens needed; cannot just say: print cos 0
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
Use them when declaring a function that takes parameters (see the Functions chapter).
|
| 104 |
+
|
| 105 |
+
Since other languages often require parentheses in lots of other places, it’s worth pointing out where parentheses are not used in MiniScript. First, don’t put parentheses around the condition of an if or while statement (more on these later). Second, parentheses are not needed (and should be omitted) when calling a function without any arguments. For example, there is a time function that gets the number of seconds since the program began. It doesn’t need any arguments, so you can invoke it without parentheses.
|
| 106 |
+
|
| 107 |
+
```miniscript
|
| 108 |
+
x = time
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
Finally, as mentioned above, you don't need parentheses around the arguments of a function that is the very first thing on a statement. The following example prints ten numbers, waiting one second each, and then prints a message. Notice how we’re calling print and wait without any parentheses. But the range call, because it has arguments and is used as part of a larger statement, does need them.
|
| 112 |
+
|
| 113 |
+
```miniscript
|
| 114 |
+
for i in range(10, 1)
|
| 115 |
+
print i
|
| 116 |
+
wait
|
| 117 |
+
end for
|
| 118 |
+
print "Boom!"
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
## Local and Global Variables
|
| 122 |
+
|
| 123 |
+
A variable is a word (also called an identifier) associated with a value. Think of variables as little boxes that you can store data in. You create a variable simply by assigning a value to it, as in many of the examples we’ve already seen.
|
| 124 |
+
|
| 125 |
+
```miniscript
|
| 126 |
+
x = 42
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
This line creates a variable called x, if it didn’t exist already, and stores 42 in it. This replaces the previous value of x, if any.
|
| 130 |
+
|
| 131 |
+
Variables in MiniScript are dynamically typed; that is, you can assign any type of data (see the chapter on Data Types) to any variable.
|
| 132 |
+
|
| 133 |
+
Variables are always local in scope. That means that a variable called “x” inside one function has nothing at all to do with another variable called “x” in another function; each variable is scoped (restricted) to the current function executing at the time of the assignment.
|
| 134 |
+
|
| 135 |
+
However, MiniScript also supports code outside of any function, as in all the examples we’ve seen so far. In this context, local and global variables are the same. In other words, assigning 42 to x outside of a function creates a global variable called x. Such global variables may be accessed from any context.
|
| 136 |
+
|
| 137 |
+
Note that when a context has a local variable of the same name as a global, an identifier will always resolve to the local variable first. Similarly, a simple assignment statement within a function will always create a local variable, rather than a global one. In cases where you really need to access the global variable instead, there is a globals object that provides this access. (See the Intrinsic Functions chapter for more detail on globals.)
|
| 138 |
+
|
| 139 |
+
```miniscript
|
| 140 |
+
demo = function
|
| 141 |
+
print x // prints the global x (40)
|
| 142 |
+
x = 2 // creates a local ‘x’ with a value of 2
|
| 143 |
+
print x // prints the local x (2)
|
| 144 |
+
print globals.x // prints the global x again (40)
|
| 145 |
+
globals.x = 42 // reassigns the global x
|
| 146 |
+
print x // still the local value (2)
|
| 147 |
+
print globals.x // prints the new global value (42)
|
| 148 |
+
end function
|
| 149 |
+
|
| 150 |
+
x = 40 // creates a global ‘x’ with a value of 40
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
demo // invokes the function above
|
| 154 |
+
|
| 155 |
+
Overuse of global variables can sometimes lead to tricky bugs, so it’s best to use them sparingly and rely on local variables as much as possible. MiniScript is designed so that this good practice is what happens naturally.
|
| 156 |
+
|
| 157 |
+
## Math-Assignment Operators
|
| 158 |
+
|
| 159 |
+
As a convenient shorthand, the math operators (+, -, *, /, %, and ^) may be used in math-assignment form. This does a math operation with a variable, and assigns the result back to that variable. For example, the math-assignment form:
|
| 160 |
+
|
| 161 |
+
x += 1
|
| 162 |
+
|
| 163 |
+
means exactly the same thing as:
|
| 164 |
+
|
| 165 |
+
```miniscript
|
| 166 |
+
x = x + 1
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
The previous rules about local and global variables still apply. So, to update a global variable in math-assignment form, you would write something like this.
|
| 170 |
+
|
| 171 |
+
globals.x *= 5
|
| 172 |
+
|
| 173 |
+
This works not only for numbers, but for any data type where the operator used is defined. For example, if the global x in the example above were "ha", then after executing that line, the value of x would be "hahahahaha".
|
| 174 |
+
|
| 175 |
+
## MiniScript is Case-Sensitive
|
| 176 |
+
|
| 177 |
+
Uppercase and lowercase matters in MiniScript. The print intrinsic function must be typed exactly print, and not Print, PRINT, or any other variation. The same applies to any variables, functions, or classes you define.
|
| 178 |
+
|
| 179 |
+
While how you use case in your own identifiers is up to you, a common convention is to capitalize classes (e.g. Shape), but use lowercase for variables. Thus the following would be a perfectly sensible bit of code.
|
| 180 |
+
|
| 181 |
+
```miniscript
|
| 182 |
+
shape = new Shape // create a Shape object called shape
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
While we're on the subject of conventions, in most cases you should avoid starting any global variables or function names with an underscore. Identifiers starting with an underscore are often used by the host environment for special “under the hood” code, and name collisions there could cause problems.
|
| 186 |
+
|
| 187 |
+
# Control Flow
|
| 188 |
+
|
| 189 |
+
*looping and branching*
|
| 190 |
+
|
| 191 |
+
Control flow is how you make code execute multiple times, or execute only under certain conditions. Without it, your scripts would be limited to starting at the first line, executing each line exactly once in order, and ending after the last line.
|
| 192 |
+
|
| 193 |
+
MiniScript includes one kind of branching (conditional) structure, and two kinds of loops.
|
| 194 |
+
|
| 195 |
+
## Branching with if
|
| 196 |
+
|
| 197 |
+
Use an if…then statement to specify some condition under which the following statements should be executed. The basic syntax is:
|
| 198 |
+
|
| 199 |
+
```miniscript
|
| 200 |
+
if condition then
|
| 201 |
+
…
|
| 202 |
+
end if
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
When the condition is not true, MiniScript will jump directly to the end if statement.
|
| 206 |
+
|
| 207 |
+
```miniscript
|
| 208 |
+
if x == 42 then
|
| 209 |
+
print "I have found the Ultimate Answer!"
|
| 210 |
+
end if
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
The whole set of lines, from if…then to end if, is known as an if block.
|
| 214 |
+
|
| 215 |
+
Sometimes you want to do something else when the specified condition is not true. You can specify this with an else block before the end if.
|
| 216 |
+
|
| 217 |
+
```miniscript
|
| 218 |
+
if x == 42 then
|
| 219 |
+
print "I have found the Ultimate Answer!"
|
| 220 |
+
else
|
| 221 |
+
print "I am still searching."
|
| 222 |
+
end if
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
Finally, you can check for additional conditions by adding else-if blocks as needed. Here's a slightly more practical example that converts a number to words.
|
| 226 |
+
|
| 227 |
+
```miniscript
|
| 228 |
+
if apples == 0 then
|
| 229 |
+
print "You have no apples."
|
| 230 |
+
else if apples == 1 then
|
| 231 |
+
print "You have one apple."
|
| 232 |
+
else if apples > 10 then
|
| 233 |
+
print "You have a lot of apples!"
|
| 234 |
+
else
|
| 235 |
+
print "You have " + apples + " apples."
|
| 236 |
+
end if
|
| 237 |
+
```
|
| 238 |
+
|
| 239 |
+
In this case, the first condition that matches will execute its block of lines. If none of the conditions match, then the else block will run instead.
|
| 240 |
+
|
| 241 |
+
Note that for all these forms, the if, else if, else, and end if statements must each be on its own line. However, there is also a "short form" if statement that allows you to write an if or if/else on a single line, provided you have only a single statement for the then block, and a single statement for the else block (if you have an else block at all). A short-form if looks like this:
|
| 242 |
+
|
| 243 |
+
```miniscript
|
| 244 |
+
if x == null then x = 1
|
| 245 |
+
```
|
| 246 |
+
|
| 247 |
+
…while a short-form if/else looks like this:
|
| 248 |
+
|
| 249 |
+
```miniscript
|
| 250 |
+
if x >= 0 then print "positive" else print "negative"
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
Notice that end if is not used with a short-form if or if/else. Moreover, there is no way to put more than one statement into the then or else block. If you need more than one statement, then use the standard multi-line form.
|
| 254 |
+
|
| 255 |
+
## Looping with for
|
| 256 |
+
|
| 257 |
+
A for…in statement loops over a block of code zero or more times. The syntax is:
|
| 258 |
+
|
| 259 |
+
```miniscript
|
| 260 |
+
for variable in list
|
| 261 |
+
…
|
| 262 |
+
end for
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
The whole block is referred to as a for loop. On each iteration through the loop, the variable is assigned one value from the specified list. You'll learn more about lists in the Data Types chapter, but for now, it's enough to know that you can easily create a list of numbers using the range function.
|
| 266 |
+
|
| 267 |
+
This example counts from 10 down to 1, and then blasts off.
|
| 268 |
+
|
| 269 |
+
```miniscript
|
| 270 |
+
for i in range(10, 1)
|
| 271 |
+
print i + "..."
|
| 272 |
+
end for
|
| 273 |
+
print "Liftoff!"
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
See the range function in the Intrinsic Functions chapter for more options on that.
|
| 277 |
+
|
| 278 |
+
Instead of a list, you can also iterate over a text string. In this case the loop variable will be assigned each character of the string in order.
|
| 279 |
+
|
| 280 |
+
Finally, it is also possible to iterate over maps. Again, maps will be explained in the Data Types chapter, but just keep in mind that when you use a for statement with a map, then on each iteration through the loop, your loop variable is a little mini-map containing key and value. For example:
|
| 281 |
+
|
| 282 |
+
```miniscript
|
| 283 |
+
m = {1:"one", 2:"two", 3:"three"}
|
| 284 |
+
for kv in m
|
| 285 |
+
print "Key " + kv.key + " has value " + kv.value
|
| 286 |
+
end for
|
| 287 |
+
```
|
| 288 |
+
|
| 289 |
+
This prints out each of the key-value pairs in the map.
|
| 290 |
+
|
| 291 |
+
## Looping with while
|
| 292 |
+
|
| 293 |
+
The other way to loop over code in MiniScript is with a while loop. The syntax is:
|
| 294 |
+
|
| 295 |
+
```miniscript
|
| 296 |
+
while condition
|
| 297 |
+
…
|
| 298 |
+
end while
|
| 299 |
+
```
|
| 300 |
+
|
| 301 |
+
This executes the contained code as long as condition is true. More specifically, it first evaluates the condition, and if it's not true, it jumps directly to end while. If it is true, then it executes the lines within the loop, and then jumps back up to the while statement. The process repeats forever, or until the condition becomes false.
|
| 302 |
+
|
| 303 |
+
This is illustrated by the very first example in this manual, repeated here.
|
| 304 |
+
|
| 305 |
+
```miniscript
|
| 306 |
+
s = "Spam"
|
| 307 |
+
while s.len < 50
|
| 308 |
+
s = s + ", spam"
|
| 309 |
+
end while
|
| 310 |
+
print s + " and spam!"
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
This code builds a string (s) by adding more spam to it, as long as the string length is less than 50. Once it is no longer less than 50, the loop exits, and the result is printed.
|
| 314 |
+
|
| 315 |
+
## Break and Continue
|
| 316 |
+
|
| 317 |
+
There are two additional keywords that let you bail out of a while or for loop early. First, the break statement jumps directly out of the loop, to the next line past the end for or end while. Consider the following.
|
| 318 |
+
|
| 319 |
+
```miniscript
|
| 320 |
+
while true // loops forever!
|
| 321 |
+
if time > 100 then break
|
| 322 |
+
end while
|
| 323 |
+
```
|
| 324 |
+
|
| 325 |
+
Whenever you see while true (or while 1, which is equivalent), it is an infinite loop — unless there is a break statement in the body of the loop. As soon as that break statement executes, we jump directly out of the loop. It works for for loops in exactly the same way. In the case of nested loops, break breaks out of only the innermost loop.
|
| 326 |
+
|
| 327 |
+
The continue statement skips the rest of the body of the loop, and proceeds with the next iteration. This is often used for "bail-out" cases in a large loop, where under certain conditions you want to skip an iteration and just go on with the next one.
|
| 328 |
+
|
| 329 |
+
```miniscript
|
| 330 |
+
for i in range(1,100)
|
| 331 |
+
if i == 42 then continue
|
| 332 |
+
print "Considering " + i + "..."
|
| 333 |
+
end for
|
| 334 |
+
```
|
| 335 |
+
|
| 336 |
+
This will print out the numbers 1 through 100, except for 42, which is skipped. Note that if you simply changed continue to break in this example, the loop would print the numbers 1 through 41, and then stop.
|
| 337 |
+
|
| 338 |
+
## The Nature of Truth
|
| 339 |
+
|
| 340 |
+
We have talked about evaluating conditions as true or false, without explaining what that really means. Usually you don't need to worry about it, but here are the details anyway.
|
| 341 |
+
|
| 342 |
+
```miniscript
|
| 343 |
+
Boolean (true/false) values in MiniScript are represented as numbers. When conditions are evaluated for if and while statements, a value of 0 (zero) is considered false; any other value is considered true. In fact the built-in keywords true and false are exactly equivalent to the numbers 1 and 0 respectively.
|
| 344 |
+
```
|
| 345 |
+
|
| 346 |
+
When you use comparison operators such as == (equal), != (not equal), > (greater than), and <= (less than or equal), these compare their operands and evaluate to either 1 (if true) or 0 (if false).
|
| 347 |
+
|
| 348 |
+
See the Numbers section of the Data Types chapter for more boolean operations you can apply to numbers (including and, or, and not).
|
| 349 |
+
|
| 350 |
+
Finally, in a context that demands a truth value — that is, in an if and while statement, or as an operand of and, or, and not — other data types will be considered false if they are empty, and true if they are not empty. So an empty string, list, or map is equivalent to 0 (zero), and any non-empty string, list or map is equivalent to 1 in these contexts. The special value null is always considered false.
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
# Data Types
|
| 354 |
+
|
| 355 |
+
*things you can store and manipulate*
|
| 356 |
+
|
| 357 |
+
Variables in MiniScript are dynamically typed; you can store any type of data in any variable. But what types of data are there? In MiniScript, there are four primary data types: numbers, strings, lists, and maps. There are a couple of other more obscure types, such as function and null. Everything else, including classes and objects, is actually a special case of a map.
|
| 358 |
+
|
| 359 |
+
## Numbers
|
| 360 |
+
|
| 361 |
+
All numeric values in MiniScript are stored in standard full-precision format (also known as “doubles” in C-derived languages). Numbers are also used to represent true (1) and false (0).
|
| 362 |
+
|
| 363 |
+
Numeric literals are written as ordinary numbers, e.g. 42, 3.1415, or -0.24.
|
| 364 |
+
|
| 365 |
+
You can use the following operators on numbers (where a and b are numbers).
|
| 366 |
+
|
| 367 |
+
| a + b | addition | numeric sum of a and b |
|
| 368 |
+
| a - b | subtraction | numeric difference of a and b |
|
| 369 |
+
| a * b | multiplication | a multiplied by b |
|
| 370 |
+
| a / b | division | a divided by b |
|
| 371 |
+
| a % b | modulo | remainder after dividing a by b |
|
| 372 |
+
| a ^ b | power | a raised to the power of b |
|
| 373 |
+
| a and b | logical and | a * b, clamped to the range [0,1] |
|
| 374 |
+
| a or b | logical or | a + b - a*b, clamped to the range [0,1] |
|
| 375 |
+
| not a | negation | 1 - abs(a), clamped to the range [0,1] |
|
| 376 |
+
| a == b | equality | 1 if a equals b, else 0 |
|
| 377 |
+
| a != b | inequality | 1 if a is not equal to b, else 0 |
|
| 378 |
+
| a > b | greater than | 1 if a is greater than b, else 0 |
|
| 379 |
+
| a >= b | greater than or equal | 1 if a is greater than or equal to b, else 0 |
|
| 380 |
+
| a < b | less than | 1 if a is less than b, else 0 |
|
| 381 |
+
| a <= b | less than or equal | 1 if a is less than or equal to b, else 0 |
|
| 382 |
+
|
| 383 |
+
Note that and, or, and not are not functions; they are operators, and go between (or in the case of not, before) their operands just like all the others.
|
| 384 |
+
|
| 385 |
+
You can check whether a variable contains a number with the isa operator. There is an intrinsic class called number, and x isa number returns true (1) whenever x is, in fact, a number.
|
| 386 |
+
|
| 387 |
+
## Strings
|
| 388 |
+
|
| 389 |
+
Text values in MiniScript are stored as strings of Unicode characters. String literals in the code are enclosed by double quotes ("). Be sure to use ordinary straight quotes, not the fancy curly quotes some word processors insist on making.
|
| 390 |
+
|
| 391 |
+
If your string literal needs to include quotation marks, you can do this by typing the quotation marks twice. For example:
|
| 392 |
+
|
| 393 |
+
```miniscript
|
| 394 |
+
s = "If you do not help us, we shall say ""Ni"" to you."
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
Strings may be concatenated with the + operator, and if you try to add a number and a string together, the number will be automatically converted to a string and then concatenated. Strings may also be replicated (repeated) or cut down to a fraction of their former selves, by multiplying or dividing them by a number.
|
| 398 |
+
|
| 399 |
+
```miniscript
|
| 400 |
+
s = "Spam" * 5 // SpamSpamSpamSpamSpam
|
| 401 |
+
s = s / 2 // SpamSpamSp
|
| 402 |
+
```
|
| 403 |
+
|
| 404 |
+
The full set of string operators is shown below; s and t are strings, and n and m are numbers.
|
| 405 |
+
|
| 406 |
+
| s + t | concatenation | string formed by concatenating t to s |
|
| 407 |
+
| s - t | subtraction (chop) | if s ends in t, returns s with t removed; otherwise just returns s |
|
| 408 |
+
| s * n | replication | s repeated n times (including some fractional amount of s) |
|
| 409 |
+
| s / n | division | equivalent to s * (1/n) |
|
| 410 |
+
| s[n] | index | character n of s (all indexes are 0-based; negative indexes count from end) |
|
| 411 |
+
| s[:n] | left slice | substring of s up to but not including character n |
|
| 412 |
+
| s[n:] | right slice | substring of s from character n to the end |
|
| 413 |
+
| s[n:m] | slice | substring of s from character n up to but not including character m |
|
| 414 |
+
| s == t | equality | 1 if s equals t, else 0 (all string comparisons are case-sensitive) |
|
| 415 |
+
| s != t | inequality | 1 if s is not equal to t, else 0 |
|
| 416 |
+
| s > t | greater than | 1 if s is greater than (collates after) t, else 0 |
|
| 417 |
+
| s >= t | greater than or equal | 1 if s is greater than or equal to t, else 0 |
|
| 418 |
+
| s < t | less than | 1 if s is less than (collates before) t, else 0 |
|
| 419 |
+
| s <= t | less than or equal | 1 if s is less than or equal to t, else 0 |
|
| 420 |
+
|
| 421 |
+
The table above does not include and, or, and not, but these operators work perfectly well on strings through boolean coercion (see "The Nature of Truth" in the previous chapter). In any boolean context, s is considered true if it contains any characters, and false if it is the empty string.
|
| 422 |
+
|
| 423 |
+
Also not listed is behavior of the isa operator with strings. There is an intrinsic type called string, and s isa string returns true (1) for any string s.
|
| 424 |
+
|
| 425 |
+
The slice operators deserve a bit of explanation. The basic syntax is s[n:m], which gets a substring of s starting at character n, and going up to (but not including) character m, where we number characters starting from 0. But this basic syntax is extended with a handful of neat tricks:
|
| 426 |
+
|
| 427 |
+
You may specify just a single index, leaving out the colon, to get a single character. Thus s[0] is the first character, s[1] is the second, etc.
|
| 428 |
+
|
| 429 |
+
You may use a negative index, and it will count from the end. So s[-1] is the last character, s[-2] is the next-to-last, etc. This works for any of the slice indexes.
|
| 430 |
+
|
| 431 |
+
You may omit the first index from the two-index form, and it will default to 0. This is a handy way to get the first n characters of a string. So s[:3] returns the first 3 characters of s; s[:-3] returns all but the last three characters of s.
|
| 432 |
+
|
| 433 |
+
You may omit the last index from the two-index form, and it will continue to the end of the string. Thus, s[3:] skips the first three characters and returns the rest of the string.
|
| 434 |
+
|
| 435 |
+
The way these indexes work results in a lot of very handy properties. For example, s[:n] + s[n:] == s for any value of n from 0 through s.len; in other words, there is a very natural syntax for splitting a string into two parts, which is a fairly common thing to do.
|
| 436 |
+
|
| 437 |
+
Finally, note that strings are immutable; just like numbers, you can never change a string, but you can create a new string and assign it to an existing variable. The following example shows one correct and one incorrect way to change “spin” into “spun”.
|
| 438 |
+
|
| 439 |
+
```miniscript
|
| 440 |
+
s = "spin"
|
| 441 |
+
s = s[:2] + "u" + s[3:] // OK
|
| 442 |
+
```
|
| 443 |
+
|
| 444 |
+
s[3] = "u" // no can do (Runtime Error)
|
| 445 |
+
|
| 446 |
+
## Lists
|
| 447 |
+
|
| 448 |
+
The third basic data type in MiniScript is the list. This is an ordered collection of elements, accessible by index starting with zero. Each element of a list may be any type, including another list.
|
| 449 |
+
|
| 450 |
+
You define a list by using square brackets around the elements, which should be separated with commas.
|
| 451 |
+
|
| 452 |
+
```miniscript
|
| 453 |
+
x = [2, 4, 6, 8]
|
| 454 |
+
```
|
| 455 |
+
|
| 456 |
+
The code above creates a list with four elements and assigns it to x. But again, list elements don't have to be numbers; they can also be strings, lists, or maps. Here's another example.
|
| 457 |
+
|
| 458 |
+
```miniscript
|
| 459 |
+
x = [2, "four", [1, 2, 3], {8:"eight"}]
|
| 460 |
+
```
|
| 461 |
+
|
| 462 |
+
Working with a list is very much like working with a string. You can concatenate two lists with +, replicate or cut a list with * and /, and access elements or sublists using the same slice syntax. Here are the operators valid on lists, where p and q are lists, and n and m are numbers.
|
| 463 |
+
|
| 464 |
+
| p + q | concatenation | list formed by concatenating q to p |
|
| 465 |
+
| p * n | replication | p repeated n times (including some fractional amount of p) |
|
| 466 |
+
| p / n | division | equivalent to p * (1/n) |
|
| 467 |
+
| p[n] | index | element n of p (all indexes are 0-based; negative indexes count from end) |
|
| 468 |
+
| p[:n] | left slice | sublist of p up to but not including element n |
|
| 469 |
+
| p[n:] | right slice | sublist of p from element n to the end |
|
| 470 |
+
| p[n:m] | slice | sublist of p from element n up to but not including element m |
|
| 471 |
+
|
| 472 |
+
In addition, you can use x isa list to check whether any variable x contains a list.
|
| 473 |
+
|
| 474 |
+
The slice operators work exactly the same way as with strings. So p[-1] is the last element of list p; p[3:] skips the first three elements and returns the rest of the list, and so forth.
|
| 475 |
+
|
| 476 |
+
However, there is one important difference: lists are mutable. You can change the contents of a list (by assigning to p[n] or using one of the list methods like p.push), and no matter how many different variables are referring to that list, they will all see the change. The following example illustrates.
|
| 477 |
+
|
| 478 |
+
```miniscript
|
| 479 |
+
a = [1, 2, 3] // creates a list and assigns to a
|
| 480 |
+
b = a // assigns that SAME list to b
|
| 481 |
+
```
|
| 482 |
+
|
| 483 |
+
a[-1] = 5 // changes the last element of our list to 5
|
| 484 |
+
|
| 485 |
+
```miniscript
|
| 486 |
+
print b // prints: [1, 2, 5]
|
| 487 |
+
```
|
| 488 |
+
|
| 489 |
+
Because a and b both refer to the same list, any changes (mutations) made to that list can be seen from either variable.
|
| 490 |
+
|
| 491 |
+
If you want to be sure you have a fresh copy of a list, rather than a shared reference, a common trick is to use [:] to make a slice that includes the entire list. This copies the elements into a new list. Compare the following example to the previous one.
|
| 492 |
+
|
| 493 |
+
```miniscript
|
| 494 |
+
a = [1, 2, 3] // creates a list and assigns to a
|
| 495 |
+
b = a[:] // assigns a COPY of that list to b
|
| 496 |
+
```
|
| 497 |
+
|
| 498 |
+
a[-1] = 5 // changes the last element of our first list to 5
|
| 499 |
+
|
| 500 |
+
```miniscript
|
| 501 |
+
print b // prints: [1, 2, 3] (our copy hasn't changed)
|
| 502 |
+
```
|
| 503 |
+
|
| 504 |
+
## Maps
|
| 505 |
+
|
| 506 |
+
The final basic data type in MiniScript is the map. A map is a set of key-value pairs, where each unique key maps to some value. In some programming environments, this same concept is called a dictionary.
|
| 507 |
+
|
| 508 |
+
Create a map with curly braces around a comma-separated list of key-value pairs. Specify each pair by separating the key and value with a colon, as shown here.
|
| 509 |
+
|
| 510 |
+
```miniscript
|
| 511 |
+
m = {1:"one", 2:"two", 3:"three"}
|
| 512 |
+
```
|
| 513 |
+
|
| 514 |
+
The map created here contains three key-value pairs, each mapping a number to a string (which happens to be the English word for that number in this example).
|
| 515 |
+
|
| 516 |
+
Map keys should be numbers or strings, and must be unique; if you reuse a key, the previous value is replaced. (Technically a key may be a list or another map as well, but in this case, it's important that you do not mutate the key, or the behavior is undefined.) Values may be any type, including lists or maps. Order within a map is not preserved; for loops iterate over a map in arbitrary order.
|
| 517 |
+
|
| 518 |
+
Maps support only a handful of operators (d and e are maps, k is a key, and v is a value):
|
| 519 |
+
|
| 520 |
+
| d + e | concatenation | map formed by assigning d[k] = v for every k,v pair in e |
|
| 521 |
+
| d[k] | index | value associated with key k in d |
|
| 522 |
+
| d.k | dot index | value associated with (string) k in d |
|
| 523 |
+
|
| 524 |
+
There are two ways to get and set members of a map. The first is to use the square-brackets index operator, just as with strings or lists, except that in the case of a map, the key can be a string as well as a number (or even a list or another map, if you are very careful).
|
| 525 |
+
|
| 526 |
+
```miniscript
|
| 527 |
+
d = {"yes":"hai", "no":"iie", "maybe":"tabun"}
|
| 528 |
+
print d["maybe"] // prints: tabun
|
| 529 |
+
```
|
| 530 |
+
|
| 531 |
+
d["maybe"] = "kamo"
|
| 532 |
+
|
| 533 |
+
```miniscript
|
| 534 |
+
print d["maybe"] // prints: kamo
|
| 535 |
+
```
|
| 536 |
+
|
| 537 |
+
The second way is using the dot indexer. This works only in the special case where the key is a string that is a valid identifier: it begins with a letter, and contains only letters, numbers, and underscores. In this case you can write the key after a dot rather than enclosing it in square brackets and quotation marks — the key essentially becomes an identifier in the language. The following is functionally equivalent to the previous example.
|
| 538 |
+
|
| 539 |
+
```miniscript
|
| 540 |
+
d = {"yes":"hai", "no":"iie", "maybe":"tabun"}
|
| 541 |
+
print d.maybe // prints: tabun
|
| 542 |
+
d.maybe = "kamo"
|
| 543 |
+
print d["maybe"] // prints: kamo
|
| 544 |
+
```
|
| 545 |
+
|
| 546 |
+
This dot indexer is mostly syntactic sugar that makes accessing elements of a map easier to read and write. But there are some subtle differences in cases where the map represents a class or object, as described in the next chapter.
|
| 547 |
+
|
| 548 |
+
Finally, like the other basic types, there is an intrinsic class that represents maps — map in this case. So x isa map will return true for any map (including any class or object, as you'll see in the next section).
|
| 549 |
+
|
| 550 |
+
## Type Checking
|
| 551 |
+
|
| 552 |
+
The isa operator was mentioned several times above. This is how you can check, at runtime, what sort of data you have. In many cases you won't care, thanks to MiniScripts automatic type conversion. But sometimes you do.
|
| 553 |
+
|
| 554 |
+
Suppose for example you want to make a method that prints its argument surrounded by parentheses... but if the caller passes in a list, then you want to join the elements of that list with commas. You could accomplish that with isa.
|
| 555 |
+
|
| 556 |
+
```miniscript
|
| 557 |
+
spew = function(x)
|
| 558 |
+
if x isa list then x = x.join(", ")
|
| 559 |
+
print "(" + x + ")"
|
| 560 |
+
end function
|
| 561 |
+
```
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
spew 42 // prints: (42)
|
| 565 |
+
|
| 566 |
+
spew [18, 42, "hike!"] // prints: (18, 42, hike!)
|
| 567 |
+
|
| 568 |
+
## Extending Built-In Types
|
| 569 |
+
|
| 570 |
+
The four built-in types — number, string, list, and map — are just ordinary maps, like your own classes (which you'll learn about next, I promise). You can add new methods to them, and then invoke those methods using dot syntax on ordinary numbers, strings, lists, and maps. (The only limitation is that you can't use dot syntax with a numeric literal.) If this sounds like Greek to you, don't worry — it's an advanced feature, and one most users will never need.
|
| 571 |
+
|
| 572 |
+
## Complete Operator List
|
| 573 |
+
|
| 574 |
+
The table below shows all the operators in the MiniScript language, along with their precedence. Operands in an expression chain will always be grouped by higher-precedence operators before lower-precedence ones; e.g., x + y * z is processed as x + (y * z), because the * operator is higher precedence than the + operator.
|
| 575 |
+
|
| 576 |
+
| Operator | Meaning | Precedence |
|
| 577 |
+
|---|---|---|
|
| 578 |
+
| A = B | assignment | 0 |
|
| 579 |
+
| A or B | logical OR: true if either operand is true | 1 |
|
| 580 |
+
| A and B | logical AND: true if both operands are true | 2 |
|
| 581 |
+
| not A | logical negation: true if its operand is false, and vice versa | 3 |
|
| 582 |
+
| A isa B | type checking | 4 |
|
| 583 |
+
| A == B | equality comparison: true if operands are equal | 5 |
|
| 584 |
+
| A != B | inequality comparison: true if operands are not equal | 5 |
|
| 585 |
+
| A > B | greater-than comparison | 5 |
|
| 586 |
+
| A < B | less-than comparison | 5 |
|
| 587 |
+
| A >= B | greater-than or equal-to comparison | 5 |
|
| 588 |
+
| A <= B | less-than or equal-to comparison | 5 |
|
| 589 |
+
| A + B | addition or concatenation | 6 |
|
| 590 |
+
| A - B | subtraction or string trimming | 6 |
|
| 591 |
+
| A * B | multiplication or replication | 7 |
|
| 592 |
+
| A / B | division or reduction | 7 |
|
| 593 |
+
| A % B | modulo (remainder) | 7 |
|
| 594 |
+
| -A | unary minus (numeric negation) | 8 |
|
| 595 |
+
| new A | instantiation | 9 |
|
| 596 |
+
| @A | address-of (reference function without invoking it) | 10 |
|
| 597 |
+
| A ^ B | power: A raised to the power of B | 11 |
|
| 598 |
+
| A[B] | indexing | 12 |
|
| 599 |
+
| A[B:C] | slicing | 12 |
|
| 600 |
+
| A(B, C...) | calling a function | 12 |
|
| 601 |
+
| A.B | dot operator | 12 |
|
| 602 |
+
|
| 603 |
+
# Functions and Classes
|
| 604 |
+
|
| 605 |
+
*the building blocks of sophisticated software*
|
| 606 |
+
|
| 607 |
+
A function is essentially a sub-program that does some particular task. We've already seen some of the functions built into MiniScript, such as time and range, and even print. There are many more of those, which will be documented in the next chapter. But the real power of a programming language comes from defining your own functions.
|
| 608 |
+
|
| 609 |
+
Beyond that, as a program grows in size and complexity, it becomes useful to start organizing it into classes. A class is basically a collection of functions and data, where objects of a class share the same functions but may have unique data.
|
| 610 |
+
|
| 611 |
+
## Functions
|
| 612 |
+
|
| 613 |
+
A function in MiniScript is a special data type, at the same level as numbers, strings, lists, and maps. You can define a function with the function keyword, assign it to a variable, and then invoke it via that variable, just like the built-in functions. Here's an example.
|
| 614 |
+
|
| 615 |
+
```miniscript
|
| 616 |
+
triple = function(n=1)
|
| 617 |
+
return n*3
|
| 618 |
+
end function
|
| 619 |
+
print triple // prints: 3
|
| 620 |
+
print triple(5) // prints: 15
|
| 621 |
+
```
|
| 622 |
+
|
| 623 |
+
This declares a function that triples any value given to it, and assigns that function to a variable called triple. The triple function is then invoked, with and without an argument.
|
| 624 |
+
|
| 625 |
+
The syntax for declaring a function is:
|
| 626 |
+
|
| 627 |
+
```miniscript
|
| 628 |
+
function(parameters)
|
| 629 |
+
…
|
| 630 |
+
end function
|
| 631 |
+
```
|
| 632 |
+
|
| 633 |
+
where parameters is a comma-separated list of zero or more parameters, each of the form name or name=defaultValue. When a function is invoked, arguments will be matched up to the functions by position. If fewer arguments are given than parameters are defined, the remaining parameters are given their default values — and if no default value was defined for that parameter, then it is set to null.
|
| 634 |
+
|
| 635 |
+
Note that the parentheses after the function keyword are required only if there are parameters. In the case of a function with no parameters, the parentheses are not required (and by standard convention, should be omitted).
|
| 636 |
+
|
| 637 |
+
It's important to understand that a function is itself a bit of data. It's just that, whenever looking up the value of a variable, MiniScript checks for this special function data type; and if found, it invokes that function, rather than returning the function itself.
|
| 638 |
+
|
| 639 |
+
Usually that is exactly what is wanted, as in the example above. But occasionally you may want to copy the function reference, rather than invoking the function. You can do this by prepending your identifier with an @ (read “address of”). Example:
|
| 640 |
+
|
| 641 |
+
```miniscript
|
| 642 |
+
triple = function(n=1)
|
| 643 |
+
return n*3
|
| 644 |
+
end function
|
| 645 |
+
x = @triple
|
| 646 |
+
print x(5) // prints: 15
|
| 647 |
+
```
|
| 648 |
+
|
| 649 |
+
Here we've again declared a function and stored it in a variable called triple. Then we copy the address of that function into another variable called x. At this point we can invoke the function either way, via triple or via x, and both do exactly the same thing. Had we left out the @ on the assignment, MiniScript would have instead evaluated the function triple refers to, and assigned the result (3) to x.
|
| 650 |
+
|
| 651 |
+
Here's a more realistic example. We'll define a function called apply which can apply a given function to each element of a list. Then we can invoke this on a list with any function, simply by using @ to refer to the function we want to apply.
|
| 652 |
+
|
| 653 |
+
```miniscript
|
| 654 |
+
apply = function(lst, func)
|
| 655 |
+
result = lst[:] // make a copy of the list
|
| 656 |
+
for i in indexes(result)
|
| 657 |
+
result[i] = func(result[i]) // apply func to each element
|
| 658 |
+
end for
|
| 659 |
+
return result // return modified result
|
| 660 |
+
end function
|
| 661 |
+
|
| 662 |
+
print apply([1, 2, 3], @triple) // prints: [3, 6, 9]
|
| 663 |
+
```
|
| 664 |
+
|
| 665 |
+
To summarize, you invoke a function by simply using any identifier that refers to it. You avoid this invocation, and refer instead to the function itself, by putting @ before the identifier.
|
| 666 |
+
|
| 667 |
+
## Nested Functions
|
| 668 |
+
|
| 669 |
+
MiniScript allows you to define functions within functions. This is an advanced feature that most users may never need, but it can come in handy on occasion, especially in conjunction with something like the “apply” method above. Just as with any other local value, you might want to avoid cluttering the global namespace just for a function that you only use in one place. Here’s a simple example that assumes we have the apply method defined above.
|
| 670 |
+
|
| 671 |
+
```miniscript
|
| 672 |
+
doubleAll = function(lst)
|
| 673 |
+
f = function(x)
|
| 674 |
+
return x + x
|
| 675 |
+
end function
|
| 676 |
+
return apply(lst, @f)
|
| 677 |
+
end function
|
| 678 |
+
```
|
| 679 |
+
|
| 680 |
+
So inside the function referred to by the (global variable) doubleAll, we define another function, and assign it to the (local variable) f. Then we pass that function in as the second argument to the apply function (or more pedantically, to the function referred to by the apply global variable).
|
| 681 |
+
|
| 682 |
+
When you have a nested function like this, it can access the local variables of the function that contains it. Just as with global variables, it can do this without any prefix (as long as there isn’t some local variable with the same name getting in the way). But to assign to a variable of the outer function, you must use the special identifier outer. Here’s an example.
|
| 683 |
+
|
| 684 |
+
```miniscript
|
| 685 |
+
makeList = function(sep)
|
| 686 |
+
counter = 0
|
| 687 |
+
makeItem = function(item)
|
| 688 |
+
outer.counter = counter + 1
|
| 689 |
+
return counter + sep + item
|
| 690 |
+
end function
|
| 691 |
+
return [makeItem("a"), makeItem("b"), makeItem("c")]
|
| 692 |
+
end function
|
| 693 |
+
|
| 694 |
+
print makeList(". ")
|
| 695 |
+
```
|
| 696 |
+
|
| 697 |
+
Here, makeList refers to the outer function, and makeItem is the inner (nested) function. Notice how makeList has a local variable called counter, initialized to 0. But the inner function both reads that value, and updates it using outer.counter. Work through this code carefully to see if you can figure out what it prints... and then try it and see if you were right!
|
| 698 |
+
|
| 699 |
+
Again, this nested-function business is an advanced feature which beginners can safely forget about. But for advanced users, it is a language feature worth understanding.
|
| 700 |
+
|
| 701 |
+
## Classes and Objects
|
| 702 |
+
|
| 703 |
+
MiniScript supports object-oriented programming (OOP) via prototype-based inheritance. That is, there is fundamentally no difference in MiniScript between a class and an object; the difference, when it exists at all, lives solely in the intent of the programmer.
|
| 704 |
+
|
| 705 |
+
A class or object is a map with a special __isa entry that points to the parent (prototype). This is an implementation detail you rarely need to worry about, because it is handled automatically by the following rules:
|
| 706 |
+
|
| 707 |
+
When you create a map using the special new operator, the __isa member is set for you.
|
| 708 |
+
|
| 709 |
+
When you look up an identifier in a map, MiniScript will walk the __isa chain looking for a map containing that identifier. The value returned is the first value found.
|
| 710 |
+
|
| 711 |
+
Finally, the isa operator also walks the __isa chain, and returns true if any map in that chain matches the right-hand operand. In other words, x isa y returns true if x is y, or any subclass of y.
|
| 712 |
+
|
| 713 |
+
These simple rules provide almost everything needed for object-oriented programming. A series of "classes" may be defined as maps containing functions and default data, which are inherited or overridden as needed. An "object" is just another map, inherited from some class, which normally contains only custom data.
|
| 714 |
+
|
| 715 |
+
Let's illustrate with an example. We'll define a class called Shape, with a subclass called Square.
|
| 716 |
+
|
| 717 |
+
```miniscript
|
| 718 |
+
Shape = {}
|
| 719 |
+
Shape.sides = 0
|
| 720 |
+
|
| 721 |
+
Square = new Shape
|
| 722 |
+
Square.sides = 4
|
| 723 |
+
```
|
| 724 |
+
|
| 725 |
+
A base class is just an ordinary map; in this case, we added a sides entry with a value of 0, signifying that “sides” is a bit of data we expect every Shape to have. Then we created a subclass by using new Shape, and assigned this to Square. In Square, we overrode the value of sides (as all squares should have 4 sides).
|
| 726 |
+
|
| 727 |
+
Now let’s create an instance of our Square class, again by using new.
|
| 728 |
+
|
| 729 |
+
```miniscript
|
| 730 |
+
x = new Square
|
| 731 |
+
print x.sides // prints: 4
|
| 732 |
+
```
|
| 733 |
+
|
| 734 |
+
Notice how we’re using the traditional OOP terminology of “class” and “instance” for convenience, but in reality, there are just three maps — Shape is the prototype of Square, and Square is the prototype of x. The __isa member of each map points to the prototype, because we created them with new.
|
| 735 |
+
|
| 736 |
+
Now let’s add a function to the Shape class, which should work for any shape subclass or object.
|
| 737 |
+
|
| 738 |
+
```miniscript
|
| 739 |
+
Shape.degrees = function
|
| 740 |
+
return 180 * (self.sides - 2)
|
| 741 |
+
end function
|
| 742 |
+
|
| 743 |
+
print x.degrees // prints: 360
|
| 744 |
+
```
|
| 745 |
+
|
| 746 |
+
This example illustrates one additional rule important to object-oriented programming:
|
| 747 |
+
|
| 748 |
+
When a function is invoked via dot indexing, it receives a special self variable that refers to the object on which it was invoked.
|
| 749 |
+
|
| 750 |
+
So in the example above, we invoked the degrees function as x.degrees, which looks for a member called “degrees” in x (and its prototypes via the __isa chain). And when that function is invoked, a special local variable called self is bound to the x object, i.e. the first map in the search chain. This allows class functions to access object data.
|
| 751 |
+
|
| 752 |
+
There is just one more bit of special support for object-oriented programming, and that is the super keyword. This is another built-in variable (similar to self) defined when you invoke a method via dot syntax, but when you call another method via super, it invokes that method on the base class, while keeping self bound to the same value as in the current function. In other words, super lets you call a superclass method, even if you've overridden it. Continuing the previous example, suppose we want to define a subclass of Square that always has 42 more degrees than nonmagical shapes would have:
|
| 753 |
+
|
| 754 |
+
```miniscript
|
| 755 |
+
MagicSquare = new Square
|
| 756 |
+
MagicSquare.degrees = function
|
| 757 |
+
return super.degrees + 42
|
| 758 |
+
end function
|
| 759 |
+
|
| 760 |
+
y = new MagicSquare
|
| 761 |
+
print y.degrees // prints: 402
|
| 762 |
+
```
|
| 763 |
+
|
| 764 |
+
Notice how the MagicSquare.degrees function calls super.degrees. That causes MiniScript to walk the __isa chain, looking for the first implementation of degrees it can find. That would be Shape.degrees, so it invokes that, with a self still bound to y.
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
## Extending the Built-In Types
|
| 768 |
+
|
| 769 |
+
There are maps that represent each of the basic data types: number, string, list, and map. These contain the built-in methods for those types. By adding new methods to one of these maps, you can add new methods usable with dot syntax on values of that type.
|
| 770 |
+
|
| 771 |
+
For example, while there are built-in string methods .upper and .lower to convert a string to upper- or lower-case, there isn’t a method to capitalize a string — that is, convert only the first letter to uppercase. But you could add such a method in your program as follows.
|
| 772 |
+
|
| 773 |
+
```miniscript
|
| 774 |
+
string.capitalized = function
|
| 775 |
+
if self.len < 2 then return self.upper
|
| 776 |
+
return self[0].upper + self[1:]
|
| 777 |
+
end function
|
| 778 |
+
```
|
| 779 |
+
|
| 780 |
+
The function itself is fairly simple: if our string (self) is less than 2 characters long, just uppercase the whole thing; otherwise uppercase the first letter, and append the rest. But because we have assigned this function to string.capitalized, that is, added it to the string map, we can call it with dot syntax on any string.
|
| 781 |
+
|
| 782 |
+
```miniscript
|
| 783 |
+
print "miniScript".capitalized // prints: MiniScript
|
| 784 |
+
```
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
There is one limitation to this trick. Numbers are a little different from other data types; MiniScript does not support dot syntax on numeric literals. So
|
| 788 |
+
|
| 789 |
+
```miniscript
|
| 790 |
+
x = 42
|
| 791 |
+
x.someMethod
|
| 792 |
+
```
|
| 793 |
+
|
| 794 |
+
works fine (assuming you have defined an appropriate number.someMethod function), but
|
| 795 |
+
|
| 796 |
+
```miniscript
|
| 797 |
+
42.someMethod
|
| 798 |
+
```
|
| 799 |
+
|
| 800 |
+
does not.
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
# Intrinsic Functions
|
| 804 |
+
|
| 805 |
+
*built-in functions you can rely on*
|
| 806 |
+
|
| 807 |
+
MiniScript comes with a standard set of built-in (or intrinsic) functions. Many of these are globals (i.e., referred to by variables in the global space). Others (particularly functions intended for use with strings, lists, and maps) are normally invoked via dot syntax after an identifier.
|
| 808 |
+
|
| 809 |
+
In fact, though, all intrinsic functions that use dot syntax are written in such a way that they can also be invoked as global functions. So, for example, you can get the length of a string s by typing s.len, but you can also do the same thing as len(s).
|
| 810 |
+
|
| 811 |
+
The following tables list the standard intrinsic functions, divided by data type on which they operate. Keep in mind that MiniScript is intended to be embedded in some host environment, such as a game or application. The host will normally add additional intrinsic functions particular to that environment. Please consult the documentation or help materials for your host environment for information on these extra functions.
|
| 812 |
+
|
| 813 |
+
## Numeric Functions
|
| 814 |
+
|
| 815 |
+
MiniScript includes a selection of trigonometric functions, which all work in radians (rather than degrees), and other math functions, as well as random numbers and conversion of numbers into strings.
|
| 816 |
+
|
| 817 |
+
In the following table, x is any number, i is an integer, and r is a number of radians.
|
| 818 |
+
|
| 819 |
+
| abs(x) | absolute value of x |
|
| 820 |
+
| acos(x) | arccosine of x, in radians |
|
| 821 |
+
| asin(x) | arcsine of x, in radians |
|
| 822 |
+
| atan(y, x=1) | arctangent of y/x, in radians (returns correct quadrant if optional x parameter is used) |
|
| 823 |
+
| bitAnd(x, y) | treats x and y as integers, and returns bitwise "and" of a and b |
|
| 824 |
+
| bitOr(x, y) | treats x and y as integers, and returns bitwise "or" of a and b |
|
| 825 |
+
| bitXor(x, y) | treats x and y as integers, and returns bitwise "exclusive or" of a and b |
|
| 826 |
+
| ceil(x) | next whole number equal to our greater than x |
|
| 827 |
+
| char(i) | returns Unicode character with code point i (see string .code for the inverse function) |
|
| 828 |
+
| cos(r) | cosine of r radians |
|
| 829 |
+
| floor(x) | next whole number less than or equal to x |
|
| 830 |
+
| log(x, base=10) | logarithm (with the given base) of x, i.e., the value y such that base^y == x |
|
| 831 |
+
| pi | 3.14159265358979 |
|
| 832 |
+
| range(x, y=0, step=null) | returns a list containing values from x through y, in increments of step; step == null is treated as a step of 1 if y > x, or -1 otherwise |
|
| 833 |
+
| round(x, d=0) | x rounded to d decimal places |
|
| 834 |
+
| rnd(seed=null) | "if seed=null, returns random number in the range [0,1); |
|
| 835 |
+
| if seed != null, seeds the random number generator with the given integer value" |
|
| 836 |
+
| sign(x) | sign of x: -1 if x < 0; 0 if x == 0; 1 if x > 0 |
|
| 837 |
+
| sin(r) | sine of r radians |
|
| 838 |
+
| sqrt(x) | square root of x |
|
| 839 |
+
| str(x) | converts x to a string |
|
| 840 |
+
| tan(r) | tangent of r radians |
|
| 841 |
+
|
| 842 |
+
## String Functions
|
| 843 |
+
|
| 844 |
+
All string functions except slice are designed to be invoked on strings using dot syntax, but can also be invoked as globals with the string passed in as the first parameter. Note that strings are immutable; all string functions return a new string, leaving the original string unchanged. In the following table, self refers to the string, s is another string argument, and i is an integer number.
|
| 845 |
+
|
| 846 |
+
| .code | Unicode code point of first character of self (see numeric char function for inverse) |
|
| 847 |
+
| .hasIndex(i) | 1 if i is in the range 0 to self.len-1; otherwise 0 |
|
| 848 |
+
| .indexes | range(0, self.len-1) |
|
| 849 |
+
| .indexOf(s, after=null) | 0-based position of first substring s within self, or null if not found; optionally begins the search after the given position |
|
| 850 |
+
| .insert(index, s) | returns new string with s inserted at position 0 |
|
| 851 |
+
| .len | length (number of characters) of self |
|
| 852 |
+
| .lower | lowercase version of self |
|
| 853 |
+
| .remove(s) | self, but with first occurrence of substring s removed (if any) |
|
| 854 |
+
| .replace(oldval, newval, maxCount=null) | returns a new string with up to maxCount occurrences of substring oldval replaced with newval (if maxCount unspecified, then replaces all occurrences) |
|
| 855 |
+
| .upper | uppercase version of self |
|
| 856 |
+
| .val | converts self to a number (if self is not a valid number, returns 0) |
|
| 857 |
+
| .values | list of individual characters in self (e.g. "spam".values = ["s", "p", "a", "m"] |
|
| 858 |
+
| slice(s, from, to) | equivalent to s[from:to] |
|
| 859 |
+
| .split(delimiter=" ", maxCount=null) | splits the string into a list by the given delimiter, with at most maxCount entries (if maxCount is unspecified, then splits into a list of any size) |
|
| 860 |
+
|
| 861 |
+
## List Functions
|
| 862 |
+
|
| 863 |
+
All list functions except slice are designed to be invoked on lists using dot syntax, but can also be invoked as globals with the list passed in as the first parameter. Lists are mutable; the pop, pull, push, shuffle, and remove functions modify the list in place. To use a list like a stack, add items with push and remove them with pop. To use a list like a queue, add items with push and remove them with pull.
|
| 864 |
+
|
| 865 |
+
In the following table, self is a list, i is an integer, and x is any value.
|
| 866 |
+
|
| 867 |
+
| .hasIndex(i) | 1 if i is in the range 0 to self.len-1; otherwise 0 |
|
| 868 |
+
| .indexes | range(0, self.len-1) |
|
| 869 |
+
| .indexOf(x, after=null) | 0-based position of first element matching x in self, or null if not found; optionally begins the search after the given position |
|
| 870 |
+
| .insert(index, value) | inserts value into self at the given index (in place) |
|
| 871 |
+
| .join(delimiter=" ") | builds a string by joining elements by the given delimiter |
|
| 872 |
+
| .len | length (number of elements) of self |
|
| 873 |
+
| .pop | removes and returns the last element of self (like a stack) |
|
| 874 |
+
| .pull | removes and returns the first element of self (like a queue) |
|
| 875 |
+
| .push(x) | appends the given value to the end of self; often used with pop or pull |
|
| 876 |
+
| .shuffle | randomly rearranges the elements of self (in place) |
|
| 877 |
+
| .sort(key=null) | sorts list in place, optionally by value of the given key (e.g. in a list of maps) |
|
| 878 |
+
| .sum | total of all numeric elements of self |
|
| 879 |
+
| .remove(i) | removes element at index i from self (in place) |
|
| 880 |
+
| .replace(oldval, newval, maxCount=null) | "replaces (in place) up to maxCount occurrences of oldval in the list with newval |
|
| 881 |
+
| (if maxCount not specified, then all occurrences are replaced)" |
|
| 882 |
+
| slice(list, from, to) | equivalent to list[from:to] |
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
## Map Functions
|
| 886 |
+
|
| 887 |
+
Functions on maps are very similar to functions on lists. Maps (like lists) are mutable; the push, pop, remove, and shuffle methods modify the map in place. You can treat a map like a set using push, which inserts 1 (true) for the value of the given key, and pop, which returns a key and removes it (and its value) from the map. Keep in mind that the order of keys in a map is undefined.
|
| 888 |
+
|
| 889 |
+
In the following table, self is a map, i is an integer, and x is any value.
|
| 890 |
+
|
| 891 |
+
| .hasIndex(x) | 1 if x is a key contained in self; 0 otherwise |
|
| 892 |
+
| .indexes | list containing all keys of self, in arbitrary order |
|
| 893 |
+
| .indexOf(x, after=null) | first key in self that maps to x, or null if none; optionally begins the search after the given key |
|
| 894 |
+
| .len | length (number of key-value pairs) of self |
|
| 895 |
+
| .pop | remove and return an arbitrary key from self |
|
| 896 |
+
| .push(x) | equivalent to self[x] = 1 |
|
| 897 |
+
| .remove(x) | removes the key-value pair where key=x from self (in place) |
|
| 898 |
+
| .replace(oldval, newval, maxCount=null) | replaces (in place) up to maxCount occurrences of value oldval in the map with newval (if maxCount not specified, then all occurrences are replaced) |
|
| 899 |
+
| .shuffle | randomly remaps values for keys |
|
| 900 |
+
| .sum | total of all numeric values in self |
|
| 901 |
+
| .values | list containing all values of self, in arbitrary order |
|
| 902 |
+
|
| 903 |
+
## System Functions
|
| 904 |
+
|
| 905 |
+
The following functions relate to the operation of MiniScript itself, or interact with the host environment. The latter (print, time, and wait) are only quasi-standard, in that support for them depends on the host application, and so they may not function in some environments.
|
| 906 |
+
|
| 907 |
+
| globals | reference to the global variable map |
|
| 908 |
+
| intrinsics | a map containing all the global intrinsic functions |
|
| 909 |
+
| locals | reference to the local variable map for the current call frame |
|
| 910 |
+
| print(x, delim) | convert x to a string and print to some text output stream, optionally followed by delim; if delim is not specified, the output is followed by a line break in most environments |
|
| 911 |
+
| refEquals(a,b) | returns 1 if a and b refer to the same instance (not just equal values) |
|
| 912 |
+
| stackTrace | returns the current call stack, as a list of strings |
|
| 913 |
+
| time | number of seconds since program execution began |
|
| 914 |
+
| wait(x=1) | wait x seconds before proceeding with the next MiniScript instruction |
|
| 915 |
+
| yield | wait for next invocation of main engine loop (e.g., next frame in a game) |
|
| 916 |
+
|
| 917 |
+
# Examples
|
| 918 |
+
|
| 919 |
+
*small programs that do interesting things*
|
| 920 |
+
|
| 921 |
+
While we’ve given short examples of MiniScript code throughout this manual, this chapter presents several longer, more interesting examples. Many of the tasks illustrated are taken from RosettaCode, an online database of programming challenges with solutions in many languages. You can go there to compare the MiniScript solution to any other language; you may be amazed how much more readable MiniScript is than the alternatives.
|
| 922 |
+
|
| 923 |
+
## FizzBuzz
|
| 924 |
+
|
| 925 |
+
FizzBuzz is a [standard](http://rosettacode.org/wiki/FizzBuzz) introductory-level programming challenge. The task is simple: print the numbers 1 through 100, but: for multiples of three, print “Fizz” instead of the number; for multiples of five, print “Buzz” instead of the number, and for any number that’s a multiple of three and five, print “FizzBuzz”.
|
| 926 |
+
|
| 927 |
+
There are clearly many ways to tackle this; here’s one.
|
| 928 |
+
|
| 929 |
+
```miniscript
|
| 930 |
+
fizzBuzz = function(n)
|
| 931 |
+
for i in range(1, n)
|
| 932 |
+
s = "Fizz" * (i%3==0) + "Buzz" * (i%5==0)
|
| 933 |
+
if s == "" then s = str(i)
|
| 934 |
+
print s
|
| 935 |
+
end for
|
| 936 |
+
end function
|
| 937 |
+
```
|
| 938 |
+
|
| 939 |
+
fizzBuzz 100
|
| 940 |
+
|
| 941 |
+
Instead of just hard-coding a loop from 1 to 100, we’ve made a function that can FizzBuzz up to any number. Within that function, the only clever bit is line 3, which takes advantage of a couple of MiniScript features. First, comparisons (such as i%3==0 — read “i mod 3 equals zero”) evaluate to 1 when true, or 0 when false. Second, you can multiply a string by a number to repeat it that many times. This means that if you multiply a string by a condition, you get either the original string (if the condition is true) or the empty string (if it is false).
|
| 942 |
+
|
| 943 |
+
That lets us easily generate “Fizz”, “Buzz”, and “FizzBuzz” depending on what our loop counter is divisible by. Line 4 simply fills in the number if we don’t get one of those strings. (Quiz: can you rewrite this line to use the same multiply-by-condition trick as line 3?)
|
| 944 |
+
|
| 945 |
+
## Filter
|
| 946 |
+
|
| 947 |
+
Here’s another [RosettaCode task](http://rosettacode.org/wiki/Filter): select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array.
|
| 948 |
+
|
| 949 |
+
```miniscript
|
| 950 |
+
filter = function(seq, f) // filter seq to where f is true
|
| 951 |
+
result = []
|
| 952 |
+
for i in seq
|
| 953 |
+
if f(i) then result = result + [i]
|
| 954 |
+
end for
|
| 955 |
+
return result
|
| 956 |
+
end function
|
| 957 |
+
|
| 958 |
+
isEven = function(x)
|
| 959 |
+
return x % 2 == 0
|
| 960 |
+
end function
|
| 961 |
+
|
| 962 |
+
list = [2,3,5,6,8,9]
|
| 963 |
+
print filter(list, @isEven)
|
| 964 |
+
```
|
| 965 |
+
|
| 966 |
+
This is a pretty straightforward conversion of the task description into MiniScript code. Our filter function takes a list and a function, and builds a new list by appending each element where the function, applied to that element, is true.
|
| 967 |
+
|
| 968 |
+
We illustrate by making an isEven function that returns true only when its argument mod 2 is zero (i.e., the argument is evenly divisible by 2). Then we pass @isEven to find just the even elements of a given list.
|
| 969 |
+
|
| 970 |
+
## Greatest Common Divisor
|
| 971 |
+
|
| 972 |
+
Here’s a [function](http://rosettacode.org/wiki/Greatest_common_divisor) that finds the biggest number that can divide evenly into two given numbers. Middle schoolers everywhere will soon be out of work.
|
| 973 |
+
|
| 974 |
+
```miniscript
|
| 975 |
+
gcd = function(a, b)
|
| 976 |
+
if a == 0 then return b
|
| 977 |
+
while b != 0
|
| 978 |
+
newA = b
|
| 979 |
+
b = a % b
|
| 980 |
+
a = newA
|
| 981 |
+
end while
|
| 982 |
+
return abs(a)
|
| 983 |
+
end function
|
| 984 |
+
print gcd(-21, 35)
|
| 985 |
+
```
|
| 986 |
+
|
| 987 |
+
The algorithm here, known as the “Euclidian algorithm for finding the GCD,” is clever. The actual MiniScript code is simple.
|
| 988 |
+
|
| 989 |
+
## Maximum Element
|
| 990 |
+
|
| 991 |
+
MiniScript does not have a standard intrinsic for finding the maximum element of a list. But you can easily add it yourself, using this code.
|
| 992 |
+
|
| 993 |
+
```miniscript
|
| 994 |
+
max = function(seq)
|
| 995 |
+
if seq.len == 0 then return null
|
| 996 |
+
max = seq[0]
|
| 997 |
+
for item in seq
|
| 998 |
+
if item > max then max = item
|
| 999 |
+
end for
|
| 1000 |
+
return max
|
| 1001 |
+
end function
|
| 1002 |
+
print max([5, -2, 12, 7, 0])
|
| 1003 |
+
```
|
| 1004 |
+
|
| 1005 |
+
Pretty simple stuff. Line 2 checks to make sure the sneaky user hasn’t given us an empty list; if they have, we return null, as there is no sensible max in that case. Otherwise, we just suppose it’s the first element, and then loop over each element in the list, keeping the biggest.
|
| 1006 |
+
|
| 1007 |
+
Notice that the max variable assigned to on line 1 is in the global variable space, while the max assigned on lines 3 and 5 (and then returned on line 7) is local to a function. These happen to have the same name, but have nothing to do with each other. As a matter of style, it might have been better to name the local variable result rather than max. But it seemed like a good opportunity to demonstrate how local and global variables are separate, even if they have the same name.
|
| 1008 |
+
|
| 1009 |
+
## Titlecase
|
| 1010 |
+
|
| 1011 |
+
MiniScript has intrinsics to convert a string to all upper- or lower-case letters. But what if you want to capitalize just the first letter of each word, and lowercase the rest?
|
| 1012 |
+
|
| 1013 |
+
```miniscript
|
| 1014 |
+
titlecase = function(s)
|
| 1015 |
+
result = ""
|
| 1016 |
+
for i in s.indexes
|
| 1017 |
+
if i == 0 or s[i-1] == " " then
|
| 1018 |
+
result = result + s[i].upper
|
| 1019 |
+
else
|
| 1020 |
+
result = result + s[i].lower
|
| 1021 |
+
end if
|
| 1022 |
+
end for
|
| 1023 |
+
return result
|
| 1024 |
+
end function
|
| 1025 |
+
print titlecase("SO LONG and thanks for all the fish")
|
| 1026 |
+
```
|
| 1027 |
+
|
| 1028 |
+
We just iterate over the string, capitalizing each letter that is either the very first character in the string, or is preceded by a space, and lower-casing the rest.
|
| 1029 |
+
|
| 1030 |
+
## Titlecase (version 2)
|
| 1031 |
+
|
| 1032 |
+
The previous version of Titlecase works fine, but is somewhat suboptimal, because it grows a string by adding to it character by character. This recopies the earlier characters in the string many times. The following code shows a better way.
|
| 1033 |
+
|
| 1034 |
+
```miniscript
|
| 1035 |
+
titlecase = function(s)
|
| 1036 |
+
result = s.split("")
|
| 1037 |
+
for i in s.indexes
|
| 1038 |
+
if i == 0 or s[i-1] == " " then
|
| 1039 |
+
result[i] = s[i].upper
|
| 1040 |
+
else
|
| 1041 |
+
result[i] = s[i].lower
|
| 1042 |
+
end if
|
| 1043 |
+
end for
|
| 1044 |
+
return result.join("")
|
| 1045 |
+
end function
|
| 1046 |
+
print titlecase("SO LONG and thanks for all the fish")
|
| 1047 |
+
```
|
| 1048 |
+
|
| 1049 |
+
Here we start by splitting the string into characters (by using the empty string as the delimiter to split on). Then we iterate over the string, updating each character in our list, and join them back together at the end.
|
data/QuickRef.md
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Welcome to MiniScript!
|
| 2 |
+
|
| 3 |
+
MiniScript is a high-level object-oriented language that is easy to read and write.
|
| 4 |
+
|
| 5 |
+
# Clean Syntax
|
| 6 |
+
|
| 7 |
+
Put one statement per line, with no semicolons, except to join multiple statements on one line.
|
| 8 |
+
|
| 9 |
+
Code blocks are delimited by keywords (see below). Indentation doesn't matter (except for readability).
|
| 10 |
+
|
| 11 |
+
Comments begin with `//`.
|
| 12 |
+
|
| 13 |
+
Don't use empty parentheses on function calls, or around conditions in `if` or `while` blocks.
|
| 14 |
+
|
| 15 |
+
All variables are local by default. MiniScript is case-sensitive.
|
| 16 |
+
|
| 17 |
+
# Control Flow
|
| 18 |
+
|
| 19 |
+
## if, else if, else, end if
|
| 20 |
+
|
| 21 |
+
Use `if` blocks to do different things depending on some condition. Include zero or more `else if` blocks and one optional `else` block.
|
| 22 |
+
|
| 23 |
+
```basic
|
| 24 |
+
if 2+2 == 4 then
|
| 25 |
+
print "math works!"
|
| 26 |
+
else if pi > 3 then
|
| 27 |
+
print "pi is tasty"
|
| 28 |
+
else if "a" < "b" then
|
| 29 |
+
print "I can sort"
|
| 30 |
+
else
|
| 31 |
+
print "last chance"
|
| 32 |
+
end if
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## while, end while
|
| 36 |
+
|
| 37 |
+
Use a `while` block to loop as long as a condition is true.
|
| 38 |
+
|
| 39 |
+
```basic
|
| 40 |
+
s = "Spam"
|
| 41 |
+
while s.len < 50
|
| 42 |
+
s = s + ", spam"
|
| 43 |
+
end while
|
| 44 |
+
print s + " and spam!"
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## for, end for
|
| 48 |
+
|
| 49 |
+
A `for` loop can loop over any list, including ones easily created with the `range` function.
|
| 50 |
+
|
| 51 |
+
```basic
|
| 52 |
+
for i in range(10, 1)
|
| 53 |
+
print i + "..."
|
| 54 |
+
end for
|
| 55 |
+
print "Liftoff!"
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
## break & continue
|
| 59 |
+
|
| 60 |
+
The `break` statement jumps out of a `while` or `for` loop. The `continue` statement jumps to the top of the loop, skipping the rest of the current iteration.
|
| 61 |
+
|
| 62 |
+
# Data Types
|
| 63 |
+
|
| 64 |
+
## Numbers
|
| 65 |
+
|
| 66 |
+
All numbers are stored in full-precision format. Numbers also represent true (1) and false (0). Operators:
|
| 67 |
+
|
| 68 |
+
|Operator|Meaning|
|
| 69 |
+
|-----|-----|
|
| 70 |
+
`+`, `-`, `*`, `/`|standard math
|
| 71 |
+
`%`|mod (remainder)
|
| 72 |
+
`^`|power
|
| 73 |
+
`and`, `or`, `not`|logical operators
|
| 74 |
+
`==`, `!=`, `>`, `>=`, `<`, `<=`|comparison
|
| 75 |
+
|
| 76 |
+
## Strings
|
| 77 |
+
|
| 78 |
+
Text is stored in strings of Unicode characters. Write strings by surrounding them with quotes. If you need to include a quotation mark in the string, type it twice.
|
| 79 |
+
|
| 80 |
+
```basic
|
| 81 |
+
print "OK, ""Bob""."
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Operators:
|
| 85 |
+
|
| 86 |
+
|Operator|Meaning|
|
| 87 |
+
|-----|-----|
|
| 88 |
+
`+`|string concatenation
|
| 89 |
+
`-`|string subtraction (chop)
|
| 90 |
+
`*`, `/`|replication, division
|
| 91 |
+
`==`, `!=`, `>`, `>=`, `<`, `<=`|comparison
|
| 92 |
+
`[i]`|get character i
|
| 93 |
+
`[i:j]`|get slice from i up to j
|
| 94 |
+
|
| 95 |
+
## Lists
|
| 96 |
+
|
| 97 |
+
Write a list in square brackets. Iterate over the list with `for`, or pull out individual items with a 0-based index in square brackets. A negative index counts from the end. Get a slice (subset) of a list with two indices, separated by a colon.
|
| 98 |
+
|
| 99 |
+
```basic
|
| 100 |
+
x = [2, 4, 6, 8]
|
| 101 |
+
x[0] // 2
|
| 102 |
+
x[-1] // 8
|
| 103 |
+
x[1:3] // [4, 6]
|
| 104 |
+
x[2]=5 // x now [2,4,5,8]
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
Operators:
|
| 108 |
+
|
| 109 |
+
|Operator|Meaning|
|
| 110 |
+
|-----|-----|
|
| 111 |
+
`+`|list concatenation
|
| 112 |
+
`*`, `/`|replication, division
|
| 113 |
+
`[i]`|get/set element i
|
| 114 |
+
`[i:j]`|get slice from i up to j
|
| 115 |
+
|
| 116 |
+
## Maps
|
| 117 |
+
|
| 118 |
+
A map is a set of values associated with unique keys. Create a map with curly braces; get or set a single value with square brackets. Keys and values may be any type.
|
| 119 |
+
|
| 120 |
+
```basic
|
| 121 |
+
m = {1:"one", 2:"two"}
|
| 122 |
+
m[1] // "one"
|
| 123 |
+
m[2] = "dos"
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
Operators:
|
| 127 |
+
|
| 128 |
+
|Operator|Meaning|
|
| 129 |
+
|-----|-----|
|
| 130 |
+
`+`|map concatenation
|
| 131 |
+
`[k]`|get/set value with key k
|
| 132 |
+
`.`*ident*|get/set value by identifier
|
| 133 |
+
|
| 134 |
+
# Functions
|
| 135 |
+
|
| 136 |
+
Create a function with `function`, including parameters with optional default values. Assign the result to a variable. Invoke by using that variable. Use `@` to reference a function without invoking.
|
| 137 |
+
|
| 138 |
+
```basic
|
| 139 |
+
triple = function(n=1)
|
| 140 |
+
return n\*3
|
| 141 |
+
end function
|
| 142 |
+
|
| 143 |
+
print triple // 3
|
| 144 |
+
print triple(5) // 15
|
| 145 |
+
f = @triple
|
| 146 |
+
print f(5) // also 15
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
# Classes & Objects
|
| 150 |
+
|
| 151 |
+
A class or object is a map with a special `__isa` entry that points to the parent. This is set automatically when you use the `new` operator.
|
| 152 |
+
|
| 153 |
+
```basic
|
| 154 |
+
Shape = {"sides":0}
|
| 155 |
+
Square = new Shape
|
| 156 |
+
Square.sides = 4
|
| 157 |
+
x = new Square
|
| 158 |
+
x.sides // 4
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
Functions invoked via dot syntax get a `self` variable that refers to the object they were invoked on.
|
| 162 |
+
|
| 163 |
+
```basic
|
| 164 |
+
Shape.degrees = function()
|
| 165 |
+
return 180\*(self.sides-2)
|
| 166 |
+
end function
|
| 167 |
+
|
| 168 |
+
x.degrees // 360
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
# Intrinsic Functions
|
| 172 |
+
|
| 173 |
+
## Numeric
|
| 174 |
+
|
| 175 |
+
| | | |
|
| 176 |
+
|---|---|---|
|
| 177 |
+
abs(x)|acos(x)|asin(x)
|
| 178 |
+
|atan(y,x)|ceil(x)|char(i)
|
| 179 |
+
|cos(r)|floor(x)|log(x,b)
|
| 180 |
+
|round(x,d)|rnd|rnd(seed)|
|
| 181 |
+
|pi|sign(x)|sin(r)|
|
| 182 |
+
sqrt(x)|str(x)|tan(r)
|
| 183 |
+
|
| 184 |
+
## String
|
| 185 |
+
|
| 186 |
+
| | | |
|
| 187 |
+
|---|---|---|
|
| 188 |
+
.indexOf(s)|.insert(i,s)|.len
|
| 189 |
+
.val|.code|.remove(s)
|
| 190 |
+
.lower|.upper|.replace(a,b)
|
| 191 |
+
.split(d)| |
|
| 192 |
+
|
| 193 |
+
## List/Map
|
| 194 |
+
|
| 195 |
+
| | | |
|
| 196 |
+
|---|---|---|
|
| 197 |
+
.hasIndex(i)|.indexOf(x)|.insert(i,v)
|
| 198 |
+
.join(s)|.push(x)|.pop
|
| 199 |
+
.pull|.indexes|.values
|
| 200 |
+
.len|.sum|.sort
|
| 201 |
+
.shuffle|.remove(i)|range(from,to,step)
|
| 202 |
+
|
| 203 |
+
## Other
|
| 204 |
+
|
| 205 |
+
| | | |
|
| 206 |
+
|---|---|---|
|
| 207 |
+
print s|time|wait sec
|
| 208 |
+
locals|outer|globals
|
| 209 |
+
yield| |
|
data/day1.txt
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 1: First Steps", startingPageNum:7}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> 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.
|
| 7 |
+
Q>— Stephen Hawking (theoretical physicist)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn how to run MiniScript code on the web.
|
| 11 |
+
A> - Use the `print` command to make MiniScript display something on the screen.
|
| 12 |
+
A> - Learn about numbers and strings.
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
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.
|
| 16 |
+
|
| 17 |
+
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:
|
| 18 |
+
|
| 19 |
+
_
|
| 20 |
+
: <https://miniscript.org/tryit/>
|
| 21 |
+
|
| 22 |
+
This should bring up a page that looks something like the figure below.
|
| 23 |
+
|
| 24 |
+

|
| 25 |
+
|
| 26 |
+
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.
|
| 27 |
+
|
| 28 |
+
{i: "code editor, Try-It!"}
|
| 29 |
+
[code editor]
|
| 30 |
+
: a text editor specialized for writing program code
|
| 31 |
+
|
| 32 |
+
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.
|
| 33 |
+
|
| 34 |
+
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.
|
| 35 |
+
|
| 36 |
+
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!
|
| 37 |
+
|
| 38 |
+
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:
|
| 39 |
+
|
| 40 |
+
{caption: "Greetings program"}
|
| 41 |
+
```miniscript
|
| 42 |
+
print "Hello world!"
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
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.
|
| 46 |
+
|
| 47 |
+
case-sensitive
|
| 48 |
+
: a language or system where upper- and lower-case letters are considered different
|
| 49 |
+
|
| 50 |
+
case-insensitive
|
| 51 |
+
: a language or system where upper- and lower-case letters are considered the same
|
| 52 |
+
|
| 53 |
+
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!
|
| 54 |
+
|
| 55 |
+
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.
|
| 56 |
+
|
| 57 |
+
D> Computers work fast, but they are very picky about the details.
|
| 58 |
+
|
| 59 |
+
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:
|
| 60 |
+
|
| 61 |
+
{caption: "Incorrect greetings program"}
|
| 62 |
+
```miniscript
|
| 63 |
+
Print "Hello world!"
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
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:
|
| 67 |
+
|
| 68 |
+
```terminal
|
| 69 |
+
Runtime Error: Undefined Identifier: 'Print' is unknown in this context [line 1]
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
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.
|
| 73 |
+
|
| 74 |
+
{i: "error, runtime"}
|
| 75 |
+
Runtime Error
|
| 76 |
+
: an error that occurs after the program starts running
|
| 77 |
+
|
| 78 |
+
{i: "error, compiler"}
|
| 79 |
+
Compiler Error
|
| 80 |
+
: an error that happens even before the program starts running, when MiniScript is studying the code
|
| 81 |
+
|
| 82 |
+
{i: "error, undefined identifier"}
|
| 83 |
+
Undefined Identifier
|
| 84 |
+
: a type of runtime error that occurs when you use a word MiniScript does not know
|
| 85 |
+
|
| 86 |
+
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.
|
| 87 |
+
|
| 88 |
+
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.
|
| 89 |
+
|
| 90 |
+
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.
|
| 91 |
+
|
| 92 |
+
{i:"data type, string"}
|
| 93 |
+
string
|
| 94 |
+
: some letters, numbers, or punctuation surrounded by quotation marks
|
| 95 |
+
|
| 96 |
+
The string in our program above was "Hello world!" But it can be anything. Try these:
|
| 97 |
+
|
| 98 |
+
{caption: "More greetings"}
|
| 99 |
+
```miniscript
|
| 100 |
+
print "Greetings, program!"
|
| 101 |
+
print "My name is 101001."
|
| 102 |
+
print "@*#$!! I spilled bits on my chips!"
|
| 103 |
+
print "Later alligator!"
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
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.
|
| 107 |
+
|
| 108 |
+
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.
|
| 109 |
+
|
| 110 |
+
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.
|
| 111 |
+
|
| 112 |
+
The solution is to enter the quotation marks *twice* if they occur within a string.{i: "quotation marks"}
|
| 113 |
+
|
| 114 |
+
I> To include quotation marks in a string, enter them twice in a row.
|
| 115 |
+
|
| 116 |
+
Here's an example:
|
| 117 |
+
|
| 118 |
+
{caption: "Quotation marks within a string"}
|
| 119 |
+
```miniscript
|
| 120 |
+
print "Hello, ""Bob,"" if that is your real name."
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
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.
|
| 124 |
+
|
| 125 |
+
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.
|
| 126 |
+
|
| 127 |
+
{i:"number;data type, number"}
|
| 128 |
+
Numbers are easy. They are exactly what you think they are. Here's an example:
|
| 129 |
+
|
| 130 |
+
{caption: "The ultimate answer"}
|
| 131 |
+
```miniscript
|
| 132 |
+
print 42
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
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.
|
| 136 |
+
|
| 137 |
+
exponential notation
|
| 138 |
+
: 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)
|
| 139 |
+
|
| 140 |
+
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.
|
| 141 |
+
|
| 142 |
+
W> 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.
|
| 143 |
+
|
| 144 |
+
W> 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.
|
| 145 |
+
|
| 146 |
+
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.
|
| 147 |
+
|
| 148 |
+
{caption: "Printing strings and numbers"}
|
| 149 |
+
```miniscript
|
| 150 |
+
print "The answer to the Ultimate Question..."
|
| 151 |
+
print "of life, the universe, and everything..."
|
| 152 |
+
print "is..."
|
| 153 |
+
print 3.14157
|
| 154 |
+
print "...wait, no, it's actually:"
|
| 155 |
+
print -2.5E6
|
| 156 |
+
print "...no, I'm sorry, the answer is:"
|
| 157 |
+
print 42
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
D> 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.
|
| 161 |
+
|
| 162 |
+
And that wraps up day 1! You have taken your first steps down an incredibly rewarding path. Let's review what you learned today:
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
A> **Chapter Review**
|
| 166 |
+
A> - You can run MiniScript code on the web at <https://miniscript.org/>.
|
| 167 |
+
A> - You know how to use `print` to display strings and numbers.
|
| 168 |
+
A> - You learned that MiniScript is case-sensitive, and how to recognize and correct mistakes in your programs.
|
| 169 |
+
|
data/day10.txt
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 10: Maps", startingPageNum:105}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Feeling a little uncomfortable with your skills is a sign of learning, and continuous learning is what the tech industry thrives on!
|
| 7 |
+
Q>— Vanessa Hurst (founder and CEO, CodeMontage)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn about the *map* data type.
|
| 11 |
+
A> - Get or set map values with square brackets or dot syntax.
|
| 12 |
+
A> - Iterate over a map with a `for` loop.
|
| 13 |
+
A> - Get an overview of intrinsic map functions.
|
| 14 |
+
|
| 15 |
+
{i:"map;data type, map"}
|
| 16 |
+
You've already learned about numbers, strings, and lists. There is one more basic data type in MiniScript: maps. A *map* is like a two-column table, where each unique value on the left column is associated with some other value on the right.
|
| 17 |
+
|
| 18 |
+
{caption:"An example map: four fictional heroes and their ages", hPad:10, vpad:3}
|
| 19 |
+
| key | value |
|
| 20 |
+
| --- | ----- |
|
| 21 |
+
| Buffy | 17 |
|
| 22 |
+
| Willow | 16 |
|
| 23 |
+
| Xander | 17 |
|
| 24 |
+
| Oz | 18 |
|
| 25 |
+
|
| 26 |
+
The values in the left column are "mapped" to values on the right. In some languages, this is called a *dictionary*, because you can think of a dictionary as a book that maps each word to a definition (or list of definitions).
|
| 27 |
+
|
| 28 |
+
{i:"map;dictionary"}
|
| 29 |
+
map
|
| 30 |
+
: a data type that contains a list of key/value pairs, with each unique key associated with one value
|
| 31 |
+
|
| 32 |
+
The keys in a map must be unique; in the table above, you can see that "Buffy", "Willow", "Xander", and "Oz" are all unique. The values, however do not need to be unique; both "Buffy" and "Xander" map to 17 in this example, and that's fine.
|
| 33 |
+
|
| 34 |
+
In MiniScript, you can create a map by enclosing it in curly braces, with the key/value pairs separated by commas like in a list. Within each pair, put a colon between the key and value, like this:
|
| 35 |
+
|
| 36 |
+
```miniscript
|
| 37 |
+
ages = {"Buffy":17, "Willow":16, "Xander":17, "Oz":18}
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
This defines a map called `ages` containing four key/value pairs. Try it! Type the above assignment into your command-line REPL. Then type
|
| 41 |
+
|
| 42 |
+
```miniscript
|
| 43 |
+
ages
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
to see what `ages` contains. You'll get back a representation of the map — but it may not be in exactly the same order you defined it in. It might, for example, look like this:
|
| 47 |
+
|
| 48 |
+
```repl
|
| 49 |
+
{"Buffy": 17, "Xander": 17, "Oz": 18, "Willow": 16}
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
A> Maps pay no attention to the *order* of their key/value pairs. Never depend on getting them out in any particular order.
|
| 53 |
+
|
| 54 |
+
This is different from a list, which preserve the order of their items. So what good are maps then? They're good for looking up (or storing) values by key. In the same REPL as the above, try this:
|
| 55 |
+
|
| 56 |
+
```miniscript
|
| 57 |
+
ages["Oz"]
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
This should print `18`. Notice that the syntax is similar to getting an element of a list or map, except instead of putting a numeric index in the square brackets, we're giving the key (index value) that we want to look up.
|
| 61 |
+
|
| 62 |
+
And while you can't tell from such a simple example, it turns out that maps are *really really good* at this sort of look-up. It basically doesn't matter how many items you have stored in a map; a lookup like this will be just as fast. And this too is different from a list, where the average time to find an element depends directly on how many items are in the list.
|
| 63 |
+
|
| 64 |
+
Now let's suppose Willow has a birthday. Let's update her age to 17:
|
| 65 |
+
|
| 66 |
+
```miniscript
|
| 67 |
+
ages["Willow"] = 17
|
| 68 |
+
ages
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
You should see that the value associated with the key "Willow" has been updated. You can add new key/value pairs to the map in exactly the same way:
|
| 72 |
+
|
| 73 |
+
```miniscript
|
| 74 |
+
ages["Cordelia"] = 18
|
| 75 |
+
ages
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Now the map contains five key/value pairs. Assignment to a map entry will just update the value if the given key is already in the map; otherwise, it will add a new key/value pair.
|
| 79 |
+
|
| 80 |
+
Keys and values can be any data type. Try another example:
|
| 81 |
+
|
| 82 |
+
```miniscript
|
| 83 |
+
d = {}
|
| 84 |
+
d[1] = "uno"
|
| 85 |
+
d["life"] = "grand"
|
| 86 |
+
d["primes"] = [1,2,3,5,7]
|
| 87 |
+
d
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
The first line above creates an empty map, that is, a map containing no key/value pairs at all. Then we added three keys, one at a time: a number (1) and two strings ("life" and "primes"). The values here include both strings and a list; and of course you previously saw an example where the values were numbers. A value could also be another map, and you can even use lists and maps as keys, though that is rare.
|
| 91 |
+
|
| 92 |
+
## Square Brackets vs. Dot Syntax
|
| 93 |
+
|
| 94 |
+
So far we have assigned and looked up values by putting the key in square brackets, just like indexing into a list or string. But with maps, there is an alternate syntax that will turn out to be really handy. It applies only in the special case where the key is (1) a string, and (2) a valid identifier — meaning that it starts with a letter or underscore, and contains only letters, numbers, and underscores (just like a variable name).
|
| 95 |
+
|
| 96 |
+
In this case, you can just put the key *without quotation marks* after the map reference, separated by a dot. If you still have `ages` and `d` defined in your REPL from the examples above, then try this:
|
| 97 |
+
|
| 98 |
+
```terminal
|
| 99 |
+
> ages.Oz
|
| 100 |
+
18
|
| 101 |
+
> ages["Oz"]
|
| 102 |
+
18
|
| 103 |
+
> d["life"] = "sweet"
|
| 104 |
+
> d.life = "sweeter"
|
| 105 |
+
> d
|
| 106 |
+
{"life": "sweeter", 1: "uno", "primes": [1, 2, 3, 5, 7]}
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
The first two commands do exactly the same thing: look up the value of the key "Oz" in map `ages`. Lines 5 and 6 each assign a new value to the key "life" in map `d`. So the dot syntax is just another way of storing and retrieving values in a map.
|
| 110 |
+
|
| 111 |
+
So why is that useful? In a very small program, you can get away without being very organized about your data, because there just isn't very much of it. But as your programs get bigger, it would get really tricky to come up with meaningful, unique variable names for all the values you need to handle, and to write code that works with them all. Maps let you group your data in whatever way makes sense for your program.
|
| 112 |
+
|
| 113 |
+
(Maps are also the basis for object-oriented programming in MiniScript, but that's such a big topic, we'll spend a whole chapter on it a couple days from now.)
|
| 114 |
+
|
| 115 |
+
## Iterating Over Maps
|
| 116 |
+
|
| 117 |
+
You already know to write a `for` loop to iterate over elements of a list, or characters in a string. It turns out you can do the same thing to iterate over key/value pairs in a map. When you do, the loop variable is set to little mini-maps containing "key" and "value" entries. An example will make it clearer:
|
| 118 |
+
|
| 119 |
+
```miniscript
|
| 120 |
+
ages = {"Buffy":17, "Willow":16, "Xander":17, "Oz":18}
|
| 121 |
+
for kv in ages
|
| 122 |
+
print "I see the key " + kv.key + " goes with value " + kv.value
|
| 123 |
+
end for
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
Try it! You can skip the first line above if you still have `ages` defined in your REPL, and it's OK if your values are a little different from mine. The important thing is to see what the for loop does: it sets the loop variable, `kv`, to each of the key/value pairs in turn. And you access that data in `kv` using `kv.key` or `kv.value`.
|
| 127 |
+
|
| 128 |
+
Of course, you could have called the loop variable anything; it doesn't have to be "kv". Here's different example:
|
| 129 |
+
|
| 130 |
+
```miniscript
|
| 131 |
+
nums = {"one":"uno", "two":"dos", "three":"tres"}
|
| 132 |
+
for n in nums
|
| 133 |
+
print n.key + " in Spanish is " + n.value
|
| 134 |
+
print n.value + " in English is " + n.key
|
| 135 |
+
end for
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Iterating over the map directly like this is usually the right thing to do. However, as noted before, you don't have any control over the order in which the data comes out this way. So, there is another approach that is often used, and that is to iterate over just the indexes (i.e. keys) of the map, in sorted order. Try this (again skipping the first line if you still have `ages` defined from before):
|
| 139 |
+
|
| 140 |
+
```miniscript
|
| 141 |
+
ages = {"Buffy":17, "Willow":16, "Xander":17, "Oz":18}
|
| 142 |
+
for name in ages.indexes.sort
|
| 143 |
+
print name + " is " + ages[name] + " years old."
|
| 144 |
+
end for
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
This prints out the age of each hero — but importantly, it prints them out in alphabetical order. How does this work? The `indexes` intrinsic function returns all the keys of a map, as a list. And `sort` is another intrinsic function that sorts a list into alphabetical or numeric order. So when we use them together, like `ages.indexes.sort`, we get all the keys of the map, in order.
|
| 148 |
+
|
| 149 |
+
But now we're iterating over just the keys. So inside the loop, if we also need the value, we just look up the value in the map using square brackets (like `ages[name]` in this example).
|
| 150 |
+
|
| 151 |
+
D> Confused? That's OK. There's a lot of new stuff here, and it's a lot to keep track of. Just take it slow, and break the example above into smaller parts, inspecting each one with the REPL: `ages`, then `ages.indexes`, then `ages.indexes.sort`. Then try a `for` loop over the result of that last one. Step by step, it will all make sense.
|
| 152 |
+
|
| 153 |
+
{gap:40}
|
| 154 |
+
## Map Intrinsic Functions
|
| 155 |
+
|
| 156 |
+
It will come as no surprise to you by now that MiniScript has a number of built-in (intrinsic) functions that work with maps. You've already seen `indexes`, but there are many others. As before, we're going to present the complete set now, but you are not expected to memorize this list. Just familiarize yourself with what's available, so you know where to look later.
|
| 157 |
+
|
| 158 |
+
{i:"functions, map;map functions"}
|
| 159 |
+
{caption:"Intrinsic map functions", colWidths:"145,*"}
|
| 160 |
+
| `.hasIndex(k)` | 1 if k is a key contained in `self`; otherwise 0 |
|
| 161 |
+
| `.indexes` | a list containing all keys in `self`, in arbitrary order |
|
| 162 |
+
| `.indexOf(x, after=null)` | first key in `self` that maps to `x`, or null if none; optionally begins the search after the given key |
|
| 163 |
+
| `.len` | length (number of key/value pairs) of `self` |
|
| 164 |
+
| `.pop` | removes and returns an arbitrary key from `self` |
|
| 165 |
+
| `.push k` | equivalent to `self[k] = 1` |
|
| 166 |
+
| `.remove k` | removes the key/value pair where key=`k` from `self` (in place) |
|
| 167 |
+
| `.replace oldval, newval, maxCount=null` | replaces (in place) up to maxCount occurrences of oldval in the map with newval (if maxCount not specified, then all occurrences are replaced) |
|
| 168 |
+
| `.shuffle` | randomly remaps values for keys |
|
| 169 |
+
| `.values` | a list containing all values in `self`, in arbitrary order |
|
| 170 |
+
|
| 171 |
+
MiniScript tends to use functions that are named the same way for multiple data types. That's why the function that checks whether a map contains a certain key is called `hasIndex` rather than `hasKey`; this same function also works for lists and strings, and the term "index" works for all three, whereas "key" would make sense only for maps. You see this also in the `indexOf` function, which returns the key (index) associated with a given value.
|
| 172 |
+
|
| 173 |
+
You're only likely to need a few of the functions on this table. We discussed `.indexes` earlier, for getting all the indexes (keys) in the map; in some cases you might also want `.values`, which returns all the values in the map. The `.hasIndex` function is very useful, since you often want to check whether the map contains a particular key (if you try to index into the map with a nonexistent key, MiniScript will print an error). Finally, you might need `.remove` to take a key/value pair (specified by the key) out of the map.
|
| 174 |
+
|
| 175 |
+
Let's wrap up this chapter with a slightly longer, more interesting example. Type in the program on the next page carefully, run it, and then teach it some vocabulary words. You can enter English words and their equivalents in some other language, or you can go the other way (French to English for example). If you don't know any other language, make one up! And be sure to sometimes repeat words you've entered before, so it can show off its knowledge.
|
| 176 |
+
|
| 177 |
+
{caption:Language-learning program}
|
| 178 |
+
```miniscript
|
| 179 |
+
print "Teach me a new language!"
|
| 180 |
+
print "(or enter ""quit"" to quit)"
|
| 181 |
+
vocab = {}
|
| 182 |
+
while true
|
| 183 |
+
word = input("Word? ")
|
| 184 |
+
if word == "quit" then break
|
| 185 |
+
if vocab.hasIndex(word) then
|
| 186 |
+
print "I know that one! It's: " + vocab[word]
|
| 187 |
+
else
|
| 188 |
+
vocab[word] = input("OK, how do you say that? ")
|
| 189 |
+
print "OK, I'll remember!"
|
| 190 |
+
end if
|
| 191 |
+
end while
|
| 192 |
+
print "You taught me " + vocab.len + " words. Thank you!"
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
Then pause to think what you've accomplished here: a program that *learns*. It starts off knowing nothing, but the more you interact with it, the more it knows. Unlike people, it will remember each fact perfectly after being told only once, and it will never forget — until, of course, you stop the program!
|
| 197 |
+
|
| 198 |
+
{pageBreak}
|
| 199 |
+
A> **Chapter Review**
|
| 200 |
+
A> - You learned how to map keys to values in MiniScript.
|
| 201 |
+
A> - You discovered the two different ways to access elements of a map: with square brackets, or with dot syntax.
|
| 202 |
+
A> - You learned to iterate over the key/value pairs of a map... and an alternate way to do it in cases where you need them in sorted order.
|
| 203 |
+
A> - You got an overview of the built-in map functions.
|
| 204 |
+
A> - You made a program that learns vocabulary, growing ever smarter as it runs.
|
| 205 |
+
|
data/day11.txt
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 11: Defining Functions", startingPageNum:115}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> You need to organize the code by breaking it into pieces.
|
| 7 |
+
Q>— Barbara Liskov (2008 A. M. Turing award winner)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn how to define your own functions.
|
| 11 |
+
A> - Start thinking about how to break big problems up into smaller, easier problems.
|
| 12 |
+
A> - Learn the difference between local and global variables, and why these make your life easier.
|
| 13 |
+
|
| 14 |
+
You've seen a lot of intrinsic (built-in) functions by now. These are things like `rnd`, which returns a random number, and `ceil`, which returns the next integer greater than or equal to the number you give it, and `val`, which converts a string into a number. Today you're going to learn how to add new functions of your very own! This is a really important milestone, because it lets you break a big complicated problem up into a bunch of smaller, simpler problems, as we'll shortly see.
|
| 15 |
+
|
| 16 |
+
Let's start by looking at an example: making a new function to help you calculate how much tip to leave at a restaurant in the United States.
|
| 17 |
+
|
| 18 |
+
{caption:Tip example 1}
|
| 19 |
+
```miniscript
|
| 20 |
+
// Calculate the tip to leave at a restaurant.
|
| 21 |
+
// Leave 20%, but never less than a dollar.
|
| 22 |
+
tip = function(costOfMeal)
|
| 23 |
+
x = costOfMeal * 0.20
|
| 24 |
+
if x < 1 then x = 1
|
| 25 |
+
return round(x)
|
| 26 |
+
end function
|
| 27 |
+
|
| 28 |
+
print "Tip calculator!"
|
| 29 |
+
print "$10 meal: $" + tip(10) + " tip"
|
| 30 |
+
print "$30 meal: $" + tip(30) + " tip"
|
| 31 |
+
cost = val(input("Cost of your meal? "))
|
| 32 |
+
print "You should leave $" + tip(cost)
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Run this code a few times, trying different amounts.
|
| 36 |
+
|
| 37 |
+
D> Remember that you now know at least three ways to run MiniScript code: in the Try-It! page on the web; typed directly into the command-line REPL; and typed into a text file, which you then run with command-line MiniScript. For this example, use whichever you like best!
|
| 38 |
+
|
| 39 |
+
A function definition begins with `function` and ends with `end function` — similar to the `if`, `for`, and `while` blocks you already know. After the `function` keyword must be parentheses, and then the name of any *parameters* you want to pass in to the function. In the example above, there is one parameter, `costOfMeal`, which will get a number to use as the cost of the meal.
|
| 40 |
+
|
| 41 |
+
parameter
|
| 42 |
+
: a variable included as part of a function definition to hold a value passed in as argument
|
| 43 |
+
|
| 44 |
+
argument
|
| 45 |
+
: a value given as input to a function
|
| 46 |
+
|
| 47 |
+
{i:"data type, function"}
|
| 48 |
+
The complete function — everything from `function` to `end function` — is a value that normally gets assigned to a variable, which is `tip` in this example. Functions are the fifth data type in MiniScript (after numbers, strings, lists, and maps). If we didn't assign the newly created function to something, we would have no way to refer to it later. So we assign it to (in this case) `tip`, and thereafter when we refer to `tip`, we are really calling this function.
|
| 49 |
+
|
| 50 |
+
Between the `function` line and the `end function` line is any amount of MiniScript code, known as the *function body*. That code will run every time the function is called. In the example above, you probably noticed that we used the new `tip` function three times. So that function body (lines 4-6) ran three times.
|
| 51 |
+
|
| 52 |
+
This illustrates one of the important benefits of making a function: it allows you to do the same thing at several different places in your program, without having to actually repeat the code more than once. In fact this is such a useful principle in programming, it has its own name: DRY.
|
| 53 |
+
|
| 54 |
+
DRY (Don't Repeat Yourself)
|
| 55 |
+
: The idea that a program should have no nontrivial lines of code that are repeated in more than one place. When you find the need to repeat some code, you should instead move it into a function, and then call that function wherever you need.
|
| 56 |
+
|
| 57 |
+
{i:"`return`"}
|
| 58 |
+
The other thing to notice in this example is the `return` statement. When the program reaches a `return` line, it immediately exits the function, and the value of that function (wherever it was called) is whatever value, if any, appears after `return`. So in this example, we calculate the tip amount as `x`, and then `return x` — so whatever the value of `x` is at that point is what is *returned* to the caller as the output of the function.
|
| 59 |
+
|
| 60 |
+
{gap:20}
|
| 61 |
+
Let's look at another example.
|
| 62 |
+
|
| 63 |
+
{caption:Simple dice roller}
|
| 64 |
+
```miniscript
|
| 65 |
+
rollD6 = function()
|
| 66 |
+
return ceil(rnd * 6)
|
| 67 |
+
end function
|
| 68 |
+
|
| 69 |
+
die1 = rollD6
|
| 70 |
+
die2 = rollD6
|
| 71 |
+
total = die1 + die2
|
| 72 |
+
print "You rolled " + die1 + " and " + die2
|
| 73 |
+
print "for a total of " + total
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Here we defined a function called `rolld6`. It doesn't need any parameters; each time you call it, it just returns a random number between 1 and 6, like a 6-sided die. Notice that even though there are no parameters, we still need parentheses after the `function` keyword. This is the only place in MiniScript where empty parentheses are ever needed!
|
| 77 |
+
|
| 78 |
+
Once the `rolld6` function has been defined on lines 1-3, we call it two times on lines 5 and 6, each time assigning the result to a variable. Then we report the value of each roll, along with the total.
|
| 79 |
+
|
| 80 |
+
## Breaking Down Big Problems
|
| 81 |
+
|
| 82 |
+
Programs can get pretty complicated. Recall the programs you entered in Chapter 7. They were only a few dozen lines long, but there was a lot going on, wasn't there? To understand them, you pretty much had to grasp the whole program at once. No one part of it made much sense without thinking about the rest at the same time.
|
| 83 |
+
|
| 84 |
+
Most programs in the real world are much, much longer than the ones in Chapter 7. How can anybody make sense of all that? Here's the secret: we don't understand them all at once. We break a big, complicated program down into a bunch of smaller, simpler subprograms (functions). Each function is small and simple enough to understand on its own. And then when we're reading the rest of the program, we'll see code that *uses* those small functions, but at that point we don't worry about how those functions work — we just assume they work and do what the function name suggests they do. This is really no different from how you have been using built-in functions like `print` and `rnd` without worrying about how they work under the hood; you trust them to do their job, so you can focus on yours.
|
| 85 |
+
|
| 86 |
+
So a big, complicated program is really just a bunch of little functions. Indeed, if you ever find yourself writing a function that's more than about a page long, you should break it into smaller functions. Each function should do just one thing, so it's easy to understand; and it should be assigned to a variable with a descriptive name, so readers of the code can correctly guess what it does without even looking at its code. *That* is the magic trick that lets us write things like operating systems, massively multiplayer online games, weather simulations, flight control software, and anything else — they're written one small function at a time.
|
| 87 |
+
|
| 88 |
+
You'll see this principle applied in all the programs in the rest of this book. Never again will you see a long functionless code listing like those in Chapter 7. We have a major power tool now, so we're going to use it!
|
| 89 |
+
|
| 90 |
+
## Local and Global Variables
|
| 91 |
+
|
| 92 |
+
It's time to introduce some important terminology.
|
| 93 |
+
|
| 94 |
+
global scope
|
| 95 |
+
: code or variables in a program that are not inside any function
|
| 96 |
+
local scope
|
| 97 |
+
: code or variables inside a function
|
| 98 |
+
|
| 99 |
+
Before this chapter, everything we did was at the global scope (of course, since we hadn't learned about functions yet). Code at the global scope starts executing at the top of the program, and proceeds line by line, of course honoring `if` blocks and `for`/`while` loops along the way.
|
| 100 |
+
|
| 101 |
+
Code at the local scope, that is, inside a function, is not executed where it is defined in the program. Instead MiniScript just tucks the function away until you actually call it. You've seen this in the examples already. In the dice program, for example, the `rollD6` function was defined at the top of the program (lines 1-3), but it wasn't executed until later code called it (lines 5-6).
|
| 102 |
+
|
| 103 |
+
So that's one difference between local and global scope. But there's an even more important difference that applies to variables in particular.
|
| 104 |
+
|
| 105 |
+
global variable
|
| 106 |
+
: a variable assigned at the global scope
|
| 107 |
+
local variable
|
| 108 |
+
: a variable assigned inside a function
|
| 109 |
+
|
| 110 |
+
Local variables can only be accessed within the function where they were assigned. They have no existence outside that function. This sounds like a limitation, but it's a really useful limitation! It means that you can use whatever variables you want inside a function, and not worry about whether some other function (or code at the global scope) might be using the same variable names. Local variables are completely independent for every function call.
|
| 111 |
+
|
| 112 |
+
Here's how it works: variables are actually stored in maps. At the global scope, all the variables are stored in a special map called `globals`. So when you do a simple assignment like
|
| 113 |
+
|
| 114 |
+
```
|
| 115 |
+
x = 42
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
this is really doing
|
| 119 |
+
|
| 120 |
+
```
|
| 121 |
+
globals["x"] = 42
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
D> Don't take my word for it -- *try it!* Open up the MiniScript REPL and experiment: enter `x = 42`, then print `globals["x"]`. Now try `globals["x"] = 123`, and print `x`. What do you find?
|
| 125 |
+
|
| 126 |
+
Inside a function, though, things are different. Every time you make a function call, MiniScript creates a *new* map for the variables inside that call. Since functions can call other functions (or even call themselves!), this can get pretty complicated, but don't worry, it's the sort of bookkeeping computers are good at. So at the start of a function, there is a fresh new map, containing only the values of the parameters.
|
| 127 |
+
|
| 128 |
+
Now inside a function, when you do an assignment, like
|
| 129 |
+
|
| 130 |
+
```
|
| 131 |
+
test = function()
|
| 132 |
+
y = "abc"
|
| 133 |
+
end function
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
it is actually stored as the value for "y" in this local variables map. That of course does not affect the globals map at all, nor does it affect the locals in any other function call. And when the function exits — either via a `return` statement or by reaching the `end function` line — the local variables map is simply destroyed. Poof! Gone.
|
| 137 |
+
|
| 138 |
+
So that's what happens when you assign to a variable: at the global scope, it stores the value in `globals`; and inside a function, it stores it in the local variables for that function call. What about when you *use* the value of a variable?
|
| 139 |
+
|
| 140 |
+
In that case, MiniScript first looks for that variable in the local variables map. If it finds it, it returns that value and is done. But if it doesn't find it, then it looks at the global variables. And if it finds a matching variable, it returns you that value instead. So global variables can always be accessed from anywhere in the program; that's why we call them "global." But local variables can only be accessed inside the function where they were assigned; they're "local" to that function. And if the same variable name is used as both a local and a global, you'll always get the local one, since locals are checked first.
|
| 141 |
+
|
| 142 |
+
This is super important, and probably not completely clear if it's the first time you've encountered the concept. Here's an example that will help. Type this in carefully:
|
| 143 |
+
|
| 144 |
+
```miniscript
|
| 145 |
+
x = 0 // assign to x as a GLOBAL variable
|
| 146 |
+
test = function()
|
| 147 |
+
print "Inside test: x is " + x // read the GLOBAL variable x
|
| 148 |
+
x = 123 // assign to x as a LOCAL variable
|
| 149 |
+
print "Still inside test: x is now " + x // read LOCAL x
|
| 150 |
+
end function
|
| 151 |
+
|
| 152 |
+
print "Here at the global scope, x is " + x // read GLOBAL x
|
| 153 |
+
test
|
| 154 |
+
print "Back at global scope again, x is " + x // read GLOBAL x
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
When you run this, the output is:
|
| 158 |
+
|
| 159 |
+
```terminal
|
| 160 |
+
Here at the global scope, x is 0
|
| 161 |
+
Inside test: x is 0
|
| 162 |
+
Still inside test: x is now 123
|
| 163 |
+
Back at global scope again, x is 0
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
Let's walk through it step by step. Line 1 is code at the global scope, and it assigns to `x`, so that creates a global variable (actually the same as doing `globals["x"] = 0`). Lines 2-6 define the function (and store it in another global variable called `test`).
|
| 167 |
+
|
| 168 |
+
Line 8 runs next, and since it's at the global scope, it prints out the value of global variable `x`, which is 0. Line 9 calls the `test` function. So line 3 runs, and prints a variable called `x`... since there isn't a local variable with that name at this point, it prints out the value of the global variable again.
|
| 169 |
+
|
| 170 |
+
Line 4 then assigns 123 to `x`. This is inside a function, so it stores the value 123 in the local variables map under "x". And on line 5, when we print the value of `x` again, it now finds this local variable, and prints out that value (123). Notice that this assignment does nothing at all to the globals map.
|
| 171 |
+
|
| 172 |
+
Then the function ends, and we pop back to where it was called. Here on line 10, back at the global scope, we print out the value of `x` again, which prints out the global value — still 0.
|
| 173 |
+
|
| 174 |
+
D> Almost all programming languages have a very similar concept of local and global variables, though they may differ in the details — in Lua, for example, assignment always creates a global variable by default, even inside a function.
|
| 175 |
+
|
| 176 |
+
If that still seems confusing, don't let it worry you too much. It will sink in as you use it. As your programs get more complex, you'll discover that local variables are a wonderful invention; they give you a fresh sheet of scratch paper for every small task (function) you need to do, and then recycle that sheet completely when the task is done. This keeps your workspace neat, and prevents your calculations in one place from messing up values somewhere else.
|
| 177 |
+
|
| 178 |
+
## Building a Program, Piece by Piece
|
| 179 |
+
|
| 180 |
+
Let's end the chapter with one more example — a shortish program that uses several functions. But this time we're going to go through how you would actually write and test such a program.
|
| 181 |
+
|
| 182 |
+
The task for this program is to convert normal text to Pig Latin — a word game in which the initial part of a word, up to the first vowel, is stripped off and then appended to the end of the word, followed by "ay". Or for words that begin with a vowel, you just append "yay" to the end.
|
| 183 |
+
|
| 184 |
+
Thinking about how to break this complex task down would go something like this:
|
| 185 |
+
|
| 186 |
+
- Well, we want to operate on each word separately.
|
| 187 |
+
- For a single word, we'll need to split it into the part before the first vowel, and everything after that point.
|
| 188 |
+
- That requires knowing if a character is a vowel or not.
|
| 189 |
+
|
| 190 |
+
The rest is pretty easy: just swapping the two parts and adding "ay" or "yay". So now we have a plan; time to start coding! And often the best way to begin is with the smallest, simplest function. In this case, that would be a function to tell if a character is a vowel or not. So we write that, and include some tests:
|
| 191 |
+
|
| 192 |
+
{caption:Step 1 of our Pig Latin program}
|
| 193 |
+
```miniscript
|
| 194 |
+
// return true if c is a vowel, false if not
|
| 195 |
+
isVowel = function(c)
|
| 196 |
+
return "aeiou".indexOf(c) != null
|
| 197 |
+
end function
|
| 198 |
+
|
| 199 |
+
print isVowel("x")
|
| 200 |
+
print isVowel("a")
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
We begin by writing a comment describing what we want to do. Then we make a function, `isVowel`, that takes one character (`c`) as its parameter. It uses `indexOf` to see whether that character is in the set of vowels. `indexOf` returns `null` if the thing you're looking for is not found in the string you're searching; so if `"aeiou".indexOf(c)` is not equal to `null`, it means that `c` is one of those five letters. After the function, we put in a couple of tests — these should print 0 for "x" since that is not a vowel, and 1 for "a" since it is.
|
| 204 |
+
|
| 205 |
+
(Type that in and verify that it works before moving on.)
|
| 206 |
+
|
| 207 |
+
OK, that's a handy function that MiniScript didn't have before; now we have it. Let's use it for the next bit: something to split a word into the part before the first vowel, and the part after. Keep what you have above, and add this:
|
| 208 |
+
|
| 209 |
+
{caption:Step 2 of our Pig Latin program}
|
| 210 |
+
```miniscript
|
| 211 |
+
// split a word into the part before the first vowel,
|
| 212 |
+
// and the part from the first vowel to the end
|
| 213 |
+
splitWord = function(word)
|
| 214 |
+
for i in word.indexes
|
| 215 |
+
if isVowel(word[i]) then return [word[:i], word[i:]]
|
| 216 |
+
end for
|
| 217 |
+
return [word, ""] // no vowel found!
|
| 218 |
+
end function
|
| 219 |
+
|
| 220 |
+
print splitWord("three")
|
| 221 |
+
print splitWord("omlets")
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
Again, we begin with a comment. That's always a good idea; it helps you focus on exactly what the function you're about to write should do, and when you come back to this code later, it reminds you what it does.
|
| 225 |
+
|
| 226 |
+
Then we iterate over all the indexes in the given `word`. If the word is five characters long, then `word.indexes` will be `[0, 1, 2, 3, 4]`. The `if` statement uses our handy `isVowel` function to determine if character `i` of the word is a vowel; if it is, then we return a list containing the part of the word before that point, and the rest of the word. Finally, after the for loop, we handle the unlikely case of no vowels at all.
|
| 227 |
+
|
| 228 |
+
(Notice that our `for` loop here is using a local variable called `i`.)
|
| 229 |
+
|
| 230 |
+
The test cases below the function should print out correct splits of the test words: `["thr", "ee"]` for the "three", and `["", "omlets"]` for "omlets" (since that one begins with a vowel).
|
| 231 |
+
|
| 232 |
+
D> Testing as you go makes programming faster, better, and more fun! Try to never write more than a handful of lines without testing them.
|
| 233 |
+
|
| 234 |
+
Again make sure this is all working before the next part, in which we convert a single word into Pig Latin:
|
| 235 |
+
|
| 236 |
+
{caption:Step 3 of our Pig Latin program}
|
| 237 |
+
```miniscript
|
| 238 |
+
// convert a single word into Pig Latin
|
| 239 |
+
convertWord = function(word)
|
| 240 |
+
parts = splitWord(word)
|
| 241 |
+
if parts[0] == "" then return word + "yay"
|
| 242 |
+
return parts[1] + parts[0] + "ay"
|
| 243 |
+
end function
|
| 244 |
+
|
| 245 |
+
print convertWord("three")
|
| 246 |
+
print convertWord("omlets")
|
| 247 |
+
```
|
| 248 |
+
|
| 249 |
+
I'm sure you're seeing the pattern by now, so we'll jump right into the meat of it: we call our own `splitWord` function to split the word into parts, which we store in local variable `parts`. If the first part is empty, then we just return the word plus "yay"; otherwise we reverse the parts and append "ay", per the rules of the game.
|
| 250 |
+
|
| 251 |
+
The two test cases here should print "eethray" and "omletsyay".
|
| 252 |
+
|
| 253 |
+
Almost done! Let's make a `convert` function that operates on a whole sentence.
|
| 254 |
+
|
| 255 |
+
{caption:Step 4 of our Pig Latin program}
|
| 256 |
+
```miniscript
|
| 257 |
+
// convert a whole sentence into Pig Latin
|
| 258 |
+
convert = function(sentence)
|
| 259 |
+
words = sentence.split
|
| 260 |
+
for i in words.indexes
|
| 261 |
+
words[i] = convertWord(words[i])
|
| 262 |
+
end for
|
| 263 |
+
return words.join
|
| 264 |
+
end function
|
| 265 |
+
|
| 266 |
+
print convert("this is a test")
|
| 267 |
+
```
|
| 268 |
+
|
| 269 |
+
Nothing too complicated here! We split the sentence into words, and then run a `for` loop over their indexes. (Note that we're using a local variable `i` here too — and this is completely unrelated to the other `i` used in `splitWord`. They don't bother each other at all.) Each word is converted and stored back into the list, and then we just join them back together. The test case at the end should print "isthay isyay ayay esttay".
|
| 270 |
+
|
| 271 |
+
And the program is now complete, apart from a main loop! If you take out the test cases, and add a main loop to the end, it will look something like the complete program below.
|
| 272 |
+
|
| 273 |
+
{caption:Complete Pig Latin program}
|
| 274 |
+
```miniscript
|
| 275 |
+
// return true if c is a vowel, false if not
|
| 276 |
+
isVowel = function(c)
|
| 277 |
+
return "aeiou".indexOf(c) != null
|
| 278 |
+
end function
|
| 279 |
+
|
| 280 |
+
// split a word into the part before the first vowel,
|
| 281 |
+
// and the part from the first vowel to the end
|
| 282 |
+
splitWord = function(word)
|
| 283 |
+
for i in word.indexes
|
| 284 |
+
if isVowel(word[i]) then return [word[:i], word[i:]]
|
| 285 |
+
end for
|
| 286 |
+
return [word, ""] // no vowel found!
|
| 287 |
+
end function
|
| 288 |
+
|
| 289 |
+
// convert a single word into Pig Latin
|
| 290 |
+
convertWord = function(word)
|
| 291 |
+
parts = splitWord(word)
|
| 292 |
+
if parts[0] == "" then return word + "yay"
|
| 293 |
+
return parts[1] + parts[0] + "ay"
|
| 294 |
+
end function
|
| 295 |
+
|
| 296 |
+
// convert a whole sentence into Pig Latin
|
| 297 |
+
convert = function(sentence)
|
| 298 |
+
words = sentence.split
|
| 299 |
+
for i in words.indexes
|
| 300 |
+
words[i] = convertWord(words[i])
|
| 301 |
+
end for
|
| 302 |
+
return words.join
|
| 303 |
+
end function
|
| 304 |
+
|
| 305 |
+
// main loop: convert sentences until empty input
|
| 306 |
+
while true
|
| 307 |
+
inp = input("Plain sentence? ")
|
| 308 |
+
if inp == "" then break // (enter empty string to exit)
|
| 309 |
+
print convert(inp)
|
| 310 |
+
end while
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
And now you've seen how real programming is done! A complex task was broken down into simpler tasks, and then written bottom up, starting with the tiniest, simplest function. Each other function made use of the ones written before, so that none of them was particularly complex.
|
| 314 |
+
|
| 315 |
+
A> **Chapter Review**
|
| 316 |
+
A> - You learned how to define your own functions, with or without parameters.
|
| 317 |
+
A> - You encountered the DRY (Don't Repeat Yourself) principle, and saw how to break big programs into lots of small functions.
|
| 318 |
+
A> - You gained insight into how variables work under the hood, and the important difference between global and local variables.
|
| 319 |
+
A> - You wrote a complex Pig Latin program by writing a bunch of simple functions that lean on each other to get the job done.
|
data/day12.txt
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 12: Object-Oriented Programming", startingPageNum:129}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Controlling complexity is the essence of computer programming.
|
| 7 |
+
Q>— Brian Kernigan (computer scientist, author)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn the basics of object-oriented programming.
|
| 11 |
+
A> - Start thinking about how to make code that can be reused in different programs.
|
| 12 |
+
|
| 13 |
+
By this point you've learned about all the important data types in MiniScript: numbers, strings, lists, maps, and functions. That's it; there are no more data types to learn! OK, technically `null` is its own data type, but it's a trivial one, and you already know about that too.
|
| 14 |
+
|
| 15 |
+
So the rest of the book, including this chapter, is not going to teach you any more data types. But we are going to look at a particular use of the map data type. Maps are incredibly versatile, as we saw in Chapter 10. By mapping keys to values, they can represent pretty much anything. Now we're going to look at how you can use them to represent "classes" and "objects" to make your code simpler, more organized, and more reusable.
|
| 16 |
+
|
| 17 |
+
## Classes and Objects
|
| 18 |
+
|
| 19 |
+
{i:"OOP;object-oriented programming"}
|
| 20 |
+
The terms *class* and *object* come from a long programming tradition called *object-oriented programming* (or OOP for short). Let's define what they mean in MiniScript terms:
|
| 21 |
+
|
| 22 |
+
class
|
| 23 |
+
: a map that is used to represent a type or category of thing, such as a Person, a Sprite, a Projectile, etc.
|
| 24 |
+
|
| 25 |
+
object
|
| 26 |
+
: a map that is used to represent a particular thing; examples might be Bob (a Person), space invader #7 (a Sprite), a softball at a certain position (a Projectile), etc.
|
| 27 |
+
|
| 28 |
+
Notice that both classes and objects are just maps, and indeed, there is very little technical difference between them as far as MiniScript is concerned. The difference is in the intent of the programmer. They are used in different ways: classes hold code and data that is common to lots of different things. Objects are those individual things, which are instances of the class.
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
All this is very abstract, so let's illustrate with an example. Suppose you're writing a program to work with colored blocks. And to make things simpler, imagine they're two-dimensional blocks, with only width and height and no depth — like what you might draw on a computer screen or graph paper. Fire up your REPL (or the Try-It! page, or whatever other MiniScript context you prefer), and let's create a class called `Block`.
|
| 32 |
+
|
| 33 |
+
```miniscript
|
| 34 |
+
Block = {}
|
| 35 |
+
Block.color = "white"
|
| 36 |
+
Block.width = 1
|
| 37 |
+
Block.height = 1
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Line 1 here creates an empty map, and assigns it to `Block`. Lines 2-4 stuff some values into that map, using dot syntax. (Turn back to Chapter 10 if you need to review maps and dot syntax.)
|
| 41 |
+
|
| 42 |
+
D> A common convention in the MiniScript world is to capitalize variable names that refer to a class. We intend to use `Block` here as a class, so we write it with a capital "B".
|
| 43 |
+
|
| 44 |
+
{i: "`new`"}
|
| 45 |
+
Now let's create an instance of the `Block` class. You do this using the `new` operator. Continuing from the previous example:
|
| 46 |
+
|
| 47 |
+
```miniscript
|
| 48 |
+
b1 = new Block
|
| 49 |
+
print b1.width
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
The first line also creates a map, but not just an empty map; it creates a map based on our previous `Block` map. We say that `b1` "is a" `Block`, or you might say that `b1` "inherits from" `Block`. These are all just ways of saying that `b1` was created from `Block` (or from some other map that itself *is a* `Block`).
|
| 53 |
+
|
| 54 |
+
And that makes `b1` special, because it means that any time we look up a value in the `b1` map, if we don't find it there, we look at the map it inherits from. That's how we are able to print `b1.width` above, even though we never assigned a "width" value to `b1`. It's no problem; since `b1` doesn't have such a value itself, it returns the value from `Block` instead.
|
| 55 |
+
|
| 56 |
+
D> Under the hood, what `new` does isn't all that complex: it creates a map, but sets the special key `__isa` to whatever value comes after `new`. So in the example above, if you examine `b1`, you will find that `b1.__isa` is equal to `Block`. This is how MiniScript keeps track of what a map was made from, and does all the OOP magic described in this chapter.
|
| 57 |
+
|
| 58 |
+
EBOOK>Here's a diagram of how `Block` and `b1` are represented in memory. Both are really just maps, but that special `__isa` entry in `b1` makes it an *instance* of class `Block`.
|
| 59 |
+
|
| 60 |
+
{width:50%}
|
| 61 |
+

|
| 62 |
+
|
| 63 |
+
{i:"instance"}
|
| 64 |
+
PRINT>A diagram of how `Block` and `b1` are represented in memory is at the top of the next page. Both are really just maps, but that special `__isa` entry in `b1` makes it an *instance* of class `Block`.
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
instance
|
| 68 |
+
: another word for "object," used when you want to emphasize the object's class
|
| 69 |
+
|
| 70 |
+
At this point you can get a glimmer of what makes OOP (object-oriented programming) so useful. You may need a *lot* of blocks, and they probably have a lot of data and functions in common. Instead of putting redundant copies of all those bits of data and code on every block, you can put it on their common base class (`Block`), and the individual blocks only need to store what makes them unique.
|
| 71 |
+
|
| 72 |
+
Let's continue with the above example by giving Block a function or two. Add this to your growing code:
|
| 73 |
+
|
| 74 |
+
```miniscript
|
| 75 |
+
Block.area = function()
|
| 76 |
+
return self.width * self.height
|
| 77 |
+
end function
|
| 78 |
+
|
| 79 |
+
Block.description = function()
|
| 80 |
+
return self.width + " x " + self.height + " " + self.color + " block"
|
| 81 |
+
end function
|
| 82 |
+
|
| 83 |
+
print b1.area
|
| 84 |
+
print b1.description
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
{i: "`self`"}
|
| 88 |
+
Here we added two functions to the `Block` class, `area` and `description`. Each of these shows another OOP trick: the `self` keyword. `self` is a special reference to the map a function was called on with dot syntax. So if we call `b1.area`, then inside that `area` function, `self` refers to `b1`. The example above should print `1` for the area, and "1 x 1 white block" for the description.
|
| 89 |
+
|
| 90 |
+
So far we have only one object of type `Block`, which is a little pointless. OOP becomes useful when there are many (or at least two) objects of the same kind. So, let's create a second block and call it `b2`. While we're at it, let's customize each of these blocks a bit so they're not boring 1-by-1 white squares.
|
| 91 |
+
|
| 92 |
+
```miniscript
|
| 93 |
+
b1.width = 3
|
| 94 |
+
b1.color = "red"
|
| 95 |
+
b2 = new Block
|
| 96 |
+
b2.height = 5
|
| 97 |
+
b2.color = "green"
|
| 98 |
+
print b1.description
|
| 99 |
+
print b2.description
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
{width:"50%", position:"bottom"}
|
| 103 |
+

|
| 104 |
+
|
| 105 |
+
Now we're getting somewhere! We changed our `b1` block so that it is red and has a width of 3. We didn't change its height, so that's still 1. Then we created another block, `b2`, with a height of 5 and a green color. In this case we didn't change its width, so it gets 1 from `Block`. Neither of them has a custom `description` method, so when we call `.description` on them, we're really calling `Block.description`, but with `self` referring to `b1` or `b2`, as appropriate. That's why they each print out a correct description of themselves. The first one (`b1`) should return "3 x 1 red block" while the second one (`b2`) prints "1 x 5 green block".
|
| 106 |
+
|
| 107 |
+
That's the basics of OOP (object-oriented programming)!
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
{gap:20}
|
| 112 |
+
|
| 113 |
+
Let's reinforce it with a different example. Suppose you're writing a program to keep track of cookies — it could be cookies baked, or cookies eaten; it's up to you! But in any case your program will be dealing with a lot of cookies, and they are all pretty similar. So it's a good idea to make a class to represent them.
|
| 114 |
+
|
| 115 |
+
```miniscript
|
| 116 |
+
Cookie = {}
|
| 117 |
+
Cookie.radius = 3
|
| 118 |
+
Cookie.area = function()
|
| 119 |
+
return pi * self.radius^2
|
| 120 |
+
end function
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
Here we have created a class called `Cookie`. Of course it's really just a map, but it's a map that we *think of* as a class; it's going to represent everything that's common about all cookies in our program. That includes `radius`, which (unless we change it) is 3 centimeters, and an `area` function that can use that radius value to compute its area (using the standard formula for area of a circle).
|
| 124 |
+
|
| 125 |
+
Now let's actually instantiate (make an instance of) the `Cookie` class by using `new`.
|
| 126 |
+
|
| 127 |
+
```miniscript
|
| 128 |
+
c1 = new Cookie
|
| 129 |
+
print c1.area
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
This should print `28.274334`, which is the area of a cookie with a radius of `3`. But let's suppose this is a somewhat larger cookie. Change the radius to 4, and print its area again:
|
| 133 |
+
|
| 134 |
+
```miniscript
|
| 135 |
+
c1.radius = 4
|
| 136 |
+
c1.area
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
This prints `50.265482`. When we call the `area` method on `c1`, it invokes the code that's actually stored on `Cookie`, but the `Cookie.area` function uses `self.radius`. In this case that is the radius of `c1`, which we just set to `4`.
|
| 140 |
+
|
| 141 |
+
Let's make our `Cookie` class a little fancier. We'll have it also keep track of how many chips are in the cookie, and use that (along with the area) to estimate how many calories the cookie has. And while we're at it, let's also give our class a `description` method, similar to the one we had above for `Block`. Just to show that there's nothing magic about the name `description`, we'll abbreviate it this time to just `desc`.
|
| 142 |
+
|
| 143 |
+
```miniscript
|
| 144 |
+
Cookie.chips = 0
|
| 145 |
+
|
| 146 |
+
Cookie.calories = function()
|
| 147 |
+
return 5 * self.area + 2 * self.chips
|
| 148 |
+
end function
|
| 149 |
+
|
| 150 |
+
Cookie.desc = function()
|
| 151 |
+
result = self.radius * 2 + " cm cookie"
|
| 152 |
+
result = result + " with " + self.chips + " chip"
|
| 153 |
+
if self.chips != 1 then result = result + "s"
|
| 154 |
+
result = result + " (" + round(self.calories) + " cal)"
|
| 155 |
+
return result
|
| 156 |
+
end function
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
This assigns a new value (`chips`) and two new methods (`calories` and `desc`) to the Cookie class. Because `c1` is a Cookie, it immediately gets to use this new stuff. Add `print c1.desc`, and you should see "8 cm cookie with 0 chips (251 cal)".
|
| 160 |
+
|
| 161 |
+
Now instead of just creating a second cookie, let's create a whole batch of cookies! And we'll make them all different, with a random radius and number of chips.
|
| 162 |
+
|
| 163 |
+
```miniscript
|
| 164 |
+
cookies = []
|
| 165 |
+
for i in range(1, 9)
|
| 166 |
+
c = new Cookie
|
| 167 |
+
c.chips = floor(rnd * 10)
|
| 168 |
+
c.radius = 2 + 3 * rnd
|
| 169 |
+
cookies.push c
|
| 170 |
+
end for
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
This will create (and print) a list of ten random cookies. If you examine this list carefully, you'll see that each has a radius, a number of chips, and an `__isa` key that points to `Cookie`. But that list is hard to read; let's print them out a bit more nicely.
|
| 174 |
+
|
| 175 |
+
```miniscript
|
| 176 |
+
for item in cookies; print item.desc; end for
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
D> Tip: you can put several short statements on one line by separating them with semicolons. This is especially handy in a REPL, since you can up-arrow to recall the whole multi-statement line at once, rather than having to repeat each statement one at a time.
|
| 180 |
+
|
| 181 |
+
This should produce a result that looks something like this:
|
| 182 |
+
|
| 183 |
+
```
|
| 184 |
+
7.679863 cm cookie with 0 chips (232 cal)
|
| 185 |
+
6.053417 cm cookie with 4 chips (152 cal)
|
| 186 |
+
7.978822 cm cookie with 0 chips (250 cal)
|
| 187 |
+
7.69492 cm cookie with 9 chips (251 cal)
|
| 188 |
+
9.87915 cm cookie with 3 chips (389 cal)
|
| 189 |
+
7.336143 cm cookie with 1 chip (213 cal)
|
| 190 |
+
8.179308 cm cookie with 7 chips (277 cal)
|
| 191 |
+
9.685048 cm cookie with 9 chips (386 cal)
|
| 192 |
+
9.216735 cm cookie with 9 chips (352 cal)
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
{i:"`list.sort`;sorting;list, sorting"}
|
| 196 |
+
Of course your numbers will be different, since they are random. Just for fun, let's sort this list by radius. The `list.sort` method takes an optional second parameter, which is the name of a key to sort by. So we can do:
|
| 197 |
+
|
| 198 |
+
```miniscript
|
| 199 |
+
list.sort "radius"
|
| 200 |
+
for item in cookies; print item.desc; end for
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
And now you should see the same batch of cookies, but ordered by radius.
|
| 204 |
+
|
| 205 |
+
To review, in this example we created a class called `Cookie`, and then created a bunch of objects (which are also called instances of the class) and stored them in the list. Each of our objects is a `Cookie`, and inherits all the properties and methods that `Cookie` defines.
|
| 206 |
+
|
| 207 |
+
## Writing Reusable Code
|
| 208 |
+
|
| 209 |
+
There are two reasons why object-oriented programming has become so popular in the last few decades. One is that it helps keep big programs neat and organized, with all the functions for a particular kind of thing bundled together into classes. The other is that it makes it easier to reuse code.
|
| 210 |
+
|
| 211 |
+
Code reuse is kind of the holy grail of programming. Faced with a need — say, drawing a little picture on the screen that can efficiently move, rotate, and change size — you only want to write code for that once, at most. Then the *next* time you face that same need, you want to just pull that code off the shelf and use it again. This is possible to do without OOP, but it's harder; you would have a collection of functions that might well conflict with other functions you already have in your program for other things. And it would get even more difficult to manage as you start defining sub-kinds of objects, with behavior that is almost, but not quite, like the general kind.
|
| 212 |
+
|
| 213 |
+
Conversely, with OOP, reusing code like that is substantially easier. If you have a little picture-moving class — let's call it Sprite — then everything there is to managing sprites can be wrapped up in that class. You can add that class to your program, and as long as you don't already have something called Sprite, it won't break anything. (This, by the way, is why MiniScript is case-sensitive, and why we capitalize classes but not ordinary variables; it reduces the chance of conflicts, since `sprite` is not the same thing as `Sprite`.) The Sprite class might have dozens of properties and methods, but they're all tucked neatly away under the Sprite class.
|
| 214 |
+
|
| 215 |
+
Of course you could get *that* benefit just by stuffing a bunch of related methods into a map, without using any of the OOP features like `new` and `self`. And in some cases that's all you need. But when those methods operate on some cluster of data, like the block example above or the position, rotation, and size of a Sprite, then it becomes really handy to have those things defined as objects.
|
| 216 |
+
|
| 217 |
+
As a new programmer, you may not see lots of opportunities to define your own classes right away, and that's OK. You will, however, start *using* classes a lot after Chapter 14, because that's when we get into Mini Micro. Mini Micro has a built-in Sprite class, along with other classes that represent sounds, files, displays, and so on. You'll also see classes crop up here and there in the examples in the rest of this book. (In fact some of the earlier examples could have been done more neatly using OOP, and believe me, it was a little painful to write them the old-fashioned way!)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
A> **Chapter Review**
|
| 221 |
+
A> - You learned about object-oriented programming (OOP), and how to do it in MiniScript using `new` and `self`.
|
| 222 |
+
A> - You began thinking about how to write code that can be reused later (your future self will thank you).
|
| 223 |
+
|
data/day13.txt
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 13: Working with Files", startingPageNum:139}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Knowledge is power.
|
| 7 |
+
Q>— Francis Bacon (1561 - 1626)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn the command-line MiniScript functions for working with disk files.
|
| 11 |
+
A> - Start using MiniScript as a superpower that lets you automate repetitive tasks.
|
| 12 |
+
|
| 13 |
+
After twelve days of MiniScript, you now know all the essential points of the MiniScript language, as well as the intrinsic functions that are common to all MiniScript environments. Congratulations! That's a real achievement.
|
| 14 |
+
|
| 15 |
+
Now we can start considering the additional functionality provided by certain MiniScript environments. In Chapter 8, you installed command-line MiniScript, and hopefully you've continued to work with it for at least some of the examples since then. If not, that's OK — but you might want to go back and brush up on it, since we're going to be using it for this chapter!
|
| 16 |
+
|
| 17 |
+
In addition to all the standard MiniScript functionality, command-line MiniScript provides some extra functions and classes for working with disk files. That is an extremely useful thing to do, as everything on a computer is organized into files and folders. With the powers you gain today, you'll be able to create files, rename them, move them around, split them into parts, combine them together, and do all sorts of other tasks that would be much harder to do by hand.
|
| 18 |
+
|
| 19 |
+
D> The file-related functions covered in this chapter also happen to be available in Mini Micro, which you'll start using in only two more days! So while you're working with command-line MiniScript today, you're also getting a head start on Mini Micro.
|
| 20 |
+
|
| 21 |
+
If you go back to the web page where you downloaded command-line MiniScript:
|
| 22 |
+
|
| 23 |
+
_
|
| 24 |
+
: <https://miniscript.org/cmdline/>
|
| 25 |
+
|
| 26 |
+
...you will find the file-related functions listed there. Note that because these are not part of the MiniScript core, they are *not* on the MiniScript Quick Reference sheet, nor in the MiniScript Manual.
|
| 27 |
+
|
| 28 |
+
## Files, Folders, and Paths
|
| 29 |
+
|
| 30 |
+
Let's begin my making sure we're all clear on some basic terminology that relates to computer files.
|
| 31 |
+
|
| 32 |
+
file
|
| 33 |
+
: a collection of bytes stored on disk. Each file has a name (often including an extension at the end, like ".txt" or ".jpg"), the actual file content, and some other metadata like a creation date. Things like pictures, text files, and word processing documents are all files.
|
| 34 |
+
|
| 35 |
+
folder
|
| 36 |
+
: a special kind of disk entry that contains files and other folders. Sometimes called a *directory*.
|
| 37 |
+
|
| 38 |
+
path
|
| 39 |
+
: a string that uniquely identifies a file or folder location by specifying the sequence of nested folders needed to get there, as well as the file or folder name itself. Each part of the path is separated by a slash (a forward slash on Mac, Linux, and Mini Micro; a backslash on Windows).
|
| 40 |
+
|
| 41 |
+
Every desktop operating system provides some way to browse files and folders as little icons in a window. But when you're working on the command line, you work with those same files and folders using paths and file names.
|
| 42 |
+
|
| 43 |
+
Paths come in two types, absolute and relative.
|
| 44 |
+
|
| 45 |
+
absolute path
|
| 46 |
+
: a path that begins with a disk identifier, and lists all the folders from the very top level of that disk down to the file. On Windows, absolute paths begin with a drive letter like "C:". On other systems, absolute paths begin with a forward slash.
|
| 47 |
+
|
| 48 |
+
relative path
|
| 49 |
+
: a path that does not start at the top level of the disk, and so it can only be interpreted relative to some other folder. Sometimes called a *partial path*. A file name is an extreme case of a relative path.
|
| 50 |
+
|
| 51 |
+
If we were not lazy, we would probably just use absolute paths all the time, since they are unambiguous. But we are, so we use relative paths a lot. How then can the computer know how to interpret them? It does so by defining one folder in particular as the *working directory*, which is the base for any relative path.
|
| 52 |
+
|
| 53 |
+
working directory
|
| 54 |
+
: the folder that partial paths are considered to be relative to. Sometimes called the *current directory* or *current folder*.
|
| 55 |
+
|
| 56 |
+
## The file module
|
| 57 |
+
|
| 58 |
+
{i:"module;`file` module"}
|
| 59 |
+
Command-line MiniScript (and Mini Micro) tucks away all the file-related function inside a map called `file`. That's just to avoid adding a dozen new identifiers into the global variable space; instead, it only adds one. Because this map is *not* a class intended to be used with `new`, it is not capitalized. We sometimes refer to such a map containing functions as a "module" (just to distinguish it frorm a class). So, let's take a look at the `file` module.
|
| 60 |
+
|
| 61 |
+
Start by firing up command-line MiniScript, and at the REPL prompt, type:
|
| 62 |
+
|
| 63 |
+
```terminal
|
| 64 |
+
> file.indexes
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Recall that the `indexes` method, when called on a map, returns a list of all the keys in the map. In this case, that tells you the names of all the functions in the file module. There are a bit over a dozen. The full set is shown below, but just like the tables of intrinsic functions in earlier chapters, don't try to memorize this. Just skim it now, so you will know where to look if you need it later.
|
| 68 |
+
|
| 69 |
+
{caption:"Functions in the `file` module", colWidths:"170,*"}
|
| 70 |
+
| `file.curdir` | returns the current working directory |
|
| 71 |
+
| `file.setdir(path)` | changes the current working directory |
|
| 72 |
+
| `file.makedir(path)` | creates a new directory |
|
| 73 |
+
| `file.children(path)` | returns list of files within the given directory |
|
| 74 |
+
| `file.name(path)` | returns the file name from the given path |
|
| 75 |
+
| `file.parent(path)` | returns the path to the directory containing the given path |
|
| 76 |
+
| `file.child(parentPath, childName)` | combines the given directory path and file name, returning path to the child |
|
| 77 |
+
| `file.exists(path)` | returns true if a file exists at the given path |
|
| 78 |
+
| `file.copy(oldPath, newPath)` | copies a file to a new location |
|
| 79 |
+
| `file.move(oldPath, newPath)` | moves/renames a file |
|
| 80 |
+
| `file.delete(path)` | deletes a file |
|
| 81 |
+
| `file.info(path)` | gets a map of details about a file including size, isDirectory, date, and (full) path |
|
| 82 |
+
| `file.readLines(path)` | returns full contents of a text file as a list of strings |
|
| 83 |
+
| `file.writeLines(path, data)` | writes out the given list as a text file, one line per list element |
|
| 84 |
+
| `file.open(path, mode="rw+")` | opens or creates a file |
|
| 85 |
+
|
| 86 |
+
About half of the functions are just for manipulating paths. Try entering
|
| 87 |
+
|
| 88 |
+
```repl
|
| 89 |
+
> file.curdir
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
This should print your current working directory. For me, that might be something like `/Users/jstrout/Documents`, but for you it will be different. That's OK. Now try
|
| 93 |
+
|
| 94 |
+
```terminal
|
| 95 |
+
> file.children
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
It should return a list of files in your current directory. Hopefully those things look familiar! Note that it may include some entries that you don't see when you look in the same folder graphically, using Finder or File Explorer. Those are "hidden" files which the makers of macOS or Windows don't think you should see. But MiniScript doesn't hide anything — you see what's really there!
|
| 99 |
+
|
| 100 |
+
Notice that we didn't give `file.children` a path, so it just returned the contents of the working directory. Now try it again, giving it either the name of a folder inside your working directory, or an absolute path to some other folder. For example, on my machine I can do:
|
| 101 |
+
|
| 102 |
+
```terminal
|
| 103 |
+
> file.children "/Users/jstrout"
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
to get a list of all the stuff in my home directory. But of course you'll need to change that to some directory on *your* system. Experiment with this a bit.
|
| 107 |
+
|
| 108 |
+
Now let's try changing the working directory. Pick some folder you were able to get the children of, then pass its path to `file.setdir`, like this:
|
| 109 |
+
|
| 110 |
+
```terminal
|
| 111 |
+
> file.setdir "/Users/jstrout"
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
(again changing the path to something that exists on your machine). If successful, this will return 1 (which means `true` in MiniScript, but is also sometimes used to indicate success, like getting a thumbs-up from the function). Now if you enter `file.curdir`, it will report back the new working directory. Doing `file.children` with no argument will list the files in that directory, and any partial paths will now be interpreted relative to that folder. Again, experiment with this until it seems clear.
|
| 115 |
+
|
| 116 |
+
Now let's consider how to build and take apart paths. Let's introduce a variable, `p` for "path" (using a short name just to save us some typing). Start by setting that to the current directory.
|
| 117 |
+
|
| 118 |
+
```terminal
|
| 119 |
+
> p = file.curdir
|
| 120 |
+
> p
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
This should print out the path of your working directory, which is an absolute path that probably contains several parts. Now pick the name of some file in that directory (use `file.children(p)` if you need to review what those files are). To get the path of a file relative to `p`, you can use the `file.child` method, like so:
|
| 124 |
+
|
| 125 |
+
```terminal
|
| 126 |
+
> f = file.child(p, "SomeFile.txt")
|
| 127 |
+
> f
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
That function basically just appends the file name you give it to the path, inserting the appropriate path separator for your platform (i.e. a forward or backward slash).
|
| 131 |
+
|
| 132 |
+
Now, let's do the reverse: strip the last part of the path off, so that it refers to the parent folder.
|
| 133 |
+
|
| 134 |
+
```terminal
|
| 135 |
+
> file.parent(f)
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
This should strip the file name off, and get you back the path `p` that you started with. Of course you could go further, and get the parent folder of `p` itself (`file.parent(p)`), or any other path, at least until you run out of path parts.
|
| 139 |
+
|
| 140 |
+
There is another way to split up a path: you might want just the *last* part, stripping off everything before the final file or folder name.
|
| 141 |
+
|
| 142 |
+
```terminal
|
| 143 |
+
> file.name(f)
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
## Listing and Searching Files
|
| 147 |
+
|
| 148 |
+
Let's combine what we've learned so far with one more function, `file.info`, that gets detailed a map of extra details about a file on disk. These details include `size` in bytes, `isDirectory` (1 for true or 0 for false), `date` that the file was last modified, and `path`, which is the absolute path to the file. This is a somewhat longer example, so you might put it into a text file and run it rather than typing it into the REPL.
|
| 149 |
+
|
| 150 |
+
{caption:List files with detials}
|
| 151 |
+
```miniscript
|
| 152 |
+
p = file.curdir
|
| 153 |
+
for f in file.children(p).sort
|
| 154 |
+
info = file.info(file.child(p, f))
|
| 155 |
+
padName = (f + " "*40)[:40]
|
| 156 |
+
padSize = (" "*8 + info.size)[-8:]
|
| 157 |
+
print padName + padSize + " " + info.date
|
| 158 |
+
end for
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
This prints out all the files in the current directory, along with their size and modification date, all in neatly formatted columns. A good demo, but not terribly useful since you can already browse the files with Finder or File Explorer. So how about something that those can't easily do? Let's say you were working on something yesterday, but you can't remember where you put it or what it was called. Here's a little program that can search by whatever criteria you do remember:
|
| 162 |
+
|
| 163 |
+
{caption:Find a file by any criteria}
|
| 164 |
+
```miniscript
|
| 165 |
+
// Find a file! Run this from some folder you know contains what
|
| 166 |
+
// you're looking for, even if it's buried several folders deeper.
|
| 167 |
+
|
| 168 |
+
// Return whether the given file info represents a good candidate.
|
| 169 |
+
isMatch = function(info)
|
| 170 |
+
// Here program whatever you can remember about the file
|
| 171 |
+
// you're looking for. An easy way is to return false for
|
| 172 |
+
// anything that is NOT what you want.
|
| 173 |
+
if info.path[-4:] != ".txt" then return false
|
| 174 |
+
if info.date[:10] != "2020-04-27" then return false
|
| 175 |
+
if info.size < 1024 then return false
|
| 176 |
+
// If none of the above apply, then this might be a good file!
|
| 177 |
+
return true
|
| 178 |
+
end function
|
| 179 |
+
|
| 180 |
+
// Print the path of all good candidates in the given directory,
|
| 181 |
+
// or any sub-folder (repeating to any depth).
|
| 182 |
+
printMatches = function(dirPath)
|
| 183 |
+
for f in file.children(dirPath)
|
| 184 |
+
info = file.info(file.child(dirPath, f))
|
| 185 |
+
if info.isDirectory then
|
| 186 |
+
// We've found a subdirectory. Print matches for THAT!
|
| 187 |
+
printMatches info.path
|
| 188 |
+
else if isMatch(info) then
|
| 189 |
+
// This file looks like a good match.
|
| 190 |
+
print info.path
|
| 191 |
+
end if
|
| 192 |
+
end for
|
| 193 |
+
end function
|
| 194 |
+
|
| 195 |
+
// Main program. Let's just operate on the current directory
|
| 196 |
+
// (wherever this script was run).
|
| 197 |
+
printMatches file.curdir
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
Notice the trick here where the `printMatches` function calls itself for any subfolder it runs across. This trick is called *recursion*.
|
| 201 |
+
|
| 202 |
+
recursion
|
| 203 |
+
: a programming technique where a function calls itself (directly or indirectly)
|
| 204 |
+
|
| 205 |
+
Recursion works because variables are local, so the variable `f` (used in the `for` loop) in one call is not the same as the variable `f` in the next call. Every call of the function gets its own local variables, so MiniScript never gets confused or loses track of what it was doing.
|
| 206 |
+
|
| 207 |
+
Note that if you type in the above exactly as it is, and run it, it probably won't print anything. That's because you probably don't have a text file created on April 27, 2020 somewhere under the folder where you run this. So adjust the criteria in the `isMatch` function to fit some file you know you have, and be sure to run the script from somewhere higher up in the folder hierarchy above that file.
|
| 208 |
+
|
| 209 |
+
## Creating, Reading, and Altering Files
|
| 210 |
+
|
| 211 |
+
The rest of the methods in the `file` module are various ways to read or change the contents of your disk. Most of these assume that you're working with text files, which includes specialized kinds of text like HTML (web pages), MiniScript script files, and so on.
|
| 212 |
+
|
| 213 |
+
To begin, let's create a new file with MiniScript. You can do this in the command-line REPL:
|
| 214 |
+
|
| 215 |
+
```terminal
|
| 216 |
+
> f = "Test.txt"
|
| 217 |
+
> file.writeLines f, ["Hello world!", "This is a test."]
|
| 218 |
+
29
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
D> Remember, when examples are given for the REPL, you only type what's next to the `>` prompt. Lines without a prompt are output from MiniScript; you don't need to type those.
|
| 222 |
+
|
| 223 |
+
Line 1 in the example above assigns a file name to `f`, and then the `file.writeLines` call on line 2 creates a file with that name in the default directory. The contents of the file are the second parameter to `file.writeLines`. This should be either a string, or a list of strings. The return value (29 in this example) is the length of the file created, in bytes.
|
| 224 |
+
|
| 225 |
+
To verify that it worked, switch over to File Explorer or Finder, and look in the folder you were using as your current directory. You should see a new file there called "Test.txt", and if you open it up, you'll find it contains two lines, "Hello world!" and "This is a test."
|
| 226 |
+
|
| 227 |
+
Switching back to MiniScript, you can verify that the file is there with `file.children`. Then, let's read it from disk back into memory:
|
| 228 |
+
|
| 229 |
+
```terminal
|
| 230 |
+
> data = file.readLines(f)
|
| 231 |
+
> data
|
| 232 |
+
["Hello world!", "This is a test."]
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
Isn't that easy? You already know how to work with strings and lists, so now that you can read and write a file as a list of strings, you can do almost anything with text files on disk! Keep in mind that our file specifier here ("Test.txt") was just a file name, which is a minimal kind of partial path. You can also use a longer partial path, or an absolute path. Any of these ways of specifying the file will work.
|
| 236 |
+
|
| 237 |
+
Now let's wrap up with other file operations you might need to do from time to time. To make a copy of the file, just call `file.copy` with the path (partial or absolute) to the original file, and where you want the copy to be:
|
| 238 |
+
|
| 239 |
+
```terminal
|
| 240 |
+
> file.copy f, "Test Copy.txt"
|
| 241 |
+
1
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
And now delete that copy using — you guessed it — `file.delete`:
|
| 245 |
+
|
| 246 |
+
```terminal
|
| 247 |
+
> file.delete "Test Copy.txt"
|
| 248 |
+
1
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
If you want to move or rename a file, use `file.move`. These sound like two different operations, but to the computer, they're really the same thing: changing the path at which a file is stored. You can think of it as "moving" the file if you specify a path to a different directory, or merely "renaming" the file if you specify a different name in the same directory.
|
| 252 |
+
|
| 253 |
+
```terminal
|
| 254 |
+
> file.move f, "Toast.txt"
|
| 255 |
+
1
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
Finally, if you need to create a directory in MiniScript, you can use `file.makedir`.
|
| 259 |
+
|
| 260 |
+
```terminal
|
| 261 |
+
> file.makedir "TestStuff"
|
| 262 |
+
1
|
| 263 |
+
> file.move "Toast.txt", file.child("TestStuff", "Toast.txt")
|
| 264 |
+
1
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
In this example, the `file.makedir` call on line 1 creates a new folder, and then on line 3 we move the "Toast.txt" file into it, using `file.child` to construct a proper partial path for the destination. That would be `TestStuff\\Toast.txt` on Windows, or `TestStuff/Toast.txt` on other platforms.
|
| 268 |
+
|
| 269 |
+
## Using Your New Superpower
|
| 270 |
+
|
| 271 |
+
As you become a programmer, you will be working with lots of files. When you make games, you will have folders full of sprite images and sounds. If you manipulate scientific data, you'll have files of data points that need summarized, analyzed, and collated. If you do business programming, you'll have files of sales receipts, tax records, and email attachments. Even if you just use programming for your own purposes around the house, you'll sooner or later see that you have thousands of photos or scans of children's drawings or *something* that could use some attention.
|
| 272 |
+
|
| 273 |
+
When most people realize they need to rename, sort through, or otherwise work on hundreds or thousands of files, they have to either find some specialized tool that does that, or else they simply give up and abandon the idea. But you're not most people. You are learning how to code, and that makes tasks possible for you that would be impractical or impossible otherwise.
|
| 274 |
+
|
| 275 |
+
I can't tell you exactly what those tasks will be and how to do them, because they're likely to be very specialized to your needs. If they were *general* needs that lots of people have, there would probably already be some easy solution programmed by somebody else. The real power of programming is that you can solve problems that are *not* common; problems that may be unique to you and what you want to accomplish.
|
| 276 |
+
|
| 277 |
+
So, start thinking about it. When you encounter a problem on a computer, especially if it involves some repetitive task that would have to be done a mind-numbingly large number of times, consider whether you could write a program to do it for you. It might take you an hour or two to write and debug the program — but if it saves you weeks of work, or makes possible something that wouldn't be possible at all otherwise, it's worth it!
|
| 278 |
+
|
| 279 |
+
Just to get those juices flowing, let's work through a small example. Let's start by creating 14 fake data files called `Data1.dat` through `Data14.dat`:
|
| 280 |
+
|
| 281 |
+
```terminal
|
| 282 |
+
> for i in range(1,14)
|
| 283 |
+
>>> file.writeLines "Data" + i + ".dat", "42"
|
| 284 |
+
>>> end for
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
That alone was pretty neat — a lot faster than using a text editor to create the first one, then using File Explorer to manually copy it 13 times! But that's just setting up our example. Now let's suppose you're working with some other tool that needs files like these to be named with the index padded to 5 digits, and following a dash, like `Data-00012.dat`. And imagine instead of 14, there were hundreds or thousands of these, so that manually renaming them would take too long. MiniScript to the rescue!
|
| 288 |
+
|
| 289 |
+
This one is a little longer, so it's probably worth creating a script file (perhaps call it *renamer.ms* or something similar).
|
| 290 |
+
|
| 291 |
+
{caption:File renamer}
|
| 292 |
+
```miniscript
|
| 293 |
+
for f in file.children
|
| 294 |
+
// make sure it's one of the files we care about
|
| 295 |
+
// (i.e. starts with Data, and ends with .dat)
|
| 296 |
+
if f[:4] != "Data" or f[-4:] != ".dat" then
|
| 297 |
+
print "Ignoring " + f
|
| 298 |
+
continue
|
| 299 |
+
end if
|
| 300 |
+
|
| 301 |
+
// Extract the number (after "Data" but before ".dat")
|
| 302 |
+
num = f[4:-4]
|
| 303 |
+
|
| 304 |
+
// Zero-pad it, and compute the new file name
|
| 305 |
+
num = ("00000" + num)[-5:]
|
| 306 |
+
newName = "Data-" + num + ".dat"
|
| 307 |
+
|
| 308 |
+
// Rename the file, and print what we did
|
| 309 |
+
file.move f, newName
|
| 310 |
+
print "Renamed " + f + " to " + newName
|
| 311 |
+
end for
|
| 312 |
+
```
|
| 313 |
+
|
| 314 |
+
Run this with MiniScript in the same folder as your data files, and voilà! They are all instantly renamed according to the needed pattern.
|
| 315 |
+
|
| 316 |
+
I've actually had needs like this from time to time. If you haven't yet, it may not fully sink in how cool it is — but someday, you'll be faced with the need for something like this, and you'll be glad you have the ability to do it with code.
|
| 317 |
+
|
| 318 |
+
A> **Chapter Review**
|
| 319 |
+
A> - You learned about the `file` module in command-line MiniScript (also found in Mini Micro).
|
| 320 |
+
A> - You know know how to create, delete, read, write, move, and rename files from your MiniScript code.
|
| 321 |
+
A> - You'll be watching for opportunities to use this new ability to make the computer do boring, repetitive file-related tasks for you.
|
data/day14.txt
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 14: Sea Battle Game", startingPageNum:153}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> I don’t understand how people live without creating.
|
| 7 |
+
Q>— Samuel L. Jackson (actor and producer)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Rest and recouperate.
|
| 11 |
+
A> - Enter and play a somewhat larger MiniScript game.
|
| 12 |
+
A> - Review & synthesize what you've learned so far.
|
| 13 |
+
|
| 14 |
+
If you've been doing one chapter a day, you've now been building your programming skills for two weeks. If you've been doing some other pace, that's fine too! Either way, you've now learned all the core basics of programming:
|
| 15 |
+
|
| 16 |
+
- strings, numbers, lists, and maps
|
| 17 |
+
- variables
|
| 18 |
+
- built-in functions like `print`, `input`, and `val`
|
| 19 |
+
- looping with `while` and `for`
|
| 20 |
+
- branching with `if`, `else if`, and `else`
|
| 21 |
+
- defining your own functions
|
| 22 |
+
- object-oriented programming with classes
|
| 23 |
+
- reading, writing, and manipulating files
|
| 24 |
+
|
| 25 |
+
And you've learned how to do all this both on the MiniScript Try-It! page on the web, as well as on the command line. That's a lot of skill!
|
| 26 |
+
|
| 27 |
+
Of course just knowing something is different from being able to do it well. If you've never played the piano, someone could very quickly explain how to press the keys in order to make sound come out, and even to play some simple songs. But you would obviously have plenty of room for improvement through practice. Programming is the same way.
|
| 28 |
+
|
| 29 |
+
You can get some idea of a programmer's level by showing them a page of code.
|
| 30 |
+
|
| 31 |
+
1. The non-programmer can't really make heads or tails of it at all.
|
| 32 |
+
2. A very new programmer will understand most or all of the syntax, and how to look up the bits they don't understand, but may still not grasp what the program is doing.
|
| 33 |
+
3. An intermediate programmer will understand what the program's doing and how it works, though they may not have been able to write such a program themselves.
|
| 34 |
+
4. An advanced programmer could have written the same program from scratch, given only a clear description of the desired behavior.
|
| 35 |
+
|
| 36 |
+
You're probably at level 2 or so at this point, working towards level 3. That's a fine place to be, and it's a place every advanced programmer has been. To progress further, all you need is practice. Just as when learning a musical instrument, the more you practice, the faster you will improve.
|
| 37 |
+
|
| 38 |
+
One of the easiest and most quickly rewarding ways to practice is by typing in programs written by advanced programmers. This is no different from a musical composer, who begins by playing music composed by others. In following the footsteps of the creators before you, you learn a great deal about how to make your own creations.
|
| 39 |
+
|
| 40 |
+
So today we're going to take a break from learning new things, and instead review and practice with a moderately-sized MiniScript game. I encourage you not to skip typing this in on your own computer. Typing it in engages your brain substantially more than just reading it. Also, you are sure to make some mistakes in entering the code, and those *really* engage your brain as you track them down. I can almost see your programming muscles growing stronger already! Let's dig in.
|
| 41 |
+
|
| 42 |
+

|
| 43 |
+
|
| 44 |
+
## The *Sea Battle* Game
|
| 45 |
+
|
| 46 |
+
The game today is a classic guessing game for two players, though in our implementation, one of those players will be the computer! Each player has five ships of various sizes, arranged on a 9 by 11 grid. The position of your opponent's ships are unknown to you. On each turn, you guess a grid cell to fire at, and you are told only whether your shot hit a ship, or missed. When all the cells covered by a ship have been hit, it sinks, and the first player to sink all of their opponent's ships wins the game.
|
| 47 |
+
|
| 48 |
+
This game will be too big for the Try-It! page, so you'll need to use command-line MiniScript (or you can use Mini Micro, if you aready know how to do so). Create a text file called "battle.ms", and enter the following:
|
| 49 |
+
|
| 50 |
+
{caption: "Listing 1 (Sea Battle begins)."}
|
| 51 |
+
```miniscript
|
| 52 |
+
// Sea Battle
|
| 53 |
+
print "Welcome to SEA BATTLE!"
|
| 54 |
+
print
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
Save this somewhere that you can easily find the path to it on the command line. You could save it right next to the `miniscript` executable if you want, and then running it would be a matter of changing to that directory (with `cd`), and then entering:
|
| 58 |
+
|
| 59 |
+
```terminal
|
| 60 |
+
miniscript battle.ms
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
For readers still not too used to the command line, this may be the hardest step, since I can't tell you exactly how to do it — it depends on what sort of computer you have, and where you have stored command-line MiniScript and your `battle.ms` file. If you need to, go back and review Chapters 8 and 9, where we learned how to use command-line MiniScript to run a script file. Make sure you can get this much to run before you go on.
|
| 64 |
+
|
| 65 |
+
Notice what we did here: we began with just a tiny piece of the program. This is the right way to approach any program, and is in fact exactly what professional programmers do!
|
| 66 |
+
|
| 67 |
+
D> When building a large program, never try to do it all at once. Instead, build it up from smaller pieces, always testing and debugging as you go.
|
| 68 |
+
|
| 69 |
+
PRINT>Now that we have a working (trivial) script, the next most important thing we have to do is figure out how we are going to represent the data in the game. Each player has a couple of map grids: one that shows their own ships, along with where their opponent has fired; and one that keeps track of where they have fired at their opponent. Each cell in a grid is referred to with coordinates like "C5", where the letter (A-K) indicates the column, and the number (1-9) indicates the row. See the diagram at the top of the next page.
|
| 70 |
+
|
| 71 |
+
EBOOK>Now that we have a working (trivial) script, the next most important thing we have to do is figure out how we are going to represent the data in the game. Each player has a couple of map grids: one that shows their own ships, along with where their opponent has fired; and one that keeps track of where they have fired at their opponent. Each cell in a grid is referred to with coordinates like "C5", where the letter (A-K) indicates the column, and the number (1-9) indicates the row. See the diagram below.
|
| 72 |
+
|
| 73 |
+

|
| 74 |
+
|
| 75 |
+
There are several ways we could represent such a grid in MiniScript. We could use a list of lists, indexed by row and column number. But instead we're going to use the `map` data type, where the key is a coordinate string like "C5", and the value is a character that indicates an empty cell, a part of a ship, a hit, or a miss.
|
| 76 |
+
|
| 77 |
+
So, having figured that out, go ahead and add the code in Listing 2 to your `battle.ms` file. (Note that the line numbers start at 5 because line 4, not shown, is blank.)
|
| 78 |
+
|
| 79 |
+
{caption: "Listing 2 (Sea Battle data model).", number-from: 5}
|
| 80 |
+
```miniscript
|
| 81 |
+
rows = "987654321".split("")
|
| 82 |
+
cols = "ABCDEFGHIJK".split("")
|
| 83 |
+
|
| 84 |
+
shipTypes = {
|
| 85 |
+
"Battleship": "BBBBB",
|
| 86 |
+
"Destroyer": "DDDD",
|
| 87 |
+
"Cruiser": "CCC",
|
| 88 |
+
"Frigate": "FFF",
|
| 89 |
+
"Patrol Boat": "PP" }
|
| 90 |
+
|
| 91 |
+
EMPTY = "."
|
| 92 |
+
MISS = "w"
|
| 93 |
+
HIT = "*"
|
| 94 |
+
|
| 95 |
+
newMap = function()
|
| 96 |
+
m = {}
|
| 97 |
+
for r in rows
|
| 98 |
+
for c in cols
|
| 99 |
+
m[c + r] = EMPTY
|
| 100 |
+
end for
|
| 101 |
+
end for
|
| 102 |
+
return m
|
| 103 |
+
end function
|
| 104 |
+
|
| 105 |
+
print "rows: " + rows
|
| 106 |
+
print "cols: " + cols
|
| 107 |
+
print "test map: " + newMap
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
Those last three lines are just test code that we'll remove in a moment. But when you run this, after the "Welcome to SEA BATTLE!" message, you should see `rows` printed as a list of strings from "9" to "1", and "cols" as a list of strings from "A" to "K". You'll also see a test map printed as a rather large dictionary, with lots of coordinates like "A9" and "K5", all mapped to the string ".", which represents an empty cell.
|
| 111 |
+
|
| 112 |
+
Strings like "." in this program are sometimes called *magic strings*.
|
| 113 |
+
|
| 114 |
+
magic string
|
| 115 |
+
: a string literal that has special meaning to the code, so that if you were to change it in one place without changing it elsewhere, the code would no longer work properly
|
| 116 |
+
|
| 117 |
+
Magic strings are generally not considered a good thing, because it's so easy to mess them up. So rather than using the string literals everywhere we need to refer to an empty cell, we assign this magic string to a variable called `EMPTY` on line 15 (and do something similar for the strings that represent a hit or miss). Now, throughout the code, we use this variable instead of the string literal. So if you decided you wanted to use something else — perhaps a space — instead of a dot to represent an empty cell, you would just change it on line 15, and the program would still work.
|
| 118 |
+
|
| 119 |
+
You probably also noticed the `shipTypes` map, which maps each ship to a string of letters that will represent it on the map. You can change those too, as long as you stick to two rules: all the letters for a particular ship must be the same, and no two ships can use the same letters. We'll assume these rules later when working out whether a ship has sunk.
|
| 120 |
+
|
| 121 |
+
Once you have that much working, let's keep going! Delete those last few lines (29-31), and continue with Listing 3.
|
| 122 |
+
|
| 123 |
+
{caption: "Listing 3 (Sea Battle input validation).", number-from: 29}
|
| 124 |
+
```miniscript
|
| 125 |
+
isRow = function(s)
|
| 126 |
+
return rows.indexOf(s) != null
|
| 127 |
+
end function
|
| 128 |
+
isCol = function(s)
|
| 129 |
+
return cols.indexOf(s) != null
|
| 130 |
+
end function
|
| 131 |
+
|
| 132 |
+
// Get coordinates from the user, and return as string in
|
| 133 |
+
// standard form, e.g. "A1" (to index into one of our sea maps).
|
| 134 |
+
inputCoordinates = function(prompt)
|
| 135 |
+
while true
|
| 136 |
+
s = input(prompt).upper
|
| 137 |
+
if s.len == 2 and isRow(s[0]) and isCol(s[1]) then
|
| 138 |
+
return s[1] + s[0]
|
| 139 |
+
else if s.len == 2 and isRow(s[1]) and isCol(s[0]) then
|
| 140 |
+
return s
|
| 141 |
+
end if
|
| 142 |
+
print "Please enter a map position like A1 or G8."
|
| 143 |
+
end while
|
| 144 |
+
end function
|
| 145 |
+
|
| 146 |
+
print inputCoordinates("Map position? ")
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
This part begins by defining a couple of handy functions to determine whether a given character is a valid row indicator (like "5") or column indicator (like "E"). They work by calling `indexOf` to find the index of the given character in our `rows` or `cols` list; if the character is not found, then `indexOf` returns `null`.
|
| 150 |
+
|
| 151 |
+
Then we define an `inputCoordinates` function that displays a prompt asking the user for a grid coordinate, and keeps asking until it gets a valid answer. It also standardizes that answer, so even if you enter "c5" or "5c" or "5C", it will be returned as "C5".
|
| 152 |
+
|
| 153 |
+
Again we have tacked a bit of test code to the end of this block. So, type in the above, and test it a few times, trying both valid and invalid map positions. Make sure it works before moving on.
|
| 154 |
+
|
| 155 |
+
What's next? The game has two players, and the data for each player is identical: two map grids, plus a list of ships that haven't been sunk yet. Any time you see a need for a collection of data, defining a class is probably a good idea; and if you have a need for two or more such collections, then a class is *definitely* a good idea.
|
| 156 |
+
|
| 157 |
+
So in Listing 4, we will define a Player class, including a function to initialize it, and a function to print out its maps. (In normal play we will never print the computer player's maps, but we might want to for debugging, so it's handy to have it as a general function on the Player class.) Again, remember to remove the test code (line 50) from your script before adding the new code.
|
| 158 |
+
|
| 159 |
+
{caption: "Listing 4 (Sea Battle Player class).", number-from: 50}
|
| 160 |
+
```miniscript
|
| 161 |
+
Player = {}
|
| 162 |
+
|
| 163 |
+
Player.init = function()
|
| 164 |
+
self.myMap = newMap
|
| 165 |
+
self.targetMap = newMap
|
| 166 |
+
self.shipsLeft = [] // names of ships not yet sunk
|
| 167 |
+
end function
|
| 168 |
+
|
| 169 |
+
Player.print = function()
|
| 170 |
+
print " YOUR SHIPS TARGET MAP" // 9 spaces in middle
|
| 171 |
+
print " +-----------+ +-----------+" // 9 dashes per group
|
| 172 |
+
for r in rows
|
| 173 |
+
temp = [r, "|"]
|
| 174 |
+
for c in cols
|
| 175 |
+
temp.push self.myMap[c + r]
|
| 176 |
+
end for
|
| 177 |
+
temp.push "| " + r + "|"
|
| 178 |
+
for c in cols
|
| 179 |
+
temp.push self.targetMap[c + r]
|
| 180 |
+
end for
|
| 181 |
+
temp.push "|"
|
| 182 |
+
print temp.join("")
|
| 183 |
+
end for
|
| 184 |
+
print " +-----------+ +-----------+"
|
| 185 |
+
print " " + cols.join("") + " " + cols.join("")
|
| 186 |
+
end function
|
| 187 |
+
|
| 188 |
+
p = new Player
|
| 189 |
+
p.init
|
| 190 |
+
p.print
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
Q> "Type it in, save it, test it out, HEY-O!"
|
| 194 |
+
Q> —lyrics from hit single *Code Me* by Noobz 2 Guruz
|
| 195 |
+
|
| 196 |
+
Each player has a map (created with the `newMap` function from Listing 2) called `myMap` that represents their own ships, and another one called `targetMap` that keeps track of where they have fired at the other player. The `Player.print` function prints these out side by side. It's a big function, but the structure is fairly simple: it loops over the rows, with smaller loops on each row looping over columns to print data from `myMap` (lines 63-65) and then `targetMap` (lines 67-79). Count your spaces and dashes carefully as you type them in, and the result should look like this.
|
| 197 |
+
|
| 198 |
+
{width:75%}
|
| 199 |
+

|
| 200 |
+
|
| 201 |
+
It's starting to look like a game! And you're more than a third done. Maybe stretch your legs a bit, and then delete lines 77-79, and enter Listing 5.
|
| 202 |
+
|
| 203 |
+
{caption: "Listing 5 (Sea Battle `writeToMap` function).", number-from: 77}
|
| 204 |
+
```miniscript
|
| 205 |
+
// Write a string representing a ship into our map, or optionally,
|
| 206 |
+
// just check whether we COULD write such a string. Return an
|
| 207 |
+
// error string if it runs out of bounds or hits another ship;
|
| 208 |
+
// or if everything is OK, then return null.
|
| 209 |
+
Player.writeToMap = function(ship, position, horizontal, checkOnly)
|
| 210 |
+
c = position[0] // column, e.g. "E"
|
| 211 |
+
r = position[1] // row, e.g. "5"
|
| 212 |
+
for i in ship.indexes
|
| 213 |
+
// check and maybe write to the map
|
| 214 |
+
if self.myMap[c + r] != EMPTY then return "Position blocked"
|
| 215 |
+
if not checkOnly then self.myMap[c + r] = ship[i]
|
| 216 |
+
|
| 217 |
+
// then, advance to the next position (unless we're done)
|
| 218 |
+
if i == ship.len-1 then return // all done!
|
| 219 |
+
if horizontal then
|
| 220 |
+
idx = cols.indexOf(c) + 1
|
| 221 |
+
if idx >= cols.len then return "Out of bounds"
|
| 222 |
+
c = cols[idx]
|
| 223 |
+
else
|
| 224 |
+
idx = rows.indexOf(r) + 1
|
| 225 |
+
if idx >= rows.len then return "Out of bounds"
|
| 226 |
+
r = rows[rows.indexOf(r) + 1]
|
| 227 |
+
end if
|
| 228 |
+
end for
|
| 229 |
+
end function
|
| 230 |
+
|
| 231 |
+
p = new Player
|
| 232 |
+
p.init
|
| 233 |
+
p.writeToMap "DDDD", "C4", true, false
|
| 234 |
+
p.print
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
This is a somewhat tricky but important function. The job of this function is to check whether a ship can be placed at a given position and orientation in the map, and optionally, to actually place it there by writing the letters that represent the ship into the map. The function takes four parameters: the string representing the ship (e.g. "DDD" for the destroyer), a board position like "E5", a true/false value indicating whether the ship should be laid out horizontally, and another true/false value determining whether the function should only check if the ship fits, or actually write it to the map.
|
| 238 |
+
|
| 239 |
+
Why do we have this check-only behavior? Determining if the ship can fit is a bit tricky. It doesn't fit if it goes off the edge of the grid, or if it hits a spot that is not empty (because some earlier ship was already using that spot). If we're placing a big ship, the first few spots might be fine, but the next spot blocked. If we were writing the ship letters into the map as we go, then after we discovered the problem, we'd have to go back and erase the already-written letters. So instead, when placing a ship, we will call this function twice: once to check if it will fit (with the `checkOnly` parameter set to `true`), and then again to actually write it (with `checkOnly` set to `false`).
|
| 240 |
+
|
| 241 |
+
The test code in Listing 5 is a bit thin. But if all is working, you should see the destroyer placed as "DDDD" in cells C4 through F4. If you want to add some additional tests to make sure it returns an error if you give it an invalid ship placement, feel free! Move on when you're ready.
|
| 242 |
+
|
| 243 |
+
The next step will be to use that function to let the player place a ship. This function prompts the user for a location (using the `inputCoordinates` function from Listing 3) and an orientation, either horizontal or vertical. Then it calls the `writeToMap` function above twice, once to check, and once to actually do it.
|
| 244 |
+
|
| 245 |
+
{caption: "Listing 6 (Sea Battle `placeShipByInput` function).", number-from: 103}
|
| 246 |
+
```miniscript
|
| 247 |
+
Player.placeShipByInput = function(name)
|
| 248 |
+
self.print
|
| 249 |
+
print
|
| 250 |
+
self.shipsLeft.push name
|
| 251 |
+
ship = shipTypes[name]
|
| 252 |
+
while true // keep trying till we succeed
|
| 253 |
+
print "Placing " + name + " (size " + ship.len + ")."
|
| 254 |
+
pos = inputCoordinates(" Top-left coordinates? ")
|
| 255 |
+
hv = ""
|
| 256 |
+
while hv != "H" and hv != "V"
|
| 257 |
+
hv = input(" Horizontal or Vertical (H/V)? ").upper
|
| 258 |
+
end while
|
| 259 |
+
err = self.writeToMap(ship, pos, hv=="H", true) // just check
|
| 260 |
+
if err then
|
| 261 |
+
print err + ". Please try again!"
|
| 262 |
+
else
|
| 263 |
+
self.writeToMap ship, pos, hv=="H", false // place ship
|
| 264 |
+
return // and we're done
|
| 265 |
+
end if
|
| 266 |
+
end while
|
| 267 |
+
end function
|
| 268 |
+
|
| 269 |
+
p = new Player
|
| 270 |
+
p.init
|
| 271 |
+
p.placeShipByInput "Destroyer"
|
| 272 |
+
p.placeShipByInput "Battleship"
|
| 273 |
+
p.print
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
Run this several times, trying different positions and orientations, including some that would run off the map, or place the ships overlapping. The code should detect the problem, and keep prompting you until you pick a valid place.
|
| 277 |
+
|
| 278 |
+
We're also going to need a function to place ships randomly. In the finished game, this is used by the computer player to place its ships. However during development, I also used it for the human player, so that I could get into a game more quickly and test whatever I was working on without having to place each of my ships.
|
| 279 |
+
|
| 280 |
+
(Note that you can save yourself a bit of typing by not deleting the test code from Listing 6, but instead only updating it to match Listing 7.)
|
| 281 |
+
|
| 282 |
+
{caption: "Listing 7 (Sea Battle `placeShipRandomly` function).", number-from: 125}
|
| 283 |
+
```miniscript
|
| 284 |
+
Player.placeShipRandomly = function(name)
|
| 285 |
+
self.shipsLeft.push name
|
| 286 |
+
ship = shipTypes[name]
|
| 287 |
+
while true // keep trying till we succeed
|
| 288 |
+
pos = cols[rnd * cols.len] + rows[rnd * rows.len]
|
| 289 |
+
horizontal = (rnd < 0.5)
|
| 290 |
+
err = self.writeToMap(ship, pos, horizontal, true) // check
|
| 291 |
+
if err then continue
|
| 292 |
+
self.writeToMap ship, pos, horizontal, false // place ship
|
| 293 |
+
return // and we're done
|
| 294 |
+
end while
|
| 295 |
+
end function
|
| 296 |
+
|
| 297 |
+
p = new Player
|
| 298 |
+
p.init
|
| 299 |
+
p.placeShipRandomly "Destroyer"
|
| 300 |
+
p.placeShipRandomly "Battleship"
|
| 301 |
+
p.print
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
Now we're getting there! The core of the game is firing shots at your opponent's map. We need a function that does that, checks the opponent's map, reports *hit* or *miss*, and records the shot in both player's maps. That function is given in Listing 8. (Lines 141 and 156 are long enough to wrap in this book, but just keep typing in your text editor; do not insert a line break.)
|
| 305 |
+
|
| 306 |
+
{caption: "Listing 8 (Sea Battle `fire` function).", number-from: 138}
|
| 307 |
+
```miniscript
|
| 308 |
+
// Fire at the other player's map.
|
| 309 |
+
// Print HIT or MISS, and return the name of the ship sunk (if any)
|
| 310 |
+
Player.fire = function(pos, otherPlayer)
|
| 311 |
+
if otherPlayer.myMap[pos] == EMPTY or otherPlayer.myMap[pos] == MISS then
|
| 312 |
+
print "Miss!"
|
| 313 |
+
otherPlayer.myMap[pos] = MISS
|
| 314 |
+
self.targetMap[pos] = MISS
|
| 315 |
+
else
|
| 316 |
+
print "HIT!"
|
| 317 |
+
wait
|
| 318 |
+
otherPlayer.myMap[pos] = HIT
|
| 319 |
+
self.targetMap[pos] = HIT
|
| 320 |
+
// Check for a ship that's been sunk.
|
| 321 |
+
// Every ship has a unique letter, so we know it's sunken if
|
| 322 |
+
// that letter is not found anywhere in the map.
|
| 323 |
+
for name in otherPlayer.shipsLeft
|
| 324 |
+
if otherPlayer.myMap.indexOf(name[0]) == null then
|
| 325 |
+
// This ship is not found, so it has been sunk.
|
| 326 |
+
otherPlayer.shipsLeft.remove otherPlayer.shipsLeft.indexOf(name)
|
| 327 |
+
return name
|
| 328 |
+
end if
|
| 329 |
+
end for
|
| 330 |
+
end if
|
| 331 |
+
end function
|
| 332 |
+
|
| 333 |
+
p = new Player
|
| 334 |
+
p.init
|
| 335 |
+
p.writeToMap "DDDD", "C4", true, false
|
| 336 |
+
p2 = new Player
|
| 337 |
+
p2.init
|
| 338 |
+
p2.fire "E6", p // should miss
|
| 339 |
+
p2.fire "E4", p // should hit
|
| 340 |
+
p.print
|
| 341 |
+
```
|
| 342 |
+
|
| 343 |
+
When you run that, it should fire two shots: the first one at E6 misses, but the second one at E4 hits. The result should look like the figure below.
|
| 344 |
+
|
| 345 |
+
{width:"75%"}
|
| 346 |
+

|
| 347 |
+
|
| 348 |
+
If you want to test this more thoroughly, try including enough `fire` calls to cover the entire ship. Also, print out the result of the last one; the function should return the name of a ship sunk, or `null` if nothing is sunk.
|
| 349 |
+
|
| 350 |
+
The last function we need for our Sea Battle game is one to choose the computer's move. This is the AI (artificial intelligence) of the game... though our version is really not very intelligent. It just chooses a move randomly.
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
{caption: "Listing 9 (Sea Battle AI).", number-from: 163}
|
| 354 |
+
```miniscript
|
| 355 |
+
// Here is the "AI" of the game, that is, the code that decides
|
| 356 |
+
// what to do on the computer's turn.
|
| 357 |
+
ai = function()
|
| 358 |
+
while true // repeat until we find spot we haven't tried
|
| 359 |
+
r = rows[rnd * rows.len]
|
| 360 |
+
c = cols[rnd * cols.len]
|
| 361 |
+
if comp.targetMap[c + r] == EMPTY then break
|
| 362 |
+
end while
|
| 363 |
+
print "I fire at " + c + r + "..."
|
| 364 |
+
sunk = comp.fire(c+r, human)
|
| 365 |
+
if sunk then print "Ha ha! I sunk your " + sunk + "!"
|
| 366 |
+
end function
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
No test code on this one, because it's referencing two global variables that we haven't defined yet. So go ahead and remove the previous test code, add Listing 9, save it, and run it. If you see just the welcome message, you're ready to move on to the next part, where we actually define those global variables.
|
| 370 |
+
|
| 371 |
+
{caption: "Listing 10 (Sea Battle player setup).", number-from: 176}
|
| 372 |
+
```miniscript
|
| 373 |
+
// Set up the human player
|
| 374 |
+
human = new Player
|
| 375 |
+
human.init
|
| 376 |
+
for s in shipTypes.indexes
|
| 377 |
+
human.placeShipByInput s // (or placeShipRandomly to speed things up)
|
| 378 |
+
end for
|
| 379 |
+
human.print
|
| 380 |
+
|
| 381 |
+
// Now set up the computer player
|
| 382 |
+
comp = new Player
|
| 383 |
+
comp.init
|
| 384 |
+
for s in shipTypes.indexes
|
| 385 |
+
comp.placeShipRandomly s
|
| 386 |
+
end for
|
| 387 |
+
comp.print // <-- Just for debugging. (No cheating!)
|
| 388 |
+
```
|
| 389 |
+
|
| 390 |
+
When you run at this point, it should present you with a blank board, and then prompt you to place each of your ships, using the `for` loop on lines 179-181. Your map layout is printed after each entry. Then the computer very quickly places its ships, using its own `for` loop on lines 189-189, and that is printed as well, just so you can be sure it worked.
|
| 391 |
+
|
| 392 |
+
And now we're almost done! All that's left is the main game loop. Be sure to comment out that `comp.print` call on line 190, since the game doesn't have much challenge if you know where the computer's ships are!
|
| 393 |
+
|
| 394 |
+
{caption: "Listing 11 (Sea Battle main loop).", number-from: 190}
|
| 395 |
+
```miniscript
|
| 396 |
+
//comp.print // <-- Just for debugging. (No cheating!)
|
| 397 |
+
|
| 398 |
+
// Main game loop
|
| 399 |
+
while true
|
| 400 |
+
print
|
| 401 |
+
sunk = human.fire(inputCoordinates("Fire at coordinates: "), comp)
|
| 402 |
+
if sunk then print "You sunk my " + sunk + "!"
|
| 403 |
+
if not comp.shipsLeft then
|
| 404 |
+
print "You win. Good game!"
|
| 405 |
+
exit
|
| 406 |
+
end if
|
| 407 |
+
print
|
| 408 |
+
ai
|
| 409 |
+
ai // (a second time, to make game more challenging)
|
| 410 |
+
print
|
| 411 |
+
human.print
|
| 412 |
+
if not human.shipsLeft then
|
| 413 |
+
print "I win! Thanks for the game."
|
| 414 |
+
exit
|
| 415 |
+
end if
|
| 416 |
+
end while
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
And that's it! Each time through the loop, we use `inputCoordinates` to get the human player's move, and `fire` at that location. This returns the name of the ship sunk, if any; so we print that out on line 196. If the computer doesn't have any ships left, then the human has won.
|
| 420 |
+
|
| 421 |
+
Otherwise, we let the computer do its move via the `ai` function. In fact we let it move *twice* (lines 202-203). This is to compensate for the rather stupid AI. I find that this makes for a pretty interesting game -- sheer dumb luck (times two) against human wit. Give it a try, and see how you do!
|
| 422 |
+
|
| 423 |
+
Remember, if you get errors or the behavior of the program is not what you think it should be, just go back and check your typing carefully. Pay attention to spelling, capitalization, and punctuation. Check the end of Chapter 7 for other trouble-shooting tips.
|
| 424 |
+
|
| 425 |
+
## Going Farther
|
| 426 |
+
|
| 427 |
+
You've worked hard today, building this game up section by section. Hopefully you've also built some good habits that will serve you well in the future. It would be completely reasonable to call it a day.
|
| 428 |
+
|
| 429 |
+
But at some point, now or later, you may get the urge to pull this program out again and build on it. The most obvious thing to improve is the AI. Fortunately that's all contained in one function, `ai` (Listing 9). Instead of picking randomly, you might try first guessing any spot next to a hit, and then guessing spots that are far away from any previous guess.
|
| 430 |
+
|
| 431 |
+
Also, over the next week or two you're going to learn how to use Mini Micro. This very same program will run as-is on Mini Micro, using the keyboard and text display... but Mini Micro can do so much more than that. You may want to revisit Sea Battle and put a nice graphical interface on it, or add sounds (or both!).
|
| 432 |
+
|
| 433 |
+
So think of what you did today as a starter kit. You've assembled it according to the directions, but as you acquire more skills and tools, you can build on it to create something uniquely your own.
|
| 434 |
+
|
| 435 |
+
A> **Chapter Review**
|
| 436 |
+
A> - You built the *Sea Battle* game, pitting human versus computer in a classic game of strategy and luck.
|
| 437 |
+
A> - You saw how to build up a big program as a series of smaller tests, stopping to test and debug at each step, rather than doing it all at the end.
|
| 438 |
+
A> - You exercised everything you've learned about MiniScript so far, including functions and classes. The more you use this stuff, the easier it will be!
|
| 439 |
+
|
data/day15.txt
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 15: Introducing Mini Micro", startingPageNum:171}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Engineering isn’t just the physics of how a transistor works. It’s using the technology, and being creative with it, and solving problems that people have or creating something beautiful with it.
|
| 7 |
+
Q>— Limor Fried (engineer, co-founder of Adafruit Industries)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Download and install Mini Micro.
|
| 11 |
+
A> - Learn the basic Mini Micro commands needed to load and run programs.
|
| 12 |
+
A> - Explore the nifty demos that come with it.
|
| 13 |
+
A> - Review the difference between a programming *language* and a programming *environment*.
|
| 14 |
+
|
| 15 |
+
This chapter begins the second half of the book, which is quite honestly the more fun half. *Any* programming is fun, but the fun of text on a web page or terminal window pales in comparison to making pictures, animations, sound effects, and music!
|
| 16 |
+
|
| 17 |
+
For the rest of this book you'll be using *Mini Micro*.
|
| 18 |
+
|
| 19 |
+
Mini Micro
|
| 20 |
+
: a neo-retro virtual home computer from an alternate, much cooler universe
|
| 21 |
+
|
| 22 |
+
Mini Micro is an application you download install on your computer. At the time of this writing, it runs on desktop computers (Windows, Mac, and Linux), though a version for mobile phones and tablets is in the works and may well be done by the time you're reading this. Mini Micro is a MiniScript programming environment, and supports all sorts of fun features:
|
| 23 |
+
|
| 24 |
+
- efficient, interactive graphics
|
| 25 |
+
- synthesized and digitized sounds
|
| 26 |
+
- mouse and keyboard input
|
| 27 |
+
- gamepads and joysticks
|
| 28 |
+
- simple networking
|
| 29 |
+
|
| 30 |
+
Using Mini Micro, you can write your own games and simulations, package them up for any platform (including web browsers), and share them with your friends or post them on sites like itch.io. The rest of this book will teach you what you need to know.
|
| 31 |
+
|
| 32 |
+
## Installing Mini Micro
|
| 33 |
+
|
| 34 |
+
You can download Mini Micro via the MiniScript home page at <https://miniscript.org>. Just click the link that says "Boot up the Mini Micro".
|
| 35 |
+
|
| 36 |
+
That will probably take you to a page that actually has Mini Micro running in demo mode, right within your web browser. Scroll on down and look for the download links, then click the one for your platform (macOS, Windows, or Linux).
|
| 37 |
+
|
| 38 |
+
On Mac or Windows, the download is a zip file. Double-click that to open it up, and in the case of Windows, you should then drag the contents out into another folder (i.e. don't try to run it directly from the zip file). On Linux, the download is a gzipped tar file; unpack that and place it wherever you like.
|
| 39 |
+
|
| 40 |
+
Then double-click the Mini Micro application. It should open a window that looks something like this:
|
| 41 |
+
|
| 42 |
+

|
| 43 |
+
|
| 44 |
+
The details will likely be different: the version number and build date will probably be later than this, and the tip that appears on the third line is selected randomly on each run. But if you see a welcome screen that looks basically like this, with no error messages, then you are ready to go!
|
| 45 |
+
|
| 46 |
+
If you do see an error message, the problem is most likely that it can't find or create a place to store your data. In that case, notice the two slots at the bottom of the window, below the black screen. Those represent *disk slots*. Click the top disk slot, and choose "Mount Folder..." from the menu that appears. Select or create an empty folder wherever you like to store your data (for example, under Documents in your home directory). Then quit Mini Micro, and relaunch it. The errors should be gone, as Mini Micro remembers where you previously told it to store your data.
|
| 47 |
+
|
| 48 |
+
Before you move on, go back to the web page where you downloaded Mini Micro, and scroll down a bit more. You should see a link that says "Mini Micro Cheat Sheet". Download that too; it is a very short PDF that summarizes all the special Mini Micro functions and classes.
|
| 49 |
+
|
| 50 |
+
## Basic Commands
|
| 51 |
+
|
| 52 |
+
After the welcome messages, you will see a `]` prompt with a boxy blinking cursor, very much like a terminal window. This is Mini Micro's command-line interface. It is a REPL (Read, Eval, Print Loop) just like command-line MiniScript. So everything you've learned in the last week still applies! But there are some important differences.
|
| 53 |
+
|
| 54 |
+
First, command-line MiniScript is a thin layer on top of your native operating system (Windows, macOS, or Linux). So, for example, you have to use backslashes on Windows to separate parts of a file path. But Mini Micro is a virtual computer with its own operating system, and works the same regardless of what kind of physical computer you have. It always uses forward slashes in file paths, even on Windows.
|
| 55 |
+
|
| 56 |
+
Similarly, command-line MiniScript is meant to integrate with the built-in command shell of your system. You navigate in your file system with commands like `cd` and `ls` or `dir`, which are all built-in shell commands, not part of MiniScript; and then you run `miniscript` as a separate command when you want to enter the MiniScript REPL, or run MiniScript code stored in a file. Mini Micro is different; the command shell is actually just MiniScript. You don't "run MiniScript" in Mini Micro; it's *always* running.
|
| 57 |
+
|
| 58 |
+
In this regard, Mini Micro is easier than command-line MiniScript. The latter really requires you to know at least two languages: MiniScript, and your command shell language. These have different syntax that you have to keep straight. But in Mini Micro, it's all MiniScript, all the time; you only need to think about one language with one syntax.
|
| 59 |
+
|
| 60 |
+
However, you will still need some commands for navigating around your virtual computer! These are very much like the ones you used in your Windows or Unix/Linux shell, but they are actually just MiniScript functions. These functions are predefined for you as part of the Mini Micro startup process, so they are ready for you to call right away.
|
| 61 |
+
|
| 62 |
+
{i:"Mini Micro, commands;commands, in Mini Micro"}
|
| 63 |
+
| `pwd` | print working directory |
|
| 64 |
+
| `cd` *path* | change working directory |
|
| 65 |
+
| `dir` | list directory contents |
|
| 66 |
+
| `mkdir` *path* | create a new directory |
|
| 67 |
+
| `delete` *path* | delete a file or empty directory |
|
| 68 |
+
| `view` *path* | preview (almost) any file |
|
| 69 |
+
| `clear` | clear the screen |
|
| 70 |
+
| `load` *path* | load a program into memory |
|
| 71 |
+
| `run` | run the currently loaded program |
|
| 72 |
+
| `edit` | edit the currently loaded program |
|
| 73 |
+
| `save` | save the current program to disk |
|
| 74 |
+
| `reset` | clear loaded program and variables |
|
| 75 |
+
|
| 76 |
+
Try it! Type `pwd` into Mini Micro right now, and press Return. You should see:
|
| 77 |
+
|
| 78 |
+
```terminal
|
| 79 |
+
]pwd
|
| 80 |
+
/usr/
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
The current working directory on startup is "/usr/", which represents the root directory of the user disk.
|
| 84 |
+
|
| 85 |
+
user disk
|
| 86 |
+
: the place where all your files are stored; selected with the top disk slot, and referenced in file paths as `/usr`
|
| 87 |
+
system disk
|
| 88 |
+
: the read-only disk where all of Mini Micro's built-in code, images, sounds, and other data are stored; referenced in file paths as `/sys`
|
| 89 |
+
|
| 90 |
+
Now try listing the contents of your user disk with `dir`:
|
| 91 |
+
|
| 92 |
+
```terminal
|
| 93 |
+
]dir
|
| 94 |
+
/usr :
|
| 95 |
+
(Directory empty)
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
Assuming you just downloaded Mini Micro a few minutes ago, it's not surprising your user disk is empty! Remember, this is just your *Mini Micro* user disk. It's *not* the disk of your host (desktop PC) system, though of course ultimately your Mini Micro files must be stored there. We'll get more into the relationship between your Mini Micro files, and the host files, a bit later. For now let's get on to the fun stuff.
|
| 99 |
+
|
| 100 |
+
## Running the Demos
|
| 101 |
+
|
| 102 |
+
You may have caught above that there are two disks available in Mini Micro: `/usr` and `/sys`. (There can actually be a third, /usr2, which accesses a disk file or folder mounted in the second disk slot. But let's ignore that for now.)
|
| 103 |
+
|
| 104 |
+
The `/sys` disk is fun and important because it contains all the built-in goodies that come with Mini Micro. This includes a bunch of fun demos (demonstration programs) and mini-games. Our goal for today is just to play with these. If you thought yesterday was hard work, don't worry — today is pure fun!
|
| 105 |
+
|
| 106 |
+
Use the `cd` command to switch to the `/sys` disk, and then `dir` to list the directory contents.
|
| 107 |
+
|
| 108 |
+
```terminal
|
| 109 |
+
]cd "/sys"
|
| 110 |
+
]dir
|
| 111 |
+
/sys :
|
| 112 |
+
data/ DIR 2020-02-23 06:39:44
|
| 113 |
+
demo/ DIR 2020-03-26 12:32:28
|
| 114 |
+
help/ DIR 2019-11-16 08:02:50
|
| 115 |
+
lib/ DIR 2020-03-13 11:54:12
|
| 116 |
+
pics/ DIR 2020-03-13 13:02:16
|
| 117 |
+
sounds/ DIR 2020-03-13 12:42:50
|
| 118 |
+
startup.ms 8607 2020-03-17 17:16:14
|
| 119 |
+
tips.txt 1229 2019-08-09 16:41:40
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
Notice that we had to put quotation marks around `"/sys"` in the `cd` command. That's different from any Unix/Linux/Windows shell. Why is that?
|
| 123 |
+
|
| 124 |
+
D> Stop and see if you can answer that question yourself. Cover up the rest of the page below while you think about it. Hint: remember that Mini Micro doesn't have a separate command shell; it's all MiniScript, all the time.
|
| 125 |
+
|
| 126 |
+
The reason quotes are needed is that `cd` here is just a MiniScript function, and `"/sys"` is just a MiniScript string. MiniScript requires strings to be quoted. Without the quotation marks, it would look like you were trying to do math (`cd` divided by `sys`), and would not work at all. So even though these *look* like standard shell commands, you must remember the quotation marks.
|
| 127 |
+
|
| 128 |
+
D> Always put quotation marks around paths and file names in Mini Micro.
|
| 129 |
+
|
| 130 |
+
Now examining the file listing that `dir` gave you, you can see a half-dozen subdirectories, plus a MiniScript file (`startup.ms`) and a text file (`tips.txt`). Let's ignore those for a moment and focus on the subdirectories... and in particular, the `demo` directory.
|
| 131 |
+
|
| 132 |
+
```terminal
|
| 133 |
+
]cd "demo"
|
| 134 |
+
]dir
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
I haven't included the result of this `dir` command for two reasons: the demos will have probably changed a bit by the time you read this, and in any case, there are too many! When a directory listing is more than a screenful of lines, you will see something like `[3 more]` in inverse text at the bottom, and Mini Micro will wait for you to press a key. At that point, press the spacebar or Return key to continue, or press Q or Escape to stop the listing there.
|
| 138 |
+
|
| 139 |
+
{i:"`/sys/demo`"}
|
| 140 |
+
What you find in this `/sys/demo` directory is a whole bunch of MiniScript programs. Some of them are tiny, like `countdown.ms`, which is only 70 characters. Others are quite large; the `speedConquest.ms` game is over 24 thousand characters! A few are simple text demos that could have been done in command-line MiniScript or the Try-It! page, but most of them make full use of Mini Micro's power.
|
| 141 |
+
|
| 142 |
+
To play any of these programs, you first `load` it with a full or partial file path, and then `run`. For example:
|
| 143 |
+
|
| 144 |
+
{i:"`/sys/demo`,`mochiBounce`"}
|
| 145 |
+
```terminal
|
| 146 |
+
]load "mochiBounce.ms"
|
| 147 |
+
193 lines loaded from /sys/demo/mochiBounce.ms
|
| 148 |
+
]run
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
{width:"75%"}
|
| 152 |
+

|
| 153 |
+
|
| 154 |
+
PRINT>That should produce a screen that looks like this picture on the previous page.
|
| 155 |
+
EBOOK>That should produce a screen that looks like the picture above.
|
| 156 |
+
|
| 157 |
+
Now you can play the game! Hold the space bar to make the mochi jump, and use the left and right arrow keys to make it veer left or right. See how far you can climb! Be sure your computer speakers are on to hear the sound effects. The game will end when you miss, or you can exit out by pressing the Escape key.
|
| 158 |
+
|
| 159 |
+
D> To exit out of most Mini Micro programs, press Escape. If that doesn't work, you can always break out by pressing Control-C.
|
| 160 |
+
|
| 161 |
+
To try the program again, just enter `run` again. Or as a shortcut, you can press the up-arrow key to bring back the last command, and then hit Return.
|
| 162 |
+
|
| 163 |
+
D> At any blinking input prompt, you can use the up and down arrows to step through previous inputs.
|
| 164 |
+
|
| 165 |
+
That was fun! Let's try a much simpler one. Clear the screen, then load a different demo:
|
| 166 |
+
|
| 167 |
+
```terminal
|
| 168 |
+
]clear
|
| 169 |
+
]load "countdown"
|
| 170 |
+
]run
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
PRINT>This is a very simple program indeed. But let's use it to explore editing and saving a program. Enter `edit`. The Mini Micro program editor opens, as shown in the picture on the next page.
|
| 174 |
+
EBBOK>This is a very simple program indeed. But let's use it to explore editing and saving a program. Enter `edit`. The Mini Micro program editor opens, as shown in the picture below.
|
| 175 |
+
|
| 176 |
+

|
| 177 |
+
|
| 178 |
+
{i: "code editor, Mini Micro"}
|
| 179 |
+
Here you can use the mouse and keyboard as you would in any code editor. It supports undo and redo, cut/copy/paste, a sophisticated search & replace function, a Navigate menu (much more useful on bigger programs), and a Code menu that can insert various code snippets for you. Hover over any of the buttons at the top of the screen for a moment, and the name of the function should appear to tell you what's what.
|
| 180 |
+
|
| 181 |
+
Right now the program counts down from 10 to 1, waiting for 1 second (the default time for `wait`) between each number. Let's say we're impatient. Change line 3 to read
|
| 182 |
+
|
| 183 |
+
{number-from: 3}
|
| 184 |
+
```miniscript
|
| 185 |
+
wait 0.25
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
so that it waits only a quarter second between each number. Now click the "X" (Close) button at the left end of the toolbar. The program editor closes. Now `run` the program again. You should see it count down much faster.
|
| 189 |
+
|
| 190 |
+
But our changes at this point are only in memory; they have not been saved to disk. So if you quit Mini Micro at this point, your changes would be gone. Normally you could just enter `save` (or use the save button in the code editor) to save a file to wherever it came from, but this file came from the `/sys` disk, which is read-only (i.e. you can't write to it). So you will need to supply a path to somewhere on the user disk.
|
| 191 |
+
|
| 192 |
+
```terminal
|
| 193 |
+
]save "/usr/fastCountdown"
|
| 194 |
+
6 lines saved to /usr/fastCountdown.ms
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
Now that you know how to load, run, edit, and save the demos, explore! There are are over two dozen demos in `/sys/demo`, all of them different. Most of them will be fairly obvious how to use; for anything that looks like a graphical game, try the arrow keys and spacebar, or in some cases the mouse. If you see a blinking cursor, type something. A few programs have no input, but just do something interesting on their own.
|
| 198 |
+
|
| 199 |
+
If you have trouble figuring out how to use a demo, `edit` it and read the comments at the top of the file. In fact, even if you *don't* have trouble using a program, look over the script anyway! There may be much you don't understand yet, but don't get discouraged. A few weeks ago you didn't know how to read MiniScript at all, and now you can! And by the end of this book, you'll know how to understand pretty much everything you see in these programs, and be well on your way to writing your own.
|
| 200 |
+
|
| 201 |
+
For now, just skim them over, read the comments at the top, and see if you can find the main loop (usually at the bottom). This will prepare your brain for all the fun new stuff we're going to pour into it over the next two weeks.
|
| 202 |
+
|
| 203 |
+
## Getting Help
|
| 204 |
+
|
| 205 |
+
Mini Micro has a lot of new functions and classes for you to use. Fortunately you don't have to remember them; there are several good resources to teach or remind you about them.
|
| 206 |
+
|
| 207 |
+
This book is one, of course. Here you find more in-depth explanation of the key features and step-by-step examples, all presented in a thoughtful order where each day builds on what you did the days before.
|
| 208 |
+
|
| 209 |
+
Another resource is the `help` command built into Mini Micro. Just type `help` at the prompt and it will print some introductory help, with a prompt to get to more by using `help "topics"`. That leads you to things like `help "files"` or `help "graphics"`. The help you find this way is brief, but may be a good enough reminder if for some reason you don't have any of the other resources on hand.
|
| 210 |
+
|
| 211 |
+
{i:"Mini Micro, Cheat Sheet;documentation, Mini Micro Cheat Sheet"}
|
| 212 |
+
Next, keep in mind the Mini Micro Cheat Sheet, a very short (currently 4-page) expansion of the MiniScript Quick Reference you used in the first half of the book. The additional pages cover almost everything there is to know about Mini Micro: all the built-in classes and functions. They are organized by topic, so you can quickly find what you need. If you don't have this yet, put the book down and go get it! I recommend you keep it handy at all times. I've included a copy of the current version here in the book just to whet your appetite, but go get your own copy that will be both more current, and big enough to read.
|
| 213 |
+
|
| 214 |
+
{width:"95%"}
|
| 215 |
+

|
| 216 |
+
|
| 217 |
+
When you need more detail than the built-in help or the cheat sheet can provide, a good place to turn is the MiniScript Wiki. This is a community-edited reference for everything having to do with MiniScript and Mini Micro. You can find it via the MiniScript home page, or go to it directly at `https://miniscript.org/wiki/`. Once there, follow the link to the Mini Micro page, which contains links to all the special Mini Micro classes and functions, as well as some very handy "How To" articles covering topics like how to make a sprite translucent, how to do simple physics, and so on.
|
| 218 |
+
|
| 219 |
+
Finally, of course, you are encouraged to join the MiniScript community. There is an active Discord server as well as web forums, and users there — including me — will be happy as a clam to help you with your MiniScript and Mini Micro questions. It's also a great place to show off what you have created!
|
| 220 |
+
|
| 221 |
+
{pageBreak}
|
| 222 |
+
## Language vs. Environment
|
| 223 |
+
|
| 224 |
+
I'd like to close this first chapter about Mini Micro with a reminder about the difference between a programming *language* and a programming *environment*.
|
| 225 |
+
|
| 226 |
+
{i:"programming language"}
|
| 227 |
+
MiniScript is a programming *language*. It has a certain syntax: a way of typing in numbers, strings, loops, branches, and so on so that the computer can understand them. It has a system of data types (strings, numbers, lists, maps, and functions), rules about how it looks up identifiers, and so on.
|
| 228 |
+
|
| 229 |
+
{i:"programming environment"}
|
| 230 |
+
Mini Micro is a programming *environment*. The environment provides a context for using the language. You've used MiniScript in at least two other environments already: the Try-It! page on the web, and command-line MiniScript. It's possible you've encountered (or will someday encounter) MiniScript in other contexts too, such as in a game. The language is the same in all these cases, but what you can *do* with it may vary quite a bit with the environment.
|
| 231 |
+
|
| 232 |
+
You already saw all this when you moved from the Try-It! page to command-line MiniScript; only the latter, for example, can access files. But Mini Micro takes this much further. As you explored the demos, you saw all sorts of fancy things going on: animated graphics and text, sound, music, etc. But, all of that is done with the MiniScript language you already know. I'm not going to teach you any new parts of the language, because there aren't any! From here on out, it's just a matter of familiarizing yourself with the extra functions and classes provided by the environment.
|
| 233 |
+
|
| 234 |
+
{pageBreak}
|
| 235 |
+
A> **Chapter Review**
|
| 236 |
+
A> - You installed Mini Micro on your own computer.
|
| 237 |
+
A> - You used Mini Micro commands to load, run, edit, and save programs.
|
| 238 |
+
A> - You explored the nifty demos that come with Mini Micro, to get a good idea of what it can do.
|
| 239 |
+
A> - You learned about the various places you can find helpful information about Mini Micro.
|
| 240 |
+
A> - You reviewed the difference between programming language and programming environment.
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
{gap:100}
|
| 244 |
+
{width:"25%"}
|
| 245 |
+

|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
|
data/day16.txt
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 16: Key Module; MiniScript Files", startingPageNum:187}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Experience is the name everyone gives to their mistakes.
|
| 7 |
+
Q>— Oscar Wilde (poet and playwright, 1854-1900)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Practice editing, saving, and managing your Mini Micro programs.
|
| 11 |
+
A> - Learn how to use the `key` module to interact more directly with the keyboard.
|
| 12 |
+
A> - Discover different ways to access files on the host computer from Mini Micro, and vice versa.
|
| 13 |
+
|
| 14 |
+
Fire up Mini Micro. Today's going to be a fun day!
|
| 15 |
+
|
| 16 |
+
## The `key` module
|
| 17 |
+
|
| 18 |
+
Before today, the only way of getting input from the user has been with the `input` function. That displays a prompt, then waits for the user to type as much as they like, until they press the Return/Enter key; then it returns what they typed as a string. That's fine for many kinds of input, but it has limitations:
|
| 19 |
+
|
| 20 |
+
- No way to enter special keys like Shift, Control, Escape, or F1.
|
| 21 |
+
- No way for the computer to react to a single keypress (other than Return).
|
| 22 |
+
- No way to tell if the user is currently pressing a key.
|
| 23 |
+
|
| 24 |
+
Those limitations are difficult to avoid in general-purpose enviroments like the Try-It! page and command-line MiniScript. But Mini Micro, being a virtual computer, can do much more! With that preamble we introduce `key`, a module of methods for reading the keyboard.
|
| 25 |
+
|
| 26 |
+
{i:"Mini Micro, `key` module;`key` module;keyboard"}
|
| 27 |
+
{caption:"Methods in Mini Micro's `key` module."}
|
| 28 |
+
| `key.available` | returns 1 if a key is in the buffer, 0 if not |
|
| 29 |
+
| `key.get` | return a key from the key buffer, or the next key pressed |
|
| 30 |
+
| `key.clear` | clear the key buffer |
|
| 31 |
+
| `key.pressed(k)` | return 1 if key *k* is currently down |
|
| 32 |
+
| `key.keyNames` | return all names usable with `key.pressed` |
|
| 33 |
+
| `key.axis(h)` | return value of analog axis *h* |
|
| 34 |
+
|
| 35 |
+
Remember that by "module" we really just mean a map containing some functions and other values. Don't take my word for it — check for yourself!
|
| 36 |
+
|
| 37 |
+
```terminal
|
| 38 |
+
]key
|
| 39 |
+
{"available": FUNCTION(), "clear": FUNCTION(), "get": FUNCTION(), "p
|
| 40 |
+
ressed": FUNCTION(keyName="space"), "axis": FUNCTION(axisName="Horiz
|
| 41 |
+
ontal"), "keyNames": FUNCTION()}
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
This just dumps the contents of the `key` module to the screen; it's not pretty, but it's good enough for you to verify what there. So let's try it! Enter:
|
| 45 |
+
|
| 46 |
+
```terminal
|
| 47 |
+
]foo = key.get
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
After entering this method call, Mini Micro doesn't show the usual "]" prompt with blinking cursor... instead it looks like it's frozen. It's actually just waiting for you to press a key! Go ahead and press your favorite letter. (I'm pressing "m" here.) As soon as you do, the prompt and cursor return. Now if you enter `foo`, you can see that it has been assigned whatever key you pressed.
|
| 51 |
+
|
| 52 |
+
That brings up the first good use of `key.get`: waiting for the user to be ready. But now our examples are going to get long enough to be worth using the code editor rather than the REPL (Read-Eval-Print Loop). So enter `edit` at the prompt to launch the Mini Micro code editor. Then type in the following.
|
| 53 |
+
|
| 54 |
+
{caption:"Press any key!"}
|
| 55 |
+
```miniscript
|
| 56 |
+
print "Press any key to begin!"
|
| 57 |
+
key.get
|
| 58 |
+
print "OK, here we go..."
|
| 59 |
+
wait
|
| 60 |
+
print "And we're done!"
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
After typing that in, click the close button in the top-left corner, or press Control-W, which does the same thing. The editor disappears and you're back to the REPL, at a fresh prompt right after `edit`. Now enter `run`, and you should see the program wait for you to indicate you're ready by pressing any key, and then run the rest of the program.
|
| 64 |
+
|
| 65 |
+
```terminal
|
| 66 |
+
]run
|
| 67 |
+
Press any key to begin!
|
| 68 |
+
OK, here we go...
|
| 69 |
+
And we're done!
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
Of course you can't really press *any* key here; `key.get` does not return modifier keys like Shift and Control, nor function keys like F1. It does, however, return values for the Escape key, Return, Delete, Backspace, and arrow keys. Here's a fun way to test exactly what `key.get` returns. Use `edit` again, delete the old code, and enter this.
|
| 73 |
+
|
| 74 |
+
{caption:"`key.get` explorer"}
|
| 75 |
+
```miniscript
|
| 76 |
+
// What exactly does key.get return?
|
| 77 |
+
while true // press Control-C to exit
|
| 78 |
+
k = key.get
|
| 79 |
+
print "char(" + k.code + "): " + k
|
| 80 |
+
end while
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
{pageBreak}
|
| 84 |
+
D> You probably noticed that the Mini Micro code editor indents lines for you. You don't need to press the Tab key within the `while` loop, and you don't need to press the Delete key before typing `end while` — in fact if you do, it deletes the line break and puts you back on the previous line. Just type `end while` in line with the previous line, and the editor will fix it as soon as you're done typing it.
|
| 85 |
+
|
| 86 |
+
D> Pro tip: you can also close any open `while`, `for`, or `if` block automatically by holding the Shift key when you press Return or Enter at the end of a line! This inserts a blank line and the block closer, then positions the cursor on the blank line, ready to add code to the body of the loop.
|
| 87 |
+
|
| 88 |
+
Again press the Close button (or hit Control-W) to exit the editor, and `run` the program. Now try various keys on the keyboard. It should print out the character code, as well as the printable character, if any. You may notice that when you press the Return key, it reports as `char(13)`, and when we print that we get an extra line break. The arrow keys display as `char(17)` through `char(20)`, and print as little arrow symbols. We made an infinite loop here, so just press Control-C to break out of the program when done.
|
| 89 |
+
|
| 90 |
+
This little program is something you might want to run again later, when you're trying to remember exactly what `key.get` returns for some special key. So you'll want to save it, so you can reload it later. Time to get organized!
|
| 91 |
+
|
| 92 |
+
## Organizing Your Files
|
| 93 |
+
|
| 94 |
+
If you enter `pwd` right now, you'll probably find that your current working directory is `/usr/`, the root directory of the user disk. You certainly could just save your program here, but as I hope you will be creating lots and lots of programs in the future, that could get pretty cluttered. It's generally a good idea to sort your stuff into folders. Let's make a folder to contain any examples you enter from this book.
|
| 95 |
+
|
| 96 |
+
{i:"`makedir`;`save`"}
|
| 97 |
+
```terminal
|
| 98 |
+
]cd
|
| 99 |
+
]file.makedir "learnToCode"
|
| 100 |
+
]cd "learnToCode"
|
| 101 |
+
]save "keyGet"
|
| 102 |
+
7 lines saved to /usr/learnToCode/keyGet.ms
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
That `cd` command on line 1 isn't really necessary if you're already in the `/usr/` directory, but it doesn't hurt; without any parameter, `cd` always returns you there. Then the `file.makedir` command creates a new directory, and the next `cd` on line 3 changes your current directory to that one. Finally, the `save` command saves your file.
|
| 106 |
+
|
| 107 |
+
Let's just verify that it really is there.
|
| 108 |
+
|
| 109 |
+
```terminal
|
| 110 |
+
]dir
|
| 111 |
+
/usr/learnToCode :
|
| 112 |
+
keyGet.ms 152 2020-07-18 14:07:18
|
| 113 |
+
]view "keyGet.ms"
|
| 114 |
+
// What exactly does key.get return?
|
| 115 |
+
print "Press any key, or Control-C to exit."
|
| 116 |
+
while true
|
| 117 |
+
k = key.get
|
| 118 |
+
print "char(" + k.code + "): " + k
|
| 119 |
+
end while
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
{i:"`view`"}
|
| 123 |
+
Pretty neat, right? The `dir` command, without any parameters, lists the contents of the current directory, along with the size and date/time of each file. The `view` command can list a program, to verify what's there. (It can also preview images and sounds, but we'll get to those later!)
|
| 124 |
+
|
| 125 |
+
Notice that a program on disk and a program in memory are not the same thing. You saw this yesterday; to run the demos you had to first `load` the program into memory, and then `run` it. To create a new program on disk is basically the same thing in reverse: first you `edit` to create the program, and then `save` it.
|
| 126 |
+
|
| 127 |
+
So we used the `view` command to list a program on disk. How do you list the program in memory? Of course you can `edit` it and see it that way, but you can also use the `source` command.
|
| 128 |
+
|
| 129 |
+
```terminal
|
| 130 |
+
]source
|
| 131 |
+
// What exactly does key.get return?
|
| 132 |
+
print "Press any key, or Control-C to exit."
|
| 133 |
+
while true
|
| 134 |
+
k = key.get
|
| 135 |
+
print "char(" + k.code + "): " + k
|
| 136 |
+
end while
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
There's our program, still in memory!
|
| 140 |
+
|
| 141 |
+
D> The `source` and `edit` commands both operate on the program in memory. The `view` command always displays a file on disk.
|
| 142 |
+
|
| 143 |
+
But we're done with the keyGet program for now. Let's clear it out of memory using the `reset` command.
|
| 144 |
+
|
| 145 |
+
{i:"`reset`"}
|
| 146 |
+
```terminal
|
| 147 |
+
]reset
|
| 148 |
+
Program source cleared and reset
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
If you try `source` now, it doesn't print anything; our current program is empty. Likewise, when you `edit`, you'll be in a blank editor. Do that, and type in this new program:
|
| 152 |
+
|
| 153 |
+
{caption:"Keyboard Dash"}
|
| 154 |
+
```miniscript
|
| 155 |
+
print "Keyboard Dash!"
|
| 156 |
+
print "Press the , and . keys as fast as you can"
|
| 157 |
+
print "to race to the finish line."
|
| 158 |
+
print
|
| 159 |
+
print "Ready..."; wait
|
| 160 |
+
print "Set..."; wait
|
| 161 |
+
print "GO!"
|
| 162 |
+
|
| 163 |
+
lastKey = ""
|
| 164 |
+
count = 0
|
| 165 |
+
startTime = time
|
| 166 |
+
while count < 25
|
| 167 |
+
k = key.get
|
| 168 |
+
if k == lastKey then continue
|
| 169 |
+
if k != "." and k != "," then continue
|
| 170 |
+
count = count + 1
|
| 171 |
+
print count
|
| 172 |
+
end while
|
| 173 |
+
elapsed = time - startTime
|
| 174 |
+
print "DONE!"
|
| 175 |
+
print "You finished in " + elapsed + " seconds. Great job!"
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
This time, before you exit the editor, try hitting the Save button (second button from the left), or pressing Control-S. Because this program has not been saved before, the editor will pop up a little box asking you where to save it.
|
| 179 |
+
|
| 180 |
+
{width:"50%"}
|
| 181 |
+

|
| 182 |
+
|
| 183 |
+
Type `keyboardDash` (with or without a `.ms` suffix), and hit Return/Enter or click Save. The program will be saved, and the program path appears in the toolbar at the top of the screen. Now exit with Control-W (or click the Close button).
|
| 184 |
+
|
| 185 |
+
First, if you like, use the `dir` and `view` commands to verify that your program really was saved to disk. So now you know *two* ways of saving a program: using the `save` command in the REPL, or using the Save button in the editor. Both do the same thing.
|
| 186 |
+
|
| 187 |
+
Finally, run your program, and alternately press the comma and period keys as fast as you can to race to the finish line. How fast can you do it? (My record is about 2.25 seconds.) Find some other people and challenge them to a race!
|
| 188 |
+
|
| 189 |
+
## More Key Methods
|
| 190 |
+
|
| 191 |
+
Sometimes you want to get a key from the user, only if they've pressed one; if they haven't, then you want to continue on with the program. There are two ways to do that. The first is to call `key.get` only if `key.available` is true. Or if you don't care what the key is, you can call `key.clear` to clear it out.
|
| 192 |
+
|
| 193 |
+
{caption:"Reaction test."}
|
| 194 |
+
```miniscript
|
| 195 |
+
print "Press any key to stop the count."
|
| 196 |
+
print "See if you can stop on exactly 50! Get ready..."
|
| 197 |
+
wait
|
| 198 |
+
print "GO!"
|
| 199 |
+
for i in range(1, 100)
|
| 200 |
+
if key.available then break
|
| 201 |
+
print i
|
| 202 |
+
wait 0.05
|
| 203 |
+
end for
|
| 204 |
+
key.clear
|
| 205 |
+
diff = abs(i - 50)
|
| 206 |
+
print "You stopped " + diff + " away from 50."
|
| 207 |
+
if diff < 5 then print "Amazing!"
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
Save this program as "reactionTest", then try it a few times. Notice how we're checking `key.available` within the loop, and when one is available (i.e. the user has pressed a key), we `break` out of the loop. Then we use `key.clear` to clear out the keyboard buffer. In fact, try taking that out, and see what happens!
|
| 211 |
+
|
| 212 |
+
{i:"keyboard buffer"}
|
| 213 |
+
The second way to detect key presses without waiting for them is to use `key.pressed`. This function is quite different from the other key functions we've looked at so far. The `key.available`, `key.get`, and `key.clear` functions all deal with the keyboard *buffer*, the set of printable characters (plus a few editing characters as discovered before) that the user has typed. These can include modified keys like capital letters, $, or π, but they don't include the modifier keys themselves. Also, when you hold a printable key down, it will be entered into the keyboard buffer multiple times, following the same key-repeat behavior you see when typing. Basically, despite being in the "key" module, what these functions actually report is keyboard *input*, one character at a time.
|
| 214 |
+
|
| 215 |
+
The `key.pressed` function is different. It reports on the status (pressed or not pressed) of individual, physical keys on the keyboard. That includes the left and right shift keys, the alt keys, the function keys, and so on. It also includes the printable keys like letters and numbers, but not the shifted version of those; to `key.pressed`, shift-2 is just two keys being pressed, not the at-sign that `key.get` would report.
|
| 216 |
+
|
| 217 |
+
To illustrate, here's a program that counts up only while the left Shift key is held.
|
| 218 |
+
|
| 219 |
+
{caption:"Demonstration of key.pressed."}
|
| 220 |
+
```miniscript
|
| 221 |
+
print "Hold left shift to count up. Press Esc to quit."
|
| 222 |
+
x = 0
|
| 223 |
+
while not key.pressed("escape")
|
| 224 |
+
if key.pressed("left shift") then
|
| 225 |
+
x = x + 1
|
| 226 |
+
print x
|
| 227 |
+
end if
|
| 228 |
+
end while
|
| 229 |
+
key.clear
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
We're actually using `key.pressed` twice in this program: once to break out of the infinite loop with the Escape key, and once to increment the count whenever the left shift key is held. Notice how fast that count goes up!
|
| 233 |
+
|
| 234 |
+
If you're interested in making games, or even interactive simulations, you'll probably be using `key.pressed` a lot. It lets you detect the keys as soon as they're pressed, for as long as they're pressed. It can even detect multiple keys at once, which is handy if you're using them to control a character running and jumping at the same time.
|
| 235 |
+
|
| 236 |
+
What are these magic strings that you use with `key.pressed` to specify the key? Well, you'll find them on the Mini Micro Cheat Sheet, as well as in the `key.keyNames` list (although that list is so long, it won't fit on one screen!). But you should also be aware of the `inputCheck` demo in the `/sys/demo` directory.
|
| 237 |
+
|
| 238 |
+
{i:"`/sys/demo`,`inputCheck`"}
|
| 239 |
+
```terminal
|
| 240 |
+
]cd "/sys/demo"
|
| 241 |
+
]load "inputCheck"
|
| 242 |
+
]run
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
When you run this, mash any keys or combinations of keys on your keyboard or game controller, and the corresponding key or axis names will appear on the screen.
|
| 246 |
+
|
| 247 |
+
We haven't covered axes yet, but it's not too hard: `key.axis` returns a value from -1 to 1 for analog axes, like joystick inputs. Mini Micro also gives you a Horizontal and a Vertical axis usable with the arrow keys and the WASD keys. You can tell axis names from key names because axis names are capitalized, while key names are all lower case.
|
| 248 |
+
|
| 249 |
+
## More on Files
|
| 250 |
+
|
| 251 |
+
You just changed to the `/sys/demo` directory. How do you get back to your files? The same question would apply after you quit Mini Micro and relaunch it again later. You'll soon get comfortable navigating your files, but for now just do:
|
| 252 |
+
|
| 253 |
+
```terminal
|
| 254 |
+
]cd
|
| 255 |
+
]cd "learnToCode"
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
and then follow this with a `dir` to make sure you see your saved files. Remember that the first `cd` above takes you to `/usr/`, your home directory on the user disk. But you could have done it instead in a one-liner:
|
| 259 |
+
|
| 260 |
+
```terminal
|
| 261 |
+
]cd "/usr/learnToCode"
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
Because the path in this case starts with a slash, it is an *absolute* path, and will work no matter where you are. Without an initial slash, it's a *relative* path, and starts in your current directory.
|
| 265 |
+
|
| 266 |
+
## Minidisk Files and Folders
|
| 267 |
+
|
| 268 |
+
For the last topic of this chapter, we're going to dig a little more into how your files are actually stored in the host operating system. This section applies to desktop computers — Windows, Mac, and Linux. If you're running Mini Micro on a tablet or phone, you can safely skip to the end.
|
| 269 |
+
|
| 270 |
+
{i:"disk slot;minidisk file;disk file"}
|
| 271 |
+
Mini Micro has two ways of storing its files. First is a "minidisk file", or just a "disk file" within the context of Mini Micro. Click on the top disk slot below the screen. A menu should pop up that looks like this:
|
| 272 |
+
|
| 273 |
+
{width:"70%"}
|
| 274 |
+

|
| 275 |
+
|
| 276 |
+
{i:"`/usr`"}
|
| 277 |
+
Try selecting the top option, "Unmount /usr". Now use the `dir` command in the REPL. Mini Micro will reply "Invalid path". The "/usr" path references a disk file or folder mounted in the top disk slot, but we just unmounted (removed) that, so there are no files there to view.
|
| 278 |
+
|
| 279 |
+
{i:"mount folder"}
|
| 280 |
+
Click the top slot again, and this time pick "Mount Folder..." A folder selection dialog appears, this time showing real files on your host (Windows, Mac, or Linux) computer. Choose some folder in your home directory, perhaps something with some text or picture files in it. Now use the `cd` command to make sure your working directory is set to `/usr/`, and use the `dir` command again. You should see the contents of the folder you selected, presented in Mini Micro as a file listing. You can use the `view` command to view any files with a suffix like `.txt`, `.png`, `.jpg`, or `.wav`.
|
| 281 |
+
|
| 282 |
+
Moreover, if you used the `file` module (from Chapter 13) to create, delete, or alter files here in Mini Micro, you would see those changes reflected in File Explorer or Finder on your host operating system. (So please be careful!)
|
| 283 |
+
|
| 284 |
+
{i:"mount disk file"}
|
| 285 |
+
Assuming that your previous user disk was a minidisk file, you can click the slot again and choose "Mount Disk File..." to remount it. (If you have trouble finding it, just search your system for a file called `user.minidisk`, which is what Mini Micro calls it by default.) Or you can use the "New Disk File..." command to create a new minidisk file with any name and location you choose.
|
| 286 |
+
|
| 287 |
+
A minidisk file is, in fact, nothing more than a zip file — a standard way of bundling a bunch of files and folders up into a single file, usually smaller than the original files thanks to compression. If you have a .minidisk file and want to convert it to into regular files, you can do so with this procedure:
|
| 288 |
+
|
| 289 |
+
1. Rename the file so that it ends in .zip rather than .minidisk.
|
| 290 |
+
2. Unzip it. Exactly how you do this depends on your system; in Windows you would use the "Extract All" button, on Mac you would just double-click it, etc.
|
| 291 |
+
|
| 292 |
+
Now you have an ordinary folder, which you could use with Mini Micro via that "Mount Folder..." command. What if you want to go the other way — take a folder and turn it into a minidisk file? That's easy too:
|
| 293 |
+
|
| 294 |
+
1. Zip the folder. On Mac, you right-click it and choose "Archive..."; on Windows you might need a third-party zip program.
|
| 295 |
+
2. Rename the zip file so that it ends in .minidisk rather than .zip.
|
| 296 |
+
|
| 297 |
+
And that's it. Now you can mount this as a disk in Mini Micro using the "Mount Disk File..." command.
|
| 298 |
+
|
| 299 |
+
Each way of representing files has its pros and cons. A minidisk file is a nice way of keeping all the MiniScript files for a particular program or task together. If you want to send somebody a copy of your program, along with all the images and sounds and other data it might need, a minidisk file is the most convenient way to do that. You'll also use this format when you package your game or program for distribution on sites like itch.io.
|
| 300 |
+
|
| 301 |
+
But mounting a folder is nice if you frequently want to access files both from Mini Micro and from the host OS. For example, you might want to use a paint program like PhotoShop to edit the artwork for a game, or use powerful audio software for editing the sound files for a music program. That's easier to do when Mini Micro simply mounts a folder on the host disk.
|
| 302 |
+
|
| 303 |
+
Now that you know about these two formats, you can choose how you prefer to store your files. Not sure? Don't worry about it — you can always convert from one to the other later.
|
| 304 |
+
|
| 305 |
+
{i:"`/usr2`"}
|
| 306 |
+
Finally, it's worth pointing out that Mini Micro has *two* disk slots. Any folder or disk file you mount in the second slot becomes available in Mini Micro as `/usr2/`. You probably won't need this at first, but someday you may have the need to load a second disk (or folder) of programs and data so that you can copy or compare to your main disk.
|
| 307 |
+
|
| 308 |
+
A> **Chapter Review**
|
| 309 |
+
A> - You experimented with the `key` module for reading the keyboard.
|
| 310 |
+
A> - You practiced editing and saving programs in Mini Micro.
|
| 311 |
+
A> - You learned about the two ways Mini Micro stores files on the host disk: as a disk file, and as a folder hierarchy, and how to convert between them.
|
data/day17.txt
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 17: Colors and Text", startingPageNum:201}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Life is a series of building, testing, changing and iterating.
|
| 7 |
+
Q>— Lauren Mosenthal (designer, researcher, & entrepreneur)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn how to specify and work with colors in Mini Micro.
|
| 11 |
+
A> - Explore the `text` module and various ways of placing text on the screen.
|
| 12 |
+
|
| 13 |
+
When you boot up Mini Micro, it looks a lot like a terminal window at first. There is monospaced text and a blinking cursor. Yesterday you learned some ways to go beyond standard terminal input/output, on the input side: ways to get a single character input or detect the state of all keys and buttons. Today we're going to go beyond standard terminal output: ways to move the cursor, change the text and background colors, and manipulate individual cells of the text display. All this will lead to more interactive, engaging programs that are as fun to use as they are to create.
|
| 14 |
+
|
| 15 |
+
## Color in Mini Micro
|
| 16 |
+
|
| 17 |
+
{i:"color;Mini Micro,colors in"}
|
| 18 |
+
Colors in Mini Micro are represented as standard HTML (that is, web page) color strings, which look like this:
|
| 19 |
+
|
| 20 |
+
{width:"50%"}
|
| 21 |
+

|
| 22 |
+
|
| 23 |
+
The first character must be a hash (`#`), followed by two characters each for red, green, and blue. The last two characters represent alpha (transparency), and are optional. If not specified, the alpha will be assumed to be FF, which is fully opaque.
|
| 24 |
+
|
| 25 |
+
Each pair of characters is a *hexadecimal* value from 00 to FF.
|
| 26 |
+
|
| 27 |
+
{i:"hexadecimal"}
|
| 28 |
+
D> The ordinary numbers everybody knows about are *decimal* numbers, with digits that go from 0 to 9. The second digit from the right is the "tens place" and digits there are multiplied by 10, so that 42 really means 4 \* 10 + 2. *Hexadecimal* numbers are similar, but instead of ten different digits, there are 16: 0 through 9 plus A through F. A in hexadecimal is the same value as 10 in decimal; B is 11, and so on. F (hex) is worth 15 (decimal). So the largest possible 2-digit value, FF, is 15 \* 16 + 15 = 255 in decimal.
|
| 29 |
+
|
| 30 |
+
PRINT>If all that about hexadecimal numbers seems confusing, don't worry about it; you don't really need to understand them to work with colors. Mini Micro comes with a `color` module that has 20 standard colors defined, so you can just refer to them by name. The table at the top of the next page lists them all.
|
| 31 |
+
EBOOK>If all that about hexadecimal numbers seems confusing, don't worry about it; you don't really need to understand them to work with colors. Mini Micro comes with a `color` module that has 20 standard colors defined, so you can just refer to them by name. The table below lists them all.
|
| 32 |
+
|
| 33 |
+
{colWidths:"50,100,50,100", caption:"Colors defined in the `color` module."}
|
| 34 |
+
|Name|Value|Name|Value|
|
| 35 |
+
|----|-----|----|-----|
|
| 36 |
+
|aqua|#00FFFF|navy|#000080|
|
| 37 |
+
|black|#000000|olive|#808000|
|
| 38 |
+
|blue|#0000FF|orange|#FF8000|
|
| 39 |
+
|brown|#996633|pink|#FF8080|
|
| 40 |
+
|clear|#00000000|purple|#800080|
|
| 41 |
+
|fuchsia|#FF00FF|red|#FF0000|
|
| 42 |
+
|gray|#808080|silver|#C0C0C0|
|
| 43 |
+
|green|#008000|teal|#008080|
|
| 44 |
+
|lime|#00FF00|white|#FFFFFF|
|
| 45 |
+
|maroon|#800000|yellow|#FFFF00|
|
| 46 |
+
|
| 47 |
+
{gap:30}
|
| 48 |
+
D> Want to see those colors in color? Check the *Mini Micro Cheat Sheet*! They are shown at the bottom of page 2.
|
| 49 |
+
|
| 50 |
+
There are many uses for colors in Mini Micro, but for today, we're just going to use them to color text. When you launch Mini Micro, it comes up with the color set to orange text on a black background, though you probably noticed that the welcome message used several other colors. Time for you to learn how to do such tricks yourself! Try this:
|
| 51 |
+
|
| 52 |
+
```terminal
|
| 53 |
+
]text.color = color.lime
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
As soon as you hit return, the `]` prompt and the blinking cursor appear a bright green. Enter `dir` just to get a bit more text to display in your current color settings.
|
| 57 |
+
|
| 58 |
+
Now perhaps that bright green is a bit too garish. Let's tone it down:
|
| 59 |
+
|
| 60 |
+
```terminal
|
| 61 |
+
]text.color = color.green
|
| 62 |
+
]dir
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
If you consult the color chart, you'll note that `color.lime` is `"#00FF00"`, while `color.green` is `"#008000"`. Both of these have red and blue equal to zero, but different amounts of green; lime uses FF, while green uses 80. Because FF is a bigger (hexadecimal) number than 80, it's a lot more green, and so a brighter color.
|
| 66 |
+
|
| 67 |
+
Green on black is nice, but what if we reduced the contrast a bit more by coloring the background?
|
| 68 |
+
|
| 69 |
+
```terminal
|
| 70 |
+
]text.backColor = color.navy
|
| 71 |
+
]dir
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Notice that we assigned to `text.backColor` here rather than `text.color`. You might have also noticed that changing this only changes the background color of subsequent printing, not text already printed, or areas that are not printed over in some way. To clear the whole screen to your new text colors, just enter `clear`.
|
| 75 |
+
|
| 76 |
+
PRINT>Take a few moments now to explore other color schemes. Are there any you particularly like? The figure below shows what my screen looked like after messing around for a while (at least, as well as we can show it in a black and white book).
|
| 77 |
+
EBOOK>Take a few moments now to explore other color schemes. Are there any you particularly like? The figure below shows what my screen looked like after messing around for a while (though if you're reading this on a monochrome ebook reader, you will have to use some imagination).
|
| 78 |
+
|
| 79 |
+
{width:"80%"}
|
| 80 |
+

|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
In addition to the 20 standard colors, the `color` module contains a couple of helper functions. One is the `color.rgb` function, which constructs a color given numeric values for red, green, and blue in the range 0 to 255.
|
| 84 |
+
|
| 85 |
+
```terminal
|
| 86 |
+
]text.color = rgb(255, 200, 100)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
There's also a `color.rgba` function that does the same, but takes an alpha value, also in the range 0-255. An alpha of 0 makes a color that is invisible because it is completely transparent; an alpha of 255 is fully opaque (non-transparent). Intermediate values make colors that are translucent, i.e., you can see through them to some degree. That's not terribly useful now because there is nothing in the background to see, but you'll have use for it later on, when you've learned to make use of Mini Micro's multiple display layers.
|
| 90 |
+
|
| 91 |
+
{i:"`lerp`;linear interpolation;`color.lerp`"}
|
| 92 |
+
The last color function we're going to talk about is `color.lerp`. "Lerp" is a computer term that comes from "linear interpolate," which is just a fancy way to describe the mixing of two values. `color.lerp` takes three parameters: *colorA*, *colorB*, and *t*, which is the interpolation value from 0 to 1. The result will be a color that is fraction *t* of the way between *colorA* and *colorB*.
|
| 93 |
+
|
| 94 |
+
A couple of examples will clear it up. Suppose that `a` and `b` are colors. Then `color.lerp(a, b, 0)` returns exactly the same thing as `a`. We've gone 0% of the way from color `a` to color `b`. If we did `color.lerp(a, b, 0.5)`, then we'd get a color exactly halfway between `a` and `b`. And of course `color.lerp(a, b, 1)` would return color `b`.
|
| 95 |
+
|
| 96 |
+
We can use this to generate a bunch of colors in between two others in a loop. Try this:
|
| 97 |
+
|
| 98 |
+
```terminal
|
| 99 |
+
]for t in range(0, 1, 0.05)
|
| 100 |
+
...]text.backColor = color.lerp(color.red, color.blue, t)
|
| 101 |
+
...]print " "
|
| 102 |
+
...]end for
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
PRINT>Here we've made a simple `for` loop that goes from 0 to 1 in increments of 0.05, and then use that value to lerp between red and blue. For each one, we set the text background color and print and handful of spaces so we can see it. (I can't effectively show the result in a black and white book, so please try it yourself!)
|
| 106 |
+
EBOOK>Here we've made a simple `for` loop that goes from 0 to 1 in increments of 0.05, and then use that value to lerp between red and blue. For each one, we set the text background color and print and handful of spaces so we can see it. (Words can't do this justice; please try it!)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
There's one more trick you should know about colors, and that is the color picker in the Mini Micro code editor. Enter `edit` to launch the editor, type `text.color =`, and then pause. Use the mouse to click on the code wizard button, which looks like a magic wand glowing above a little document icon. A menu should drop down from the button; select "Insert Color..." and the color picker will appear.
|
| 110 |
+
|
| 111 |
+

|
| 112 |
+
|
| 113 |
+
Here you can adjust the red, green, blue, and alpha values by using the sliders or by typing in values. You can also select one of the standard colors by clicking on the little color boxes below. A large color preview is shown against a checkered background, so you can see what effect the alpha channel has. Once you've found a color you like, click the Insert button to insert the color value into your code.
|
| 114 |
+
|
| 115 |
+
## The Text Display
|
| 116 |
+
|
| 117 |
+
So far we've just been using `print` and `input` to manipulate the text on the display, just like a terminal or even the Try-It! web page. You may have also caught `clear` for clearing the screen. Now we're going to learn some more advanced ways to put text on the Mini Micro screen.
|
| 118 |
+
|
| 119 |
+
The Mini Micro text display uses a friendly, monospaced font arranged in a grid of 26 rows by 68 columns. Columns are numbered starting on the left, and like many things in computers, they begin at 0 with the leftmost column. The rightmost column is column 67. Rows start at the bottom of the screen with 0, and proceed up to row 25 at the top of the screen.
|
| 120 |
+
|
| 121 |
+

|
| 122 |
+
|
| 123 |
+
In terms of pixels, each cell is 16 pixels wide and 24 pixels tall, but they overlap horizontally by 2 pixels. So effectively, you can think of the text cells as 14 by 24 pixels in size. (You don't really need to worry about pixel coordinates yet, but we will start thinking about such things soon when we get into pixel graphics.)
|
| 124 |
+
|
| 125 |
+
The text display has the concept of a cursor, which is where any printing goes. You've seen this already: it's the blinking block that shows you where you can type. But the cursor is only visible when it's waiting for input. At other times, it's invisible, but it's still there — and the output of any `print` statement goes wherever that cursor is. You can control where the cursor is by setting the `text.row` and `text.column` properties. Try this (either via `edit`, or just typed into the REPL):
|
| 126 |
+
|
| 127 |
+
```miniscript
|
| 128 |
+
for row in range(20, 5)
|
| 129 |
+
text.row = row
|
| 130 |
+
text.column = 10 + row*2
|
| 131 |
+
print "Hello world!"
|
| 132 |
+
end for
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
You already used `text.color` and `text.backColor` in the previous section, and now you've done something similar with `row` and `column`. As you've surely noticed, there is a `text` module much like the `key` module. It's actually *slightly* different, because Mini Micro can have not just one, but up to eight different text display layers, as you'll see in a couple of days. But one of these is always the "default" text display, which handles `print` and `input`, and `text` is a reference to that. So it's perfectly fine to think of `text` as just a module of text-related functionality.
|
| 136 |
+
|
| 137 |
+
{i:"Mini Micro, `text` module;`text` module;text properties"
|
| 138 |
+
{caption:"Properties that can be read or assigned to in the `text` module."}
|
| 139 |
+
| `text.color` | foreground (text) color of subsequent printing |
|
| 140 |
+
| `text.backColor` | background color of subsequent printing |
|
| 141 |
+
| `text.column` | cursor column (0-67) |
|
| 142 |
+
| `text.row` | cursor row (0-25) |
|
| 143 |
+
| `text.inverse` | boolean: when true, foreground and background colors are swapped |
|
| 144 |
+
| `text.delimiter` | string to follow the text of every `print`; by default, `char(13)` |
|
| 145 |
+
|
| 146 |
+
PRINT>Some of that functionality is in the form of properties you can both read, and assign new values to, like we did with `text.row` and `text.column` above. The full set of these text properties is shown in the table on the previous page.
|
| 147 |
+
EBOOK>Some of that functionality is in the form of properties you can both read, and assign new values to, like we did with `text.row` and `text.column` above. The full set of these text properties is shown in the table above.
|
| 148 |
+
|
| 149 |
+
But the `text` module also contains functions, like the `key` module did yesterday. You never assign new values to these; you just call them and pass in any parameters they need. Here is the list of those functions.
|
| 150 |
+
|
| 151 |
+
{caption:"Functions in the `text` module.", colWidths:"150,*"}
|
| 152 |
+
| `text.clear` | clear the display using the current foreground and background colors |
|
| 153 |
+
| `text.cell(x, y)` | get the character displayed at column *x*, row *y* |
|
| 154 |
+
| `text.setCell x, y, s` | set the character displayed at column *x*, row *y* to *s* |
|
| 155 |
+
| `text.cellColor(x, y)` | get the foreground character at column *x*, row *y* |
|
| 156 |
+
| `text.setCellColor x, y, c` | set the foreground color at column *x*, row *y* to *c* |
|
| 157 |
+
| `text.cellBackColor(x, y)` | get the background character at column *x*, row *y* |
|
| 158 |
+
| `text.setCellBackColor x, y, c` | set the background color at column *x*, row *y* to *c* |
|
| 159 |
+
| `text.print s` | print *s* to this display starting at `text.column`, `text.row` |
|
| 160 |
+
|
| 161 |
+
As usual, you should not try to memorize these! Just skim them so you have some idea of what's available, and then look them up (here, or on the Mini Micro Cheat Sheet) when you need them.
|
| 162 |
+
|
| 163 |
+
{i:"`text.inverse`"}
|
| 164 |
+
The `text.inverse` property is a switch that causes the foreground and background colors to be swapped on subsequent output. Try it: just enter `text.inverse = true` at the Mini Micro prompt. Maybe follow it with `dir`, or `print` something, so you can really see the effect. Do `text.inverse = false` to turn it back off.
|
| 165 |
+
|
| 166 |
+
{i:"`text.delimeter`;`print`"}
|
| 167 |
+
The last text property to consider is `text.delimiter`. This is a special string that is added to the console after every `print` statement. Try this:
|
| 168 |
+
|
| 169 |
+
```terminal
|
| 170 |
+
]print 1; print 2; print 3
|
| 171 |
+
1
|
| 172 |
+
2
|
| 173 |
+
3
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
We're just putting three `print` statements on one line, joining them with semicolons. You can see that each number appears on its own line. But now enter `text.delimiter="*"`, and then repeat the previous command. (Remember to user the up-arrow key to save yourself some typing!)
|
| 177 |
+
|
| 178 |
+
```terminal
|
| 179 |
+
]text.delimiter="*"
|
| 180 |
+
]print 1; print 2; print 3
|
| 181 |
+
1*2*3*
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
The difference this time is that all the output appears on one line, but after each number is an asterisk (the value you assigned to `text.delimiter`). To restore the standard behavior, do `text.delimiter=char(13)`. To understand that, first recall that the `char` intrinsic function returns a character (string) defined by its numeric Unicode value. For example, `char(65)` is capital letter "A". Unicode values less than 32 are called *control characters*, and are generally not printable, but instead cause special things to happen.
|
| 185 |
+
|
| 186 |
+
{i:"line break"}
|
| 187 |
+
`char(13)`, in particular, is a line break. It causes the text cursor to go to the column 0 of the next line. If the cursor was already on row 0, then it scrolls the whole text display up (i.e. moves everything up by one line), and then puts the cursor at the start of row 0.
|
| 188 |
+
|
| 189 |
+
D> There are a couple other useful control characters, and a whole host of character codes that produce special glyphs in Mini Micro. To learn these, run `/sys/demo/specialChars.ms`.
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
Changing `text.delimiter` to the empty string (that is, `""`) is handy when you need to print something, do some extended calculations, and then print something else, all on the same line. It's even more handy when you want to print something on row 0 without scrolling the screen.
|
| 193 |
+
|
| 194 |
+
That covers all the `text` properties. As for the functions, `text.clear` does almost the same thing as the `clear` method you already know, though it applies only to the text display (and not to the graphical displays you'll learn about soon). The other text functions all have to do with getting or setting the data in a particular cell on the display. Each cell contains three pieces of data:
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
|Data|How to get it|How to change it|
|
| 198 |
+
|----|-------------|----------------|
|
| 199 |
+
|the text character displayed|`text.cell`|`text.setCell`|
|
| 200 |
+
|the text color|`text.cellColor`|`text.setCellColor`|
|
| 201 |
+
|the background color|`text.cellBackColor`|`text.setCellBackColor`|
|
| 202 |
+
|
| 203 |
+
You use all these methods with parameters that specify the column and row of interest. For example, try this:
|
| 204 |
+
|
| 205 |
+
```terminal
|
| 206 |
+
]clear
|
| 207 |
+
]print "Neat?"
|
| 208 |
+
Neat!
|
| 209 |
+
]print text.cell(4, 24)
|
| 210 |
+
?
|
| 211 |
+
]text.setCell 4, 24, "!"
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
In this way, you can read or set the contents (or colors) of any cell on the screen. Many classic games, like *Rogue* and *Dwarf Fortress*, use exactly this sort of technique to draw 2D games using only a text display. In Mini Micro, the need for this is reduced, since it has powerful graphics capabilities you'll learn by the end of this book. But the ability to do advanced text-based user interfaces is there if you need it.
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
## ASCII Bear
|
| 218 |
+
|
| 219 |
+
{i:"ASCII art"}
|
| 220 |
+
To celebrate your new understanding of the text displays and color, here's a program that creates an adorable little bear using "ASCII art" (artwork made only with standard letters, numbers, and punctuation). Type carefully!
|
| 221 |
+
|
| 222 |
+
```miniscript
|
| 223 |
+
text.color = color.black
|
| 224 |
+
text.backColor = color.white
|
| 225 |
+
clear
|
| 226 |
+
print " _ _"
|
| 227 |
+
print " (c).-.(c)"
|
| 228 |
+
print " / ._. \"
|
| 229 |
+
print " __\( Y )/__"
|
| 230 |
+
print " (_.-/'-'\-._)"
|
| 231 |
+
print " || x ||"
|
| 232 |
+
print " _.' `-' '._"
|
| 233 |
+
print " (.-./`-~\.-.)"
|
| 234 |
+
print " `-' `-'"
|
| 235 |
+
text.setCellColor 7, 20, color.gray // belly button
|
| 236 |
+
text.setCellColor 6, 23, color.blue // left eye
|
| 237 |
+
text.setCellColor 8, 23, color.blue // right eye
|
| 238 |
+
```
|
| 239 |
+
Feel free to tweak this and improve it if you can!
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
## Exploring the Demos
|
| 243 |
+
|
| 244 |
+
{i:"`/sys/demo`,`theMatrix`;`/sys/demo`,`forestFire`"}
|
| 245 |
+
There are several demos in `/sys/demo/` that you are better equipped to understand now. `theMatrix.ms` demonstrates direct manipulation of the text display. The logic for managing all those dropping columns of characters is a little complex, but see if you can find where the characters and colors are poked onto the screen with text.setCell and text.setCellColor. Slightly simpler is the `forestFire.ms` program, which simulates a forest fire entirely on the text display.
|
| 246 |
+
|
| 247 |
+
{i:"`/sys/demo`,`typing`"}
|
| 248 |
+
There's a typing game called `typing.ms` that also uses the text display. Right near the top of the program, you'll find a `printAt` function that uses the things you learned today to print things exactly where they should appear on screen.
|
| 249 |
+
|
| 250 |
+
{i:"`/sys/demo`,`therapist`;`/sys/demo`,`textAdventure`;`/sys/demo`,`acey-deucey`"}
|
| 251 |
+
Finally, several of the other demos are primarily text-based, but don't do anything too fancy with the display. The `therapist`, `textAdventure`, and `acey-deucey` programs all fall into this category.
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
A> **Chapter Review**
|
| 255 |
+
A> - You learned how to represent colors in Mini Micro using HTML color syntax.
|
| 256 |
+
A> - You found the `color` module with 20 built-in colors, plus several handy functions.
|
| 257 |
+
A> - You explored the `text` module, and its several properties and methods that let you display (or read) text anywhere on the screen, in any colors you like.
|
| 258 |
+
|
data/day18.txt
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 18: Pixel Graphics", startingPageNum:213}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> The future belongs to those who believe in the beauty of their dreams.
|
| 7 |
+
Q>— Eleanor Roosevelt (First Lady and activist, 1884-1962)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn about the graphics display and the `gfx` module.
|
| 11 |
+
A> - Read and write individual pixels on the display.
|
| 12 |
+
A> - Learn to draw lines, rectangles, polygons, strings, and images.
|
| 13 |
+
|
| 14 |
+
Today is a very special day. For the first 17 chapters of this book — and perhaps your entire programming career up till now — your programs have been built around strings of text. Strings come in, strings go out. In the last chapter we got a little fancy about how and where the strings go out, but still, it was all just text on the screen.
|
| 15 |
+
|
| 16 |
+
Today that changes forever.
|
| 17 |
+
|
| 18 |
+
As of today, you are no longer limited to creating text. Today you learn to create *graphics*: pictures composed of tiny pixels! Of course if you ran the demos in `/sys/demo`, or have played any Mini Micro games on the web, then you already know what that looks like. So let's jump right in with a short program. Type this in and see what it does:
|
| 19 |
+
|
| 20 |
+
{caption:"Our first graphics program."}
|
| 21 |
+
```miniscript
|
| 22 |
+
clear
|
| 23 |
+
gfx.clear color.white
|
| 24 |
+
gfx.color = color.gray
|
| 25 |
+
for x in range(0, 960, 64)
|
| 26 |
+
gfx.line x, 0, x, 640
|
| 27 |
+
gfx.print x, x,0
|
| 28 |
+
end for
|
| 29 |
+
for y in range(0, 640, 64)
|
| 30 |
+
gfx.line 0, y, 960, y
|
| 31 |
+
gfx.print y, 0,y
|
| 32 |
+
end for
|
| 33 |
+
key.get // wait for a keypress
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
The first line clears the screen, and the last line waits for a keypress; you already know about these. The rest of the program uses the built-in `gfx` global, which is new. This is pronounced "graphics," and it is a reference to Mini Micro's pixel display, in the same way that `text` is a reference to the text display. For brevity, we'll just refer to "the `gfx` module" in this chapter.
|
| 37 |
+
|
| 38 |
+
{width:"75%"}
|
| 39 |
+

|
| 40 |
+
|
| 41 |
+
When you run that program, it should draw a grid with the X (horizontal) and Y (vertical) values listed every 64 pixels.
|
| 42 |
+
|
| 43 |
+
As you can see, the graphics display is 960 pixels across horizontally, and 640 pixels vertically. Just as with the text display, 0,0 is the lower-left corner of the screen; X values increase to the right, and Y values increase towards the top.
|
| 44 |
+
|
| 45 |
+
In this program you used one graphics property, `gfx.color`, as well as three methods: `gfx.clear`, `gfx.line`, and `gfx.print`. There are a few more graphics properties:
|
| 46 |
+
|
| 47 |
+
{i:"Mini Micro, `gfx` module;`gfx` module;graphics properties"}
|
| 48 |
+
{caption:"Properties in the `gfx` module. `width` and `height` are read-only; the others can be assigned new values."}
|
| 49 |
+
| `gfx.color` | default color for subsequent drawing |
|
| 50 |
+
| `gfx.width` | width of the graphics display, in pixels |
|
| 51 |
+
| `gfx.height` | height of the graphics display, in pixels |
|
| 52 |
+
| `gfx.scrollX` | horizontal scroll position, in pixels |
|
| 53 |
+
| `gfx.scrollY` | vertical scroll position, in pixels |
|
| 54 |
+
| `gfx.scale` | scale factor, or [hScale, vScale] factors |
|
| 55 |
+
|
| 56 |
+
EBOOK>Functions in the `gfx` module are listed below. You've already used `gfx.clear`, which has three optional parameters: color, width, and height. The color parameter (listed as `c` in the table) defaults in this case to `color.black`, while `width` and `height` default to 960 and 640, respectively. We'll get into why you might use different values for these later.
|
| 57 |
+
|
| 58 |
+
{caption:"Functions in the `gfx` module. Parameters: `points` is a list; `c` is a color; `s` and `font` are strings; `img` is an Image; all other parameters are numbers measured in pixels. All parameters have default values; in particular, color, pen size, and font parameters are usually omitted.", colWidths:"200,*"}
|
| 59 |
+
| `gfx.clear c, width, height` | clear and resize the graphics display |
|
| 60 |
+
| `gfx.pixel(x, y)` | get the color of pixel at *x*, row *y* |
|
| 61 |
+
| `gfx.setPixel x, y, c` | set the color of pixel at *x*, row *y* to *c* |
|
| 62 |
+
| `gfx.line x1, y1, x2, y2, c, penSize` | draw a line |
|
| 63 |
+
| `gfx.drawRect left, bottom, width, height, c, penSize` | outline a rectangle |
|
| 64 |
+
| `gfx.fillRect left, bottom, width, height, c` | fill a rectangle |
|
| 65 |
+
| `gfx.drawEllipse left, bottom, width, height, c, penSize` | outline an ellipse |
|
| 66 |
+
| `gfx.fillEllipse left, bottom, width, height, c` | fill an ellipse |
|
| 67 |
+
| `gfx.drawPoly points, c, penSize` | outline a polygon |
|
| 68 |
+
| `gfx.fillPoly points, c` | fill a polygon |
|
| 69 |
+
| `gfx.print s, x, y, c, font` | draw string `s` in the given font |
|
| 70 |
+
| `gfx.drawImage img, left, bottom, width, height, srcLeft, srcBottom, srcWidth, srcHeight` | draw an Image (or a rectangular portion of an image) |
|
| 71 |
+
| `gfx.getImage(left, bottom, width, height)` | get a portion of the display as an Image |
|
| 72 |
+
|
| 73 |
+
PRINT>Functions in the `gfx` module are listed on the next page. You've already used `gfx.clear`, which has three optional parameters: color, width, and height. The color parameter (listed as `c` in the table) defaults in this case to `color.black`, while `width` and `height` default to 960 and 640, respectively. We'll get into why you might use different values for these later.
|
| 74 |
+
|
| 75 |
+
## Getting and Setting Pixels
|
| 76 |
+
|
| 77 |
+
Just as you can read or change individual cells of the text display with methods like `text.cell`, you can get and set individual pixels of the graphics display with the `gfx.pixel` and `gfx.setPixel` methods. The program listed on the next page is a quick demo that randomly changes pixels from black to gray, and from gray to aqua. As always, I recommend you type it and and try it out.
|
| 78 |
+
|
| 79 |
+
There is one important trick to note on line 5 of this program. Recall that colors are represented as a string containing a hash symbol, plus two digits each for red, green, blue, and *optionally* alpha. The predefined color strings like `color.black` and `color.aqua` do not include the alpha characters (with the exception of `color.clear`, which needs them). But whenever you get the color of a pixel with `gfx.pixel`, it includes the alpha, even if the pixel is fully opaque.
|
| 80 |
+
|
| 81 |
+
{caption:"Pixel fog."}
|
| 82 |
+
```miniscript
|
| 83 |
+
gfx.clear
|
| 84 |
+
while true
|
| 85 |
+
x = 960 * rnd
|
| 86 |
+
y = 640 * rnd
|
| 87 |
+
c = gfx.pixel(x, y)[:7] // (ignore alpha)
|
| 88 |
+
if c == color.black then
|
| 89 |
+
gfx.setPixel x, y, color.gray
|
| 90 |
+
else
|
| 91 |
+
gfx.setPixel x, y, color.aqua
|
| 92 |
+
end if
|
| 93 |
+
end while
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Let's poke at this with the REPL to make sure it's clear. If the program above is still running, hit control-C to stop it, then try the following.
|
| 97 |
+
|
| 98 |
+
```terminal
|
| 99 |
+
]color.red
|
| 100 |
+
#FF0000
|
| 101 |
+
]gfx.setPixel 200,200, color.red
|
| 102 |
+
]gfx.pixel(200,200)
|
| 103 |
+
#FF0000FF
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
So `color.red` is defined as "#FF0000": full red, and zero green and blue. Alpha is not included in this string, because alpha is optional when it would be equal to FF (fully opaque). But when we store this color as a pixel and then read it back out, we get the full color string including alpha, "#FF0000FF". This is equivalent to the color we put in, but simple string comparison would say they are different.
|
| 107 |
+
|
| 108 |
+
The solution is as shown in the example above: when you don't care about alpha, just truncate the color you get back to 7 characters.
|
| 109 |
+
|
| 110 |
+
```terminal
|
| 111 |
+
]gfx.pixel(200,200)[:7]
|
| 112 |
+
#FF0000
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
Now you can compare this to other 7-character color strings with no problem.
|
| 116 |
+
|
| 117 |
+
## Drawing Lines, Rectangles, and Ellipses
|
| 118 |
+
|
| 119 |
+
Next up, let's look at some of the figure drawing routines. All of these have an optional `color` parameter, which defaults to whatever color you set on `gfx.color`; and `penSize`, which defaults to one. Try this at the prompt:
|
| 120 |
+
|
| 121 |
+
```terminal
|
| 122 |
+
]gfx.color = color.green
|
| 123 |
+
]gfx.line 200,100, 500,540
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
This sets the default drawing color to green, then draws a line from X=200, Y=0 (i.e. a point at the bottom of the screen, 200 pixels from the left edge) to X=500, Y=640 (a point at the top of the screen, 500 pixels from the left). Now use the up-arrow to recall that last command, but specify a different color:
|
| 127 |
+
|
| 128 |
+
```terminal
|
| 129 |
+
]gfx.line 200,100, 500,540, color.yellow
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
The line turns yellow. Now let's try one more variation, specifying a pen size of 20:
|
| 133 |
+
|
| 134 |
+
```terminal
|
| 135 |
+
]gfx.line 200,100, 500,540, color.yellow, 20
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
The first two commands produced a very thin line, but this produces a fat, chunky line with square ends. Let's use this to make a "screen saver" that endlessly fills the screen with random lines!
|
| 139 |
+
|
| 140 |
+
{caption:"Random-lines screen saver."}
|
| 141 |
+
```miniscript
|
| 142 |
+
while true
|
| 143 |
+
c = color.rgb(255*rnd, 255*rnd, 255*rnd)
|
| 144 |
+
pen = 1 + rnd*20
|
| 145 |
+
gfx.line 960*rnd,640*rnd, 960*rnd,640*rnd, c, pen
|
| 146 |
+
end while
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
Drawing the outline of a rectangle or ellipse is very similar, but the third and fourth parameters are the width and height of the figure, rather than the other end of a line. The first two parameters are the position of the bottom-left corner (since Mini Micro always measures things from the bottom left). Just keep saying "left, bottom, width, height" to yourself as you type these! Try it:
|
| 150 |
+
|
| 151 |
+
```terminal
|
| 152 |
+
]gfx.drawRect 200,100, 300,80
|
| 153 |
+
]gfx.drawRect 200,100, 300,80, color.lime
|
| 154 |
+
]gfx.drawEllipse 200,100, 300,80, color.orange, 20
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
{width:"75%"}
|
| 158 |
+

|
| 159 |
+
|
| 160 |
+
But a rectangle or ellipse can also be filled rather than outlined. In this case there is no `penSize` parameter. Type the next one in on the REPL, line by line, to see a surprise.
|
| 161 |
+
|
| 162 |
+
{caption:"Sometimes, when you stare at the computer long enough... the computer stares back."}
|
| 163 |
+
```terminal
|
| 164 |
+
]gfx.clear
|
| 165 |
+
]gfx.fillRect 200,100, 400,500, color.brown
|
| 166 |
+
]gfx.fillEllipse 250,400, 150,50, color.white
|
| 167 |
+
]gfx.fillEllipse 400,400, 150,50, color.white
|
| 168 |
+
]gfx.fillEllipse 455,410, 40,40, color.blue
|
| 169 |
+
]gfx.fillEllipse 305,410, 40,40, color.blue
|
| 170 |
+
]gfx.fillRect 300,250, 200,20, color.red
|
| 171 |
+
]text.clear
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
If your eyes glaze over when you see so many numbers, don't worry. It's actually not very common to write code like this; usually if you need a picture, you would just load a picture from disk (as we'll see later in this chapter). More often when you're using drawing commands like these, the coordinates are computed from other values, for example when drawing a bar chart. But you already know how to do math; and now you know how to draw too, so when that need arises, you'll be all set.
|
| 176 |
+
|
| 177 |
+
## Drawing Polygons
|
| 178 |
+
|
| 179 |
+
{i:"polygons"}
|
| 180 |
+
Mini Micro can also draw polygons of three or more sides, and by "draw" we mean either outline or fill, just like rectangles and ellipses. But polygons are a little trickier to specify, since they can include any number of points. Mini Micro solves this by using a list of points. Each element of the list can be itself an [x,y] list specifying the location of one point.
|
| 181 |
+
|
| 182 |
+
```terminal
|
| 183 |
+
]gfx.clear
|
| 184 |
+
]gfx.drawPoly [[100,100], [200,300], [300,100]]
|
| 185 |
+
]gfx.drawPoly [[100,100], [200,300], [300,100]], color.red
|
| 186 |
+
]gfx.drawPoly [[100,100], [200,300], [300,100]], color.red, 10
|
| 187 |
+
]gfx.fillPoly [[100,100], [200,300], [300,100]], color.blue
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
As an alternative, each point can be a little map containing "x" and "y" values. This is mostly useful when working with other things that already have coordinates in this form, like the mouse pointer or sprites (all things we'll get to later). For now, let's just prove that it works:
|
| 191 |
+
|
| 192 |
+
```terminal
|
| 193 |
+
]clear
|
| 194 |
+
]gfx.drawPoly [{"x":100,"y":100}, {"x":200,"y":300}, {"x":300,"y":100}]
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
D> Note that this line of code does not quite fit on one line on the screen. That's OK; just keep typing, and don't let it worry you when it wraps to the next line!
|
| 198 |
+
|
| 199 |
+
## Drawing Text
|
| 200 |
+
|
| 201 |
+
Sure, you already know how to print text to the text display. But it turns out you can also draw text to the graphics display, and it's more flexible in two ways. First, you can draw the text anywhere you like, rather than only in predefined rows and columns. Second, you can draw it in a smaller or larger font, in addition to the standard font size. All this is done with the `gfx.print` method. Explore:
|
| 202 |
+
|
| 203 |
+
```terminal
|
| 204 |
+
]@gfx.print
|
| 205 |
+
FUNCTION(self, str, x=0, y=0, color, fontName="normal")
|
| 206 |
+
]gfx.print "Hello world!", 600, 400
|
| 207 |
+
]gfx.print "Hello world!", 600, 350, color.aqua
|
| 208 |
+
]gfx.print "Hello world!", 600, 300, color.aqua, "small"
|
| 209 |
+
]gfx.print "Hello world!", 600, 250, color.aqua, "large"
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
That first line above displays the parameter list of the `gfx.print` function. This is a handy trick that works with any function.
|
| 213 |
+
|
| 214 |
+
D> If you remember the name of a function but need to review its parameters, enter an at sign (@) followed by the function name. The REPL will display the parameter names and default values.
|
| 215 |
+
|
| 216 |
+
The rest of the above example draws our classic greeting in various colors and sizes.
|
| 217 |
+
|
| 218 |
+
{width:"75%"}
|
| 219 |
+

|
| 220 |
+
|
| 221 |
+
Of course there are costs to the increased flexibility of drawing text with `gfx`: it is substantially slower than using `text`, you can't easily change the text once it's drawn, and you certainly can't read the text back from the display, as it's just a bunch of pixels.
|
| 222 |
+
|
| 223 |
+
## Working with Images
|
| 224 |
+
|
| 225 |
+
There are only a couple more methods left on the `gfx` module: `gfx.drawImage` and `gfx.getImage`. But to understand them, we first need to cover the Image class.
|
| 226 |
+
|
| 227 |
+
{i:"`Image`;Mini Micro, `Image` class;pictures, in Mini Micro"}
|
| 228 |
+
`Image` is a class built into Mini Micro for representing pictures. Images are usually loaded from disk, but they can also be built pixel by pixel from scratch, or plucked right out of a graphics display. Once you have an image, you can either draw it directly to a graphics display, or (as we'll see in Chapter 22) turn it into a sprite that can be moved around very efficiently.
|
| 229 |
+
|
| 230 |
+
Let's jump in with an example first, and then we'll go over the details.
|
| 231 |
+
|
| 232 |
+
```terminal
|
| 233 |
+
]img = file.loadImage("/sys/pics/Mochi.png")
|
| 234 |
+
]gfx.drawImage img, 0, 0
|
| 235 |
+
]gfx.drawImage img, 120, 0, img.width*6, img.height*6
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
{gap:20}
|
| 239 |
+
{width:"50%"}
|
| 240 |
+

|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
All the `file` methods you learned in Chapter 13 still apply in Mini Micro. But in Mini Micro there are a couple of additional functions, including `file.loadImage`, which simply returns an image from the given file path.
|
| 244 |
+
|
| 245 |
+
The following table shows the properties and methods of the `Image` class.
|
| 246 |
+
|
| 247 |
+
{caption:"Image properties (all read-only) and methods.", colWidths:"150,*"}
|
| 248 |
+
| `img.width` | get the image width, in pixels |
|
| 249 |
+
| `img.height` | get the image height, in pixels |
|
| 250 |
+
| `img.pixel(x, y)` | get the color of pixel at *x*, row *y* |
|
| 251 |
+
| `img.setPixel x, y, c` | set the color of pixel at *x*, row *y* to *c* |
|
| 252 |
+
| `img.getImage(left, bottom, width, height)` | get a portion of the image as a new Image |
|
| 253 |
+
| `Image.create(width, height, c)` | create a new image filled with color c |
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
The identifier `Image` is capitalized because, unlike `color`, `text`, and `graphics`, you are expected to be working with an *instance* of this class, rather than calling methods on `Image` itself. The one exception is `Image.create`, which is the method for creating an image from scratch. So in the table above, we use `img` to stand in for any `Image` instance, like the one we got from `file.loadImage` in the example above.
|
| 258 |
+
|
| 259 |
+
Now you know all the methods available on the Image class, but honestly, you will almost never use any of them. The typical pattern is to load an image from disk, and then draw it to the screen, just as we did above. Rarely do you need to modify the content of an image, but it's nice to know that you can.
|
| 260 |
+
|
| 261 |
+
Getting back to the `gfx` module, `gfx.drawImage` takes more parameters than anything else in the Mini Micro API — a total of nine! But you can think of it as: the image to draw, the area to draw it in, and the area of the image to use. These let you basically take any rectangular portion of the source image, and stretch or squash it into ane rectangular area of the graphics display. All the parameters except the image are optional. If you leave off the last four, the source area, then the entire image will be used. And if you leave off the *width* and *height* parameters, it will be drawn without any stretching or squashing.
|
| 262 |
+
|
| 263 |
+
To illustrate, follow the example above with one more try that uses all nine parameters to draw just the mochi's smile, super-sized:
|
| 264 |
+
|
| 265 |
+
```terminal
|
| 266 |
+
]gfx.drawImage img, 0,0,500,100, 52,14,20,10
|
| 267 |
+
```
|
| 268 |
+
This grabs the rectangular area of the image with a bottom-left corner of 52,14, a width of 20, and a height of 10; and draws it onto the screen with its bottom-left corner at 0,0, and a stretched-out size of 500 wide by 100 tall.
|
| 269 |
+
|
| 270 |
+
## Exploring the Demos
|
| 271 |
+
|
| 272 |
+
{i:"`/sys/demo`,`sunset`"}
|
| 273 |
+
Of the demos in `/sys/demo`, the `sunset.ms` program is the best one to review at this point. It uses only the functions you've seen here to make a lovely picture, with details that are slightly different every time. The `stars.ms` demo is also good, although it's so simple, you may find it too easy!
|
| 274 |
+
|
| 275 |
+
{i:"turtle graphics;`/sys/demo`,`turtleDemo`"}
|
| 276 |
+
The other drawing demo is `turtleDemo.ms`. This uses a trick you'll learn more about tomorrow: `import`. The `import` function lets you load some code from another file — in this case, a "turtle" module that provides for a very different approach to drawing called *turtle graphics*. The basic idea here is that there is a little turtle on the screen that can be told to move and turn while drawing a line. Go ahead and play with this demo; just keep in mind that those turtle methods are not built into Mini Micro, but instead are only available after importing the turtle module. (We'll explain more about `import` in the next chapter.)
|
| 277 |
+
|
| 278 |
+
A> **Chapter Review**
|
| 279 |
+
A> - You explored the Mini Micro pixel display, accessed via `gfx`.
|
| 280 |
+
A> - You learned how to get and set individual pixels, as well as how to draw lines, rectangles, ellipses, and polygons.
|
| 281 |
+
A> - You drew text in three different sizes and in various colors.
|
| 282 |
+
A> - You learned about the Image class, including how to load an image from disk and draw it (in whole or in part) to the screen.
|
data/day19.txt
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 19: Display Layers, Mouse, and Import", startingPageNum:225}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
Q> In some ways, programming is like painting. You start with a blank canvas and certain basic raw materials. You use a combination of science, art, and craft to determine what to do with them.
|
| 8 |
+
Q>— Andrew Hunt (software developer and author)
|
| 9 |
+
|
| 10 |
+
A> **Chapter Objectives**
|
| 11 |
+
A> - Learn about the 8-layer display system in Mini Micro.
|
| 12 |
+
A> - Discover how to get the position of the mouse cursor and the state of its buttons.
|
| 13 |
+
A> - Learn how to use `import` to load extra functionality into your program.
|
| 14 |
+
|
| 15 |
+
PRINT>You've learned how to draw to the default graphics display with `gfx`, and how to print text to the screen with `text`. But it turns out that the Mini Micro display system is more sophisticated than this. It actually consists of eight layers, any of which can be set to any display mode. The available display modes are shown in the table on the next page.
|
| 16 |
+
EBOOK>You've learned how to draw to the default graphics display with `gfx`, and how to print text to the screen with `text`. But it turns out that the Mini Micro display system is more sophisticated than this. It actually consists of eight layers, any of which can be set to any display mode. The available display modes are shown in the table below.
|
| 17 |
+
|
| 18 |
+
{i:"display modes", "Mini Micro, display modes"}
|
| 19 |
+
| 0 | off | no display |
|
| 20 |
+
| 1 | solid color | displays one color over the whole screen |
|
| 21 |
+
| 2 | text | 26 row, 68 column text display |
|
| 22 |
+
| 3 | pixel | 960 by 640 (by default) pixel display |
|
| 23 |
+
| 4 | tile | displays a rectangular grid of small images |
|
| 24 |
+
| 5 | sprite | displays a set of scaleable, rotatable, resizable images |
|
| 25 |
+
|
| 26 |
+
{pageBreak}
|
| 27 |
+
The layers are numbered from 0 to 7, and stacked up with 0 in the front, and 7 in the back. Display layers that are off, or have any transparent areas, let you see through to the next layer behind it, and so on all the way to the back. (If all layers are off or see-through, the screen appears black.)
|
| 28 |
+
|
| 29 |
+
When you start up Mini Micro, or use the `clear` command, the display layers are set up like this:
|
| 30 |
+
|
| 31 |
+
{width:"75%"}
|
| 32 |
+

|
| 33 |
+
|
| 34 |
+
So in the standard configuration, displays 0, 1, and 2 are off; 3 is text; 4 is sprites (which we'll learn about in a few days); 5 is pixel graphics; 6 is off; and 7 is a solid color (black). You might have noticed yesterday that when you have overlapping pixel graphics and text on the screen, the text appears on top of the pixel graphics. Now you can see why: the text is in display 3, which is layered in front of the graphics layer in display 5.
|
| 35 |
+
|
| 36 |
+
But this is only the default configuration; as a programmer, you can change this however you like! The eight display layers can be set to any configuration, including multiple displays of the same type if desired. Let's prove it! Try this:
|
| 37 |
+
|
| 38 |
+
{caption:"Filling all 8 displays with random text."}
|
| 39 |
+
```miniscript
|
| 40 |
+
for layer in range(7, 0)
|
| 41 |
+
// set the layer to text mode, with a random text color
|
| 42 |
+
display(layer).mode = displayMode.text
|
| 43 |
+
display(layer).color = rgb(255*rnd, 255*rnd, 255*rnd)
|
| 44 |
+
display(layer).clear
|
| 45 |
+
// fill it with random characters
|
| 46 |
+
for row in range(0,25)
|
| 47 |
+
for col in range(0,67)
|
| 48 |
+
c = char(32 + rnd*64)
|
| 49 |
+
display(layer).setCell col, row, c
|
| 50 |
+
end for
|
| 51 |
+
end for
|
| 52 |
+
wait
|
| 53 |
+
end for
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Run this, and it should make an absolute mess of your Mini Micro screen. Don't worry; entering `clear` will of course clean it up! Each of the eight layers is set to text mode, and then filled with random text. By the end, every text position on the screen contains eight overlapping characters.
|
| 57 |
+
|
| 58 |
+
This program introduces several new things you can use in your own programs:
|
| 59 |
+
|
| 60 |
+
- `displayMode`, which is a built-in map that lets you refer to the different display modes by name, for example `displayMode.text`, `displayMode.pixel`, and `displayMode.solidColor`. These simply map to the mode numbers (0-5) shown in the table on the previous page.
|
| 61 |
+
- `display(num)`, a function that returns a reference to the display object for the given layer number (0-7).
|
| 62 |
+
- `mode`, a property on every display class that controls what mode that layer is.
|
| 63 |
+
|
| 64 |
+
So in the listing above, line 3 uses the `display` function to get a reference to one of the layers (using the `layer` variable from the `for` loop); and then it changes it to text mode by assigning `displayMode.text` to its `.mode` property.
|
| 65 |
+
|
| 66 |
+
Let's use the REPL to do this step by step. Start by resetting your displays:
|
| 67 |
+
|
| 68 |
+
```terminal
|
| 69 |
+
]clear
|
| 70 |
+
]text.color = color.orange
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
After the `clear` call, display 3 is text and display 2 is off. Let's change display 2 so that it is *also* text, and print some overlapping text.
|
| 74 |
+
|
| 75 |
+
```terminal
|
| 76 |
+
]display(2).mode = displayMode.text
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
As soon as you enter this line, all that random text that was created from the program before suddenly appears! The `clear` command turns display 2 off, but it does not actually clear the underlying text display. So we'll do that next, and then set the color, and print some dashes on line 10.
|
| 80 |
+
|
| 81 |
+
```terminal
|
| 82 |
+
]display(2).clear
|
| 83 |
+
]display(2).color = color.green
|
| 84 |
+
]display(2).row = 10; display(2).print "-----"
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
Those dashes appear in display 2, which is in front of the default `text` display (3). So now let's print some text behind the dashes:
|
| 88 |
+
|
| 89 |
+
```terminal
|
| 90 |
+
]text.row = 10; text.print "DONE!"
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Below is a handy function to list what the current display types are.
|
| 94 |
+
|
| 95 |
+
{caption:"Function to list the current mode of all eight display layers."}
|
| 96 |
+
```miniscript
|
| 97 |
+
dispDump = function()
|
| 98 |
+
for layer in range(0,7)
|
| 99 |
+
d = display(layer)
|
| 100 |
+
print layer + ". " + displayMode.str(d.mode)
|
| 101 |
+
end for
|
| 102 |
+
end function
|
| 103 |
+
|
| 104 |
+
dispDump
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
This uses the `displayMode.str` function to convert a mode number back into a string (basically doing the same thing as `displayMode.indexOf` in this case). The `for` loop here has been wrapped in a function so that, once you've run this code, you can just call `dispDump` at any time to see how your displays are arranged.
|
| 108 |
+
|
| 109 |
+
Before we move on, let's create a couple of functions to do a fade-out or fade-in effect. This will work by setting the frontmost display (layer 0) to solid color, and then using a loop to gradually change that from clear to black or vice versa. This acts like a sort of stage curtain, covering or revealing the other seven layers.
|
| 110 |
+
|
| 111 |
+
{caption:"Display fade-out and fade-in functions."}
|
| 112 |
+
{i:"fade out"}
|
| 113 |
+
```miniscript
|
| 114 |
+
// fade a black curtain from alpha0 to alpha1
|
| 115 |
+
// (where 0 means clear and 1 means solid black)
|
| 116 |
+
// over `duration` seconds.
|
| 117 |
+
fade = function(alpha0, alpha1, duration=1)
|
| 118 |
+
// set the frontmost display to solid color
|
| 119 |
+
display(0).mode = displayMode.solidColor
|
| 120 |
+
t0 = time // note the time
|
| 121 |
+
while true // loop until done
|
| 122 |
+
t = (time - t0) / duration // fraction done
|
| 123 |
+
if t > 1 then break // done when t > 1
|
| 124 |
+
a = alpha0 + (alpha1 - alpha0) * t
|
| 125 |
+
display(0).color = color.rgba(0,0,0,a)
|
| 126 |
+
yield // wait till next display frame
|
| 127 |
+
end while
|
| 128 |
+
display(0).color = color.rgba(0,0,0,alpha1)
|
| 129 |
+
end function
|
| 130 |
+
|
| 131 |
+
// fade to black over `duration` seconds
|
| 132 |
+
fadeOut = function(duration=1)
|
| 133 |
+
fade 0, 255, duration
|
| 134 |
+
end function
|
| 135 |
+
|
| 136 |
+
// fade from black to clear over `duration` seconds
|
| 137 |
+
fadeIn = function(duration=1)
|
| 138 |
+
fade 255, 0, duration
|
| 139 |
+
display(0).mode = displayMode.off
|
| 140 |
+
end function
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Notice how the `fadeOut` and `fadeIn` functions do very little work themselves, instead calling a `fade` function that does all the heavy lifting. This follows the DRY (Don't Repeat Yourself) principle from Chapter 11; without this helper function, `fadeIn` and `fadeOut` would be almost identical.
|
| 144 |
+
|
| 145 |
+
After running the above code to define the functions, try them out with:
|
| 146 |
+
|
| 147 |
+
```terminal
|
| 148 |
+
]fadeOut; key.get; fadeIn
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Neat, huh? You can use these functions any time you need a dramatic fade to black in your own programs.
|
| 152 |
+
|
| 153 |
+
## Reading the Mouse
|
| 154 |
+
|
| 155 |
+
Let's turn now to a different topic: detecting where the mouse cursor is, and the state of the buttons. This is a very useful thing to do, since it lets us go beyond keyboard input and make programs that can be controlled with a mouse (or track pad or touch screen!).
|
| 156 |
+
|
| 157 |
+
{i:"`mouse` module;Mini Micro, `mouse` module"}
|
| 158 |
+
This is done in Mini Micro with a very simple built-in module called `mouse`. It has two read-only properties, one read/write property, and one function:
|
| 159 |
+
|
| 160 |
+
{i:"Mini Micro, `gfx` module;`gfx` module;graphics properties"}
|
| 161 |
+
{caption:"Properties and function in the `mouse` module. `x` and `y` are read-only; `visible` can be assigned true or false."}
|
| 162 |
+
| `mouse.x` | horizontal position of the mouse pointer (0-959) |
|
| 163 |
+
| `mouse.y` | vertical position of the mouse pointer (0-639) |
|
| 164 |
+
| `mouse.visible` | true if mouse cursor can be seen; false if hidden |
|
| 165 |
+
| `mouse.button(which=0)` | true when the given button is pressed |
|
| 166 |
+
|
| 167 |
+
To start exploring the `mouse` module, position the mouse somewhere over the Mini Micro screen, and simply enter `mouse` at the prompt. You'll see something like this:
|
| 168 |
+
|
| 169 |
+
```terminal
|
| 170 |
+
]mouse
|
| 171 |
+
{"x": 417, "y": 166, "button": FUNCTION(which=0), "visible": FUNCTIO
|
| 172 |
+
N()}
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
Note the `x` and `y` values shown — these vary with the mouse position. Try moving the mouse, and then entering `mouse` again. In fact, on some systems, you can even read the mouse position beyond the bounds of the screen; for example, if you move the mouse to the left of the Mini Micro window, you'll see a negative `x` value.
|
| 176 |
+
|
| 177 |
+
Next, try setting `mouse.visible = false` at the prompt, and observe that the mouse pointer disappears. This is useful for some kinds of games, where you might want to use a sprite (coming up in Chapter 22) in place of the standard mouse cursor. Set `mouse.visible = true` to bring it back.
|
| 178 |
+
|
| 179 |
+
Finally, let's look at the `button` method. A gaming mouse can have up to seven buttons, numbered 0 through 6. A more typical mouse has two buttons, with the main button as number 0 and the secondary or right-click button as number 1. Often the scroll wheel can be pushed, which reads as button 3.
|
| 180 |
+
|
| 181 |
+
When you don't supply the `which` parameter to `mouse.button`, it reports the state of button 0. So try it: enter `mouse.button` at the prompt, without touching the mouse, and it should report 0, meaning that the button is not pressed. Then enter it again (remember the up-arrow trick!), but this time, hold down the primary mouse button while you press Enter or Return. This time it reports 1.
|
| 182 |
+
|
| 183 |
+
Now that you can get the mouse position and button state, you can do all sorts of neat things. Try this simple drawing program:
|
| 184 |
+
|
| 185 |
+
{caption:"A simple drawing program in Mini Micro."}
|
| 186 |
+
```miniscript
|
| 187 |
+
clear
|
| 188 |
+
gfx.color = color.white
|
| 189 |
+
prev = {}
|
| 190 |
+
while not key.pressed("escape")
|
| 191 |
+
// The mouse might move within this loop, so let's grab a copy
|
| 192 |
+
// of it right away as "m", and use only that.
|
| 193 |
+
m = {"x": mouse.x, "y": mouse.y}
|
| 194 |
+
|
| 195 |
+
// If the button is down, draw a line from
|
| 196 |
+
// our previous mouse position.
|
| 197 |
+
if mouse.button then gfx.line prev.x, prev.y, m.x, m.y
|
| 198 |
+
// ...and then remember that as the previous position next time.
|
| 199 |
+
prev = m
|
| 200 |
+
|
| 201 |
+
yield // wait for next frame
|
| 202 |
+
end while
|
| 203 |
+
key.clear
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
Run that code, and then try drawing with the mouse. Can you draw a house? Can you use the mouse to draw a mouse? (Fortunately this is not a *Learn to Draw* book, so random scribbles are also perfectly fine.)
|
| 207 |
+
|
| 208 |
+
## Importing prewritten code
|
| 209 |
+
|
| 210 |
+
{i:"`import`;Mini Micro, `import`"}
|
| 211 |
+
As the last topic for this chapter, we're going to learn about the `import` command. This very useful function loads a file of MiniScript code stored somewhere else on disk. For example:
|
| 212 |
+
|
| 213 |
+
{i:"`/sys/lib`,`chars`"}
|
| 214 |
+
```terminal
|
| 215 |
+
]import "chars"
|
| 216 |
+
]print chars.heart
|
| 217 |
+
♥
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
{i:"`/sys/lib`;`/usr/lib`"}
|
| 221 |
+
The first line above tells Mini Micro to search for a MiniScript source file called `chars.ms` in the current directory, `/sys/lib`, or `/usr/lib`. In computers, "lib" stands for "library," and refers to a place to find reusable code that may be useful to a variety of programs. (You can also define other folders to check by assigning them to `env.importPaths`.) All the standard, built-in import modules are in `/sys/lib`, so let's go there and check them out.
|
| 222 |
+
|
| 223 |
+
```terminal
|
| 224 |
+
]cd "/sys/lib"
|
| 225 |
+
]dir
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
You'll find `chars.ms` in this directory. Use `load "chars"` and `edit` to view this file. You'll see that it looks like an ordinary MiniScript program, with some helpful comments and (in this case) a bunch of assignments to things like `left`, `upArrow`, `mu`, `emptyBox`, and `heart`. That last one is the value you used above when you printed `chars.heart`.
|
| 229 |
+
|
| 230 |
+
So here's how `import` works: the name file is found, and then run in a special way, such that any global variables created by that file become entries in a map with the name of the module. That assignment to `heart` in `chars.ms` becomes accessible as `chars.heart`, and so on for all the other values assigned. Explore the file and note a few others that you want to try, then exit the editor and try them. For example:
|
| 231 |
+
|
| 232 |
+
```terminal
|
| 233 |
+
]chars.dieFace[3]
|
| 234 |
+
⚂
|
| 235 |
+
]chars.bullet
|
| 236 |
+
•
|
| 237 |
+
```
|
| 238 |
+
|
| 239 |
+
D>Always read an import file to learn how to use it! Unlike the MiniScript language or the built-in Mini Micro classes, which are documented in places like the MiniScript wiki, most import modules are documented only within their own source.
|
| 240 |
+
|
| 241 |
+
{i:"`listUtil` module;Mini Micro, `listUtil` module"}
|
| 242 |
+
Let's try another one. There's a library module called `listUtil` ("util" here is short for "utilities"). As always with import modules, begin by reading the source:
|
| 243 |
+
|
| 244 |
+
{i:"`/sys/lib`,`listUtil`"}
|
| 245 |
+
```terminal
|
| 246 |
+
]load "listUtil"
|
| 247 |
+
356 lines loaded from /sys/lib/listUtil.ms
|
| 248 |
+
]edit
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
This one looks a little different, because most of the assignments in this file are adding to the built-in `list` type. For example, near the top of the file you should find something like this:
|
| 252 |
+
|
| 253 |
+
```miniscript
|
| 254 |
+
// contains: return true if this list contains the given element.
|
| 255 |
+
list.contains = function(item)
|
| 256 |
+
return self.indexOf(item) != null
|
| 257 |
+
end function
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
This assigns a function to `list.contains`. The built-in list type does not have a `contains` method, but after importing this module, it does! Try it out:
|
| 261 |
+
|
| 262 |
+
```terminal
|
| 263 |
+
]import "listUtil"
|
| 264 |
+
]a = [2, 4, 6, 8]
|
| 265 |
+
]a.contains 2
|
| 266 |
+
1
|
| 267 |
+
]a.contains 3
|
| 268 |
+
0
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
Edit `listUtils` again to see what other goodies have been added. Some of them are a bit complex, and it's OK if you don't understand everything in here just yet. But many of them are easy to understand, and could be quite useful:
|
| 272 |
+
|
| 273 |
+
```terminal
|
| 274 |
+
]a.min
|
| 275 |
+
2
|
| 276 |
+
]a.max
|
| 277 |
+
8
|
| 278 |
+
]a.any
|
| 279 |
+
6
|
| 280 |
+
```
|
| 281 |
+
|
| 282 |
+
Of course when you try it, you may get a different value for `a.any`, since the whole point of the new `list.any` method is to return a random element!
|
| 283 |
+
|
| 284 |
+
One particularly useful function added by `listUtil` is `list.removeVal`. You will of course find this in the `listUtil` source code, and it begins like this:
|
| 285 |
+
|
| 286 |
+
```miniscript
|
| 287 |
+
// removeVal: remove the first (or all) occurrences of a
|
| 288 |
+
// given value.
|
| 289 |
+
list.removeVal = function(val, removeAll=false)
|
| 290 |
+
```
|
| 291 |
+
|
| 292 |
+
This is handy because the standard `list.remove` method takes an element *index* to remove, not a value. You would pass `list.remove` an argument of 0 to remove the first element, 1 to remove the second element, and so on. But in many cases, what you have is a particular *value* you want to remove, and you don't know its index. You just want to take that value out of the list, wherever it is (if it's there at all). After doing `import "listUtil"`, you can do exactly that:
|
| 293 |
+
|
| 294 |
+
```terminal
|
| 295 |
+
]a.removeVal 6
|
| 296 |
+
]a
|
| 297 |
+
[2, 4, 8]
|
| 298 |
+
```
|
| 299 |
+
|
| 300 |
+
Of course all this works not only on the REPL command line, but also in your own programs. Now that you know about it, you'll notice `import` statements near the top of many of the demo programs. You should take some time to explore what these `/sys/lib` modules have to offer. Here's a quick summary of the most important ones.
|
| 301 |
+
|
| 302 |
+
{i:"import modules;`/sys/lib`"}
|
| 303 |
+
{caption:"Import modules found in `/sys/lib`."}
|
| 304 |
+
|chars|defines names for various special characters|
|
| 305 |
+
|grfon|functions to save and load data in GRFON format|
|
| 306 |
+
|json|functions to save and load data in JSON format|
|
| 307 |
+
|listUtil|adds additional methods to the `list` type|
|
| 308 |
+
|mapUtil|adds additional methods to the `map` type|
|
| 309 |
+
|mathUtil|additional math & geometry functions|
|
| 310 |
+
|pathUtil|functions for working with 2D paths|
|
| 311 |
+
|sounds|some predefined synthesized sounds|
|
| 312 |
+
|spriteControllers|extra functionality for sprites|
|
| 313 |
+
|stringUtil|handy string constants, and adds methods to the `string` type|
|
| 314 |
+
|textUtil|functions related to drawing text|
|
| 315 |
+
|tileUtil|functions related to tile displays|
|
| 316 |
+
|tsv|functions to read tab-separated data|
|
| 317 |
+
|turtle|defines a `Turtle` class, for doing turtle graphics|
|
| 318 |
+
|
| 319 |
+
Finally, it should be noted that an import module is also a perfectly valid MiniScript program in its own right. You can `load` an import module, and then `run` it like any other program. When you do, it will often run some testing code or otherwise demonstrate its functionality. This works via a special trick. When a MiniScript file is being executed via `import`, assignments at the "global" scope do not actually go into `globals` (they go into an in-between scope we might call *module scope*). You can tell when this is the case because `globals != locals`. Conversely, when a program is being run normally (not via `import`), then `globals == locals`. That's why you'll often see something at the bottom of an import module like
|
| 320 |
+
|
| 321 |
+
```miniscript
|
| 322 |
+
if globals == locals then runUnitTests
|
| 323 |
+
```
|
| 324 |
+
|
| 325 |
+
This says, if we're being run as a regular program (rather than imported), then call `runUnitTests`.
|
| 326 |
+
|
| 327 |
+
At some point, you'll want to create your own modules of handy code that you like to use in multiple programs. You can simply create your library directory with `file.makedir "/usr/lib"`, and put your own scripts there. These will be found by `import` just like the ones in `/sys/lib`.
|
| 328 |
+
|
| 329 |
+
## Exploring the Demos
|
| 330 |
+
|
| 331 |
+
{i:"`/sys/demo`,`scribble`"}
|
| 332 |
+
Going back to `/sys/demo`, you'll find one called `scribble.ms` that is just a slightly expanded version of the mouse-drawing program you made above. That one is worth studying a bit to see how the mouse is used.
|
| 333 |
+
|
| 334 |
+
{i:"`/sys/demo`,`forestFire`"}
|
| 335 |
+
For an example of display layers, you might look at the `forestFire` demo. This sets up layers 1 and 2 both in text mode, and then switches back and forth between them on each step of the simulation. You could also look at the `wumpusTrap` game, which uses several display layers, though two of these are tile and sprite, which we haven't covered yet.
|
| 336 |
+
|
| 337 |
+
{i:"`/sys/demo`,`theMatrix`;`/sys/demo`,`turtleDemo`"}
|
| 338 |
+
If it's `import` you're looking for, you can find that in many of the demos. The `balloons` demo imports both `mathUtil` and `pathUtil` to help move the balloons around the track. The `chars` module we introduced first in this chapter is used in `theMatrix` demo. And of course `turtleDemo`, which you first saw in the previous chapter, imports the `turtle` module to provide all that turtle graphics goodness.
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
A> **Chapter Review**
|
| 342 |
+
A> - You gained insight into Mini Micro's 8 display layers, and how to control them.
|
| 343 |
+
A> - You learned how to use the `mouse` module to read the mouse position and buttons.
|
| 344 |
+
A> - You came to grips with `import`, and explored the library of modules available to you in `/sys/lib/`.
|
| 345 |
+
A> - You have begun to think about what sort of code you might want to put into your own import modules, to make your future programs shorter and simpler.
|
| 346 |
+
|
data/day2.txt
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 2: Simple Math and Functions", startingPageNum:15}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> There’s so many exciting things going on in the computer industry, that if you have an idea, a dream, something that you want to do, then just go for it.
|
| 7 |
+
Q>— Stephanie Shirley (IT entrepreneur and philanthropist)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn how to add, subtract, multiply, and divide numbers and strings.
|
| 11 |
+
A> - Learn what *functions* are and how to use them.
|
| 12 |
+
A> - Explore a few of MiniScript's most common built-in functions.
|
| 13 |
+
A> - Appreciate that coding is an open-book exercise; you don't need to remember everything!
|
| 14 |
+
|
| 15 |
+
## Doing Math
|
| 16 |
+
|
| 17 |
+
In Day 1, you learned how to use `print` to make MiniScript display a number or string to the output area. Except for some minor changes in formatting, what you put in was exactly what you got out -- MiniScript wasn't really doing any work for you.
|
| 18 |
+
|
| 19 |
+
Today we'll learn how to put that computer to work! Some people are good at doing math in their heads, but nobody is as good at arithmetic as a computer. How many minutes are in a year? Let's use MiniScript to find out!
|
| 20 |
+
|
| 21 |
+
{caption: "Minutes in a year"}
|
| 22 |
+
```miniscript
|
| 23 |
+
print 365 * 24 * 60
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
The `*` character in MiniScript (and most other programming languages) means multiplication. So the program above multiplies 365 days in a year, times 24 hours in a day, times 60 minutes in an hour. The answer is printed to the output box.
|
| 27 |
+
|
| 28 |
+
The multiplication symbol `*` is just one of several *operators* that can be applied to numbers in MiniScript.
|
| 29 |
+
|
| 30 |
+
operator
|
| 31 |
+
: a symbol or word used to indicate an operation (such as addition, division, etc.)
|
| 32 |
+
|
| 33 |
+
Everyone learns the four basic arithmetic operators in school. MiniScript numbers support the same four, plus two more: power (raise the first number to the second), and modulo (remainder after division). We'll expand on these in a moment. For now, focus on how to write addition, subtraction, multiplication, and division, since these are by far the most common operators you are likely to use.
|
| 34 |
+
|
| 35 |
+
{i:"numbers, operators;operators, numeric"}
|
| 36 |
+
| `+` | addition |
|
| 37 |
+
| `-` | subtraction |
|
| 38 |
+
| `*` | multiplication |
|
| 39 |
+
| `/` | division |
|
| 40 |
+
| `%` | modulo |
|
| 41 |
+
| `^` | power |
|
| 42 |
+
|
| 43 |
+
These operators go between the numbers they operate on, just like you always did in school. So, `39 + 3` adds three to 39, just as you would expect. The order of operation is the same as standard arithmetic, too; power is always done first, then multiplication and division (and modulo), and finally addition and subtraction is done last. You can always control the order explicitly by putting in parentheses, again, just like standard math.
|
| 44 |
+
|
| 45 |
+
{caption: "Order of operations"}
|
| 46 |
+
```miniscript
|
| 47 |
+
print 2 + 3 * 4
|
| 48 |
+
print (2 + 3) * 4
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Line 1 in the above example first multiplies 3 and 4 to get 12, then adds 2 to get 14. This is because multiplication is always done before addition, unless you force it otherwise with parentheses. The second line above does exactly that: first it adds 2 and 3 to get 5, and then multiplies that by 4 to get 20.
|
| 52 |
+
|
| 53 |
+
D> Hang in there! We'll be making creating beautiful art and engrossing games before you know it.
|
| 54 |
+
|
| 55 |
+
## String Operators
|
| 56 |
+
|
| 57 |
+
Yesterday you learned about two types of data: numbers and strings. The mathy stuff above was all about numbers. What about strings?
|
| 58 |
+
|
| 59 |
+
It turns out that you can use most of the same operators on strings, too, but they have different effects. This is a type of math you probably did *not* learn in school, but fortunately it's very simple. When you add two strings together, it simply joins them in order into one big string. This operation is technically called *concatenation*.
|
| 60 |
+
|
| 61 |
+
{i: "string, concatenation"}
|
| 62 |
+
concatenation
|
| 63 |
+
: forming one larger string by joining two smaller strings together
|
| 64 |
+
|
| 65 |
+
For example:
|
| 66 |
+
|
| 67 |
+
{caption: "String concatenation"}
|
| 68 |
+
```miniscript
|
| 69 |
+
print "How" + "dy"
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
Can you guess what output this produces? Try it and see if you were right!
|
| 73 |
+
|
| 74 |
+
You can also subtract two strings. This lops the second string off the end of the first one, if indeed it is found at the end; otherwise it returns the first string as-is. Some examples will help:
|
| 75 |
+
|
| 76 |
+
{caption: "String subtraction"}
|
| 77 |
+
```miniscript
|
| 78 |
+
print "Howdy" - "dy"
|
| 79 |
+
print "Alien.png" - ".png"
|
| 80 |
+
print "No Such Thing" - "Item"
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
Line 1 prints out "How", which is what's left after you subtract "dy" from "Howdy". The second line similarly lops ".png" off the end of "Alien.png", and leaves you with just "Alien" (hey, that example's actually useful!). And the third example prints "No Such Thing" -- the subtraction has no effect in this case, since the string we're trying to subtract ("Item") does not occur at the end of "No Such Thing".
|
| 84 |
+
|
| 85 |
+
Multiplication with numbers can be thought of as a shortcut for repeated addition. For example, `5 * 3` is the same as `5 + 5 + 5`. With strings, it's same idea: you can multiply a string by a number, and this is the same as adding the string that many times. So `"Foo" * 3` is the same as `"Foo" + "Foo" + "Foo".` When you mix multiple operators, the order of operations is the same as with numbers, too. Try this one:
|
| 86 |
+
|
| 87 |
+
{i:"string, replication"}
|
| 88 |
+
{caption: "Spam and beans"}
|
| 89 |
+
```miniscript
|
| 90 |
+
print "Spam, " * 4 + "Baked Beans, and Spam!"
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Multiplying a string by a number this way is known as *string replication*. And it works not only for whole numbers. You can multiply a string by 0.5 to cut it in half, or by 2.5 to add it to itself two whole times and half of once more. Moreover, you can also use the division operator, `/`, to divide a string down to a fraction of its former self.
|
| 94 |
+
|
| 95 |
+
{pageBreak}
|
| 96 |
+
D> A common application of string replication is to print out some number of characters in a row. For example, `print "=" * 60` is much easier way to print a row of 60 equal signs than counting them as you type them in. And sometimes you'll need to print out some number of spaces that is calculated based on the length of *other* stuff you've printed out... string replication really comes in handy then!
|
| 97 |
+
|
| 98 |
+
Here are the operators you can use with strings:
|
| 99 |
+
|
| 100 |
+
{i:"string, operators;operators, string"}
|
| 101 |
+
| `+` | concatenation |
|
| 102 |
+
| `-` | subtraction |
|
| 103 |
+
| `*` | replication (by a number) |
|
| 104 |
+
| `/` | division (by a number) |
|
| 105 |
+
|
| 106 |
+
All of these operators begin with a string on the left side of the operator. With `*` and `/`, the right-hand side must be a number. But with `+` and `-`, the right-hand side can be anything... but if it's not a string, it gets automatically converted to a string, before being added to or subtracted from the left-hand string.
|
| 107 |
+
|
| 108 |
+
This is frequently used with `print`, to output some combination of strings and numeric values.
|
| 109 |
+
|
| 110 |
+
{caption: "The number 3.5E6 is automatically converted to a string"}
|
| 111 |
+
```miniscript
|
| 112 |
+
print "Your projected net worth is $" + 3.5E6 + "!"
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
## Functions
|
| 116 |
+
|
| 117 |
+
MiniScript has a variety of built-in *functions*, which are like commands or operations that you invoke by name. You've used one a bunch of times already: `print`.
|
| 118 |
+
|
| 119 |
+
function
|
| 120 |
+
: a block of code that can be called upon from other code
|
| 121 |
+
|
| 122 |
+
When you write
|
| 123 |
+
|
| 124 |
+
```miniscript
|
| 125 |
+
print 6 * 7
|
| 126 |
+
```
|
| 127 |
+
You are really saying, "Invoke the function called *print* and give it the value of 6 \* 7." (The values you give a function are called its *arguments* in computer jargon.)
|
| 128 |
+
|
| 129 |
+
argument
|
| 130 |
+
: a value given as input to a function
|
| 131 |
+
|
| 132 |
+
You probably saw this concept in middle-school math. Whenever you wrote an equation of like *y = f(x)*, this meant there was some function *f* that took *x* as its argument, and returned a value equal to *y*.
|
| 133 |
+
|
| 134 |
+
(You may also hear the term *parameter* -- for the sake of Day 2, consider this a synonym for *argument*. We'll elaborate on this in Chapter 11.)
|
| 135 |
+
|
| 136 |
+
Functions in MiniScript can cause things to happen -- for example, `print` causes output to appear on the screen -- or they can return a result (or both). Many of the built-in functions in MiniScript are the sort that return a result, usually based on the argument (or several arguments) that you give it. For example, the `sign(x)` function returns the sign of its argument: 1 if the argument is positive, -1 if the argument is negative, and 0 if the argument is exactly zero. Experiment a bit with this:
|
| 137 |
+
|
| 138 |
+
```miniscript
|
| 139 |
+
print sign(-0.1)
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
Try some other values, too.
|
| 143 |
+
|
| 144 |
+
D> Experimenting with code is an extremely powerful way to learn. Don't give up your power -- experiment!
|
| 145 |
+
|
| 146 |
+
Notice that when we're supplying arguments to a function, and doing something with the result, then we need to put parentheses around the arguments, just like you did with *f(x)* in school. Math functions are usually like this; try the `sqrt(x)` function (which returns the square root of its argument) for another example.
|
| 147 |
+
|
| 148 |
+
What if you need to supply more than one argument? In this case you just list all your arguments, separated by commas, within the parentheses. For example, there is a `round(x,d)` function that rounds a number *x* to *d* decimal places. You invoke it like this:
|
| 149 |
+
|
| 150 |
+
{caption:"Rounding numbers"}
|
| 151 |
+
```miniscript
|
| 152 |
+
print round(1.23468, 0)
|
| 153 |
+
print round(1.23468, 1)
|
| 154 |
+
print round(1.23468, 2)
|
| 155 |
+
print round(1.23468, 3)
|
| 156 |
+
print round(1.23468, 4)
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
In the first line above, the first argument is `1.23468`, and the second argument is `0`. Order matters -- that's the only way MiniScript can know which argument is which. So when you use an unfamiliar function, you'll look up exactly what the arguments are so you can supply them in the correct order.
|
| 160 |
+
|
| 161 |
+
Some functions have *optional* arguments. These can be left out, and MiniScript will assume some value for them. Because order matters, you can only omit arguments at the *end* of the argument list; you can't omit something in the middle and then provide more arguments after that, because the computer would have no way to know which ones you meant.
|
| 162 |
+
|
| 163 |
+
optional argument
|
| 164 |
+
: an argument that may be omitted when calling a function; a default value is used in this case. Also called an *optional parameter*.
|
| 165 |
+
|
| 166 |
+
As an example, let's revisit that `round` function above. The second argument -- the number of decimal places to round to -- is actually optional, with a default value of 0. So if you write just `round(1.23468)`, with a single argument, this is exactly the same as writing `round(1.23468, 0)`. But don't take my word for it -- try it!
|
| 167 |
+
|
| 168 |
+
However, sometimes a function doesn't need *any* arguments. Two good examples are `pi` and `rnd`. The `pi` function always returns the value of pi, `3.141593`. Conversely, `rnd` (which is short for "random") returns a different random number between 0 and 1 every time you call it. Try it:
|
| 169 |
+
|
| 170 |
+
{caption:"Using `pi` and `rnd`"}
|
| 171 |
+
```miniscript
|
| 172 |
+
print pi
|
| 173 |
+
print rnd
|
| 174 |
+
print rnd
|
| 175 |
+
print rnd
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
You should run this script multiple times, until you're satisfied that `rnd` really does return a different result every time you use it.
|
| 179 |
+
|
| 180 |
+
Now notice that when invoking a call without any arguments, you don't need any parentheses. (Technically you can put empty parentheses after the function name, but this is considered bad MiniScript style.)
|
| 181 |
+
|
| 182 |
+
You also don't need parentheses when the function you're calling is the first (main) word on the statement, as with `print`. This won't come as a surprise to you, since you've been using `print` without any parentheses since Day 1!
|
| 183 |
+
|
| 184 |
+
There's one more trick when it comes to invoking functions. Many functions that operate on a particular type of data can be invoked in a different way, using a dot (i.e. period) after the data, and before the function name. The value before the dot then gets passed in as the first argument. This seems a little pointless now, but will become more useful once we have variables (which are coming next). Here's an example:
|
| 185 |
+
|
| 186 |
+
```miniscript
|
| 187 |
+
print "Hello world".len
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
This uses the `len` function, which returns the length of the string (that is, a count of how many characters it contains). The above could also be written as:
|
| 191 |
+
|
| 192 |
+
```miniscript
|
| 193 |
+
print len("Hello world")
|
| 194 |
+
```
|
| 195 |
+
|
| 196 |
+
...but the dot syntax is more convenient in many cases we'll get to in the future.
|
| 197 |
+
|
| 198 |
+
{i:"functions, numeric;numeric functions"}
|
| 199 |
+
## Built-In Numeric Functions
|
| 200 |
+
|
| 201 |
+
In the table below is a list of built-in (or *intrinsic*) MiniScript functions that work with numbers. In this table, x and y are any number, i is an integer, and r is a number of radians.
|
| 202 |
+
|
| 203 |
+
intrinsic
|
| 204 |
+
: built into MiniScript, rather than added by your own code
|
| 205 |
+
|
| 206 |
+
{i:"intrinsic functions, numeric;numeric functions"}
|
| 207 |
+
{caption:"Intrinsic numeric functions"}
|
| 208 |
+
| `abs(x)` | absolute value of `x` |
|
| 209 |
+
| `acos(x)` | arccosine of `x`, in radians |
|
| 210 |
+
| `asin(x)` | arcsine of `x`, in radians |
|
| 211 |
+
| `atan(y, x=1)` | arctangent of `y/x`, in radians |
|
| 212 |
+
| `ceil(x)` | next whole number equal to or greater than `x` |
|
| 213 |
+
| `char(i)` | returns Unicode character with code point `i` |
|
| 214 |
+
| `cos(r)` | cosine of `r` radians |
|
| 215 |
+
| `floor(x)` | next whole number less than or equal to `x` |
|
| 216 |
+
| `pi` | 3.14159265358979 |
|
| 217 |
+
| `round(x, d=0)` | `x` rounded to `d` decimal places |
|
| 218 |
+
| `rnd(seed=null)` | returns random number which is at least 0 but less than 1 |
|
| 219 |
+
| `sign(x)` | sign of `x`: -1 if `x` < 0; 0 if `x` == 0; 1 if `x` > 0 |
|
| 220 |
+
| `sin(r)` | sine of `r` radians |
|
| 221 |
+
| `sqrt(x)` | square root of `x` |
|
| 222 |
+
| `str(x)` | converts `x` to a string |
|
| 223 |
+
| `tan(r)` | tangent of `r` radians |
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
It looks like a lot, but that's OK! You don't need to remember or even understand all of this table yet. It's included here just so you'll have a complete table to refer to later. For now, let's just touch on a few of the highlights.
|
| 227 |
+
|
| 228 |
+
Some of these functions you have seen already; we covered `sign`, `sqrt`, `pi`, and `round` above. Many of the others -- `sin`, `cos`, `tan`, `asin`, `acos`, and `atan` -- relate to trigonometry. Unless you are a mathematician or engineer, you may not have much use for these yet, but you may need them someday.
|
| 229 |
+
|
| 230 |
+
Two of these functions convert a number to a string, but in different ways. The `char` function gets a character from its Unicode code point; for example char(65) is "A", char(66) is "B", and so on.
|
| 231 |
+
|
| 232 |
+
Unicode
|
| 233 |
+
: a standard assignment of a unique number to every character in every human language
|
| 234 |
+
|
| 235 |
+
On the other hand, `str` converts a number to a string in the same way that `print` does. So `str(65)` returns the string "65". (If you print this out, this will look the same as printing 65 directly; for now you'll just have to trust that you really did convert it to a string yourself.)
|
| 236 |
+
|
| 237 |
+
Here's an example that uses the numeric function `sqrt`.
|
| 238 |
+
```miniscript
|
| 239 |
+
print "The square root of 100 is " + sqrt(100)
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
{i:"functions, string;string functions"}
|
| 243 |
+
## Built-In String Functions
|
| 244 |
+
|
| 245 |
+
All the string functions except `slice` are designed to be invoked on strings using dot syntax. But as noted above, they can also be invoked by putting the function name first, and then passing the string in as the first argument. The table on the next page shows them with dot syntax. In this table, `self` refers to the string you called it on, `s` is another string argument, and `i` is an integer (whole) number.
|
| 246 |
+
|
| 247 |
+
Again, don't worry about understanding all of this. You'll only need a few of these for quite a while. `len`, which you've already seen, is handy to get the length of a string. You may use `upper` and `lower` to convert a string to uppercase or lowercase.
|
| 248 |
+
|
| 249 |
+
To find the Unicode code point of the first character in a string, you can call the `code` function. This is the inverse of the `char` function you saw in the *numeric functions* table. To do the inverse of `str`, that is convert a string into a number, you'll use `val`, but that's covered in detail on Day 4.
|
| 250 |
+
|
| 251 |
+
{pageBreak}
|
| 252 |
+
{i:"intrinsic functions, string;string functions"}
|
| 253 |
+
{caption:"Intrinsic string functions", colWidths:"150,*"}
|
| 254 |
+
| `.code` | Unicode code point of first character of `self` |
|
| 255 |
+
| `.hasIndex(i)` | 1 if `i` is >= 0 and \< self.len; otherwise 0 |
|
| 256 |
+
| `.indexes` | a list of all valid indexes of the string |
|
| 257 |
+
| `.indexOf(s, after=null)` | 0-based position of first substring `s` within `self`, or `null` if not found; optionally begins the search after the given position |
|
| 258 |
+
| `.len` | length (number of characters) of `self` |
|
| 259 |
+
| `.lower` | lowercase version of `self` |
|
| 260 |
+
| `.remove(s)` | `self`, but with first occurrence of substring s removed (if any) |
|
| 261 |
+
| `.replace(oldVal, newVal, maxCount=null)` | returns a string with the first `maxCount` elements matching `oldVal` replaced with `newVal`; if `maxCount` not specified, replaces all |
|
| 262 |
+
| `.split(delimiter=" ", maxCount=null)` | splits `self` into a list of at most `maxCount` elements |
|
| 263 |
+
| `.upper` | uppercase version of `self` |
|
| 264 |
+
| `.val` | converts `self` to a number (if `self` is not a valid number, returns 0) |
|
| 265 |
+
| `.values` | list of individual characters in `self` (e.g. "spam".values = ["s", "p", "a", "m"] |
|
| 266 |
+
| `slice(s, from, to)` | a substring of `s` starting at index `from` and going up to index `to` |
|
| 267 |
+
|
| 268 |
+
Example usage:
|
| 269 |
+
|
| 270 |
+
```miniscript
|
| 271 |
+
print "Hello World!".upper
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
## Coding is an Open-Book Process
|
| 276 |
+
|
| 277 |
+
Some readers will feel a strong urge to study and memorize all the details thrown at you in this chapter. Don't bother! There is no final exam at the end of this book. The only test is how well you can apply your new coding skills to solve your own problems, and when you do that, you are allowed -- nay, encouraged! -- to use the book, the Internet, the MiniScript Cheat Sheet, the person sitting next to you, and any other resources at your disposal.
|
| 278 |
+
|
| 279 |
+
So, far more valuable than memorizing all those functions is just remembering that you saw them. When you need to do something with a number or a string, say to yourself, "hmm, there's probably a function for that," and then either come back to this chapter, or use one of the other resources you know about to find the details. You will naturally come to remember any functions you use a lot; for everything else, look them up as needed.
|
| 280 |
+
|
| 281 |
+
To help stretch those new coding muscles, here's one more sample program to try.
|
| 282 |
+
|
| 283 |
+
{caption: "String and number functions review"}
|
| 284 |
+
```miniscript
|
| 285 |
+
print "The next whole number after pi is " + ceil(pi)
|
| 286 |
+
print "...which is " + "Huge!".upper
|
| 287 |
+
print "Rounded to 2 decimal places, pi is " + round(pi, 2)
|
| 288 |
+
print "...which is " + "NOT So Huge".lower
|
| 289 |
+
print """Hello World"" has " + "Hello World".len + " characters"
|
| 290 |
+
print "...and the code point of the first one is " + "H".code
|
| 291 |
+
print "Your lucky number is: " + floor(rnd * 100)
|
| 292 |
+
```
|
| 293 |
+
|
| 294 |
+
As always, be sure to type carefully. Especially be careful with the embedded (and so doubled) quotation marks in line 5. (Review Day 1 if you've forgotten what that's about.)
|
| 295 |
+
|
| 296 |
+
A> **Chapter Review**
|
| 297 |
+
A> - You discovered how to do math with numbers and strings.
|
| 298 |
+
A> - You can invoke functions, including providing arguments, and using dot syntax.
|
| 299 |
+
A> - You browsed a list of built-in numeric and string functions.
|
| 300 |
+
A> - You learned that you don't need to memorize all the details, because it's OK to look them up when you need them.
|
| 301 |
+
|
data/day20.txt
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 20: Sounds & Music", startingPageNum:237}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> There is no recipe, there is no one way to do things — there is only your way. And if you can recognize that in yourself and accept and appreciate that in others, you can make magic.
|
| 7 |
+
Q>— Ara Katz (co-founder of Seed Health, Spring, and BeachMint)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Load and play digitized sounds from files on disk.
|
| 11 |
+
A> - Learn how to synthesize sounds from scratch.
|
| 12 |
+
A> - Use your new audio skills to create music from code.
|
| 13 |
+
|
| 14 |
+
So far, working with Mini Micro has been like watching a silent movie. Unless you happen to have printed `char(7)` at some point, your programs have not made a peep. Grab your earbuds or apologize to your neighbor, because that's going to change today!
|
| 15 |
+
|
| 16 |
+
## Playing Sound Files
|
| 17 |
+
|
| 18 |
+
There are two ways to make sounds in Mini Micro. The first one involves loading a digitized sound from disk, and simply playing it.
|
| 19 |
+
|
| 20 |
+
Mini Micro comes with a bunch of sound files in `/sys/sounds`. `cd` to that directory, then use `dir` to list them. Use the `view` command to hear what they sound like (remember to put quotes around the file name!). Many of the sounds are musical instruments, and we'll cover how to use these to make music in the last part of this chapter. Others are sound effects, like *bonus.wav*, *pickup.wav*, and *pop.wav*.
|
| 21 |
+
|
| 22 |
+
To play these sounds from code is easy: load the sound, and then play it.
|
| 23 |
+
|
| 24 |
+
```terminal
|
| 25 |
+
]snd = file.loadSound("/sys/sounds/bonus.wav")
|
| 26 |
+
]snd.play
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
{i:"`Sound` class"}
|
| 30 |
+
The result of `file.loadSound` is a `Sound` object, another built-in class in Mini Micro. This class has some properties that don't apply to file-based sounds, so for now let's just consider the following:
|
| 31 |
+
|
| 32 |
+
{caption:"Properties and methods for digitized sounds. *snd* is any `Sound` object.", colWidths:"150,*"}
|
| 33 |
+
|`snd.duration`|length of the sound, in seconds|
|
| 34 |
+
|`snd.loop`|if true, repeat the sound indefinitely until stopped|
|
| 35 |
+
|`snd.play` *volume=1*, *pan=0*, *speed=1*|play this sound|
|
| 36 |
+
|`snd.stop`|stop playing this sound|
|
| 37 |
+
|`snd.isPlaying`|returns 1 (true) if sound is playing, 0 (false) if not|
|
| 38 |
+
|`Sound.stopAll`|stop all currently playing sounds|
|
| 39 |
+
|
| 40 |
+
The `play` method is the only one with any parameters, though they are all optional. The parameters are:
|
| 41 |
+
|
| 42 |
+
- *volume*: how loud to play, from 0 (silent) to 1 (full volume).
|
| 43 |
+
- *pan*: adjusts the left/right stereo balance, from -1 (left speaker only) to 1 (right speaker only). 0 means to play in both speakers equally.
|
| 44 |
+
- *speed*: a factor that controls payback speed and pitch. 1 is normal speed, 0.5 is half speed, 2 is double speed, and so on. Faster speeds produce a higher pitch.
|
| 45 |
+
|
| 46 |
+
As an example, try this `for` loop:
|
| 47 |
+
|
| 48 |
+
{caption:"How to play the guitar."}
|
| 49 |
+
```miniscript
|
| 50 |
+
snd = file.loadSound("/sys/sounds/elecGuitarC4.wav")
|
| 51 |
+
for x in range(1, 2, 0.25)
|
| 52 |
+
snd.play 1, 0, x
|
| 53 |
+
wait snd.duration
|
| 54 |
+
end for
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
This plays the sound five times, at a different speed each time. Notice that when you play a sound at double speed, it sounds exactly one octave higher.
|
| 58 |
+
|
| 59 |
+
Of course you are not limited to the sounds that ship with Mini Micro. You can import your own sounds, in WAV or OGG format. The easiest way to do this is to click on the lower disk slot, use "Mount Folder..." to mount a folder in the host OS containing your sound files, and then access these in Mini Micro under the `/usr2` directory. When you find a sound file you want to use in your own programs, copy it onto your *user.minidisk* file for easy access.
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
## Synthesizing Sounds
|
| 63 |
+
|
| 64 |
+
Loading a sound file is one way of making sounds. The other way is to create sounds from scratch, using Mini Micro's sophisticated synthesizer.
|
| 65 |
+
|
| 66 |
+
To understand how synthesized sounds work, we first have to talk a bit about how sound works in general. Sound is repeated, tiny changes in air pressure over time. These air pressure variations cause little receptors in your ear to vibrate. Each receptor is tuned to a different *frequency*, which is how many times the air pressure goes up and down per second. Humans can typically hear frequencies between 20 and 20,000 cycles per second or so. (The shorthand for "cycles per second" is a unit called Hertz, and abbreviated Hz.)
|
| 67 |
+
|
| 68 |
+
Low frequencies, like 20 Hz, sound like very deep, low sounds, while high frequencies are high-pitched sounds. The relationship between frequency and pitch is not linear; to go up one octave in pitch, you must double the frequency. Conversely, to go down one octave in pitch, you would cut the frequency in half.
|
| 69 |
+
|
| 70 |
+
Speakers are simply hardware that produce these changes in air presure, by moving the speaker cone back and forth according to an electronic signal. Microphones do the reverse, responding to changes in air pressure by producing a signal that a computer can read. This is known as *digitizing* the sound, and is how most of those sound files in `/sys/sounds/` were created.
|
| 71 |
+
|
| 72 |
+
If you were to take the signal from a microphone and graph it, to represent the air pressure changes visually, you would often see some pattern that repeats over and over, hundreds or thousands of times per second. That pattern is called the *waveform*.
|
| 73 |
+
|
| 74 |
+
waveform
|
| 75 |
+
: one cycle of a sound wave, representing the air pressure changes that are repeated *frequency* times per second
|
| 76 |
+
|
| 77 |
+
frequency
|
| 78 |
+
: how many times per second the waveform is repeated to produce a sound
|
| 79 |
+
|
| 80 |
+
Note that in the context of Mini Micro, *waveform* refers to just *one* cycle of the air pressure changes, which is repeated many times per second. In other contexts, people may use "waveform" to refer to a graph of the entire sound, from beginning to end.
|
| 81 |
+
|
| 82 |
+
So to define a simple sound, we need to know:
|
| 83 |
+
|
| 84 |
+
1. What the waveform looks like.
|
| 85 |
+
2. How many times per second that waveform should be repeated (i.e. the frequency).
|
| 86 |
+
3. How long the sound should last.
|
| 87 |
+
4. How the volume should change over the course of the sound.
|
| 88 |
+
|
| 89 |
+
That third one, how long the sound should last, is called the *duration* of the sound; and that last one is called the *envelope*.
|
| 90 |
+
|
| 91 |
+
envelope
|
| 92 |
+
: how the amplitude (volume) of a sound varies from the beginning to the end of the sound
|
| 93 |
+
|
| 94 |
+
And now you have all the background you need to understand sound synthesis in Mini Micro. The `Sound` class has some additional properties that correspond to the concepts above.
|
| 95 |
+
|
| 96 |
+
{caption:"Properties and methods related to synthesizing sounds from scratch.", colWidths:"120,*"}
|
| 97 |
+
|`snd.duration`|length of the sound, in seconds|
|
| 98 |
+
|`snd.freq`|frequency (repeats of `waveform` per second)|
|
| 99 |
+
|`snd.envelope`|how the sound amplitude varies over the course of the sound|
|
| 100 |
+
|`snd.fadeIn`|length of fade-in period when sound begins, in seconds|
|
| 101 |
+
|`snd.fadeOut`|length of fade-out period when sound begins, in seconds|
|
| 102 |
+
|`snd.init` *duration, freq, envelope, waveform*|shortcut for setting the four key properties|
|
| 103 |
+
|`snd.mix` *sound2, level|add another synthesized sound into this one|
|
| 104 |
+
|
| 105 |
+
Let's begin, as usual, by experimenting on the REPL command line.
|
| 106 |
+
|
| 107 |
+
```terminal
|
| 108 |
+
]s = new Sound
|
| 109 |
+
]s.duration = 1
|
| 110 |
+
]s.freq = 440
|
| 111 |
+
]s.envelope = 1
|
| 112 |
+
]s.waveform = Sound.sineWave
|
| 113 |
+
]s.play
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
You should hear a clean, pure note (for the musically inclined, this is A above middle C) that lasts for 1 second. Let's go over each of these properties in turn.
|
| 117 |
+
|
| 118 |
+
First, `duration`. This one is easy enough: it's how long the sound lasts, in seconds. Try changing it and hear the difference.
|
| 119 |
+
|
| 120 |
+
```terminal
|
| 121 |
+
]s.duration = 1.5
|
| 122 |
+
]s.play
|
| 123 |
+
]s.duration = 0.5
|
| 124 |
+
]s.play
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
Next, frequency. You probably have a good idea of this by now, but go ahead and play with it a bit to be sure.
|
| 128 |
+
|
| 129 |
+
```terminal
|
| 130 |
+
]s.freq = 220
|
| 131 |
+
]s.play
|
| 132 |
+
]s.freq = 880
|
| 133 |
+
]s.play
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
However, you aren't limited to a single, constant frequency for the whole sound. If you give Mini Micro a list of frequencies, it will smoothly interpolate between them. Try these:
|
| 137 |
+
|
| 138 |
+
```terminal
|
| 139 |
+
]s.duration = 2
|
| 140 |
+
]s.freq = [220, 880]
|
| 141 |
+
]s.play
|
| 142 |
+
]s.freq = [880, 220]
|
| 143 |
+
]s.play
|
| 144 |
+
]s.freq = [220,300] * 8
|
| 145 |
+
]s.play
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
That last one is using list replication; go ahead and print out `s.freq` to make sure you understood that correctly. And you can hear what it does to the sound: the pitch varies between 220 and 300 Hz, 8 times over the 2-second duration of the sound.
|
| 149 |
+
|
| 150 |
+
Envelope is a little trickier. Here, Mini Micro is expecting either 1, which indicates a constant amplitude for the sound; or a list of values between 0 and 1, which indicate how the amplitude should vary over the course of the sound. For example, if you use an envelope of `[0,1]`, then the sound will start at an amplitude of 0 (silent) and ramp up te full volume by the end of the sound. An envelope of `[1,0]` would do the opposite. Try it!
|
| 151 |
+
|
| 152 |
+
```terminal
|
| 153 |
+
]s.freq = 440
|
| 154 |
+
]s.envelope = [0,1]
|
| 155 |
+
]s.play
|
| 156 |
+
]s.envelope = [1,0]
|
| 157 |
+
]s.play
|
| 158 |
+
]s.envelope = [0,1,0]
|
| 159 |
+
]s.play
|
| 160 |
+
]s.envelope = [1,0,1]
|
| 161 |
+
]s.play
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
You can use as many values in your `envelope` list as you like; the synthesizer will evenly space these amplitude changes over the length of the sound. And of course you don't have to stick to only values of 0 and 1; you can use any values in between. For example, using list replication again:
|
| 165 |
+
|
| 166 |
+
```terminal
|
| 167 |
+
]s.envelope = [1, 0.25] * 8
|
| 168 |
+
]s.play
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
It should be noted that the envelope isn't the *only* factor that affects the amplitude of the sound over time; there are also `fadeIn` and `fadeOut` properties. These are a simple way to make the sound fade in (go from zero to full amplitude) at the start of the sound, and fade out (go from full amplitude down to zero) at the end of the sound. This is an important feature in digital sounds, because without some fade-in and fade-out, you may hear an unpleasant click when the sound begins or ends. If you don't specify a value for one of these, a value of 0.01 seconds is used by default.
|
| 172 |
+
|
| 173 |
+
Finally, let's consider the waveform. In the examples so far we've been using a sine wave, which is a pure, smooth variation in air pressure over time. Such a smooth waveform strongly excites only one of the frequency detectors in your ear, producing a sound that is clean and pure (and so rather boring).
|
| 174 |
+
|
| 175 |
+
You can specify a waveform as a list of values from -1 to 1, and Mini Micro will interpolate over that list for each cycle of the sound. But the `Sound` class also has five common waveforms built right in, as shown below.
|
| 176 |
+
|
| 177 |
+
{width:"97%"}
|
| 178 |
+

|
| 179 |
+
|
| 180 |
+
We've been using `Sound.sineWave`. Try `Sound.triangleWave` next, which is pretty close to a sine wave, but not quite so pure.
|
| 181 |
+
|
| 182 |
+
```terminal
|
| 183 |
+
]s.waveform = Sound.triangleWave
|
| 184 |
+
]s.play
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
It's the same pitch as before, but now a little richer, less pure. (If you need to compare again, switch back to `Sound.sineWave` and play that again.) Next try `Sound.sawtoothWave`. (I'm not showing the commands for that — you know what you're doing by now — but please try it, since you can't really know what it sounds like until you try!) A sawtooth wave is substantially buzzier than the triangle wave. Finally, try `Sound.squareWave`, which has a nice retro "8-bit" sound to it.
|
| 188 |
+
|
| 189 |
+
There is one more waveform which we haven't tried yet: `Sound.noiseWave`. This one is different from all the others; while the others have a fairly simple shape, this one looks like complex, random gibberish. And that's pretty much what it is. Random, chaotic air pressure changes like that don't sound like tones to us at all; they sound like noise. But if you repeat this noisy waveform hundreds or thousands of times per second, our ears will *still* detect the repeating pattern and hear a tone. So when you want to make pure noise, use it with a very low frequency, like so:
|
| 190 |
+
|
| 191 |
+
```terminal
|
| 192 |
+
]s.waveform = Sound.noiseWave
|
| 193 |
+
]s.freq = 5
|
| 194 |
+
]s.play
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
Of course you may want to try other frequencies too, and there's certainly no harm in using high frequencies with noise if you like the sound. It's totally up to you. With the right choice of parameters, you can approximate the sound of footsteps, impacts, wind, waves, and so on.
|
| 198 |
+
|
| 199 |
+
The `init` method is a shorthand for setting `duration`, `freq`, `envelope`, and `waveform` all at once, in that order. For just playing around on the REPL, assigning (or changing) these properties one at a time is probably nicer. But in code, you might want to do more of it at once, something like:
|
| 200 |
+
|
| 201 |
+
```terminal
|
| 202 |
+
]s = new Sound
|
| 203 |
+
]s.init 0.5, [2000,50], [1,0.25]
|
| 204 |
+
{"__isa": Sound, "duration": 0.5, "freq": [2000, 50], "waveform": [1
|
| 205 |
+
, -1], "envelope": [1, 0.25], "fadeOut": 0.01, "fadeIn": 0.01, "_han
|
| 206 |
+
dle": null}
|
| 207 |
+
]s.play
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
Note that each of the parameters to `Sound.init` has a default value; in the example above, we omitted the last one (waveform), and it used `Sound.sawtoothWave` by default.
|
| 211 |
+
|
| 212 |
+
The last topic to cover in synthesizing sounds is the `mix` method. This lets you take a second synthesized sound, and add it to the first, so that when you play them you essentially get both at once. For example:
|
| 213 |
+
|
| 214 |
+
```terminal
|
| 215 |
+
]pew = new Sound
|
| 216 |
+
]pew.init 0.5, [2000,10], [1,0]
|
| 217 |
+
]pew.play
|
| 218 |
+
]psh = new Sound
|
| 219 |
+
]psh.init 0.2, 5, [1,0], Sound.noiseWave
|
| 220 |
+
]psh.play
|
| 221 |
+
]pew.mix psh
|
| 222 |
+
]pew.play
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
In lines 1-3 above, we synthesize and test a "pew" sound (a rapid falling tone). Then in lines 4-6, we synthesize and test a noisy burst sound. Line 7 mixes the noisy burst into the pew sound. Now when we play that sound, we hear the noisy burst at the beginning.
|
| 226 |
+
|
| 227 |
+
I think you can see by now that Mini Micro's sound synthesizer is very versatile. With only a few lines of code, you can make a wide variety of sounds. You could make the audio for a game entirely with synthesized sounds, especially if you're going for a retro feel; or you could use synthesized sounds as stand-ins until you find the digitized sounds you need. Synthesized sounds also have a lot of flexibility to respond to what's going on in the program, changing any of their parameters according to user input or other data. In this way, they have the potential to provide endless variation, and avoid that repetitive feeling that often results from digitized sounds.
|
| 228 |
+
|
| 229 |
+
## Making Music
|
| 230 |
+
|
| 231 |
+
One use for both digitized and sythesized sounds is making music. Of course if you just want a background score, you could load a sound file in OGG format and simply play it. But if you want to use synthesized sounds, or make music on the fly from code, then you will need to know what frequency to use for each note.
|
| 232 |
+
|
| 233 |
+
{i:"`noteFreq`"}
|
| 234 |
+
Mini Micro has an intrinsic global function just for that, called `noteFreq`. It takes a *note number*, and returns the proper frequency for that note.
|
| 235 |
+
|
| 236 |
+
note number
|
| 237 |
+
: a standard way of identifying notes over a 9-octave range, with each note assigned a unique number
|
| 238 |
+
|
| 239 |
+
Middle C (also known as C4, i.e. note C in octave 4) is note number 60, and the next highest note, C sharp, is note 61. After that is 62 (D), 63 (D sharp or E flat), and so on. When you include all the sharps and flats, there are 12 notes per octave, so high C (also known as C5) is note 72, and low C (i.e. C3) is note 48.
|
| 240 |
+
|
| 241 |
+

|
| 242 |
+
|
| 243 |
+
By passing these note numbers to the `noteFreq` function, you can get the right frequency to make any note.
|
| 244 |
+
|
| 245 |
+
```terminal
|
| 246 |
+
]snd = new Sound
|
| 247 |
+
]snd.init 1, noteFreq(60)
|
| 248 |
+
{"__isa": Sound, "duration": 1, "freq": 261.625549, "waveform": [1,
|
| 249 |
+
-1], "envelope": 1, "fadeOut": 0.01, "fadeIn": 0.01, "_handle": null
|
| 250 |
+
}
|
| 251 |
+
]snd.play
|
| 252 |
+
]snd.freq = noteFreq(67)
|
| 253 |
+
]snd.play
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
The above plays a sawtooth wave middle C (note 60) followed by middle G (note 67).
|
| 257 |
+
|
| 258 |
+
With digitized sounds, the procedure is a little different. You first need to know what pitch the sound was recorded as. All of the digitized instruments in `/sys/sounds` were recorded at note 60 (C4). Then, divide the desired frequency by the original note frequency, and use this ratio as the `speed` parameter to `Sound.play`.
|
| 259 |
+
|
| 260 |
+
```terminal
|
| 261 |
+
]snd = file.loadSound("/sys/sounds/celloLongC4.wav")
|
| 262 |
+
]snd.play // plays as note 60 (C4)
|
| 263 |
+
]snd.play 1, 0, noteFreq(67)/noteFreq(60) // plays as note 67 (G4)
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
Here's a little program from the Mini Micro Cheat Sheet that illustrates how to make a little song. The notes are defined by a list, where each element is a note number and duration.
|
| 267 |
+
|
| 268 |
+
{caption:"Playing a song with code. Charge!"}
|
| 269 |
+
```miniscript
|
| 270 |
+
// notes defined as: [note, duration]
|
| 271 |
+
notes = [[60, 0.1], [64, 0.1], [67, 0.1],
|
| 272 |
+
[72, 0.2], [67, 0.1], [72, 0.4]]
|
| 273 |
+
snd = new Sound
|
| 274 |
+
for n in notes
|
| 275 |
+
snd.init n[1], noteFreq(n[0])
|
| 276 |
+
snd.play
|
| 277 |
+
wait snd.duration
|
| 278 |
+
end for
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
**Challenge:** modify the above program to use a digitized horn sound (`/sys/sounds/hornC4.wav`). You will need to remove the `snd.init` call, and change the `snd.play` line to calculate the correct pitch for each note as shown above. Finally, the `wait` command will need changing to use `n[0]` as the wait time.
|
| 282 |
+
|
| 283 |
+
It's worth noting that computers and music have a long and beautiful history together. In recent years the practice of "live coding" has become an increasingly popular form of performance art, where a composer/programmer/performer writes code to create music in real-time, in front of an audience. Who knows, perhaps your own practice creating music in Mini Micro will lead to performing on stage one day!
|
| 284 |
+
|
| 285 |
+
## Exploring the Demos
|
| 286 |
+
|
| 287 |
+
{i:"`/sys/demo`,`drumMachine`"}
|
| 288 |
+
The poster child for sound and music is certainly `drumMachine.ms` (in the `/sys/demo` folder). It uses a display type (tile) that you haven't learned about yet, but you should be able to understand how it is loading and playing sounds. It's also a fun program to play with. Feel free to load a different set of sounds, and get your jam on!
|
| 289 |
+
|
| 290 |
+
{i:"`sounds` module;Mini Micro, `sounds` module;`/sys/lib`,`listUtil`"}
|
| 291 |
+
Most of the other game demos use sounds of either sort, but for synthesized sounds, the best place to look might actually be the import module `/sys/lib/sounds.ms`. This defines a handful of generally useful sounds. To use these in your own program, you can `import "sounds"` and then simply call (for example) `sounds.ding.play`. But today you should actually `load` this as a program, `run` it (it goes into a demo mode when run this way), and then study the source code.
|
| 292 |
+
|
| 293 |
+
A> **Chapter Review**
|
| 294 |
+
A> - You learned how to load and play digitized sounds from WAV and OGG files.
|
| 295 |
+
A> - You synthesized sounds from scratch, using nothing but code and ingenuity.
|
| 296 |
+
A> - You created music with the help of the `noteFreq` function.
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
{gap:50}
|
| 300 |
+
{width:"28%"}
|
| 301 |
+

|
| 302 |
+
|
| 303 |
+
|
data/day21.txt
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 21: Fireworks Demo", startingPageNum:249}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> After a long time of practicing, our work will become natural, skillful, swift, and steady.
|
| 7 |
+
Q>— Bruce Lee (martial artist, actor, instructor, and philosopher)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Rest and recouperate.
|
| 11 |
+
A> - Enter and play with a fun Mini Micro demo that includes display layers, sound, and mouse input.
|
| 12 |
+
A> - Review & synthesize what you've learned so far.
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
Congratulations! You have come a long way since Day 1. You've learned all about the MiniScript language, and how to use it in three different environments: the Try-It! page, command-line MiniScript, and Mini Micro. You've also learned many of the custom classes and functions available in MiniScript to work with the display, mouse, and keyboard. If you've been doing one chapter a day, then it's been three weeks since you started your journey, and you have just a bit over one week left in this course.
|
| 16 |
+
|
| 17 |
+
It's time to take a break, and instead of trying to pile on any new knowledge, let your existing knowledge settle a bit. You deserve a rest! In fact, your achievements so far are worthy of celebration! And what better way to celebrate than... fireworks?
|
| 18 |
+
|
| 19 |
+

|
| 20 |
+
|
| 21 |
+
This program will generate pretty, physics-based fireworks, launched from wherever you click the mouse, complete with sounds on launch and burst. To create all the visual effects, we will use several display layers:
|
| 22 |
+
|
| 23 |
+
- Display 7 will be the background, but we'll switch it to pixel mode so we can draw a nice deep gradient.
|
| 24 |
+
- Display 5, the standard `gfx` layer, is where most of the drawing will take place.
|
| 25 |
+
- Display 2 will be used to draw a brief "flash" (white circle) when a rocket bursts.
|
| 26 |
+
|
| 27 |
+
We will leave the standard `text` layer (display 3) alone, so you can see your typing when the program is not running. The graphics displays will be set to a scale of 3, making the pixels three times bigger than normal, so that the firework particles are easier to see.
|
| 28 |
+
|
| 29 |
+
Also, to help us with some list operations like removing an element by value, or selecting a random value, we will import the *listUtil* module. So, as you might expect, our program begins with the `import` statement, followed by setting up the displays. Use `reset` (or freshly launch Mini Micro) to clear any program you might have in memory, then `edit` to enter the code in Listing 1.
|
| 30 |
+
|
| 31 |
+
{caption:"Listing 1 (Fireworks set-up code)."}
|
| 32 |
+
```miniscript
|
| 33 |
+
// set up
|
| 34 |
+
import "listUtil"
|
| 35 |
+
clear
|
| 36 |
+
gfx.clear color.clear, 960/3, 640/3
|
| 37 |
+
gfx.scale = 3
|
| 38 |
+
|
| 39 |
+
display(2).mode = displayMode.pixel
|
| 40 |
+
flashGfx = display(2)
|
| 41 |
+
flashGfx.clear color.clear, gfx.width, gfx.height
|
| 42 |
+
flashGfx.scale = gfx.scale
|
| 43 |
+
flashGfx.color = color.white
|
| 44 |
+
|
| 45 |
+
display(7).mode = displayMode.pixel
|
| 46 |
+
bkgnd = display(7)
|
| 47 |
+
bkgnd.clear color.black, gfx.width, gfx.height
|
| 48 |
+
bkgnd.scale = gfx.scale
|
| 49 |
+
for y in range(0, bkgnd.height-1)
|
| 50 |
+
c = color.lerp("#550055", "#000022", y/bkgnd.height)
|
| 51 |
+
bkgnd.line 0, y, bkgnd.width, y, c
|
| 52 |
+
end for
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
Save this program as `fireworks.ms`. Then run, and you should see a purple gradient representing the evening sky. (This also makes a nice background; someday you may want to put something like this into `/usr/startup.ms` to make it your standard work background!)
|
| 56 |
+
|
| 57 |
+
Here's the next portion of the fireworks program:
|
| 58 |
+
|
| 59 |
+
{caption: "Listing 2 (more Fireworks set-up).", number-from: 22}
|
| 60 |
+
```miniscript
|
| 61 |
+
burstColors = [color.yellow, color.red, color.blue,
|
| 62 |
+
color.aqua, color.pink, color.lime, color.fuchsia]
|
| 63 |
+
|
| 64 |
+
launchSnd = new Sound
|
| 65 |
+
launchSnd.init 0.3, 5, [0,1,0], Sound.noiseWave
|
| 66 |
+
|
| 67 |
+
burstSnd = new Sound
|
| 68 |
+
burstSnd.init 1, 2, [1,0.1,0.01,0], Sound.noiseWave
|
| 69 |
+
|
| 70 |
+
panForX = function(x)
|
| 71 |
+
return 2 * (x / gfx.width - 0.5)
|
| 72 |
+
end function
|
| 73 |
+
|
| 74 |
+
for x in range(0, gfx.width, 100)
|
| 75 |
+
launchSnd.play
|
| 76 |
+
wait
|
| 77 |
+
burstSnd.play
|
| 78 |
+
wait
|
| 79 |
+
end for
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Lines 22-23 set up a list of colors to use for the firework bursts. This is a long list, so we simply hit return after a comma, and continue it on the next line. (Note that this might slightly confuse the code editor, and cause it to mark the closing square bracket in red — don't let that alarm you.)
|
| 83 |
+
|
| 84 |
+
Next, we define a couple of synthesized sounds for the rocket launch and burst. Remember that the parameters to `Sound.init` are *duration*, *frequency*, *envelope*, and *waveform*.
|
| 85 |
+
|
| 86 |
+
We want to use the stereo pan (i.e. left-right balance) to make these sounds appear in the left speaker when they occur on the left side of the screen, and in the right speaker when they occur on the right (and smoothly interpolate in between). The `panForX` function does that calculation, converting the *x* coordinate (which goes from 0 to `gfx.width`, the width of the graphics display) into a pan value (-1 to 1). Finally, the `for` loop on lines 35-40 tests all that out, playing sounds that should pan from left to right. (You might need to put on some headphones or ear buds to hear the effect.)
|
| 87 |
+
|
| 88 |
+
D> Code a little, test a little!
|
| 89 |
+
|
| 90 |
+
Once that's working, delete that `for` loop starting on line 35, and add this code instead.
|
| 91 |
+
|
| 92 |
+
{caption: "Listing 3 (Fireworks `Particle` class).", number-from: 35}
|
| 93 |
+
```miniscript
|
| 94 |
+
// make a Particle class
|
| 95 |
+
Particle = {}
|
| 96 |
+
Particle.x = 0
|
| 97 |
+
Particle.y = 0
|
| 98 |
+
Particle.vx = 0
|
| 99 |
+
Particle.vy = 0
|
| 100 |
+
Particle.color = color.yellow
|
| 101 |
+
Particle.trail = null
|
| 102 |
+
Particle.maxTrails = 5
|
| 103 |
+
Particle.gravity = -15
|
| 104 |
+
Particle.dragFactor = 0.99
|
| 105 |
+
Particle.update = function(dt=0.1)
|
| 106 |
+
// apply gravity and drag to velocity
|
| 107 |
+
self.vy = (self.vy + self.gravity*dt) * self.dragFactor
|
| 108 |
+
self.vx = self.vx * self.dragFactor
|
| 109 |
+
|
| 110 |
+
// apply velocity to position
|
| 111 |
+
self.x = self.x + self.vx * dt
|
| 112 |
+
self.y = self.y + self.vy * dt
|
| 113 |
+
|
| 114 |
+
// draw, appending to the trail
|
| 115 |
+
gfx.setPixel self.x, self.y, self.color
|
| 116 |
+
if self.trail == null then self.trail = []
|
| 117 |
+
self.trail.push [self.x, self.y]
|
| 118 |
+
|
| 119 |
+
// erase when the trail is too long
|
| 120 |
+
if self.trail.len > self.maxTrails then
|
| 121 |
+
pos = self.trail.pull
|
| 122 |
+
gfx.setPixel pos[0], pos[1], color.clear
|
| 123 |
+
end if
|
| 124 |
+
end function
|
| 125 |
+
Particle.die = function()
|
| 126 |
+
// erase trail
|
| 127 |
+
for pos in self.trail
|
| 128 |
+
gfx.setPixel pos[0], pos[1], color.clear
|
| 129 |
+
end for
|
| 130 |
+
// remove from global list
|
| 131 |
+
particles.removeVal self // (removeVal is from listUtil)
|
| 132 |
+
end function
|
| 133 |
+
|
| 134 |
+
// keep a list of all Particle instances
|
| 135 |
+
particles = []
|
| 136 |
+
|
| 137 |
+
p = new Particle
|
| 138 |
+
p.vx = 30
|
| 139 |
+
p.vy = 90
|
| 140 |
+
for i in range(90)
|
| 141 |
+
p.update
|
| 142 |
+
yield
|
| 143 |
+
end for
|
| 144 |
+
p.die
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
In Listing 3, we define a class called Particle. This represent things that move according to simply physics, like the rockets and the embers (i.e. burst particles). The physics is quite simple: in addition to the position (*x* and *y*), we also keep track of velocity (*vx* and *vy*). On every step, the vertical velocity *vy* is updated by gravity, and then the position is updated by the velocity.
|
| 148 |
+
|
| 149 |
+
To draw a particle, we're just using `gfx.setPixel`. But we also keep track of the last several positions it was drawn, in the `trail` list. So when we draw the particle at a new position, we add that position to the trail; and when the trail is too long, we pull off the oldest point and erase it (by setting the pixel to `color.clear`).
|
| 150 |
+
|
| 151 |
+
The `Particle.die` function is called when we want to remove a particle completely. It erases all the pixels in the trail, and then removes the particle from the global `particles` list. Note that this `removeVal` method we're using here is not standard MiniScript; it is something added by the `listUtil` module imported on line 1.
|
| 152 |
+
|
| 153 |
+
Finally, all that code at the end (lines 78-85) is, again, test code just to make sure that things are working so far. When you run this, you should see a particle leap up from the 0, 0 corner of the screen, arc across the screen, and then disappear.
|
| 154 |
+
|
| 155 |
+
When that's working, delete lines 78-85, and then continue on with Listing 4. Here we make a *subclass* of Particle, to handle the special case of a particle that is actually a Rocket (i.e. launched from the ground, and not yet burst).
|
| 156 |
+
|
| 157 |
+
subclass
|
| 158 |
+
: a class created from another class using `new`, so that it inherits all of the values and methods of that other class
|
| 159 |
+
|
| 160 |
+
superclass
|
| 161 |
+
: the more general class that a subclass is created from
|
| 162 |
+
|
| 163 |
+
Subclasses can be a very handy OOP (object-oriented programming) technique. They allow us to make a more specialized version of a class, one that is like the superclass in most ways, but also specialized in certain ways. In this case, the superclass is our general-purpose `Particle` class, and the subclass is `Rocket`. A rocket behaves like other particles in most ways, except that at some point in its flight, it bursts, creating a shower of other particles.
|
| 164 |
+
|
| 165 |
+
{caption: "Listing 4 (Fireworks `Rocket` class).", number-from: 78}
|
| 166 |
+
```miniscript
|
| 167 |
+
// make a subclass of Particle that represents a rocket
|
| 168 |
+
Rocket = new Particle
|
| 169 |
+
Rocket.timeTillBurst = 3
|
| 170 |
+
Rocket.update = function(dt=0.1)
|
| 171 |
+
// do standard particle update...
|
| 172 |
+
super.update dt
|
| 173 |
+
|
| 174 |
+
// then, update time till burst, and burst when it's time
|
| 175 |
+
self.timeTillBurst = self.timeTillBurst - dt
|
| 176 |
+
if self.timeTillBurst <= 0 then
|
| 177 |
+
// remove the rocket particle and its trail
|
| 178 |
+
self.die
|
| 179 |
+
|
| 180 |
+
// create the burst particles
|
| 181 |
+
c = burstColors.any // (.any provided by listUtil)
|
| 182 |
+
for i in range(1,40)
|
| 183 |
+
p = new Ember
|
| 184 |
+
p.startColor = c
|
| 185 |
+
p.x = self.x
|
| 186 |
+
p.y = self.y
|
| 187 |
+
angle = 2 * pi * rnd
|
| 188 |
+
speed = 10 + 50*rnd
|
| 189 |
+
p.vx = speed * cos(angle)
|
| 190 |
+
p.vy = speed * sin(angle)
|
| 191 |
+
particles.push p
|
| 192 |
+
end for
|
| 193 |
+
|
| 194 |
+
// flash and bang
|
| 195 |
+
flashGfx.fillEllipse self.x-10, self.y-10, 20, 20
|
| 196 |
+
globals.haveFlash = true
|
| 197 |
+
burstSnd.play 1, panForX(self.x), 0.9 + 0.2*rnd
|
| 198 |
+
end if
|
| 199 |
+
end function
|
| 200 |
+
|
| 201 |
+
Ember = new Particle
|
| 202 |
+
p = new Rocket
|
| 203 |
+
p.vx = 30
|
| 204 |
+
p.vy = 90
|
| 205 |
+
particles.push p
|
| 206 |
+
for i in range(100)
|
| 207 |
+
for p in particles
|
| 208 |
+
p.update
|
| 209 |
+
end for
|
| 210 |
+
yield
|
| 211 |
+
end for
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
{i:"`super`"}
|
| 215 |
+
Notice the `Rocket.update` function, which overrides the `Particle.update` function in the superclass. But the first thing that this function does is call `super.update`, which means that it runs the standard `Particle.update` code.
|
| 216 |
+
|
| 217 |
+
D> `super` is a special MiniScript keyword that finds the identifier after the dot somewhere higher in the chain of classes related by `new`. It's commonly used in a subclass method to call the same method in the superclass.
|
| 218 |
+
|
| 219 |
+
It then goes on to figure out if it's time to burst. When it is, it calls its own `die` method, then creates a bunch of burst particles (using the `Ember` class we trivially defined in the test code on line 112), as well as drawing a flash (white circle).
|
| 220 |
+
|
| 221 |
+
The test code here defines `Ember` as a `new Particle`, but does not override any properties or methods. That's a pointless thing to do, *except* in a case like this, where we know we're going to need an ember class later, but for now are content with standard particle behavior. The test code then creates and launches a `Rocket`, with a little update loop to make it go.
|
| 222 |
+
|
| 223 |
+
Note that there is nothing here yet to erase the flash on the `flashGfx` display. So once the rocket bursts, it leaves a yellow circle behind. That's OK — we'll fix that later.
|
| 224 |
+
|
| 225 |
+
Moving on, clear out that test code starting on line 112, and let's create that Ember class for real.
|
| 226 |
+
|
| 227 |
+
{caption: "Listing 5 (Fireworks `Ember` class).", number-from: 112}
|
| 228 |
+
```miniscript
|
| 229 |
+
// make another Particle subclass that represents the
|
| 230 |
+
// embers that float down after the rocket bursts
|
| 231 |
+
Ember = new Particle
|
| 232 |
+
Ember.age = 0
|
| 233 |
+
Ember.gravity = -5
|
| 234 |
+
Ember.dragFactor = 0.90
|
| 235 |
+
Ember.startColor = color.pink
|
| 236 |
+
Ember.endColor = "#88000088" // translucent red
|
| 237 |
+
Ember.update = function(dt=0.1)
|
| 238 |
+
// age, adjust our color, and when it's time, die
|
| 239 |
+
self.age = self.age + dt
|
| 240 |
+
if self.age > 3 then
|
| 241 |
+
self.die
|
| 242 |
+
else
|
| 243 |
+
// update our color
|
| 244 |
+
self.color = color.lerp(self.startColor, self.endColor, self.age/3)
|
| 245 |
+
// and then do standard particle update
|
| 246 |
+
super.update dt
|
| 247 |
+
end if
|
| 248 |
+
end function
|
| 249 |
+
|
| 250 |
+
p = new Ember
|
| 251 |
+
p.x = 120
|
| 252 |
+
p.y = 200
|
| 253 |
+
p.vx = 30
|
| 254 |
+
for i in range(50)
|
| 255 |
+
p.update
|
| 256 |
+
yield
|
| 257 |
+
end for
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
As usual, we include a bit of test code at the bottom so you can make sure it's working. When you run this, a little pink ember should appear near the top of the screen, fly off to the right, and fade out. That's what makes embers different from other particles: they change colors over time. Notice that the call to `super.update` here doesn't happen until later in `Ember.update`, *after* updating the color; otherwise the very first appearance of the ember would be in the wrong color.
|
| 261 |
+
|
| 262 |
+
Now we're almost done! We need a function to launch a rocket, and a main loop. Since any test code for the launch function would be practically the full main loop anyway, let's just press on and finish the program. Delete the test code starting on line 134, and wrap it up with Listing 6.
|
| 263 |
+
|
| 264 |
+
{caption: "Listing 6 (Fireworks launch method and main loop).", number-from: 134}
|
| 265 |
+
```miniscript
|
| 266 |
+
// function to create and launch a new firework
|
| 267 |
+
launchAt = function(x)
|
| 268 |
+
p = new Rocket
|
| 269 |
+
p.x = x / gfx.scale
|
| 270 |
+
p.y = 0
|
| 271 |
+
p.vx = 30 * rnd - 15
|
| 272 |
+
p.vy = 10 * rnd + 80
|
| 273 |
+
p.timeTillBurst = 3 + 3 * rnd
|
| 274 |
+
particles.push p
|
| 275 |
+
launchSnd.play 0.3, panForX(p.x), 0.9 + 0.2*rnd
|
| 276 |
+
end function
|
| 277 |
+
|
| 278 |
+
// main loop
|
| 279 |
+
mouseWasDown = false
|
| 280 |
+
haveFlash = false
|
| 281 |
+
while true
|
| 282 |
+
// clear the flashes, if we have any
|
| 283 |
+
if haveFlash then
|
| 284 |
+
flashGfx.fillRect 0, 0, flashGfx.width,
|
| 285 |
+
flashGfx.height, color.clear
|
| 286 |
+
globals.haveFlash = false
|
| 287 |
+
end if
|
| 288 |
+
// launch whenever the mouse is clicked
|
| 289 |
+
mouseIsDown = mouse.button
|
| 290 |
+
if mouseIsDown and not mouseWasDown then
|
| 291 |
+
launchAt mouse.x
|
| 292 |
+
end if
|
| 293 |
+
mouseWasDown = mouseIsDown
|
| 294 |
+
// update all particles
|
| 295 |
+
for p in particles
|
| 296 |
+
p.update
|
| 297 |
+
end for
|
| 298 |
+
yield
|
| 299 |
+
end while
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
The `launchAt` function takes an *x* position in unscaled screen coordinates, like the mouse position (and unlike the `gfx` display in this program, which is scaled by a factor of 3). It creates a new `Rocket` instance, just like our test code from Listing 4. Many of the rocket properties — its initial velocity, and the time until it bursts — are randomized, which makes the fireworks more interesting and fun. The function also plays the launch sound, with stereo pan adjusted for the particle position, and the speed (pitch) randomized a bit so the launches don't sound too monotonous.
|
| 303 |
+
|
| 304 |
+
The main loop has several jobs. First, it clears the flash display, if indeed any flashes were drawn the last time through the loop. We do this with `flashGfx.fillRect`, filling with `color.clear`, because if we used `flashGfx.clear`, it would reset the display scale and then we'd just have to set it back.
|
| 305 |
+
|
| 306 |
+
Second, it watches `mouse.button` and compares it to the previous value, to determine when the mouse has just been clicked. When that happens, it calls our `launchAt` method to launch a rocket at the mouse position.
|
| 307 |
+
|
| 308 |
+
{i:"`yield`"}
|
| 309 |
+
Finally, it loops over all particles and calls `update` on them. And then it calls the `yield` intrinsic, which tells Mini Micro to wait until the start of the next frame (frames are when the screen is updated, roughly 60 times per second).
|
| 310 |
+
|
| 311 |
+
Run the program, and click around the screen. A rocket should launch from below the mouse each time you click. Go ahead and spam the mouse button! These fireworks are for *you*; you deserve it! (Just press control-C to break out of the main loop when done.)
|
| 312 |
+
|
| 313 |
+
## Going Farther
|
| 314 |
+
|
| 315 |
+
This has turned out to be a pretty short program — considerably shorter than the Sea Battle game you did in Chapter 14. Mini Micro allows you to make a lot of fun with not that much code! But since it was so short, perhaps you have time to try a bit more on your own?
|
| 316 |
+
|
| 317 |
+
One simple hack would be to make it launch *two* rockets each time the mouse is clicked, instead of just one. This is literally just one extra line in the main loop. Why not give it a try?
|
| 318 |
+
|
| 319 |
+
Another tweak is to change how long the embers last before they die. Right now they disappear after 3 seconds. Can you change that to 6 seconds? You will need to change the code in two places, because this time is used both to make the color fade out, and to actually remove the particles. Change it in both places, and make sure that works.
|
| 320 |
+
|
| 321 |
+
{i:"magic number"}
|
| 322 |
+
Then, realize that this is a rather poor design, having that magic number in two different places. (This is similar to the concept of *magic strings* discussed in Chapter 14.) Add a `maxAge` property to the Ember class, and use that instead of the number in both places.
|
| 323 |
+
|
| 324 |
+
Finally, we still have all the embers from a particular burst fading out and disappearing at the same time. Wouldn't it be more interesting if that time were randomized a bit too, so some embers last longer than others? Find where the embers are created, and we assign a random velocity. Assign a random `maxAge` there as well. Run your program and confirm that the embers in a burst now disappear at different times rather than all at once.
|
| 325 |
+
|
| 326 |
+
If you have difficulty with any of this, don't be discouraged! I encourage you to make use of the community resources you can find via the MiniScript web site (`https://miniscript.org`). There is a Discord server, forums, and more. Don't be afraid to ask for help — it is a very supportive and welcoming community, and asking for help is something even professional programmers do on a regular basis.
|
| 327 |
+
|
| 328 |
+
{pageBreak}
|
| 329 |
+
A> **Chapter Review**
|
| 330 |
+
A> - You built the *Fireworks* demo, celebrating all your hard work and progress up to this point.
|
| 331 |
+
A> - You reviewed and practiced using display layers, mouse input, pixel graphics, and sound.
|
| 332 |
+
A> - You learned about subclasses, superclasses, and the `super` keyword.
|
| 333 |
+
A> - You went "beyond the book" and made some significant changes to the program on your own. Day by day, your coding skills are growing!
|
data/day22.txt
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 22: Sprites", startingPageNum:263}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> With too many bells and whistles, it gets complicated. With too few, there are inefficiencies. Designing something just powerful enough is an art.
|
| 7 |
+
Q>— Barbara Liskov (2008 A. M. Turing award winner)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn about *sprites* and how they are used in games and utilities.
|
| 11 |
+
A> - Explore the SpriteDisplay, Sprite, and Bounds classes in Mini Micro.
|
| 12 |
+
A> - Write code to make sprites move, rotate, scale, and respond to mouse clicks.
|
| 13 |
+
|
| 14 |
+
If you look carefully at any two-dimensional (2D) video game, you will see the screen full of little images that move around. This is easiest to see in older games (though still true today). Consider one of the greatest arcade games of all time, *Ms. Pac-Man*. Our heroine, Ms. Pac-Man, travels around the maze eating dots; and if you look closely she often overlaps the walls of the maze slightly. The four ghosts also travel around the maze, passing right over the dots and power-up pills, as well as each other.
|
| 15 |
+
|
| 16 |
+
Now consider how you would create such an effect using the tools you have so far, such as the `drawImage` and `fillRect` methods on `PixelDisplay`. You could certainly keep track of where the ghosts are, and draw them in their correct positions for each frame. But to make them move, you would need to erase them, perhaps by filling the space they previously occupied with black. But this would clobber any dots that had been there, as well as any parts of the maze they happened to overlap. So to fix this, you would have to redraw the dots *and* the maze on every frame, too.
|
| 17 |
+
|
| 18 |
+
All this drawing would be difficult and inefficient, resulting in a slow, flickery display. Yet these machines from the 1980s drew things like this — and much more complicated scenes, with lots of moving objects overlapping a complex background — at video rates, without breaking a sweat. How did they do it? And more importantly, how can *you* do it?
|
| 19 |
+
|
| 20 |
+
The answer is... sprites.
|
| 21 |
+
|
| 22 |
+
sprite
|
| 23 |
+
: an image, often with transparent areas and usually much smaller than the screen, which can be made to appear on screen and efficiently moved, rotated, and scaled, all without disrupting the background or other sprites
|
| 24 |
+
|
| 25 |
+
D> OK, fine, some readers will realize that in Mini Micro there is another answer, which is to take advantage of display layers. By drawing your ghost and player images in a different display layer than the maze and dots, you could clear the moving images on each frame without clobbering the background, and thereby make such an animation work. But sprites are both easier and far more efficient than this approach.
|
| 26 |
+
|
| 27 |
+
PRINT>The image on the next page is from a Mini Micro game called *Dr. Yond's Zombie Experiment*. The characters (both human and zombie), the giant floating brain, and the balls of energy are all sprites, as indicated with the white boxes in the figure. These are drawn and animated very efficiently over the pavement and buildings in the background.
|
| 28 |
+
EBOOK>The following image is from a Mini Micro game called *Dr. Yond's Zombie Experiment*. The characters (both human and zombie), the giant floating brain, and the balls of energy are all sprites, as indicated with the yellow boxes in the figure. These are drawn and animated very efficiently over the pavement and buildings in the background.
|
| 29 |
+
|
| 30 |
+

|
| 31 |
+
|
| 32 |
+
## Creating and Drawing Sprites
|
| 33 |
+
|
| 34 |
+
To make a program like this with your own code, you first have to create a sprite object. You may recall from Chapter 12 (or yesterday's fireworks program) that you create an object in MiniScript using `new` with the desired class. In this case what we desire is the built-in Sprite class. Try it right on the command line:
|
| 35 |
+
|
| 36 |
+
```miniscript
|
| 37 |
+
spr = new Sprite
|
| 38 |
+
spr.image = file.loadImage("/sys/pics/Wumpus.png")
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
This creates a new Sprite object, and assigns an image (a fuzzy purple wumpus image from `/sys/pics`) to its `image` property.
|
| 42 |
+
|
| 43 |
+
It does not, however, cause the wumpus to appear on screen. Right now our sprite object is just hanging out in memory, not attached to any display. To make it appear, we need to add it to a sprite display. In the default configuration, display 4 is a sprite display, so we can do:
|
| 44 |
+
|
| 45 |
+
```miniscript
|
| 46 |
+
display(4).sprites.push spr
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
You should see a wumpus peeking out from the lower-left corner of the screen. To bring it more into view, assign to its `x` and `y` properties:
|
| 50 |
+
|
| 51 |
+
```miniscript
|
| 52 |
+
spr.x = 480
|
| 53 |
+
spr.y = 320
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
That will move the sprite into the center of the screen.
|
| 57 |
+
|
| 58 |
+
If you don't see the sprite, then the most likely cause is that you made a typo in the file path. You could print out `spr.image` and if it is null, repeat the `file.loadImage` line above, checking your typing and capitalization very carefully.
|
| 59 |
+
|
| 60 |
+
{i:"`Sprite` class"}
|
| 61 |
+
PRINT>So far, you've seen the `image`, `x`, and `y` properties of the `Sprite` class. The full set is presented in the table at the top of the next page. We'll cover the rest before the chapter is done.
|
| 62 |
+
EBOOK>So far, you've seen the `image`, `x`, and `y` properties of the `Sprite` class. The full set is presented in the table below. We'll cover the rest before the chapter is done.
|
| 63 |
+
|
| 64 |
+
{gap:20}
|
| 65 |
+
|
| 66 |
+
{caption:"Properties and methods for the Sprite class (where `spr` is any Sprite object). The last three rows are functions; all the others are properties which may be read or assigned."}
|
| 67 |
+
|`spr.image`|image to use for the sprite's appearance|
|
| 68 |
+
|`spr.x`|horizontal position of the center of the sprite in the display|
|
| 69 |
+
|`spr.y`|vertical position of the center of the sprite in the display|
|
| 70 |
+
|`spr.scale`|scale factor: 1 is normal size, 0.5 is half size, etc.|
|
| 71 |
+
|`spr.rotation`|sprite rotation angle in degrees|
|
| 72 |
+
|`spr.tint`|tint color (white for no tint)|
|
| 73 |
+
|`spr.localBounds`|defines rectangular bounds relative to the sprite itself|
|
| 74 |
+
|`spr.worldBounds`|get the bounds of the sprite on screen|
|
| 75 |
+
|`contains`(*pt*)|return true if the sprite bounds contains the given x/y point|
|
| 76 |
+
|`overlaps`(*other*)|return true if the sprite is touching other sprite or Bounds|
|
| 77 |
+
|
| 78 |
+
## Animating Sprites
|
| 79 |
+
|
| 80 |
+
Sprites excel at animation! And to do it is simple: you only need to change one or more of the sprite's properties (like position, scale, and rotation) from frame to frame. Let's first try a simple animation of our sprite's `rotation` property.
|
| 81 |
+
|
| 82 |
+
```miniscript
|
| 83 |
+
for ang in range(0,360)
|
| 84 |
+
spr.rotation = ang
|
| 85 |
+
yield
|
| 86 |
+
end for
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
{i:"`yield`"}
|
| 90 |
+
You should see the wumpus slowly spin counter-clockwise. The `yield` call here makes the script wait until the next frame; frames happen 60 times per second. Since we're changing our angle by 1 degree on each frame, it takes 6 seconds to complete the loop. If we wanted to spin faster, we could simply change the angle more on each step. Try replacing the `range` call above with `range(0, 360, 6)` for example, which should complete six times faster.
|
| 91 |
+
|
| 92 |
+
What about position? That's just as easy:
|
| 93 |
+
|
| 94 |
+
```miniscript
|
| 95 |
+
for x in range(100, 900, 10)
|
| 96 |
+
spr.x = x
|
| 97 |
+
yield
|
| 98 |
+
end for
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Type that in, and watch the wumpus zoom across the screen from left (x=100) to right (x=900). Now you try: make a loop that moves the Wumpus vertically instead of horizontally. (Remember that `y` values in Mini Micro range from 0 at the bottom of the screen, to 640 at the top.)
|
| 102 |
+
|
| 103 |
+
Finally, let's look at the `scale` property. This is a factor that's multiplied by the sprite's natural size. When `scale` is 1, then one pixel in the image appears as one pixel on screen. If you set `scale` to 2, then each image pixel covers two pixels on screen. You're not limited to whole numbers, either; you can set the scale to 0.1 or 1.25 or anything else, and the sprite will be scaled accordingly.
|
| 104 |
+
|
| 105 |
+
But this section is about animation, so let's animate! This time, how about a `while` loop:
|
| 106 |
+
|
| 107 |
+
```miniscript
|
| 108 |
+
while true
|
| 109 |
+
spr.scale = 1 + sin(time)/2
|
| 110 |
+
yield
|
| 111 |
+
end while
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
{i:"`time`;`sin`"}
|
| 115 |
+
The scale here is set using the built-in `time` function, which returns the time in seconds since the start of the program. This is passed through `sin` to produce a scale factor that slowly changes between 0.5 and 1.5. Just press Control-C when you've had enough of this animation.
|
| 116 |
+
|
| 117 |
+
Our furry Wumpus is a single image, so loading it was very easy. But most animated characters have many different versions of the image, in different poses or with different expressions. Sometimes these are stored on disk as separate little image files, but other times, multiple sprite images are arranged into one big image file called a "sprite sheet."
|
| 118 |
+
|
| 119 |
+
sprite sheet
|
| 120 |
+
: a single image file that contains multiple smaller images meant for use as sprites
|
| 121 |
+
|
| 122 |
+
Mini Micro has examples of both styles in the `/sys/pics/` directory. For example, `cd` down into "/sys/pics/KP" and do a `dir`. You will see eight images of K.P., a cute little character who looks like a handheld video game with arms and legs. (Remember that you can use the `view` command to preview an image in Mini Micro.)
|
| 123 |
+
|
| 124 |
+
But now go back up to the `/sys/pics` directory (perhaps by using `cd ".."`), and view the file "Enemies.png".
|
| 125 |
+
|
| 126 |
+

|
| 127 |
+
|
| 128 |
+
Here you can see one image file that includes quite a lot of little pictures: four versions of four different enemies, plus eight facial expressions, and a box of instructions on the right. (That's a feature most sprite sheets don't have, but this one does.)
|
| 129 |
+
|
| 130 |
+
To make a sprite from a sprite-sheet is a two-step process: (1) load the sprite sheet itself; (2) extract the smaller image you need using `Image.getImage`. For example:
|
| 131 |
+
|
| 132 |
+
```miniscript
|
| 133 |
+
sheet = file.loadImage("Enemies.png")
|
| 134 |
+
spr = new Sprite
|
| 135 |
+
spr.image = sheet.getImage(0, 128*3, 128, 128)
|
| 136 |
+
display(4).sprites.push spr
|
| 137 |
+
spr.x = 480; spr.y = 320
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
The only real difference between this and the Wumpus example you did before is the `getImage` call on line 3, which plucks out a square area that starts at 0 on the left, 128\*3 pixels up from the bottom, and is 128 pixels wide by 128 pixels tall.
|
| 141 |
+
|
| 142 |
+
This leads to the final common trick for animating sprites: changing the image over time. You probably noticed in the Enemies sprite sheet that there were two versions of the colored enemies, differing only in which foot is down. By alternating between these two images, we can give the appearance of the enemy marching in place. Continuing from the previous example...
|
| 143 |
+
|
| 144 |
+
```miniscript
|
| 145 |
+
img1 = sheet.getImage(0, 128*3, 128, 128)
|
| 146 |
+
img2 = sheet.getImage(0, 128*2, 128, 128)
|
| 147 |
+
while true
|
| 148 |
+
spr.image = img1
|
| 149 |
+
wait 0.2
|
| 150 |
+
spr.image = img2
|
| 151 |
+
wait 0.2
|
| 152 |
+
end while
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
You should see the yellow enemy grumpily stamping his feet.
|
| 156 |
+
|
| 157 |
+
At this point we've just done very simple, quick animation demos at the REPL prompt. In real games, things get a little more complicated: you probably have multiple sprites all doing different things. How do you keep track of what to change on every frame? ...Object-oriented programming to the rescue!
|
| 158 |
+
|
| 159 |
+
The solution is to create a subclass of `Sprite` for each kind of sprite you need in your game, all with an `update` method to be called on each frame. Each such object is responsible for keeping track of its own state, so it knows what it needs to change and when. Then the main loop has nothing to do but call `update` on all the sprites. Here's an example that illustrates that, using the same enemy sprite as above. But this is getting too long to type in on the command line, so you will probably want to use `edit` to invoke the code editor.
|
| 160 |
+
|
| 161 |
+
{i:"`/sys/lib`,`mathUtil`"}
|
| 162 |
+
{caption:"Stampy demo."}
|
| 163 |
+
```miniscript
|
| 164 |
+
import "mathUtil"
|
| 165 |
+
clear
|
| 166 |
+
sheet = file.loadImage("/sys/pics/Enemies.png")
|
| 167 |
+
// Make a subclass of Sprite called Stamper
|
| 168 |
+
Stamper = new Sprite
|
| 169 |
+
Stamper.frames = [] // (image for each frame of animation)
|
| 170 |
+
Stamper.frames.push sheet.getImage(0, 128*3, 128, 128)
|
| 171 |
+
Stamper.frames.push sheet.getImage(0, 128*2, 128, 128)
|
| 172 |
+
Stamper.target = {"x":480, "y":320}
|
| 173 |
+
Stamper.lastStepTime = 0
|
| 174 |
+
Stamper.curFrame = 0
|
| 175 |
+
Stamper.update = function()
|
| 176 |
+
if time > self.lastStepTime + 0.2 then
|
| 177 |
+
// Change to the other image (stamp stamp!)
|
| 178 |
+
self.curFrame = 1 - self.curFrame
|
| 179 |
+
self.image = self.frames[self.curFrame]
|
| 180 |
+
self.lastStepTime = time
|
| 181 |
+
end if
|
| 182 |
+
// Move towards the target
|
| 183 |
+
mathUtil.moveTowardsXY self, self.target, 5
|
| 184 |
+
end function
|
| 185 |
+
|
| 186 |
+
// Create a Stamper instance, and add to the sprite display.
|
| 187 |
+
stampy = new Stamper // yes, it's stampy the Stamper!
|
| 188 |
+
display(4).sprites.push stampy
|
| 189 |
+
stampy2 = new Stamper // and he has a friend
|
| 190 |
+
display(4).sprites.push stampy2
|
| 191 |
+
stampy2.target = {"x":800, "y":100}
|
| 192 |
+
|
| 193 |
+
// Main loop: update sprites, and set target on mouse click
|
| 194 |
+
while true
|
| 195 |
+
for spr in display(4).sprites
|
| 196 |
+
spr.update // (assumes all sprites have an update function)
|
| 197 |
+
end for
|
| 198 |
+
if mouse.button then stampy.target = mouse + {}
|
| 199 |
+
yield
|
| 200 |
+
end while
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
When you run this, you should see two enemy sprites appear. One slinks off into the corner and stays there, while the other moves to any point on the screen that you click with the mouse. And both enemies stamp their feet the whole time.
|
| 204 |
+
|
| 205 |
+
Let's quickly go over how this works. The first line imports the "mathUtil" module, so we can use the handy `mathUtil.moveTowardsXY` function to move our sprite towards a target. On lines 5-21 we define a Sprite subclass called Stampy, with properties to keep track of both sprite frames (images plucked from the sprite sheet), as well as a target position, what time we last took a step, and the current frame. The class also includes an `update` method, that assigns a new `image` when it is time to take a step, and moves the whole sprite 5 pixels closer to the target.
|
| 206 |
+
|
| 207 |
+
Lines 24-25 create a new `Stamper` instance named `stampy`, and add it to the sprite display. Lines 26-28 create *another* `Stamper` instance, and give it a different initial target.
|
| 208 |
+
|
| 209 |
+
Finally, the main loop updates all the sprites (assuming that all sprites have an `update` method, which is true in this demo because they are all derived from `Stampy`). Also, when the mouse button is pressed, it sets the target of our `stampy` sprite to the mouse position (plus an empty dictionary; see note below). Finally, we remember to call `yield` in the main loop, so that it the loop will run only once per screen update.
|
| 210 |
+
|
| 211 |
+
D> What's going on with `mouse + {}` in line 35? Adding two maps together always results in a *new* map, even if one of the maps you're adding is empty. So this is a way of creating a fresh copy of the `mouse` map. Without this trick, we would be telling `stampy` to use the built-in `mouse` map as its target, and when the values in that map get updated (as they automatically do whenever you move the mouse), the sprite would automatically follow it. Try it: remove `+ {}` from that line, and see what happens!
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
## Controlling Draw Order
|
| 215 |
+
|
| 216 |
+
The last example had two sprites on screen. If you directed the the first one to the lower-right corner, so that it overlapped the second sprite, then you may have noticed that at always appeared behind the second one.
|
| 217 |
+
|
| 218 |
+
That's controlled by the order in which sprites appear in the `sprite` list of the display. In that last example, we first pushed `stampy` onto the list at position 0, and then we pushed `stampy2`, which would put it at position 1. You can think of the sprite display as simply walking through its sprite list, drawing the sprites in order, so in this case `stampy2` appears on top.
|
| 219 |
+
|
| 220 |
+
Run that example again, and position the moving sprite so that it's partially overlapping the stationary one. Then break the program (Control-C), and type in this:
|
| 221 |
+
|
| 222 |
+
```miniscript
|
| 223 |
+
while true
|
| 224 |
+
display(4).sprites.push display(4).sprites.pull
|
| 225 |
+
wait 1
|
| 226 |
+
end while
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
Every second, this simply loop pulls element 0 off the sprites list, and pushes it onto the end of the list. Changing the order of sprites in a list changes the order in which they are drawn on screen.
|
| 230 |
+
|
| 231 |
+
Some games like to sort the sprites to produce a pseudo-3D effect, where sprites higher up on the screen are meant to be further away from the viewer, and so should be drawn behind sprites that are lower on the screen. We can make the Stampy demo do that with two small changes. First, insert this line at the bottom of the `Stamper.update` function:
|
| 232 |
+
|
| 233 |
+
{number-from: 21}
|
| 234 |
+
```miniscript
|
| 235 |
+
self.sortOrder = -self.y
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
This adds a new `sortOrder` property to the sprites that decreases as Y increases, that is, the sortOrder gets smaller as sprites move up the screen. Then add these lines in the main loop, after `end for` but before the `if mouse.button` line:
|
| 239 |
+
|
| 240 |
+
{number-from: 36}
|
| 241 |
+
```miniscript
|
| 242 |
+
// sort sprites by their sortOrder property
|
| 243 |
+
display(4).sprites.sort "sortOrder"
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
Now run again, and move our moving Stampy around near the stationary one. You should observe that whichever sprite is higher on the screen is now drawn behind, and whichever one is lower on the screen is drawn in front. This creates the illusion that the sprites are moving in 3D space.
|
| 247 |
+
|
| 248 |
+
{width:"50%"}
|
| 249 |
+

|
| 250 |
+
|
| 251 |
+
Before we move on, save this program if you haven't already — I called it "StampyDemo", but you can call it whatever you like. We will use it again later.
|
| 252 |
+
|
| 253 |
+
## Hit Detection
|
| 254 |
+
|
| 255 |
+
The last topic of this chapter is about detecting when something is touching a sprite. When that something is the mouse, this is called *hit detection*; when it's another sprite, it's more commonly called *collision detection*.
|
| 256 |
+
|
| 257 |
+
hit detection
|
| 258 |
+
: determining whether a point on the screen (usually, the mouse) is touching a sprite
|
| 259 |
+
collision detection
|
| 260 |
+
: determining whether two sprites are touching
|
| 261 |
+
|
| 262 |
+
{i:"`Bounds` class"}
|
| 263 |
+
PRINT>Both of these tasks are done in Mini Micro with the help of another built-in class called `Bounds`. `Bounds` has the properties listed below, and the methods at the top of the next page.
|
| 264 |
+
EBOOK>Both of these tasks are done in Mini Micro with the help of another built-in class called `Bounds`. `Bounds` has the properties listed below.
|
| 265 |
+
|
| 266 |
+
{caption:"Properties of the Bounds class (where `b` is any Bounds object). All of these may be written (i.e. assigned to) as well as read."}
|
| 267 |
+
|`b.x`|horizontal position of the center of the bounding box|
|
| 268 |
+
|`b.y`|vertical position of the center of the bounding box|
|
| 269 |
+
|`b.width`|bounding box width|
|
| 270 |
+
|`b.height`|bounding box height
|
| 271 |
+
|`b.rotation`|rotation angle of the bounding box, in degrees|
|
| 272 |
+
|
| 273 |
+
EBOOK>`Bounds` also has the following three methods.
|
| 274 |
+
|
| 275 |
+
{caption:"Methods of the Bounds class (where `b` is any Bounds object)."}
|
| 276 |
+
|`b.corners`|returns box corners as a list of [x,y] coordinates|
|
| 277 |
+
|`b.overlaps(`*b2*`)`|returns whether `b` is touching box *b2*|
|
| 278 |
+
|`b.contains(`*x*`, `*y*`)`|return true if point *x, y* is within box `b`|
|
| 279 |
+
|
| 280 |
+
You can use `Bounds` by itself, just to define a rectangular (possibly rotated) area and see whether any point is inside or outside that area. But the more usual way to use it is via the `Sprite` class. `Sprite` has special support for a Bounds object called `localBounds`. Once you assign and configure the `localBounds` of a sprite, you can then do hit testing and collision testing on that sprite.
|
| 281 |
+
|
| 282 |
+
Some examples will make this clearer. Let's create a fresh sprite, using our old friend the Wumpus.
|
| 283 |
+
|
| 284 |
+
```miniscript
|
| 285 |
+
clear
|
| 286 |
+
spr = new Sprite
|
| 287 |
+
spr.image = file.loadImage("/sys/pics/Wumpus.png")
|
| 288 |
+
display(4).sprites.push spr
|
| 289 |
+
```
|
| 290 |
+
|
| 291 |
+
You should see the Wumpus once again peeking out from the lower-left corner. If you look at `spr.localBounds`, you will see it is null. Sprites do not automatically get any bounding box defined. But let's define one:
|
| 292 |
+
|
| 293 |
+
```miniscript
|
| 294 |
+
spr.localBounds = new Bounds
|
| 295 |
+
spr.localBounds.width = spr.image.width
|
| 296 |
+
spr.localBounds.height = spr.image.height
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
Now we've created a `Bounds` object, assigned it to the special `localBounds` property of our Sprite, and then set its width and height to match the image. We didn't assign to the `x` or `y` properties of the bounds, so they are implicitly `0,0`, which is the center of the sprite.
|
| 300 |
+
|
| 301 |
+
That's all the setup you need to do to enable the `contains` and `overlaps` methods of Sprite to work. For example, try this code to make the Wumpus bashful and jump away from the mouse.
|
| 302 |
+
|
| 303 |
+
{caption:Bashful Wumpus doesn't want to be clicked on!}
|
| 304 |
+
```miniscript
|
| 305 |
+
while true
|
| 306 |
+
if spr.contains(mouse) then
|
| 307 |
+
spr.x = 960*rnd
|
| 308 |
+
spr.y = 640*rnd
|
| 309 |
+
end if
|
| 310 |
+
end while
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
Type that in and then see if you can click on the Wumpus. Slippery little monster, isn't he?
|
| 314 |
+
|
| 315 |
+
Because this is such a common and useful task, let's summarize.
|
| 316 |
+
|
| 317 |
+
D> **Hit-Testing Summary**
|
| 318 |
+
D> 1. Set the sprite's `localBounds` to define the bounding box relative to the sprite itself.
|
| 319 |
+
D> 2. Call `contains` on the sprite with a point of interest.
|
| 320 |
+
|
| 321 |
+
Note that the `contains` method actually allows several different parameter styles for defining the point of interest:
|
| 322 |
+
|
| 323 |
+
- give it the *x* and *y* coordinates as two separate numeric parameters; or
|
| 324 |
+
- give it a list containing [*x*, *y*]; or
|
| 325 |
+
- give it a map containing "x" and "y" keys.
|
| 326 |
+
|
| 327 |
+
In the example above, we gave it `mouse`, which happens to be a map containing *x* and *y*, so we were using the third style.
|
| 328 |
+
|
| 329 |
+
Finally, let's consider collision-testing. This is what we use to tell if two sprites are touching each other. You set this up exactly the same way, except that there are two sprites involved instead of one; and then you use the `overlaps` method to test whether they are touching.
|
| 330 |
+
|
| 331 |
+
To illustrate, please load up that Stampy demo you made in the previous section. We're going to modify it to tint the moving sprite whenever it touches the stationary one. First, where we are defining the `Stamper` class, we need to add a `localBounds`.
|
| 332 |
+
|
| 333 |
+
{number-from: 9}
|
| 334 |
+
```miniscript
|
| 335 |
+
Stamper.localBounds = new Bounds
|
| 336 |
+
Stamper.localBounds.width = 128
|
| 337 |
+
Stamper.localBounds.height = 128
|
| 338 |
+
```
|
| 339 |
+
|
| 340 |
+
Then, let's add a special version of the `update` method just for `stampy`, our moving Stamper. It will begin by calling the superclass version of `update`, so that it does whatever all Stampers do; but it will then do the `overlaps` test against `stampy2`, and blush accordingly.
|
| 341 |
+
|
| 342 |
+
{number-from: 34}
|
| 343 |
+
```miniscript
|
| 344 |
+
stampy.update = function()
|
| 345 |
+
super.update // do regular update first
|
| 346 |
+
if self.overlaps(stampy2) then
|
| 347 |
+
self.tint = color.red
|
| 348 |
+
else
|
| 349 |
+
self.tint = color.white
|
| 350 |
+
end if
|
| 351 |
+
end function
|
| 352 |
+
```
|
| 353 |
+
|
| 354 |
+
With those changes, run the program again, and guide your stamper around the screen. You should see that whenever it touches the second stamper, it turns red. Note that the argument to `overlaps` can be either a `Bounds` object, or a `Sprite` object; either will work (but passing a `Sprite` is more common).
|
| 355 |
+
|
| 356 |
+
## Sprites in the Wild
|
| 357 |
+
|
| 358 |
+
Now that you know how to create, animate, hit-test, and collision-check sprites in Mini Micro, be on the lookout for sprites in the apps you use every day. Any little image that moves, rotates, reacts to clicks or taps, and animates by switching among some series of predefined frames is likely a sprite. You'll see them in any 2D game, but sometimes in serious productivity software too, where they may be serving as custom widgets in the user interface. Sprites also appear in 3D games, as an efficient way to draw things that are far away from the camera, or as status bars, icons, and other such elements that appear in the user interface, or float over units in the game.
|
| 359 |
+
|
| 360 |
+
Sprites are one of the most powerful, general, and widely useful concepts in real-time computer graphics. Now that you have this tool in your toolbelt, you will be using it a lot. Keep it sharp!
|
| 361 |
+
|
| 362 |
+
A> **Chapter Review**
|
| 363 |
+
A> - You learned about sprites, and how to create them in Mini Micro.
|
| 364 |
+
A> - You animated sprites by changing their position, rotation, or image.
|
| 365 |
+
A> - You discovered the `Bounds` class, and used it to test whether a sprite is touching a point or another sprite.
|
data/day23.txt
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 23: Fun with Words", startingPageNum:279}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
Q> Sometimes it's better to leave something alone, to pause, and that's very true of programming.
|
| 8 |
+
Q>— Joyce Wheeler (Executive Director of Technology, LinkedIn)
|
| 9 |
+
|
| 10 |
+
A> **Chapter Objectives**
|
| 11 |
+
A> - Discover Mini Micro's built-in English word list.
|
| 12 |
+
A> - Write some code to analyze data and generate random strings of letters.
|
| 13 |
+
A> - Lay the foundation for a word game (to be completed tomorrow).
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
{i:"`/sys/data`"}
|
| 17 |
+
Today we're going to do something a bit different. Mini Micro comes with a list of over 64,000 common English words, found in the file `/sys/data/englishWords.txt`. We'll use this to explore how code can be used to answer questions about data that would be very hard to answer in any other way. Then, we'll make a solid start on a fun word game, where the player tries to find words in a grid of random letters. We'll get about halfway through that game today, then take a break and finish it tomorrow.
|
| 18 |
+
|
| 19 |
+
## Exploring the Words File
|
| 20 |
+
|
| 21 |
+
Let's begin by using the `view` command in Mini Micro to peek at the file:
|
| 22 |
+
|
| 23 |
+
```terminal
|
| 24 |
+
]view "/sys/data/englishWords.txt"
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
You should see a pageful of words in alphabetical order: *a*, *aah*, *aardvark*, and so on, followed by something like "64637 more". You can press Return a few times to see more pages, but chances are good you'll lose interest before even getting out of the A's. When that happens, press Q or the Escape key to exit `view`.
|
| 28 |
+
|
| 29 |
+
You can see that the structure of this file is quite simple: one word per line. So we can read all the words into a list by doing:
|
| 30 |
+
|
| 31 |
+
```miniscript
|
| 32 |
+
words = file.readLines("/sys/data/englishWords.txt")
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
I wouldn't suggest trying to print `words` at this point (but hey, go ahead and try if you want — it's not going to hurt anything, though it may take a while). But print `words.len` to see how many words there are.
|
| 36 |
+
|
| 37 |
+
This list of words is a data set, so put on your "data scientist" hat and let's ask some questions about it. We've already seen the first few items, alphabetically. What are the *last* few words? Print out `words[-10:]` to see.
|
| 38 |
+
|
| 39 |
+
We've also already seen one of the shortest words in the English language, "a". Are there any other 1-letter words? Let's use a simple `for` loop to find out. It's a loop so short that, if you like, you can do it as a one-liner:
|
| 40 |
+
|
| 41 |
+
```miniscript
|
| 42 |
+
for w in words; if w.len==1 then print w; end for
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
In addition to "a", this also prints out "I" (the pronoun) and "O" (as in "O say can you see?"). It also prints out "x", which surprised me when I did this. But finding surprises in data is part of the fun! (And yes, if you look up "x" in many dictionaries, you will find it defined as a word meaning to cross out or indicate choice.)
|
| 46 |
+
|
| 47 |
+
Now let's find the longest word in the set. This is slightly bigger `for` loop.
|
| 48 |
+
|
| 49 |
+
```miniscript
|
| 50 |
+
biggest = ""
|
| 51 |
+
for w in words
|
| 52 |
+
if w.len > biggest.len then biggest = w
|
| 53 |
+
end for
|
| 54 |
+
biggest
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
This loops over all words, comparing each one to the biggest word found so far. Whenever it finds a new biggest word, it stores that in `biggest`, which we print out at the end. What word did you find? And, how many letters does it have? (No fair counting them by hand — make MiniScript do that for you!)
|
| 58 |
+
|
| 59 |
+
Next up is a question I actually needed an answer to. I was pondering making a word-search game, where the user would try to make words out of randomly selected letters in a grid, and I wondered what to do with "Q". Usually "Q" in English is followed by a "u", but is that always the case? Maybe there are a bunch of exceptions we're not thinking of. Let's find out!
|
| 60 |
+
|
| 61 |
+
{i:"`/sys/lib`,`stringUtil`"}
|
| 62 |
+
```miniscript
|
| 63 |
+
import "stringUtil"
|
| 64 |
+
for w in words
|
| 65 |
+
if w.contains("q") and not w.contains("qu") then print w
|
| 66 |
+
end for
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
Notice that we had to import "stringUtil" before doing this `for` loop. That's because `contains` is not a standard MiniScript intrinsic function; it is something added by the `stringUtil` module. (The standard MiniScript solution would be to check whether `w.indexOf("q") != null`, but `contains` is a lot clearer.)
|
| 70 |
+
|
| 71 |
+
So this loop prints out every word that contains a "q", but does not contain "qu". Exactly three words popped out: "burqa", "burqas", and "qwerty". Out of more than 64 thousand words, that's not too many!
|
| 72 |
+
|
| 73 |
+
If we also import the "listUtil" module, we'll get some additional handy functions, like the `any` method that returns a random element of a list.
|
| 74 |
+
|
| 75 |
+
```miniscript
|
| 76 |
+
import "listUtil"
|
| 77 |
+
for i in range(1,10); print words.any; end for
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
But enough playing! Keep your data-scientist hat on a bit longer, but now balance your game-developer hat on top (programmers often have to wear many hats). We're going to be making a game that involves a grid of random letters. But we don't want to pick all letters with equal likelihood; that would result in a lot of Z's and X's that aren't terribly useful. We want to pick more common letters more often, and less common letters less often. But which letters are the most common, and by how much?
|
| 81 |
+
|
| 82 |
+
## Letter Frequency Analysis
|
| 83 |
+
|
| 84 |
+
That's another data analysis question we can answer with code. This one requires a little more code than you probably want to do on the REPL command line, though. So fire up the editor, and enter the following.
|
| 85 |
+
|
| 86 |
+
{caption: "Letter frequency analysis program."}
|
| 87 |
+
```miniscript
|
| 88 |
+
import "mapUtil"
|
| 89 |
+
import "listUtil"
|
| 90 |
+
|
| 91 |
+
// load the word list
|
| 92 |
+
words = file.readLines("/sys/data/englishWords.txt")
|
| 93 |
+
|
| 94 |
+
// convert all words to uppercase
|
| 95 |
+
for i in words.indexes
|
| 96 |
+
words[i] = words[i].upper
|
| 97 |
+
end for
|
| 98 |
+
|
| 99 |
+
// count the frequency of each letter
|
| 100 |
+
print "Analyzing words..."
|
| 101 |
+
counts = {} // key: letter; value: count
|
| 102 |
+
for word in words
|
| 103 |
+
for letter in word
|
| 104 |
+
counts[letter] = counts.get(letter, 0) + 1
|
| 105 |
+
end for
|
| 106 |
+
end for
|
| 107 |
+
print counts
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
This one takes a little longer to run, as it's iterating not only over the words, but the letters within the words. But before too long, out pops the answer: the total number of times each letter occurs in the word list. Save this program as `freqCount.ms` in case you need it later.
|
| 111 |
+
|
| 112 |
+
Now we're going to do a trick. Select that output by clicking and dragging over it with the mouse. Now copy with Control-C (or on a Mac, you can use Command-C). Use `reset` to clear the frequency-counting program, then `edit` to start a new one. Finally, type "freq =", and then paste the output you copied before (using the Paste button or Control+V). Adjust the line breaks, and voila! The result should look something like this (though the order of the letters may be different — remember that when you print or iterate over a map, the order of the entries is undefined).
|
| 113 |
+
|
| 114 |
+
{caption: "The start of our word game, with frequencies copied from the output of the previous program."}
|
| 115 |
+
```miniscript
|
| 116 |
+
freq = {"A": 40116, "H": 12329, "R": 38506, "D": 21334,
|
| 117 |
+
"V": 5427, "K": 5275, "S": 49034, "B": 10303, "C": 21554,
|
| 118 |
+
"I": 47047, "U": 17692, "E": 62155, "L": 27954, "O": 33150,
|
| 119 |
+
"N": 37001, "G": 16930, "M": 14495, "T": 36982, "Y": 8191,
|
| 120 |
+
"J": 941, "Z": 2090, "P": 15815, "F": 7635, "W": 5081,
|
| 121 |
+
"Q": 990, "X": 1487}
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Save this as "wordGame.ms" and run it. It doesn't generate any output, but once run you should be able to enter `freq` and see your frequency map.
|
| 125 |
+
|
| 126 |
+
D> You just used code to write code. Programs making programs. Scary, or cool? Maybe both!
|
| 127 |
+
|
| 128 |
+
## Starting the Word Game
|
| 129 |
+
|
| 130 |
+
Let's start building the rest of the game. Edit your program, and insert some lines above your frequency table, so that it looks like this.
|
| 131 |
+
|
| 132 |
+
{i:"`/sys/lib`,`mapUtil`;`/sys/lib`,`listUtil`;`/sys/lib`,`mathUtil`;`/sys/lib`,`sounds`"}
|
| 133 |
+
{caption: "Listing 1 (Start of the actual game)."}
|
| 134 |
+
```miniscript
|
| 135 |
+
import "mapUtil"
|
| 136 |
+
import "listUtil"
|
| 137 |
+
import "mathUtil"
|
| 138 |
+
import "sounds"
|
| 139 |
+
|
| 140 |
+
clear
|
| 141 |
+
text.color = color.silver
|
| 142 |
+
|
| 143 |
+
display(2).mode = displayMode.pixel
|
| 144 |
+
overlay = display(2)
|
| 145 |
+
overlay.clear
|
| 146 |
+
|
| 147 |
+
kRows = 5
|
| 148 |
+
kCols = 5
|
| 149 |
+
|
| 150 |
+
words = file.readLines("/sys/data/englishWords.txt")
|
| 151 |
+
for i in range(0, words.len-1)
|
| 152 |
+
words[i] = words[i].upper
|
| 153 |
+
end for
|
| 154 |
+
|
| 155 |
+
freq = {"A": 40116, "H": 12329, "R": 38506, "D": 21334,
|
| 156 |
+
"V": 5427, "K": 5275, "S": 49034, "B": 10303, "C": 21554,
|
| 157 |
+
"I": 47047, "U": 17692, "E": 62155, "L": 27954, "O": 33150,
|
| 158 |
+
"N": 37001, "G": 16930, "M": 14495, "T": 36982, "Y": 8191,
|
| 159 |
+
"J": 941, "Z": 2090, "P": 15815, "F": 7635, "W": 5081,
|
| 160 |
+
"Qu": 990, "X": 1487}
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
{i:"`/sys/lib`"}
|
| 164 |
+
The first four lines simply import some modules from `/sys/lib` that we will make use of elsewhere. (When writing your own programs from scratch, you can add these as you need them, or just put your favorites at the top of any program you begin. There's no harm in importing them even if you don't actually use them.)
|
| 165 |
+
|
| 166 |
+
Lines 6-11 clear the screen and set up the displays. That includes changing the text color to silver, so don't be surprised to see that happen when you run this code.
|
| 167 |
+
|
| 168 |
+
Lines 13 and 14 define how many rows and columns we will use in our grid of random letters. The "k" prefix is commonly used to identify a "constant" value, that is, a value that should not change throughout the life of the program. (Yes, I know that "constant" does not start with a "k" in English. Nonetheless this is a common convention.)
|
| 169 |
+
|
| 170 |
+
Then lines 16-19 load the words file, and convert all the words to upper case. That saves us from having to worry about mixed upper/lower case later on.
|
| 171 |
+
|
| 172 |
+
Finally, after all that comes the frequency table you developed in the last section, with one little change: find the "Q" entry, and change it to "Qu". Because we determined earlier that words that use a "q" without a "u" are extremely rare, our game will never use a "q" by itself; instead we'll always pick that as the "qu" combo.
|
| 173 |
+
|
| 174 |
+
## Random Letters
|
| 175 |
+
|
| 176 |
+
Now we need some code to generate a random letter, or a whole grid of random letters. And we want to do this in a way that mirrors the normal frequency of letters in our word set, so that "E" is the most common letter picked, "J" is the least, and so on. Add the listing below to your growing program.
|
| 177 |
+
|
| 178 |
+
{caption: "Listing 2 (Selecting random letters).", number-from: 28}
|
| 179 |
+
```miniscript
|
| 180 |
+
totalFreq = freq.values.sum
|
| 181 |
+
|
| 182 |
+
randomLetter = function()
|
| 183 |
+
i = floor(rnd * totalFreq)
|
| 184 |
+
for kv in freq
|
| 185 |
+
if i < kv.value then return kv.key
|
| 186 |
+
i = i - kv.value
|
| 187 |
+
end for
|
| 188 |
+
end function
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
Run that, and again nothing happens. But let's test the code out as we consider how it works. Line 28 calculates the total of all the frequency values in our table, i.e., the total number of letters in our word set. `freq.values` would give you a list of all the frequencies, and appending `.sum` adds them up. Enter `totalFreq` to make sure it gives you a nice big number like 539514. (Feel free to proudly tell your neighbor that your code processes over half a million letters without breaking a sweat.)
|
| 192 |
+
|
| 193 |
+
The `randomLetter` function picks a random number `i` from 0 to this total frequency count. Then it iterates over the frequency table (using `kv` to remind us that these are key/value pairs), checking whether `i` is less than the frequency value of each letter. This will of course be more likely for numbers with big values (like E and S) than for numbers with small values (like X and J). If our random `i` is in fact less than the value of the letter, we return that letter. Otherwise, we subtract that letter's value from `i`, and go on to check the next letter. This makes `i` smaller and smaller, and guarantees that by the time we reach the end of the frequency table, we *will* find some letter that fits — and the probability of each letter being chosen is exactly equal to their relative frequencies.
|
| 194 |
+
|
| 195 |
+
D> This is an algorithm known as a *weighted random selection*, and it can be used any time you want to pick from a set of things, but with a different probability or "weight" for each thing.
|
| 196 |
+
|
| 197 |
+
Enter `randomLetter` at the REPL prompt, and it should print out a letter (or in the case of "Qu", two letters). Repeat it a few times (or maybe even use a `for` loop!), and convince yourself that the more common English letters are appearing more often.
|
| 198 |
+
|
| 199 |
+
## Creating Letter Tiles
|
| 200 |
+
|
| 201 |
+
Our game is going to involve a grid of letter tiles, much like the playing pieces in Scrabble. These little tiles need to move around, detect mouse clicks, etc., so we'll make a Sprite subclass to represent them.
|
| 202 |
+
|
| 203 |
+
D> Careful: we're using "tile" here just to describe the shape and usage of the sprites in this game. Don't confuse it with "tile" as in `TileDisplay`, which we'll be learning about in Chapter 25. In this chapter and the next, remember that our "tiles" are just ordinary sprites that happen to look like letter tiles.
|
| 204 |
+
|
| 205 |
+
In most games, you load sprite images from picture files on disk. But in this case, we're going to draw the tile images in a PixelDisplay, and then pull out that part of the display as an image to use for the sprite. It's a neat trick to consider any time you can work out a way to draw your sprite images with code.
|
| 206 |
+
|
| 207 |
+
{caption: "Listing 3 (Tile-drawing code, and Tile class).", number-from: 38}
|
| 208 |
+
```miniscript
|
| 209 |
+
blockPic = file.loadImage("/sys/pics/Block.png")
|
| 210 |
+
drawBlock = function(letter, x=100, y=100)
|
| 211 |
+
gfx.drawImage blockPic, x, y, 40, 40
|
| 212 |
+
if letter.len < 2 then
|
| 213 |
+
gfx.print letter, x+8, y+4, color.black, "large"
|
| 214 |
+
else
|
| 215 |
+
gfx.print letter, x+6, y+8, color.black
|
| 216 |
+
end if
|
| 217 |
+
end function
|
| 218 |
+
|
| 219 |
+
Tile = new Sprite
|
| 220 |
+
Tile.letter = ""
|
| 221 |
+
Tile.scale = 2
|
| 222 |
+
Tile.tint = color.yellow
|
| 223 |
+
Tile.target = {"x":0, "y":0}
|
| 224 |
+
Tile.speed = 100
|
| 225 |
+
Tile.localBounds = new Bounds
|
| 226 |
+
Tile.localBounds.width = 36
|
| 227 |
+
Tile.localBounds.height = 36
|
| 228 |
+
|
| 229 |
+
Tile.goTo = function(x,y, speed)
|
| 230 |
+
self.target.x = x
|
| 231 |
+
self.target.y = y
|
| 232 |
+
if speed != null then self.speed = speed
|
| 233 |
+
end function
|
| 234 |
+
|
| 235 |
+
Tile.goToGridPos = function(col, row)
|
| 236 |
+
self.goTo 300 + col * 90, 135 + row * 90
|
| 237 |
+
end function
|
| 238 |
+
|
| 239 |
+
Tile.update = function(dt = 0.1)
|
| 240 |
+
mathUtil.moveTowardsXY(self, self.target, self.speed * dt)
|
| 241 |
+
end function
|
| 242 |
+
|
| 243 |
+
Tile.updateAll = function(dt = 0.1)
|
| 244 |
+
updatedAny = false
|
| 245 |
+
for s in spriteDisp.sprites
|
| 246 |
+
if not s isa Tile then continue
|
| 247 |
+
if s.x == s.target.x and s.y == s.target.y then continue
|
| 248 |
+
s.update
|
| 249 |
+
updatedAny = true
|
| 250 |
+
end for
|
| 251 |
+
return updatedAny
|
| 252 |
+
end function
|
| 253 |
+
|
| 254 |
+
Tile.selected = function()
|
| 255 |
+
return self.tint != Tile.tint
|
| 256 |
+
end function
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
Add that to your program, then run it, and let's test it out on the command line.
|
| 260 |
+
|
| 261 |
+
```terminal
|
| 262 |
+
]drawBlock "E"
|
| 263 |
+
]drawBlock "Qu", 140, 100
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
This should produce two tiles near the bottom of the screen: one "E", and one with a smaller "Qu".
|
| 267 |
+
|
| 268 |
+
{width:"50%"}
|
| 269 |
+

|
| 270 |
+
|
| 271 |
+
Now let's try grabbing the first of these as the image for a Tile instance.
|
| 272 |
+
|
| 273 |
+
```terminal
|
| 274 |
+
]t = new Tile
|
| 275 |
+
]t.image = gfx.getImage(100,100,40,40)
|
| 276 |
+
]display(4).sprites.push t
|
| 277 |
+
[t]
|
| 278 |
+
]t.x = 200; t.y = 300
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
This should create a large (due to `Tile.scale`), yellowish (due to `Tile.tint`) letter "E" tile. The `Tile` class includes some simple animation code, too. Let's test it:
|
| 282 |
+
|
| 283 |
+
```terminal
|
| 284 |
+
]t.goTo 800, 600
|
| 285 |
+
]while true; t.update; yield; end while
|
| 286 |
+
```
|
| 287 |
+
|
| 288 |
+
If you see your "E" tile slide up towards the upper-right corner of the screen, then you're ready to press Control-C and move on to the next code listing. If not, go back and check your typing carefully.
|
| 289 |
+
|
| 290 |
+
{caption: "Listing 4 (Letter grid storage and set-up).", number-from: 86)
|
| 291 |
+
```miniscript
|
| 292 |
+
// 2D array to keep track of the tiles that belong in each
|
| 293 |
+
// row and column of the grid. Indexed first by column,
|
| 294 |
+
// and within a column indexed bottom-up, so within a column
|
| 295 |
+
// we can easily remove something and the rest shift down.
|
| 296 |
+
grid = list.init2d(kCols, kRows)
|
| 297 |
+
|
| 298 |
+
makeSprite = function(letter)
|
| 299 |
+
gfx.fillRect 0, 0, 40, 40, color.clear
|
| 300 |
+
drawBlock letter, 0, 0
|
| 301 |
+
spr = new Tile
|
| 302 |
+
spr.image = gfx.getImage(0, 0, 40, 40)
|
| 303 |
+
spr.letter = letter
|
| 304 |
+
return spr
|
| 305 |
+
end function
|
| 306 |
+
|
| 307 |
+
letterSprites = {} // key: letter; value: Tile
|
| 308 |
+
for code in range("A".code, "Z".code)
|
| 309 |
+
gfx.clear
|
| 310 |
+
c = char(code)
|
| 311 |
+
if c == "Q" then c = "Qu"
|
| 312 |
+
letterSprites[c] = makeSprite(c)
|
| 313 |
+
end for
|
| 314 |
+
gfx.clear
|
| 315 |
+
|
| 316 |
+
display(4).mode = displayMode.sprite
|
| 317 |
+
spriteDisp = display(4)
|
| 318 |
+
spriteDisp.clear
|
| 319 |
+
|
| 320 |
+
newTile = function(col, row)
|
| 321 |
+
tile = new letterSprites[randomLetter]
|
| 322 |
+
tile.target = {"x":0, "y":0} // make sure tile has its own target map
|
| 323 |
+
spriteDisp.sprites.push tile
|
| 324 |
+
tile.goToGridPos col, row
|
| 325 |
+
tile.x = tile.target.x
|
| 326 |
+
tile.y = tile.target.y + 500 + 50 * rnd + 100*row
|
| 327 |
+
grid[col][row] = tile
|
| 328 |
+
return tile
|
| 329 |
+
end function
|
| 330 |
+
|
| 331 |
+
for col in range(0, kCols-1)
|
| 332 |
+
for row in range(0, kRows-1)
|
| 333 |
+
newTile col, row
|
| 334 |
+
end for
|
| 335 |
+
end for
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
This code uses the `list.init2d` method from the `listUtil` module to initialize a two-dimensional array, that is, a list of lists. It's stored in global variable `grid`, and to get to any particular Tile, you index into this twice: `grid[c][r]` gets you the Tile in column `c` and row `r`. Columns start at 0 on the left and go up to 4 on the right; rows start at 0 on the bottom, and go up to 4 on top. So the layout of these accessors is just like X and Y pixel positions, or column and row in a text display.
|
| 339 |
+
|
| 340 |
+
The `makeSprite` function does what we did by hand earlier: it draws the given letter into the `gfx` PixelDisplay, then grabs that image and assigns it to a freshly created Tile. To save time later on, we do this once for each letter in the loop on lines 102-107. Also notice the special trick we do on line 105, where instead of making a "Q" tile, we make it "Qu". All these sprites are stored in a map called `letterSprites`, so we can easily look up a sprite for any letter.
|
| 341 |
+
|
| 342 |
+
Lines 110-112 just set up the sprite display, and the `newTile` function starting on line 114 creates a new tile, with a random letter (using the `randomLetter` function we made earlier), and stores it in `grid`. It also tells the tile to go to its grid position, but then on lines 119-120, sets its *current* position to some spot much higher on the screen. That's so that we can have all the tiles fall pleasingly into place when the game begins.
|
| 343 |
+
|
| 344 |
+
Finally, the nested `for` loops at the end of Listing 4 call `newTile` for every row and column, creating our initial grid of tiles. Our program does not yet have a main loop to make them animate, so after you enter all that and run it, let's test it out by manually entering, on the REPL command line:
|
| 345 |
+
|
| 346 |
+
```terminal
|
| 347 |
+
]while true; Tile.updateAll; yield; end while
|
| 348 |
+
```
|
| 349 |
+
|
| 350 |
+
PRINT>This should cause all the tiles to slide neatly down from the top of the screen. The final result should look something like the image on the next page.
|
| 351 |
+
EBOOK>This should cause all the tiles to slide neatly down from the top of the screen. The final result should look something like the image below.
|
| 352 |
+
|
| 353 |
+
{width: "80%"}
|
| 354 |
+

|
| 355 |
+
|
| 356 |
+
{pageBreak}
|
| 357 |
+
And we're going to stop there for today. You've worked hard and made a great start on your most complex program yet — you deserve a break!
|
| 358 |
+
|
| 359 |
+
A> **Chapter Review**
|
| 360 |
+
A> - You explored the `englishWords.txt` file included with Mini Micro.
|
| 361 |
+
A> - You learned how to use your coding powers to get answers about large datasets.
|
| 362 |
+
A> - You wrote code to load the word set, draw tiles, turn those into sprites, and animate them into place.
|
| 363 |
+
|
| 364 |
+
|
data/day24.txt
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 24: Word-Find Game", startingPageNum:293}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> When to use iterative development? You should use iterative development only on projects that you want to succeed.
|
| 7 |
+
Q>— Martin Fowler (software developer and author)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Finish the word game we started yesterday.
|
| 11 |
+
A> - Get practice at making sprites interact with the mouse.
|
| 12 |
+
A> - Learn techniques for debugging with a Read, Eval, Print Loop.
|
| 13 |
+
|
| 14 |
+
Yesterday we made a solid start on our word-finding game: we prepared the word list, wrote code to randomly select letters in the same proportions as real words, made a `Sprite` subclass named `Tile`, and animated a grid of tiles sliding into place. Today we're going to finish the game, with selection of letters to make a word, checking these against the word list, calculating a score, and a timer to make it exciting.
|
| 15 |
+
|
| 16 |
+
## Tile selection
|
| 17 |
+
|
| 18 |
+
Start by adding the code in Listing 1 to the program you began yesterday.
|
| 19 |
+
|
| 20 |
+
{caption:"Listing 1 (tile selection with the mouse).", number-from: 131}
|
| 21 |
+
```miniscript
|
| 22 |
+
tileUnderMouse = function()
|
| 23 |
+
for s in spriteDisp.sprites
|
| 24 |
+
if not s isa Tile then continue
|
| 25 |
+
if s.contains(mouse) then return s
|
| 26 |
+
end for
|
| 27 |
+
end function
|
| 28 |
+
|
| 29 |
+
wordInProgress = ""
|
| 30 |
+
addToWord = function(tile)
|
| 31 |
+
globals.wordInProgress = wordInProgress + tile.letter
|
| 32 |
+
if lastTile != null then
|
| 33 |
+
overlay.line lastTile.x, lastTile.y, tile.x, tile.y, "#88FF8888", 5
|
| 34 |
+
end if
|
| 35 |
+
globals.lastTile = tile
|
| 36 |
+
tile.tint = color.aqua
|
| 37 |
+
tile.selected = true
|
| 38 |
+
end function
|
| 39 |
+
|
| 40 |
+
trackMouseOnTiles = function()
|
| 41 |
+
while mouse.button
|
| 42 |
+
updateTime
|
| 43 |
+
yield
|
| 44 |
+
tile = tileUnderMouse
|
| 45 |
+
if tile == null or tile.selected then continue
|
| 46 |
+
if mathUtil.distance(tile, lastTile) > 150 then continue
|
| 47 |
+
addToWord tile
|
| 48 |
+
end while
|
| 49 |
+
end function
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
{i:"`isa` operator;operator, `isa`"}
|
| 53 |
+
We've added several new functions here. The `tileUnderMouse` function is responsible for figuring out which `Tile` instance, if any, is under the mouse. It does this by iterating over all sprites in the display, skipping any that is not actually a `Tile`. It checks whether each sprite `s` is a `Tile` by using MiniScript's `isa` (pronounced "is a") operator.
|
| 54 |
+
|
| 55 |
+
D> `isa` is the operator used to check data types in MiniScript; it returns 1 (true) if the operand on the left matches the type on the right, and 0 (false) otherwise. Built-in types can be identified as `number`, `string`, `list`, `map`, and `funcRef`. In the case of a class, `isa` returns true if the object on the left is the class on the right, or any subclass of it.
|
| 56 |
+
|
| 57 |
+
The `tileUnderMouse` function then uses the `Sprite.contains` method to check whether each tile contains the mouse. (Recall that this works because we assigned the `localBounds` of the `Tile` class.)
|
| 58 |
+
|
| 59 |
+
The next function, `addToWord`, adds a given tile to the growing word, stored in the `wordInProgress` global variable. Then it draws a line in the overlay display (a `PixelDisplay` we prepared at the top of the program), and highlights the given tile by tinting it aqua.
|
| 60 |
+
|
| 61 |
+
Finally, the `trackMouseOnTiles` function is a loop that continues as long as the mouse is down. It's meant to be called after the first tile has been clicked, and it handles dragging of the mouse over subsequent tiles. Lines 154 avoids any problems when the mouse is between tiles. Line 155 prevents users from cheating by snaking the mouse in between tiles to reach some farther-away tile. Neighboring tiles are always less than 150 pixels away, so if we find the mouse is over some tile farther away than that, we just ignore it.
|
| 62 |
+
|
| 63 |
+
To test this code requires a little bit of work: we need to first initialize our grid, and then wait for the user to click the mouse. Then we need to update `lastTile` and call `addToWord` before we can finally call that `trackMouseOnTiles` function. Add the following test code to your program so you can try it out and make sure it works.
|
| 64 |
+
|
| 65 |
+
{caption:"Test code for Listing 1.", number-from: 160}
|
| 66 |
+
```miniscript
|
| 67 |
+
// test code:
|
| 68 |
+
updateTime = null // (we'll fill this in later)
|
| 69 |
+
for i in range(1000); Tile.updateAll; end for
|
| 70 |
+
while not mouse.button; yield; end while
|
| 71 |
+
lastTile = tileUnderMouse
|
| 72 |
+
addToWord lastTile
|
| 73 |
+
trackMouseOnTiles
|
| 74 |
+
print wordInProgress
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
It's worth pointing out the trick on line 161: if you assign `null` to a variable, you can use that like a do-nothing function with no parameters. That's needed in this case because `trackMouseOnTiles` calls `updateTime` to update a timer, but we haven't gotten to that code yet.
|
| 78 |
+
|
| 79 |
+
With this test code in place, run your program. Tiles should settle very quickly into place, and then if you click any tile and drag, you can construct a word (or a string of random gibberish). Run it a few times. What's the longest word you can find? (Mine was "FILET"... but I bet you can do better!)
|
| 80 |
+
|
| 81 |
+
## Clearing tiles
|
| 82 |
+
|
| 83 |
+
To turn this word-selection functionality into a game, we'll need at least two more things. First, if the word is valid, then we need to clear out the tiles used, move any higher-up tiles down, and add new tiles to fill the columns. Second, in the case where the letters traced do not make a valid word, we need to just deselect those tiles so the player can try again.
|
| 84 |
+
|
| 85 |
+
The code in Listing 2 below provides these functions. Insert this code *before* your existing test code, as you'll still need that to test.
|
| 86 |
+
|
| 87 |
+
{caption:"Listing 2 (Tile clearing and deselection).", number-from: 160}
|
| 88 |
+
```miniscript
|
| 89 |
+
clearUsedTiles = function()
|
| 90 |
+
for col in range(0, kCols-1)
|
| 91 |
+
// first iterate top-down, deleting any selected tiles
|
| 92 |
+
for row in range(kRows-1, 0)
|
| 93 |
+
tile = grid[col][row]
|
| 94 |
+
if tile == null or not tile.selected then continue
|
| 95 |
+
spriteDisp.sprites.removeVal tile // remove sprite
|
| 96 |
+
grid[col].remove row // remove used tile
|
| 97 |
+
grid[col].push null // add empty spot to column
|
| 98 |
+
end for
|
| 99 |
+
// then iterate again bottom-up, adding new tiles
|
| 100 |
+
for row in range(0, kRows-1)
|
| 101 |
+
if grid[col][row] == null then
|
| 102 |
+
newTile col, row
|
| 103 |
+
else
|
| 104 |
+
grid[col][row].goToGridPos col, row
|
| 105 |
+
end if
|
| 106 |
+
end for
|
| 107 |
+
end for
|
| 108 |
+
overlay.clear
|
| 109 |
+
globals.lastTile = null
|
| 110 |
+
end function
|
| 111 |
+
|
| 112 |
+
deselectTiles = function()
|
| 113 |
+
for col in range(0, kCols-1)
|
| 114 |
+
for row in range(0, kRows-1)
|
| 115 |
+
tile = grid[col][row]
|
| 116 |
+
tile.selected = false
|
| 117 |
+
tile.tint = Tile.tint
|
| 118 |
+
end for
|
| 119 |
+
end for
|
| 120 |
+
overlay.clear
|
| 121 |
+
globals.lastTile = null
|
| 122 |
+
end function
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
Let's discuss how these functions work. The `clearUsedTiles` function iterates over the columns of the grid. For each column, it iterates over the rows twice. First it goes top-down, deleting any selected tiles from the list of tiles in that column, and pushing an empty entry (`null`) onto the end of the list. Then it goes bottom-up, telling each tile to go to (i.e. set its target position to) the proper place on screen, and creating new tiles for any `null` entries it finds. The net effect of all this is to take out the selected tiles, shift the ones above it down, and create new tiles as needed.
|
| 126 |
+
|
| 127 |
+
The `deselectTiles` function is simpler. It just iterates over all rows and columns, turning off the `selected` flag, and setting the tint back to the standard `Tile` tint. Then it clears the `overlay` display where the tracing line is drawn, and while we're at it, also clears the global `lastTile` variable that keeps track of the last tile clicked.
|
| 128 |
+
|
| 129 |
+
After inserting that code, run the program again, and then use the mouse to trace out some letters. Then enter `deselectTiles` at the command prompt. The selected tiles should go back to normal, and the tracing overlay should disappear.
|
| 130 |
+
|
| 131 |
+
Then run the program again, and again select a sequence of tiles. This time call `clearUsedTiles`, and you should see the selected tiles disappear. The surrounding tiles (and new tiles, currently off the top of the screen) have had their targets set, but they need an animation loop in order to reach those targets. Let's give them one:
|
| 132 |
+
|
| 133 |
+
```terminal
|
| 134 |
+
]while true; Tile.updateAll; yield; end while
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
This should cause the tiles to slide down into place. Press Control-C to break the loop once that is done.
|
| 138 |
+
|
| 139 |
+
## Adding a score and history
|
| 140 |
+
|
| 141 |
+
Now let's add some more functions to handle when a word has been entered. We want to draw the word near the top of the screen, above the tile grid; and then score it based on whether it's in the dictionary, and how long it is. Long words are much harder to find than short ones, so we want to really reward the player for finding these. So we'll define the score for a word with `n` letters as `2 ^ n`, that is, 2 to the `n`th power. That gives us 2 points for a 1-letter word, 4 points for 2-letter words, 8 points for 3-letter words, and so on.
|
| 142 |
+
|
| 143 |
+
In addition to the total score, we'll also keep a history of all the words found in the course of the game. This will be displayed on the left side of the screen, so when you find some really amazing word like EVACUATE, you can show people even if it's not the last word in the game.
|
| 144 |
+
|
| 145 |
+
Again insert the new code (in Listing 3 this time) above your existing test code.
|
| 146 |
+
|
| 147 |
+
{caption:"Listing 3 (Word drawing and scoring functions).", number-from: 195}
|
| 148 |
+
```miniscript
|
| 149 |
+
drawWord = function(word, valid)
|
| 150 |
+
if valid then c = color.aqua else c = color.teal
|
| 151 |
+
gfx.clear
|
| 152 |
+
gfx.print word, 480 - word.len/2*20.5, 550, c, "large"
|
| 153 |
+
end function
|
| 154 |
+
|
| 155 |
+
score = 0
|
| 156 |
+
wordsFound = [] // each element will be [word, points]
|
| 157 |
+
scoreWord = function(word)
|
| 158 |
+
valid = words.contains(word)
|
| 159 |
+
drawWord word, valid
|
| 160 |
+
if not valid then return false
|
| 161 |
+
points = 2 ^ word.len
|
| 162 |
+
wordsFound.insert 0, [word, points]
|
| 163 |
+
text.row = 21
|
| 164 |
+
for w in wordsFound
|
| 165 |
+
print (w[0] + " "*11)[:11] + (" "*5 + w[1])[-5:]
|
| 166 |
+
if text.row < 2 then break
|
| 167 |
+
end for
|
| 168 |
+
globals.score = score + points
|
| 169 |
+
text.row = 25
|
| 170 |
+
print "SCORE: " + score
|
| 171 |
+
return true
|
| 172 |
+
end function
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
There are two functions in this chunk as well. The `drawWord` function simply sets a color based on whether the word is valid, then clears the `gfx` PixelDisplay, and uses `gfx.print` to print the word in a large font.
|
| 176 |
+
|
| 177 |
+
The `scoreWord` function is responsible for determining whether the word is valid, by checking whether our `words` list contains it. (Recall that `contains` is a method added to the list type by the `listUtil` module.) It calls that `drawWord` function, and then if the word is not valid, bails out on line 206. Otherwise (that is, if the word is valid), it calculates the points, inserts the word and score at the front a `wordsFound` list, and then updates the text display. Notice also that `scoreWord` returns `true` if the word was valid, and `false` if not; this lets the calling code do other things based on whether the word was good.
|
| 178 |
+
|
| 179 |
+
To test this, go down to the last line of your test code. If we've stuck together on all the blank lines and whatnot, it'll be line 227. In any case, replace the `print` statement at the end of your test code with:
|
| 180 |
+
|
| 181 |
+
{number-from: 227}
|
| 182 |
+
```miniscript
|
| 183 |
+
scoreWord wordInProgress
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
Now run the program. First select a bunch of gibberish characters that do not make a valid word. You should see the word drawn above the tiles, but no score appear. Now run it again, but this time find some valid word. You should see the word drawn in a brighter color, a score appear in the top-left corner of the screen, and the word plus its score appear to the left of the grid — a fairly redundant display when there's only one word, but nice once we start entering multiple words.
|
| 187 |
+
|
| 188 |
+
## Wrapping up
|
| 189 |
+
|
| 190 |
+
Almost done! To finish the game, we're going to finally add that `updateTime` function, which puts a timer in the upper-right corner of the screen. And finally, as in most games, we'll have a main loop. Delete that test code at the end of your program, and enter the following.
|
| 191 |
+
|
| 192 |
+
{caption:"Listing 4 (Timer and main loop).", number-from: 220}
|
| 193 |
+
```miniscript
|
| 194 |
+
endTime = time + 120
|
| 195 |
+
updateTime = function()
|
| 196 |
+
timeLeft = ceil(endTime - time)
|
| 197 |
+
text.row = 25
|
| 198 |
+
text.column = 58
|
| 199 |
+
if timeLeft <= 0 then
|
| 200 |
+
print "TIME'S UP!"
|
| 201 |
+
else
|
| 202 |
+
mins = floor(timeLeft/60)
|
| 203 |
+
secs = ("00" + (timeLeft % 60))[-2:]
|
| 204 |
+
print "TIME: " + mins + ":" + secs
|
| 205 |
+
end if
|
| 206 |
+
end function
|
| 207 |
+
|
| 208 |
+
lastTile = null
|
| 209 |
+
while true
|
| 210 |
+
while Tile.updateAll; updateTime; yield; end while
|
| 211 |
+
if time > endTime then break
|
| 212 |
+
while not mouse.button; updateTime; yield; end while
|
| 213 |
+
tileHit = tileUnderMouse
|
| 214 |
+
if tileHit == null or tileHit.selected then continue
|
| 215 |
+
addToWord tileHit
|
| 216 |
+
trackMouseOnTiles
|
| 217 |
+
|
| 218 |
+
if scoreWord(wordInProgress) then
|
| 219 |
+
sounds.daDing.play
|
| 220 |
+
clearUsedTiles
|
| 221 |
+
else
|
| 222 |
+
sounds.land.play
|
| 223 |
+
deselectTiles
|
| 224 |
+
end if
|
| 225 |
+
wordInProgress = ""
|
| 226 |
+
end while
|
| 227 |
+
|
| 228 |
+
s = "Final Score: " + score
|
| 229 |
+
text.row = 2
|
| 230 |
+
text.column = 34 - s.len/2
|
| 231 |
+
print s
|
| 232 |
+
sounds.wow.play
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
This code uses the `time` intrinsic method, which is the number of seconds that have passed since the start of the session, to calculate an `endTime` once, when the program first runs. Then every time the `updateTime` method is called, we can calculate how much time is left, and print that at the top of the screen. All that math on lines 228 and 229 is just a way to convert a number of seconds (`timeLeft`) into minutes and seconds, and ensure that the seconds always display as two digits so you get "1:08" instead of "1:8".
|
| 236 |
+
|
| 237 |
+
The main loop, lines 235-252, is mostly just calling all the other functions you defined and tested yesterday and today. It has a couple of smaller loops inside it. The one on line 236 updates all the tiles, until they have all slid into place. Line 237 checks for the timer running out, and breaks out of the main loop. Then the little loop on line 238 waits for the user to click the mouse. Both of those little loops update the timer while they wait.
|
| 238 |
+
|
| 239 |
+
Once we know the user has clicked the mouse, we find the tile hit by calling `tileUnderMouse`, just like our old test code. But now there's a check for the case where the user failed to hit any tile (line 240), which is something we ignored before. Remember that `continue` jumps to the next iteration of the loop, skipping the rest of the loop body.
|
| 240 |
+
|
| 241 |
+
If the user hit a valid tile, then we add it to the word (line 241), and track the mouse until it's released (line 242). Then we call that `scoreWord` function, which both updates the display, and tells us whether the word was valid. Depending on whether it was valid, we either clear the tiles used, or just deselect them (while also playing a sound).
|
| 242 |
+
|
| 243 |
+
Finally, we reset our `wordInProgress` variable, end our main loop, repeating all of the above until the timer runs out.
|
| 244 |
+
|
| 245 |
+
When that happens, the `break` on line 237 will jump down past the `end while`, where we print the final score, and play a "wow" sound to signal the end of the game.
|
| 246 |
+
|
| 247 |
+
This is a pretty long program — great job hanging in there! You should pause at this point and just play with it a bit. Grab some friends or family and challenge them. I got a score of 170 just now. Can you beat that?
|
| 248 |
+
|
| 249 |
+
## Taking it further
|
| 250 |
+
|
| 251 |
+
This is a complete, fun game as it is. But there are certainly ways you could extend it or modify it to make it your own, and I encourage you to try!
|
| 252 |
+
|
| 253 |
+
You could very easily change the number of rows and columns, since these magic numbers were stored in constants at the top of the program. I just changed mine from 5 columns to 6, and immediately found the word ANIME. What can you find?
|
| 254 |
+
|
| 255 |
+
One obvious change would be to the scoring formula. Replace `2 ^ word.len` with something else. It could be another formula based on the word length, or you could iterate over the letters of the word, and add a certain score for each letter, like in Scrabble. How does this affect your strategy when you play?
|
| 256 |
+
|
| 257 |
+
As written, the history (the words and scores previously obtained) always has the newest words at the top. That made sense to me, but maybe you'd like it better if the newest words were at the bottom. Can you figure out how to make that change? (Hint: look for where a new entry is beeing added to the `wordsFound` list.)
|
| 258 |
+
|
| 259 |
+
A somewhat more substantial change would be to add a feature that lets the player destroy letters without making them part of a word. For example, maybe if the user right-clicks a letter, you clear that letter (select it and call `clearUsedTiles`), but subtract 50 points from the score. This really enhances the strategy, since it makes it possible to connect much longer words, but there's a penalty for doing it.
|
| 260 |
+
|
| 261 |
+
Or, consider giving the user some way to clear all the letters at once and get a fresh set, for those times when you feel like you've just gotten rotten luck on the draw. Perhaps detect when a certain key has been pressed (with `key.available` and `key.get`), and in that case, select all tiles and call `clearUsedTiles`.
|
| 262 |
+
|
| 263 |
+
A> **Chapter Review**
|
| 264 |
+
A> - You finished a word game, your longest and most sophisticated program yet.
|
| 265 |
+
A> - You probably got some practice debugging and tracking down typos. This is an important skill and well worth practicing!
|
| 266 |
+
A> - You considered ways to go beyond the code in the book, changing things and adding features to make it your own.
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
|
data/day25.txt
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 25: Tile Display", startingPageNum:305}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Testing leads to failure, and failure leads to understanding.
|
| 7 |
+
Q>— Burt Rutan (aerospace engineer and entrepreneur)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn the last type of Mini Micro graphics display, `TileDisplay`.
|
| 11 |
+
A> - Get familiar with presenting grid-based data or images.
|
| 12 |
+
A> - Learn to draw hexagonal grids as well as rectangular ones.
|
| 13 |
+
|
| 14 |
+
You've learned a lot about Mini Micro's sophisticated display system by now. To review, it has eight display layers, each of which can be configured to any of the following modes:
|
| 15 |
+
|
| 16 |
+
| 0 | off | no display |
|
| 17 |
+
| 1 | solid color | displays one color over the whole screen |
|
| 18 |
+
| 2 | text | 26 row, 68 column text display |
|
| 19 |
+
| 3 | pixel | 960 by 640 (by default) pixel display |
|
| 20 |
+
| 4 | tile | displays a rectangular grid of small images |
|
| 21 |
+
| 5 | sprite | displays a set of scaleable, rotatable, resizable images |
|
| 22 |
+
|
| 23 |
+
Most of these were covered on Day 19, though pixel displays were covered on Day 18, and sprite displays on Day 22. The only display mode we haven't explored yet is `tile` mode.
|
| 24 |
+
|
| 25 |
+
So today, let's do that! After today, your training in Mini Micro graphics will be complete.
|
| 26 |
+
|
| 27 |
+
## TileDisplay
|
| 28 |
+
|
| 29 |
+
The big idea with a `TileDisplay` is that it takes little rectangular sub-images from a source image called a "tile set," and places them into a grid of locations on the screen.
|
| 30 |
+
|
| 31 |
+

|
| 32 |
+
|
| 33 |
+
{i:"`/sys/demo`,`platformer`"}
|
| 34 |
+
The figure above shows one of the built-in images (`/sys/pics/SimplePlatformTiles.png`) on the left, with grid lines added so you can see where the tiles are. Such an image is called a *tile set*. On the right is a screen shot of the platform demo (`/sys/demo/platformer.ms`), also with reference lines added. Each of those little squares in the `TileDisplay` is called a *cell*, and each cell shows some *tile* from the tile set. Let's get that terminology straight to avoid confusion later.
|
| 35 |
+
|
| 36 |
+
tile set
|
| 37 |
+
: an image composed of a rectangular grid of smaller images intended to be used with a tile display
|
| 38 |
+
tile
|
| 39 |
+
: one of those little images in a tile set
|
| 40 |
+
tile display
|
| 41 |
+
: a display composed of rectangular cells, each displaying zero or one tiles from a tile set; in Mini Micro, represented by the `TileDisplay` class
|
| 42 |
+
cell
|
| 43 |
+
: one of those little rectangular areas of the display
|
| 44 |
+
|
| 45 |
+
## Sprites vs. Tiles
|
| 46 |
+
|
| 47 |
+
Remember those letter tiles in the word game of Chapters 23 and 24? Those were *sprites*, drawn in a `SpriteDisplay`, and for good reason: we wanted them to fall smoothly into position, and we might even want to add a little bit of rotation to each one to make them look more natural. That sort of fine control is not possible with a `TileDisplay`; every cell in a `TileDisplay` is positioned precisely next to its neighbors like every other cell, and no rotation is possible.
|
| 48 |
+
|
| 49 |
+
Why would you ever use a `TileDisplay`, then? There are two chief advantages. First, a `TileDisplay` is somewhat easier to manage, since you need only assign a tile number to any cell of the display, and the graphics on screen automatically update. You'll see how easy that is by the end of the chapter. Second, while `SpriteDisplay` is the most efficient way to draw a bunch of moving/rotating pictures, it can't compete with a `TileDisplay` when it comes to drawing a large grid of same-sized little images. So if you're making something like a map or game board, in most cases `TileDisplay` is both easier and faster.
|
| 50 |
+
|
| 51 |
+
## The `TileDisplay` class
|
| 52 |
+
|
| 53 |
+
When you set a display's `mode` to `displayMode.tile`, it changes the type of that display to `TileDisplay`, which means it gets the following assignable properties:
|
| 54 |
+
|
| 55 |
+
{caption:"Properties of the `TileDisplay` class (where `td` is any `TileDisplay` reference). All these may be both read and assigned to. The `extent`, `tileSetTileSize`, `cellSize`, and `overlap` properties may be either a single number applied to both X and Y, or an `[x,y]` list."}
|
| 56 |
+
|`td.extent`|[columns, rows] display size|
|
| 57 |
+
|`td.tileSet`|`Image` containing tiles to draw from|
|
| 58 |
+
|`td.tileSetTileSize`|size of tiles in `tileSet`|
|
| 59 |
+
|`td.cellSize`|size of tiles (cells) on screen|
|
| 60 |
+
|`td.overlap`|cell overlap on screen, in pixels|
|
| 61 |
+
|`td.oddRowOffset`|amount to shift odd rows horizontally; use 0.5 for hex rows|
|
| 62 |
+
|`td.oddColOffset`|amount to shift odd columns vertically; use 0.5 for hex columns|
|
| 63 |
+
|`td.scrollX`|horizontal scroll amount, in pixels|
|
| 64 |
+
|`td.scrollY`|vertical scroll amount, in pixels|
|
| 65 |
+
|
| 66 |
+
{pageBreak}
|
| 67 |
+
And it gets the following methods (you can only call these, not assign to them):
|
| 68 |
+
|
| 69 |
+
{caption:"Methods of the `TileDisplay` class."}
|
| 70 |
+
|`td.clear` *toIndex*|set all tiles to null (the default) or the given index|
|
| 71 |
+
|`td.cell(x,y)|get the tile index of cell `x`,`y`|
|
| 72 |
+
|`td.setCell x, y, idx|set the tile index of cell `x`,`y` to `idx`|
|
| 73 |
+
|`td.cellTint(x,y)|get the tint color of cell `x`,`y`|
|
| 74 |
+
|`td.setCellTint x, y, c|set the tint of cell `x`,`y` to color `c`|
|
| 75 |
+
|
| 76 |
+
That seems like a lot, but as we'll see shortly, they fall into just a couple of groups: things for configuring the TileDisplay at setup time, and things for controlling the content (the tiles shown and their tint color) as your program runs.
|
| 77 |
+
|
| 78 |
+
## Basic Configuration
|
| 79 |
+
|
| 80 |
+
EBOOK>It's time to put hands to keyboard and start using this thing! You may recall from Day 19 the default display types that Mini Micro gets at startup (or when you use the `clear` command). These include a PixelDisplay (display 5), a SpriteDisplay (4), and of course a TextDisplay (3). They do not, however, include a TileDisplay.
|
| 81 |
+
|
| 82 |
+
EBOOK>So the first thing to do is create such a display! You can put it in any layer you want, but for this chapter, let's repurpose layer 5, as we won't be doing any pixel drawing anyway. Fire up Mini Micro, and let's get started.
|
| 83 |
+
|
| 84 |
+
{width: "50%", position:"top"}
|
| 85 |
+

|
| 86 |
+
|
| 87 |
+
PRINT>It's time to put hands to keyboard and start using this thing! You may recall from Day 19 the default display types that Mini Micro gets at startup (or when you use the `clear` command). These include a PixelDisplay (display 5), a SpriteDisplay (4), and of course a TextDisplay (3). They do not, however, include a TileDisplay.
|
| 88 |
+
|
| 89 |
+
PRINT>So the first thing to do is create such a display! You can put it in any layer you want, but for this chapter, let's repurpose layer 5, as we won't be doing any pixel drawing anyway. Fire up Mini Micro, and let's get started.
|
| 90 |
+
|
| 91 |
+
```terminal
|
| 92 |
+
]display(5).mode = displayMode.tile
|
| 93 |
+
]td = display(5)
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Nothing much appears to happen at this point, but invisibly, display 5 has transmogrified from a pixel display into a tile display. We've also assigned it to a variable called `td` so we can refer to it more easily. Now let's load a tile set (and also use the `view` command so you can get a glimpse of what it looks like).
|
| 97 |
+
|
| 98 |
+
```terminal
|
| 99 |
+
]td.tileSet = file.loadImage("/sys/pics/TileShapes.png")
|
| 100 |
+
]view td.tileSet
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
The tile set we've loaded here is a selection of eight different simple shapes, in eight different colors. The image is 512 by 512 pixels, and since there are 8 rows and columns, this means the tile size (in the tile set) is 64 pixels wide and tall. This is the next thing we have to do: tell the tile display how big the tiles are.
|
| 104 |
+
|
| 105 |
+
```terminal
|
| 106 |
+
]td.tileSetTileSize = 64
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
We used just a simple number here (64) because the tiles are square. That's usually the case, but if you ever find or make a tile set with non-square tiles, you can specify the width and height in a list like `[48,32]`.
|
| 110 |
+
|
| 111 |
+
Finally we're ready to get some tiles onto the display! The easiest way to do that is with the `.clear` method, which takes a *tile index* to know which tile it should clear everything to.
|
| 112 |
+
|
| 113 |
+
tile index
|
| 114 |
+
: a number which identifies a tile in a tile set, starting with 0 at the top-left, and counting left-to-right, then top-to-bottom
|
| 115 |
+
|
| 116 |
+
The figure above shows the tile indexes for this tile set. Let's clear the tile display to the dark blue circle, which is tile index 20.
|
| 117 |
+
|
| 118 |
+
```terminal
|
| 119 |
+
]td.clear 20
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
The result should look something like this:
|
| 123 |
+
|
| 124 |
+
{width:"75%"}
|
| 125 |
+

|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
Now we can see the tile display: it's that grid of blue circles! Check your understanding of tile index by trying a few other values. Can you fill the display with red diamonds? How about purple hexagons?
|
| 129 |
+
|
| 130 |
+
You probably noticed that the tile display does not fill the whole screen. There 12 columns and 7 rows of cells, which is called the *extent* of the display.
|
| 131 |
+
|
| 132 |
+
extent
|
| 133 |
+
: how many columns and rows a tile display has
|
| 134 |
+
|
| 135 |
+
In fact if you type `td.extent` at the prompt, it will tell you `[12, 7]`. You can change it by simply assigning a new pair of numbers. Note that if you make the tile set *smaller*, you see the change right away; but if you make it bigger, it's not so obvious, because the new rows and columns are filled in with empty cells. You need to use the `.clear` method (or otherwise fill in the new cells) to see the new extent. Try this, carefully observing the result at each step:
|
| 136 |
+
|
| 137 |
+
```terminal
|
| 138 |
+
]td.extent = [8,6]
|
| 139 |
+
]td.extent = [15,10]
|
| 140 |
+
]td.clear 20
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Now the screen should be full of blue circles. But that's a function of the extent of the tile display, and also the cell size. The default cell size is 64, which happens to be the same as our tile size in this case. But you can easily change it. Explore:
|
| 144 |
+
|
| 145 |
+
```terminal
|
| 146 |
+
]td.cellSize = 32
|
| 147 |
+
]td.cellSize = 320
|
| 148 |
+
]td.cellSize = [128,32]
|
| 149 |
+
]td.cellSize = 64
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
Note that just like the `tileSetTileSize` property, you can specify `cellSize` as either a simple number for square cells, or as a `[width, height]` list for non-square cells.
|
| 153 |
+
|
| 154 |
+
Changing the tile size is how you can scale a tile display. What about scrolling? That uses the same `scrollX` and `scrollY` properties you already saw on `PixelDisplay` and `SpriteDisplay`.
|
| 155 |
+
|
| 156 |
+
```terminal
|
| 157 |
+
]for x in range(0,100); td.scrollX = x; wait 0.1; end for
|
| 158 |
+
]td.scrollX = 0
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
A tile display could be configured to be many times bigger than the actual screen, with different areas being scrolled into view as needed during a run.
|
| 162 |
+
|
| 163 |
+
## Using Cells
|
| 164 |
+
|
| 165 |
+
You've already been using tile indexes with the `.clear` method, to clear the whole tile display to the same cell. Now let's learn to set, read, and tint specific cells.
|
| 166 |
+
|
| 167 |
+
The methods for doing this are very similar to those you would use on a `TextDisplay` (Day 17): `cell(column, row)` to read the tile index at a given column and row, or `setCell column, row, index` to set it. And just like a `TextDisplay`, rows count up from the bottom, and columns count from the left side of the display. So to change the lower-left cell to index 8 — a round-cornered square in our tile set — just do:
|
| 168 |
+
|
| 169 |
+
```terminal
|
| 170 |
+
]td.setCell 0, 0, 8
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
Now try using the `cell` method to read back the tile index at several positions.
|
| 174 |
+
|
| 175 |
+
```terminal
|
| 176 |
+
]td.cell 0,0
|
| 177 |
+
8
|
| 178 |
+
]td.cell 1,0
|
| 179 |
+
20
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
Simple, right? Cover up the code below, and see if you can solve the following challenge without looking: change the cell that's 6th from the left, and 3rd from the bottom, into a white diamond. (Remember that rows and columns begin at 0, not at 1.)
|
| 183 |
+
|
| 184 |
+
```terminal
|
| 185 |
+
]td.setCell 5, 2, 40
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
Did you get it right?
|
| 189 |
+
|
| 190 |
+
D> Make up some more challenges for yourself if you need more practice; the computer is a calm and infinitely patient teacher.
|
| 191 |
+
|
| 192 |
+
Instead of assigning a tile index to a cell, you can also set it to `null`, which means "don't draw any tile here at all." In fact this is what the `.clear` method does to all cells if you don't specify an index value. Go ahead and try it now:
|
| 193 |
+
|
| 194 |
+
```terminal
|
| 195 |
+
]td.setCell 3, 3, null
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
The other thing you can do with tile display cells is tint them, just like sprites. If you tint a pixel that's white in the source image, it comes out exactly the tint color; but if the source image is darker, then you get a darker version of the tint color. That's why white images are so useful. In fact, this `SimpleTiles.png` is really eight times bigger than it needs to be; it could have been *only* white shapes, as all the other colors could be made by tinting. (But sometimes it's convenient to use the prebaked colors, too.) Anyway, try this:
|
| 199 |
+
|
| 200 |
+
```terminal
|
| 201 |
+
]td.setCellTint 5, 2, color.orange
|
| 202 |
+
]td.setCellTint 5, 1, color.gray
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
The first line above tints that white diamond a nice strong orange. The second line tints a blue circle gray, which really just makes it a darker blue.
|
| 206 |
+
|
| 207 |
+
Hopefully you see how by assigning different tile indexes and/or tints to different cells, you can build a complex display that looks like a map, or a platformer game level, or anything else that has a basically grid-like structure.
|
| 208 |
+
|
| 209 |
+
## Overlap and Offset
|
| 210 |
+
|
| 211 |
+
So far we have only seen cells arranged into a neat square or rectangular grid. Tile displays in Mini Micro are more versatile than that, however.
|
| 212 |
+
|
| 213 |
+
First, it is possible to set the cells in the display to overlap horizontally, vertically, or both. To do this you assign to the `overlap` property a list that contains the desired horizontal and vertical overlap. For example:
|
| 214 |
+
|
| 215 |
+
```terminal
|
| 216 |
+
]td.overlap = [0, 8]
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
This scrunches the cells so that they overlap in Y. This can be useful for certain art styles, where each tile contains bits at the top that overlap, for example, grass or flowers that stick up from the ground on a grass tile. When tiles are overlapped, they're always layered so that lower rows on the screen are drawn on top of higher rows, producing the correct result in this case. In other cases, `overlap` is simply used to spread the cells apart, or squeeze them together, as needed.
|
| 220 |
+
|
| 221 |
+
The second trick you can do with the cell arrangement is to offset odd-numbered rows or columns by some fraction of the cell width. This is useful in making isometric or hexagonal maps. Let's start with an isometric map. That's one where the map is made of little diamonds that fit together neatly, as if you were looking at graph paper from an angle.
|
| 222 |
+
|
| 223 |
+
{width: "50%"}
|
| 224 |
+

|
| 225 |
+
|
| 226 |
+
To do set this up, we'll use a diamond-shaped tile with a rectangular cell size. Then we'll use `overlap` to make it so that each row overlaps the one above it, and the `oddRowOffset` property to shift the odd-number rows over by one half the cell width. Try it:
|
| 227 |
+
|
| 228 |
+
```terminal
|
| 229 |
+
]td.overlap = 0
|
| 230 |
+
]td.clear 40
|
| 231 |
+
]td.cellSize = [64, 48]
|
| 232 |
+
]td.overlap = [0, 24]
|
| 233 |
+
]td.oddRowOffset = 0.5
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
Line 1 above just clears out the `overlap` values from our previous experiment. Line 2 clears the display to a white diamond tile, and line 3 squashes that vertically so that each cell on screen is wider than it is tall. Line 4 makes the rows overlap, and then — here's the real trick — line 5 shifts the odd rows (i.e. row 1, 3, 5, etc.) over by one half (0.5) of the cell width. The result is a nice neat isometric display, as shown in the figure above.
|
| 237 |
+
|
| 238 |
+
The other use for shifting odd rows or columns is to make a hexagonal display. The basic idea here is the same: make your tiles overlap, and then add a row or column offset, depending on which way your hexagons are rotated. We'll walk through each case, using circle tiles at first (which make it slightly easier to see what's going on) and then switching to hexagons.
|
| 239 |
+
|
| 240 |
+
First, let's get back to an ordinary square grid of circles.
|
| 241 |
+
|
| 242 |
+
```terminal
|
| 243 |
+
]td.oddRowOffset = 0
|
| 244 |
+
]td.cellSize = 64
|
| 245 |
+
]td.overlap = 0
|
| 246 |
+
]td.clear 16
|
| 247 |
+
```
|
| 248 |
+
|
| 249 |
+
Remember that the 16 used on line 4 is just the tile index for a white circle in our tile set. If you look back at the tile set, you'll see that right below that, at index 24, is a hexagon with a flat top and points on its left/right sides. That means when we're all done, the cells are going to overlap a bit horizontally, and we'll be offsetting the odd columns to make them all fit. Try it step by step:
|
| 250 |
+
|
| 251 |
+
```terminal
|
| 252 |
+
]td.overlap = [11, 0]
|
| 253 |
+
]td.oddColOffset = 0.5
|
| 254 |
+
]td.clear 24
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
{gap:20}
|
| 258 |
+
{width: "50%"}
|
| 259 |
+

|
| 260 |
+
|
| 261 |
+
The next row in our tile set, at index 32, is the opposite kind of hexagon: it's flat on the sides, and pointy on top and bottom. To fit together neatly, it needs to overlap in Y, and have the odd rows shifted over by half a cell.
|
| 262 |
+
|
| 263 |
+
```terminal
|
| 264 |
+
]td.clear 16
|
| 265 |
+
]td.oddColOffset = 0
|
| 266 |
+
]td.overlap = [0, 11]
|
| 267 |
+
]td.oddRowOffset = 0.5
|
| 268 |
+
]td.clear 32
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
The first two lines above are just undoing our previous demo; lines 3-5 do the actual setup for this kind of hexagonal display.
|
| 272 |
+
|
| 273 |
+
{width: "50%"}
|
| 274 |
+

|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
## Exploring the Demos
|
| 278 |
+
|
| 279 |
+
`TileDisplay` is used by quite a few of the demos in `/sys/demo/`. Here's a quick run-down of how each of them use it, and what you might be able to learn.
|
| 280 |
+
|
| 281 |
+
{i:"`/sys/demo`,`drumMachine`"}
|
| 282 |
+
**drumMachine**: this demo uses two overlaid tile displays, in display layers 5 and 6. Both use the same `TileShapes.png` tile set you've been working with in this chapter. The frontmost layer uses the square with rounded corners, and uses a *negative* `overlap` value to spread them apart so there's a nice gap between the cells. The background layer uses no gap, and a solid square tile; this is used to highlight the column of cells that represents the current point in the music loop. The result of all this is an interactive grid where each row represents a different instrument, and each column represents a point in time; by clicking those cells on and off, you can lay down a beat.
|
| 283 |
+
|
| 284 |
+
{i:"`/sys/demo`,`levelEditor`"}
|
| 285 |
+
**levelEditor**: this is an interesting one, because it's not just a demo, but also a useful tool. It sets up `display(6)` as the tile display, with `display(5)` used in pixel mode to draw on top of the tiles. It then provides functions to define the pattern of tiles in a tile display, save these out to disk as a data file, and load them back in for further editing next time.
|
| 286 |
+
|
| 287 |
+
{i:"`/sys/demo`,`platformer`"}
|
| 288 |
+
**platformer**: this game demo uses a layout defined by `levelEditor`, and also adds a sprite character who can run, jump, and climb. The very first figure in this chapter was a screen shot of this demo and its tile set. The code illustrates how to check the tile display where the character is trying to walk or climb, and use that information to react appropriately. It's one of the more sophisticated demos in Mini Micro, but if you're interested in making platformer games, it's definitely the place to start.
|
| 289 |
+
|
| 290 |
+
{i:"`/sys/demo`,`speedConquest`"}
|
| 291 |
+
**speedConquest**: this turn-based strategy game also uses the `TileShapes.png` tile set, with a hexagonal layout (using `oddColOffset`). In this case it uses only the white tile, and then tints them to each player's color to make their territories clear. There's also a sprite layer, used to draw the units and flags on top of the tile display. In the code you'll find some handy functions for converting between tile coordinates and pixel coordinates, which is a bit trickier in a hex layout than in a rectangular one. These functions are useful for handling mouse clicks and figuring out where to position the sprites. (It's also a really fun game — if you haven't given it a serious try yet, I recommend it! It's a much deeper game than it first appears.)
|
| 292 |
+
|
| 293 |
+
{i:"`/sys/demo`,`wumpusTrap`"}
|
| 294 |
+
**wumpusTrap**: this puzzle game also uses a hex grid, but this time using `oddRowOffset` because the hexagons are in the other orientation. Also, it uses different color tiles from the tile set rather than using tint. Like `speedConquest`, it has some handy functions for converting between pixels and tile coordinates, so between the two, you should have a starting point for any sort of hex map you might want to make. Naturally the wumpus in this game is in a separate sprite layer on top of the tile display. (And yes, it is always possible to trap the wumpus — but not always easy!)
|
| 295 |
+
|
| 296 |
+
A> **Chapter Review**
|
| 297 |
+
A> - You explored the `TileDisplay` class, the last type of Mini Micro display.
|
| 298 |
+
A> - You learned how to load a tile set, and configure the tile display.
|
| 299 |
+
A> - You discovered how to control what a tile display shows by assigning a tile index or tint color to each cell.
|
| 300 |
+
A> - You learned about the overlap and offset properties that enable you to make an isometric or hexagonal display.
|
| 301 |
+
A> - You toured the built-in demos that illustrate some of the many ways a tile display can be put to use.
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
{gap:250}
|
| 305 |
+
{width:"25%"}
|
| 306 |
+

|
| 307 |
+
|
data/day26.txt
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 26: Treasure Hunt", startingPageNum:319}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> No more training do you require.
|
| 7 |
+
Q> Already know you that which you need.
|
| 8 |
+
Q>— Yoda (Star Wars: Episode VI - Return of the Jedi)
|
| 9 |
+
|
| 10 |
+
A> **Chapter Objectives**
|
| 11 |
+
A> - Build and enjoy the *Treasure Hunt* game.
|
| 12 |
+
A> - See how `TileDisplay` is used in a real program.
|
| 13 |
+
A> - Practice installing resources onto your user disk, so you're not limited to only the stuff on the `/sys` disk.
|
| 14 |
+
|
| 15 |
+
Your introduction to MiniScript and Mini Micro are essentially complete at this point. You learned the basics of coding, and flexed your skills via the Try-It! page, in the first week. The second week you learned to use command-line MiniScript, while also learning about lists, maps, and classes. Since then you've been exploring Mini Micro, and have learned about displaying text, pixel graphics, sprites, and tiles, not to mention playing sounds and music and interacting with the mouse and keyboard. As Yoda said: already know you that which you need.
|
| 16 |
+
|
| 17 |
+
However, just as with Luke's journey to master the Force, your journey is not yet over. Your head is full of knowledge, but can you actually *use* that knowledge to create your own software? For most readers, the answer at this point will be "not yet," and that's OK. Learning to apply what you have learned takes practice.
|
| 18 |
+
|
| 19 |
+
So the next few chapters of the book will be practice and review, in the form of programs for you to type in. I urge you not to skip this exercise! It will make your programming skills stronger.
|
| 20 |
+
|
| 21 |
+
(And to any eager readers who skipped the first half of the book to get to the "good stuff," I say welcome! But please remember to go back and go through the rest of the book at some point. It will give you a strong foundation in the basics, and ultimately save you a lot of time learning things the hard way.)
|
| 22 |
+
|
| 23 |
+
## *Treasure Hunt*
|
| 24 |
+
|
| 25 |
+
The program for this chapter is a game based on the classic *Minesweeper*. The basic idea behind *Minesweeper* dates all the way back to the era of mainframe computers in the 1960s. For many years a version of *Minesweeper* was included with the Microsoft Windows operating system, leading to a great surge in popularity, and probably causing a noticeable drain on the office economy.
|
| 26 |
+
|
| 27 |
+
The core game play for all *Minesweeper* variants is the same: you click squares on a map to discover what they contain. If they contain a mine, it's game-over. Otherwise, the square reveals how many mines there are in the neighboring squares. Using these numbers, you can usually find a safe place to try next.
|
| 28 |
+
|
| 29 |
+
Our version of the game is called *Treasure Hunt*, and adds a little twist: hidden along with the bombs are half a dozen treasures, and uncovering these treasures scores you points. The faster you discover them, the more points you earn!
|
| 30 |
+
|
| 31 |
+
{width: "80%"}
|
| 32 |
+

|
| 33 |
+
|
| 34 |
+
Incidentally, this game is so much fun, and the code so straightforward, that it almost didn't make it into this book. I was very tempted to add it to the built-in demos in `/sys/demo/` in the final version of Mini Micro. But in the end I decided to instead include it here, as a reward for those of you who took the time to work through this book. Enjoy!
|
| 35 |
+
|
| 36 |
+
## Getting the Tile Set
|
| 37 |
+
|
| 38 |
+
This is the first program in this book that does not rely entirely on resources included on Mini Micro's `/sys` disk. Instead, you'll need to download a tile set from the internet, and install it on your `/usr` disk. This will become a very common task as you start building more of your own programs, so it's a good skill to learn.
|
| 39 |
+
|
| 40 |
+
The tiles for this game are available on OpenGameArt.org, a web site dedicated to sharing artwork for making games. You can find it by searching for "treasure hunt" on the main page there, or by pointing your web browser directly to `https://opengameart.org/content/treasure-hunt-tiles`. When you find the right page, there will be a download link for `TreasureHunt.png`, an image that looks like the picture on the next page.
|
| 41 |
+
|
| 42 |
+
{width: "50%"}
|
| 43 |
+

|
| 44 |
+
|
| 45 |
+
Now you need to get this onto your `/usr` disk. You have several options for this:
|
| 46 |
+
|
| 47 |
+
{pageBreak}
|
| 48 |
+
- If you are using a *folder* for your user disk rather than a "minidisk" file, you can simply download the image with your web browser, and save it to that folder.
|
| 49 |
+
- If not, you can download the image somewhere else, then use the `file.import` command in Mini Micro to copy it into your `usr` disk.
|
| 50 |
+
- Or you can use `http.get` to download the file directly within Mini Micro, by right-clicking on the file link at OpenGameArt, then pasting it into a command like so:
|
| 51 |
+
|
| 52 |
+
```terminal
|
| 53 |
+
]img = http.get("https://opengameart.org/sites/default/files/treasurehunt_0.png")
|
| 54 |
+
]file.saveImage "TreasureHunt.png", img
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
No matter which method you use, at the end you should have a `TreasureHunt.png` file on your user disk, in the folder where you plan to save the program. If needed, review Chapter 14, which discusses how to convert your `/usr` disk between the minidisk (zip file) format and a folder of real files. When you've got that sorted out, move on to the next step.
|
| 58 |
+
|
| 59 |
+
## Starting the Program
|
| 60 |
+
|
| 61 |
+
Now it's time to start on the code! As in past chapters, we'll break this into sections, with a bit of explanation after each one. But we won't lead you explicitly through testing code anymore. You should still test as you go, though — *at least* run the program to make sure it doesn't generate any errors right away. We'll point out further tests you can do at each point, but it will be up to you to write them. Your programming skills are growing!
|
| 62 |
+
|
| 63 |
+
{caption:"Listing 1 (Program set-up).", number-from: 1}
|
| 64 |
+
```miniscript
|
| 65 |
+
// Treasure Hunt!
|
| 66 |
+
// A Minesweeper-type game with treasures.
|
| 67 |
+
|
| 68 |
+
import "listUtil"
|
| 69 |
+
|
| 70 |
+
// Constants
|
| 71 |
+
kCols = 20
|
| 72 |
+
kRows = 15
|
| 73 |
+
kCellGrass = 16
|
| 74 |
+
kCellFlag = 17
|
| 75 |
+
kCellBomb = 18
|
| 76 |
+
kCellTreasure = 10 // (first treasure on sand background)
|
| 77 |
+
kCellTransTreasure = 26 // (first one on transparent background)
|
| 78 |
+
|
| 79 |
+
// Set up the displays
|
| 80 |
+
clear
|
| 81 |
+
display(4).mode = displayMode.tile
|
| 82 |
+
td = display(4)
|
| 83 |
+
td.tileSet = file.loadImage("TreasureHunt.png")
|
| 84 |
+
td.tileSetTileSize = 32
|
| 85 |
+
td.cellSize = 32
|
| 86 |
+
td.extent = [kCols, kRows]
|
| 87 |
+
td.clear kCellGrass
|
| 88 |
+
td.scrollX = -80; td.scrollY = -80
|
| 89 |
+
|
| 90 |
+
gold = "#FFDD52FF"
|
| 91 |
+
gfx.color = gold
|
| 92 |
+
gfx.print "Treasures Found", 780, 540, gold, "small"
|
| 93 |
+
gfx.line 780-4, 540-4, 780+"Treasures Found".len * 9 + 4, 540-4
|
| 94 |
+
treasureListY = 540 - 48
|
| 95 |
+
treasureListX = 780
|
| 96 |
+
|
| 97 |
+
text.color = gold
|
| 98 |
+
text.row = 25; print "TREASURE HUNT!"
|
| 99 |
+
score = 0
|
| 100 |
+
treasuresLeft = 0
|
| 101 |
+
|
| 102 |
+
// Load sounds
|
| 103 |
+
treasureSnd = file.loadSound("/sys/sounds/cha-ching.wav")
|
| 104 |
+
bombSnd = file.loadSound("/sys/sounds/airburst.wav")
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
Here's a pretty typical first page of a Mini Micro game. After a header comment, we import the `listUtil` module on line 4. We'll be using the `list.init2d` method this module adds to conveniently create a 2D array to keep track of the hidden treasures and bombs.
|
| 108 |
+
|
| 109 |
+
Then we define a bunch of constants on lines 7-13. `kCols` and `kRows` define the size of the play area, and the other constants define the indexes of various tiles in the tile map, so we're not stuck looking at mysterious numbers like `17` for the rest of the program.
|
| 110 |
+
|
| 111 |
+
The next block of lines, from 16 through 24, set up a `TileDisplay` and name it `td`, just as we saw in the previous chapter. Then we set up the graphics display, with a nice gold color for the treasure list, and use the same color on the text display. So this game is using three of Mini Micro's eight displays:
|
| 112 |
+
|
| 113 |
+
- a `PixelDisplay` called `gfx` in layer 5, for the treasure list;
|
| 114 |
+
- a `TileDisplay` called `td` in layer 4, for the game board; and
|
| 115 |
+
- a `TextDisplay` called `text` in layer 3, for the time and score.
|
| 116 |
+
|
| 117 |
+
Note that `gfx` and `text` are the standard layers set up by the `clear` command, but there is no standard `TileDisplay`, which is why we have to explicitly create one on lines 17-18.
|
| 118 |
+
|
| 119 |
+
Finally, on lines 39-40, we load a couple of sounds we'll need later.
|
| 120 |
+
|
| 121 |
+
You should run at this point, and make sure you don't see any errors. You should also see a field of green tiles, a blank "Treasures Found" list on the right, and the "TREASURE HUNT!" title at the top.
|
| 122 |
+
|
| 123 |
+
D> Also remember to save your work often!
|
| 124 |
+
|
| 125 |
+
## The `GridPos` Class
|
| 126 |
+
|
| 127 |
+
In this program we are going to be dealing with grid positions a lot. We'll have code that figures out what grid position the mouse is over, what secrets are buried at that grid position, which grid positions are neighboring this one, and so on. We could represent such grid positions as an `[x, y]` list, but a little more effort up front to define a `GridPos` class will pay off in simpler, clearer code later.
|
| 128 |
+
|
| 129 |
+
{caption:"Listing 2 (The `GridPos` class.)", number-from: 42}
|
| 130 |
+
```miniscript
|
| 131 |
+
// Define a "GridPos" class to represent a grid
|
| 132 |
+
// position (i.e. column, row).
|
| 133 |
+
GridPos = {"col":0, "row":0}
|
| 134 |
+
|
| 135 |
+
// Function to make a GridPos at a given column and row
|
| 136 |
+
GridPos.make = function(c,r)
|
| 137 |
+
gp = new GridPos
|
| 138 |
+
gp.col = c
|
| 139 |
+
gp.row = r
|
| 140 |
+
return gp
|
| 141 |
+
end function
|
| 142 |
+
|
| 143 |
+
// Function to make a random (but in-bounds) GridPos.
|
| 144 |
+
GridPos.random = function()
|
| 145 |
+
return GridPos.make(floor(kCols * rnd), floor(kRows * rnd))
|
| 146 |
+
end function
|
| 147 |
+
|
| 148 |
+
// Function to find the GridPos at a screen position;
|
| 149 |
+
// returns null if out of bounds.
|
| 150 |
+
GridPos.atXY = function(screenPos)
|
| 151 |
+
col = floor((screenPos.x + td.scrollX) / td.cellSize)
|
| 152 |
+
row = floor((screenPos.y + td.scrollY) / td.cellSize)
|
| 153 |
+
if col < 0 or col >= kCols then return null
|
| 154 |
+
if row < 0 or row >= kRows then return null
|
| 155 |
+
return GridPos.make(col, row)
|
| 156 |
+
end function
|
| 157 |
+
|
| 158 |
+
// Method to get all in-bounds neighbors of this GridPos
|
| 159 |
+
GridPos.neighbors = function()
|
| 160 |
+
result = []
|
| 161 |
+
for i in range(-1, 1)
|
| 162 |
+
for j in range(-1, 1)
|
| 163 |
+
if i == 0 and j == 0 then continue
|
| 164 |
+
p = GridPos.make(self.col + i, self.row + j)
|
| 165 |
+
if p.col < 0 or p.col >= kCols then continue
|
| 166 |
+
if p.row < 0 or p.row >= kRows then continue
|
| 167 |
+
result.push p
|
| 168 |
+
end for
|
| 169 |
+
end for
|
| 170 |
+
return result
|
| 171 |
+
end function
|
| 172 |
+
|
| 173 |
+
// Method to get the tile cell through this GridPos
|
| 174 |
+
GridPos.cell = function()
|
| 175 |
+
return td.cell(self.col, self.row)
|
| 176 |
+
end function
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
Line 44 declares the `GridPos` class by simply assigning a map with default `col` and `row` properties. To make it easier to create an instance of this class, we have the `GridPos.make` function on line 47. Getting a *random* grid position is also a useful thing to do, especially when burying bombs and treasures, so we have a function for that starting line 55. Notice how `GridPos.random` uses `GridPos.make` to make its job easier.
|
| 180 |
+
|
| 181 |
+
Next, the `GridPos.atXY` function at line 61 works out what grid position is at a certain screen position (such as that given by `mouse`). The code here is fairly general; it would work for any tile display `td`, provided that its `cellSize` is a simple number (rather than a `[width, height]` list), and no column or row offset is used. Note that this function also does bounds checking, and returns `null` for any location outside the bounds of the grid.
|
| 182 |
+
|
| 183 |
+
Lines 70-82 define the `GridPos.neighbors` method. This is the first one intended to be called on a `GridPos` instance, i.e. some particular grid position, rather than on the `GridPos` class itself. Its job is to return a list of all the neighboring in-bounds grid positions. We need that in the game mainly to count how many bombs are hidden in neighboring cells, so we know what number to display.
|
| 184 |
+
|
| 185 |
+
Finally, the `GridPos.cell` method at line 85 is just a shortcut for looking up the cell index from the tile display. This turned out to be a sufficiently common thing in the rest of the code, that it was worth making this little helper method.
|
| 186 |
+
|
| 187 |
+
At this point you should not only make sure the code runs, but also try out these `GridPos` functions. You can do this right on the command line: call each one, passing in some reasonable parameter value, and make sure you get a sensible result.
|
| 188 |
+
|
| 189 |
+
## Handling mouse clicks
|
| 190 |
+
|
| 191 |
+
The next part of the program is a function to handle mouse clicks. We want to treat each tile cell kind of like a button: darken it while the mouse is pressed and inside the cell, but return it to normal appearance fi the mouse is dragged outside the cell. If the mouse is released outside the cell, it should have no effect.
|
| 192 |
+
|
| 193 |
+
If it's released *inside* the cell, then the effect depends on which mouse button was used. A normal (button 0) click reveals the hidden content of that cell, but a right-click (button 1) toggles a flag.
|
| 194 |
+
|
| 195 |
+
{caption:"Listing 3 (`handleClick` function.)", number-from: 89}
|
| 196 |
+
```miniscript
|
| 197 |
+
handleClick = function(btn=0)
|
| 198 |
+
hitPos = GridPos.atXY(mouse)
|
| 199 |
+
if hitPos == null or hitPos.cell < kCellGrass then
|
| 200 |
+
// invalid click; just wait for mouse-up and return
|
| 201 |
+
while mouse.button(btn); yield; end while
|
| 202 |
+
return
|
| 203 |
+
end if
|
| 204 |
+
// Valid click: highlight until mouse-up
|
| 205 |
+
while mouse.button(btn)
|
| 206 |
+
inCell = (GridPos.atXY(mouse) == hitPos)
|
| 207 |
+
if inCell then
|
| 208 |
+
td.setCellTint hitPos.col, hitPos.row, "#DDDDDD"
|
| 209 |
+
else
|
| 210 |
+
td.setCellTint hitPos.col, hitPos.row, color.white
|
| 211 |
+
end if
|
| 212 |
+
yield
|
| 213 |
+
end while
|
| 214 |
+
// If mouse was not released in the hit cell, bail out
|
| 215 |
+
if not inCell then return
|
| 216 |
+
td.setCellTint hitPos.col, hitPos.row, color.white
|
| 217 |
+
// Otherwise, process the click.
|
| 218 |
+
// Left click (btn 0), reveal the cell.
|
| 219 |
+
// Right click (btn 1), toggle flag.
|
| 220 |
+
if btn == 0 then
|
| 221 |
+
reveal hitPos
|
| 222 |
+
else
|
| 223 |
+
if hitPos.cell == kCellFlag then
|
| 224 |
+
td.setCell hitPos.col, hitPos.row, kCellGrass
|
| 225 |
+
else
|
| 226 |
+
td.setCell hitPos.col, hitPos.row, kCellFlag
|
| 227 |
+
end if
|
| 228 |
+
end if
|
| 229 |
+
end function
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
The function begins by making sure we have clicked a valid cell. The click is ignored if it is out of bounds, or if the cell index at the clicked point is less than the grass cell; all the tiles in the tile set before that represent already-revealed locations, and clicking those should have no effect.
|
| 233 |
+
|
| 234 |
+
The loop from line 97 to 105 handles the "button" behavior, darkening the cell while the mouse is pressed within its bounds. It also sets a local variable `inCell` to note whether the mouse is actually within the cell originally clicked. So, once the mouse is finally released, line 107 can bail out if it was released outside the cell.
|
| 235 |
+
|
| 236 |
+
D> If you're confused by all this, open up any ordinary program or web page that has a clickable button. Mouse-down on the button, then drag the mouse away before you release. The button should pop back up as soon as you're outside the button, and the button's effect is not triggered. That's all we're doing here.
|
| 237 |
+
|
| 238 |
+
Finally, if we make it to line 109, then it's a valid click. Here we do different things depending on the mouse button used: either reveal the contents of the cell hit, or toggle between grass and flag.
|
| 239 |
+
|
| 240 |
+
To test this, you will need to make a mock `reveal` method that takes one parameter. It doesn't need to do anything, but you might have it just print the value of the parameter for testing purposes. (We'll get to the real `reveal` method later.) Then, call `handleClick 0` while you hold the left mouse button down on some cell of the grid; or call `handleClick 1` while holding the right mouse button.
|
| 241 |
+
|
| 242 |
+
## Time, Score, and Burying Stuff
|
| 243 |
+
|
| 244 |
+
Here are a handful of little functions we'll need. Dividing your program into small functions like this is almost always a good idea. Within the function, you can focus on a problem small enough to understand completely; and elsewhere, where you *use* the function, you can forget about the details and just trust that it does what it says it does.
|
| 245 |
+
|
| 246 |
+
{caption:"Listing 4 (Drawing time and score, and tracking hidden items.)", number-from: 123}
|
| 247 |
+
```miniscript
|
| 248 |
+
// Function to draw the score and time.
|
| 249 |
+
drawTimeAndScore = function()
|
| 250 |
+
minutes = floor(time/60)
|
| 251 |
+
seconds = ("00" + (floor(time) % 60))[-2:]
|
| 252 |
+
s = "Time: " + minutes + ":" + seconds
|
| 253 |
+
s = s + " " * 6 + "Score: " + ("000000" + score)[-6:]
|
| 254 |
+
text.row = 25; text.column = 38
|
| 255 |
+
print s
|
| 256 |
+
end function
|
| 257 |
+
drawTimeAndScore
|
| 258 |
+
|
| 259 |
+
// Our map of where stuff is hidden. This is stored as a 2D
|
| 260 |
+
// list, indexed by column, row, with values of 0,
|
| 261 |
+
// kCellBomb, or kCellTreasure through kCellTreasure+5.
|
| 262 |
+
hidden = list.init2d(kCols, kRows, 0)
|
| 263 |
+
|
| 264 |
+
// Find an empty (grass) spot in the hidden map.
|
| 265 |
+
findEmptyPos = function()
|
| 266 |
+
while true
|
| 267 |
+
p = GridPos.random
|
| 268 |
+
if hidden[p.col][p.row] == 0 then return p
|
| 269 |
+
end while
|
| 270 |
+
end function
|
| 271 |
+
|
| 272 |
+
// Populate the hidden map with bombs and treasures.
|
| 273 |
+
buryStuff = function(qtyBombs=40, qtyTreasures=6)
|
| 274 |
+
for i in range(1, qtyBombs)
|
| 275 |
+
p = findEmptyPos
|
| 276 |
+
hidden[p.col][p.row] = kCellBomb
|
| 277 |
+
end for
|
| 278 |
+
for i in range(1, qtyTreasures)
|
| 279 |
+
p = findEmptyPos
|
| 280 |
+
hidden[p.col][p.row] = kCellTreasure + (i % 6)
|
| 281 |
+
end for
|
| 282 |
+
globals.treasuresLeft = qtyTreasures
|
| 283 |
+
end function
|
| 284 |
+
```
|
| 285 |
+
|
| 286 |
+
Most of the `drawTimeAndScore` function is just composing the string we want to draw. Notice the trick being used to add leading zeros to the numbers: add a string of zeros to the front, and then use `[-2:]` to grab just the last two characters of the result (or in the case of score, `[-6:]` to grab the last six).
|
| 287 |
+
|
| 288 |
+
The global variable called `hidden`, defined on line 137, is important. It is a two-dimensional list (i.e. list of lists) that keeps track of where all the treasures and bombs are buried. Each entry is either `0`, indicating nothing of interest, `kCellBomb`, indicating a bomb (of course), or the index of one of the treasure tiles. We use the `list.init2d` method, which was added by the `listUtil` module imported on line 4, to prepare this data structure.
|
| 289 |
+
|
| 290 |
+
The next two functions work with that `hidden` list. The `findEmptyPos` function uses an infinite loop to just keep trying random locations, until it finds one that is empty. The `buryStuff` function makes use of that to store a number of bombs and treasures.
|
| 291 |
+
|
| 292 |
+
To test these functions is pretty easy. When you run the code at this point, you'll now see a time and score (both zero, of course) in the upper-right corner of the screen. You can print out `hidden` and see that it's all zeros, then print it again after calling `buryStuff`, and see that it now contains some nonzeros (mostly 18, which are the bombs, but also some values between 10 and 16, which represent treasures).
|
| 293 |
+
|
| 294 |
+
## Game Over!
|
| 295 |
+
|
| 296 |
+
Next we'll need a couple of functions to handle winning or losing the game. You lose the game when you click on a bomb, at which point it explodes, we reveal the positions of all the bombs, and then offer to play again. Winning is simpler, as we just display a happy message, and also offer to replay.
|
| 297 |
+
|
| 298 |
+
{caption:"Listing 5 (Functions to handle losing or winning the game.)", number-from: 160}
|
| 299 |
+
```miniscript
|
| 300 |
+
// Show an explosion at the given grid position; end the game.
|
| 301 |
+
doBoom = function(p)
|
| 302 |
+
bombSnd.play
|
| 303 |
+
for i in range(0,3)
|
| 304 |
+
td.setCell p.col, p.row, kCellBomb + i
|
| 305 |
+
wait 0.1
|
| 306 |
+
end for
|
| 307 |
+
for c in range(0, kCols-1)
|
| 308 |
+
for r in range(0, kRows-1)
|
| 309 |
+
if hidden[c][r] == kCellBomb then
|
| 310 |
+
td.setCell c, r, kCellBomb
|
| 311 |
+
end if
|
| 312 |
+
end for
|
| 313 |
+
end for
|
| 314 |
+
td.setCell p.col, p.row, kCellBomb + 2
|
| 315 |
+
text.row = 1
|
| 316 |
+
print "Play again (Y/N)?"
|
| 317 |
+
if key.get.upper == "N" then exit
|
| 318 |
+
run
|
| 319 |
+
end function
|
| 320 |
+
|
| 321 |
+
gameWon = function()
|
| 322 |
+
text.row = 2; text.column = 30
|
| 323 |
+
print "YOU WIN!"
|
| 324 |
+
print "Play again (Y/N)?"
|
| 325 |
+
if key.get.upper == "N" then exit
|
| 326 |
+
run
|
| 327 |
+
end function
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
To test the `gameWon` method is trivial (just call it on the command line). To test `doBoom`, you'll need to pass in a grid position. Remember that you can use `GridPos.make` to construct one of these very easily — for example, `GridPos.make(5,5)`.
|
| 331 |
+
|
| 332 |
+
## Final Functions
|
| 333 |
+
|
| 334 |
+
Only two more functions are needed in the Treasure Hunt game. The first one is called when you discover a treasure; it updates the display and your score, and checks for successful completion of the game. The other one reveals the contents of any cell, and takes appropriate action.
|
| 335 |
+
|
| 336 |
+
{caption:"Listing 6 (`getTreasure` and `reveal` functions.)", number-from: 189}
|
| 337 |
+
```miniscript
|
| 338 |
+
// Show the treasure found; add it to our list and score
|
| 339 |
+
getTreasure = function(p, found)
|
| 340 |
+
td.setCell p.col, p.row, found
|
| 341 |
+
treasureSnd.play
|
| 342 |
+
img = td.tileSet.getImage(32*(found-kCellTreasure+2), 0, 32, 32)
|
| 343 |
+
gfx.drawImage img, treasureListX + 20, treasureListY
|
| 344 |
+
points = 100 + ceil(1E6/(10+time))
|
| 345 |
+
gfx.print points, treasureListX+60, treasureListY+6, gold, "small"
|
| 346 |
+
globals.treasureListY = treasureListY - 40
|
| 347 |
+
globals.score = score + points
|
| 348 |
+
drawTimeAndScore
|
| 349 |
+
wait 0.5
|
| 350 |
+
globals.treasuresLeft = treasuresLeft - 1
|
| 351 |
+
if not treasuresLeft then gameWon
|
| 352 |
+
end function
|
| 353 |
+
|
| 354 |
+
// Reveal the given grid position. If it's a bomb,
|
| 355 |
+
// game over! Otherwise show how many neighboring cells
|
| 356 |
+
// contain bombs. If that is 0, reveal all neighbors.
|
| 357 |
+
reveal = function(p)
|
| 358 |
+
if td.cell(p.col, p.row) < kCellGrass then return
|
| 359 |
+
found = hidden[p.col][p.row]
|
| 360 |
+
// If we found a bomb, then it's game-over
|
| 361 |
+
if found == kCellBomb then
|
| 362 |
+
doBoom p
|
| 363 |
+
return
|
| 364 |
+
end if
|
| 365 |
+
// If we found treasure, reveal it
|
| 366 |
+
if found >= kCellTreasure and found < kCellTreasure+6 then
|
| 367 |
+
getTreasure p, found
|
| 368 |
+
return
|
| 369 |
+
end if
|
| 370 |
+
// Otherwise, count bombs and show the number
|
| 371 |
+
bombCount = 0
|
| 372 |
+
for n in p.neighbors
|
| 373 |
+
if hidden[n.col][n.row] == kCellBomb then
|
| 374 |
+
bombCount = bombCount + 1
|
| 375 |
+
end if
|
| 376 |
+
end for
|
| 377 |
+
td.setCell p.col, p.row, bombCount
|
| 378 |
+
// ...and if the bomb count was 0, then reveal neighbors too
|
| 379 |
+
if bombCount == 0 then
|
| 380 |
+
for n in p.neighbors; reveal n; end for
|
| 381 |
+
end if
|
| 382 |
+
end function
|
| 383 |
+
```
|
| 384 |
+
|
| 385 |
+
The `getTreasure` function is fairly straightforward, but it contains a handy trick: it's calling `getImage` on the tile set image itself, to pluck out an image of the treasure for drawing on the pixel display. You probably noticed that this tile set actually contains two versions of each treasure: one on the sandy background, and one on a transparent background. This function grabs the transparent one, so we can draw it neatly into our list of collected treasures.
|
| 386 |
+
|
| 387 |
+
The `reveal` method contains a technique you may find surprising. If you've ever played Minesweeper, you know that when you click on a cell with *no* bombs next to it, then the game reveals not only that square, but all adjacent squares too. And if ane of *those* squares have no neighboring bombs, the process repeats, potentially revealing a large hunk of the map at once. How does this work?
|
| 388 |
+
|
| 389 |
+
{i:"recursion"}
|
| 390 |
+
It's actually quite simple: line 230 checks for the case where the bomb count is zero, and then that little loop on line 231 does the rest. We simply loop over the neighbors of this grid position, and call `reveal` on each one. The `reveal` method is calling itself, which is a technique called *recursion*. This was first introduced in Chapter 13, in the "find a file" program. You might go back and compare that program to the listing above, and see if recursion "clicks" for you yet. (If not, don't worry — it will eventually!)
|
| 391 |
+
|
| 392 |
+
Testing these functions is pretty straightforward. You'll need to pass `getTreasure` a grid position (use `GridPos.make` again) as well as a treasure tile index, from 10 to 15. You should see the treasure appear both on the map and on the "Treasures Found" list on the right side of the screen.
|
| 393 |
+
|
| 394 |
+
To test `reveal`, just pass it a grid position. But you might want to call `buryStuff` first, otherwise the map will be empty, and a single `reveal` will simply turn the whole map from grass to sand.
|
| 395 |
+
|
| 396 |
+
## Main Loop
|
| 397 |
+
|
| 398 |
+
Finally, as with most programs, the main loop comes at the end. The main loop in this program is very simple, because we have so neatly divided all the real work out into functions.
|
| 399 |
+
|
| 400 |
+
{caption:"Listing 7 (setup and main loop.)", number-from: 235}
|
| 401 |
+
```miniscript
|
| 402 |
+
// Setup and main loop
|
| 403 |
+
buryStuff
|
| 404 |
+
while true
|
| 405 |
+
drawTimeAndScore
|
| 406 |
+
if mouse.button(0) then handleClick(0)
|
| 407 |
+
if mouse.button(1) then handleClick(1)
|
| 408 |
+
yield
|
| 409 |
+
end while
|
| 410 |
+
```
|
| 411 |
+
|
| 412 |
+
And that's it! After you've put this in, go and play a while! It's not an easy game to win, but not impossible either. My high score is about 250,000 points. Can you beat that?
|
| 413 |
+
|
| 414 |
+
## Taking it Further
|
| 415 |
+
|
| 416 |
+
This is a pretty polished game, but you could make it even better!
|
| 417 |
+
|
| 418 |
+
You might start with some simple tweaks to optimize the fun. You can easily change the board size by tweaking those constants on lines 7-8. You could also change the number of bombs and treasures, by changing the default values on the `buryStuff` function on line 148, or by overriding those defaults where the function is called on line 236. These tweaks can make the game longer or shorter, easier or harder. It's up to you!
|
| 419 |
+
|
| 420 |
+
Beyond that, you might want to do something more exciting when the game ends. If you lose, there's a fairly satisfying boom and a small animation, but you might want to do something more spectacular... maybe draw a *giant* explosion sprite that covers the whole screen? Or use a `SolidColorDisplay` to make the whole screen flash? In the case of the user winning, you should at least play a triumphant fanfare, and maybe some sort of big "YOU WIN" graphic, rather than the easy-to-miss text under the map. Maybe you'll even want to incorporate the fireworks animation from Day 21, and give the user a *real* treat!
|
| 421 |
+
|
| 422 |
+
A> **Chapter Review**
|
| 423 |
+
A> - You entered and debugged the *Treasure Hunt* game.
|
| 424 |
+
A> - You practiced working with tile displays.
|
| 425 |
+
A> - You also reviewed use of sounds, pixel displays, and text.
|
| 426 |
+
A> - Most importantly, you practiced the "code a little, test a little" habit, this time with your *own* tests at each step.
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
data/day27.txt
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 27: Algorithms, Step by Step", startingPageNum:335}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> First, solve the problem. Then, write the code.
|
| 7 |
+
Q>— John Johnson
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn about algorithms and pseudocode.
|
| 11 |
+
A> - Translate several pseudocode algorithms into MiniScript.
|
| 12 |
+
A> - See how to fix an incomplete algorithm.
|
| 13 |
+
|
| 14 |
+
Today we're going to address head-on a topic we've only hinted before now: *algorithms*.
|
| 15 |
+
|
| 16 |
+
algorithm
|
| 17 |
+
: a process to be followed in order to solve a problem
|
| 18 |
+
|
| 19 |
+
Algorithms are wonderful things. They are clear, step-by-step instructions for accomplishing something. In mathematics, you learned algorithms for multiplying or dividing big numbers. In the kitchen, you might have an entire book of algorithms for making various foods (those algorithms are usually called "recipes"). But it's in computing that algorithms are most famous, and most useful. A computer is very good at following instructions quickly and accurately — but it has to be told exactly what to do.
|
| 20 |
+
|
| 21 |
+
Of course programming is also telling a computer specifically what to do. We've been doing that this whole book. But programming is giving instructions to a computer in a specific programming language, like MiniScript. Algorithms are at a slightly more generic level; they are instructions on how to solve a problem regardless of the specific programming language used. They are usually written in either natural language (for example, English), or else in pseudocode.
|
| 22 |
+
|
| 23 |
+
pseudocode
|
| 24 |
+
: a made-up, natural-ish programming language used to convey an algorithm to human readers
|
| 25 |
+
|
| 26 |
+
You can find algorithms for all sorts of things. Need to efficiently combine two sorted lists into one bigger list that's still sorted? There's an algorithm for that. Need to divide a bunch of data points into clusters? There's one for that too. Want to find the first 1000 prime numbers? You can find several different algorithms for that! In many cases, when you face some common problem like this, you can save yourself some time by digging up a known algorithm for it, and then just converting the pseudocode into whatever real programming language you're using. And *that's* the cool thing about algorithms: they represent things humanity has figured out how to do, regardless of the particulars of a programming language.
|
| 27 |
+
|
| 28 |
+
D> Programming languages come and go, but algorithms are eternal.
|
| 29 |
+
|
| 30 |
+
So in the end, an algorithm is just a fancy word for a simple concept: step-by-step instructions on how to do something. Let's make all this concrete by looking at a few simple, well-known algorithms.
|
| 31 |
+
|
| 32 |
+
## Greatest Common Divisor
|
| 33 |
+
|
| 34 |
+
The greatest common divisor (or "GCD" for short) of two numbers is the largest whole number that will divide evenly into them both. For example, the GCD of 8 and 12 is 4, because 4 divides both 8 and 12 without any fractions or remainder. The GCD has all sorts of uses. For example, if you want to simplify a fraction, you just divide the top and bottom by their GCD: so 8/12 simplifies to 2/3 (dividing them both by 4).
|
| 35 |
+
|
| 36 |
+
A pretty neat algorithm for finding the GCD was developed by Euclid, a Greek mathematician who lived around 300 BC. This is one of the oldest algorithms still in common use. If you search for "Euclidean algorithm for greatest common divisor," you will find a whole lot of material about it, including a Wikipedia page that gives several variations of the algorithm in pseudocode. The first one is given as:
|
| 37 |
+
|
| 38 |
+
```pseudo
|
| 39 |
+
function gcd(a, b)
|
| 40 |
+
while b != 0
|
| 41 |
+
t := b
|
| 42 |
+
b := a mod b
|
| 43 |
+
a := t
|
| 44 |
+
return a
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
I bet you can read that! It looks *almost* like MiniScript, but not quite. It uses `:=` to indicate assignment, while we use a simple `=` sign. It's written `mod` as a word, while in MiniScript we use the `%` operator. And finally, you may notice that the `while` loop does not have an `end while`, and the `function` does not have an `end function`, but you can easily guess where these should go. So, in MiniScript this would be:
|
| 48 |
+
|
| 49 |
+
```miniscript
|
| 50 |
+
gcd = function(a, b)
|
| 51 |
+
while b != 0
|
| 52 |
+
t = b
|
| 53 |
+
b = a % b
|
| 54 |
+
a = t
|
| 55 |
+
end while
|
| 56 |
+
return a
|
| 57 |
+
end function
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Pretty direct conversion, isn't it? Type that in and try it out. What is the GCD of 294 and 546?
|
| 61 |
+
|
| 62 |
+
Skipping ahead to the third version of the algorithm, the pseudocode is given as:
|
| 63 |
+
|
| 64 |
+
```pseudo
|
| 65 |
+
function gcd(a, b)
|
| 66 |
+
if b = 0
|
| 67 |
+
return a
|
| 68 |
+
else
|
| 69 |
+
return gcd(b, a mod b)
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
This is a fun one because it's recursive — it is defined in terms of itself. But as MiniScript supports recursion too, this too is a straightforward translation:
|
| 73 |
+
|
| 74 |
+
```miniscript
|
| 75 |
+
gcd = function(a, b)
|
| 76 |
+
if b == 0 then
|
| 77 |
+
return a
|
| 78 |
+
else
|
| 79 |
+
return gcd(b, a % b)
|
| 80 |
+
end if
|
| 81 |
+
end function
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
D> Remember that MiniScript uses `==` for comparing two numbers. Pseudocode often uses a single `=` (especially pseudocode that uses `:=` for assignment).
|
| 85 |
+
|
| 86 |
+
And finally, the second version in the Wikipedia page is actually Euclid's original version, as he hadn't thought of *mod*. This is given in pseudocode as:
|
| 87 |
+
|
| 88 |
+
```pseudo
|
| 89 |
+
function gcd(a, b)
|
| 90 |
+
while a != b
|
| 91 |
+
if a > b
|
| 92 |
+
a := a - b
|
| 93 |
+
else
|
| 94 |
+
b := b - a
|
| 95 |
+
return a
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
Can you translate this to MiniScript code yourself? Try it!
|
| 99 |
+
|
| 100 |
+
## Binary Search
|
| 101 |
+
|
| 102 |
+
Another useful algorithm is finding the position of an element in a sorted list. Of course you could just search every element with this algorithm:
|
| 103 |
+
|
| 104 |
+
```pseudo
|
| 105 |
+
function find(x, list)
|
| 106 |
+
i := 0
|
| 107 |
+
while i < length of list
|
| 108 |
+
if list[i] = x then return i
|
| 109 |
+
i := i + 1
|
| 110 |
+
return -1
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
This is actually an algorithm called *sequential search*, and is in fact what MiniScript does when you use the `indexOf` intrinsic method. It's the best possible algorithm for an *unsorted* list of items, where the thing you're looking for could be anywhere; you simply have to check each one. But if we know the list is sorted, then we can do much better. The first thing we might do is simply bail out as soon as we find an item bigger than what you're looking for, since in a sorted list, there's no way it could be found after that.
|
| 114 |
+
|
| 115 |
+
```pseudo
|
| 116 |
+
function find(x, list)
|
| 117 |
+
i := 0
|
| 118 |
+
while i < length of list
|
| 119 |
+
if list[i] = x then return i
|
| 120 |
+
if list[i] > x then return -1
|
| 121 |
+
i := i + 1
|
| 122 |
+
return -1
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
But it turns out we can do even better, by using the *binary search* algorithm. Instead of keeping track of just one position in the list (like `i` in the pseudocode above), binary search keeps track of two positions, called `min` and `max`. And on each step, it moves one of those by quite a lot, quickly zeroing in on the target value.
|
| 126 |
+
|
| 127 |
+
Googling "binary search" quickly led me to a nice lesson about at Kahn Academy, which gives the pesudocode as:
|
| 128 |
+
|
| 129 |
+
D>The inputs are the array, which we call array; the number n of elements in array; and target, the number being searched for. The output is the index in array of target:
|
| 130 |
+
D>1. Let min = 0 and max = n-1.
|
| 131 |
+
D>2. Compute guess as the average of max and min, rounded down (so that it is an integer).
|
| 132 |
+
D>3. If array[guess] equals target, then stop. You found it! Return guess.
|
| 133 |
+
D>4. If the guess was too low, that is, array[guess] \< target, then set min = guess + 1.
|
| 134 |
+
D>5. Otherwise, the guess was too high. Set max = guess - 1.
|
| 135 |
+
D>6. Go back to step 2.
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
Here's a very different style of pseudocode! In case it wasn't clear already, everybody's pseudocode is a little different. That's OK, because it only needs to be clear to humans, not to computers. We can work with this. Just convert it into MiniScript, step by step.
|
| 139 |
+
|
| 140 |
+
```miniscript
|
| 141 |
+
find = function(array, target)
|
| 142 |
+
n = array.len // (no need to pass this as a parameter!)
|
| 143 |
+
// step 1:
|
| 144 |
+
min = 0
|
| 145 |
+
max = n-1
|
| 146 |
+
while true // (loop from step 2 to step 6)
|
| 147 |
+
// step 2:
|
| 148 |
+
guess = floor((max + min)/2)
|
| 149 |
+
// step 3:
|
| 150 |
+
if array[guess] == target then return guess
|
| 151 |
+
// steps 4 and 5:
|
| 152 |
+
if array[guess] < target then
|
| 153 |
+
min = guess + 1
|
| 154 |
+
else
|
| 155 |
+
max = guess - 1
|
| 156 |
+
end if
|
| 157 |
+
end while // step 6
|
| 158 |
+
end function
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
Note that while the pseudocode said that the number `n` of elements in the array was to be one of the inputs (i.e. parameters to the function), there is no need for that in MiniScript; a list already knows its own length. So our implementation takes only the list, and the target value. Also, while the pseudocode uses "go to" to make a loop, MiniScript (like most other modern languages) uses `for` or `while` to loop instead. So we just threw a `while true` loop around the steps in the algorithm that should loop.
|
| 162 |
+
|
| 163 |
+
Type that in and give it a try on this data:
|
| 164 |
+
|
| 165 |
+
```terminal
|
| 166 |
+
]find [3,6,10,14,19,27], 10
|
| 167 |
+
2
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
It works! We asked for the index of value 10, and it returned 2, which is correct since element 2 of our list is indeed 10. But now try this one:
|
| 171 |
+
|
| 172 |
+
```terminal
|
| 173 |
+
]find [3,6,10,14,19,27], 11
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
Uh-oh! This call never returns; it is stuck in an infinite loop. Looking at the pseudocode (or our MiniScript implementation), it is easy to see why: the only `return` statement in it is when the target element is found. If the target is not found, it will never return. So the pseudocode algorithm we found here is slightly flawed.
|
| 177 |
+
|
| 178 |
+
When you run into something like this, first, give a cheer for testing! It's so much better to discover things like this right away, rather than later when this code has become some small part of a much larger program. And next, you have two options. Either search for a different variation of the algorithm, and implement that, or just fix the problem with this one. We're going to do the latter.
|
| 179 |
+
|
| 180 |
+
When a program is stuck in an infinite loop, the first step is usually to get a better understanding of what state it's in when it's stuck. Press Control-C if your program is still stuck, and then insert a `print` statement right after we calculate the guess, on line 9:
|
| 181 |
+
|
| 182 |
+
{number-from: 9}
|
| 183 |
+
```miniscript
|
| 184 |
+
print "min:" + min + " max:" + max + " guess:" + guess
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
Now run that same test that failed before. It will very quickly start repeating this line over and over:
|
| 188 |
+
|
| 189 |
+
```terminal
|
| 190 |
+
min:3 max:2 guess:2
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
Now notice something odd about this — the "min" is actually greater than the "max" value! As we move the `min` value up and the `max` value down, we will always either find the target value, or end up in this situation where `min > max`. So, the solution is to just check for that. Change the `while` statement so that instead of `while true`, it reads `while min < max`. And finally, add a `return -1` down after the `end while` (but before `end function`).
|
| 194 |
+
|
| 195 |
+
Now try both tests again (remember that in Mini Micro or command-line MiniScript, you can press the up arrow to recall a previous command). It should work now.
|
| 196 |
+
|
| 197 |
+
If you have a very large list of items, and know that this list is always sorted, this algorithm will often be faster than the built-in `indexOf` method. So now you have a handy new tool in your toolbox, *and* you've learned how to fix a flawed algorithm you find on the internet!
|
| 198 |
+
|
| 199 |
+
## k-Means Clustering
|
| 200 |
+
|
| 201 |
+
For our last example, we're going to look at a machine learning algorithm called "k-means clustering." Suppose you have a bunch of data points, characterized by X and Y values, and you want to divide those points into groups ("clusters") so that each point is mostly surrounded by other points in the same group. How do you do that?
|
| 202 |
+
|
| 203 |
+
D> This problem actually came up in my day job quite recently. We were building a large multiplayer game. To keep network traffic down, we wanted to divide all the players into groups of nearby players, so we can send frequent updates only to other players in the same group. k-means clustering is one way to do that!
|
| 204 |
+
|
| 205 |
+
The k-means clustering algorithm is a fancy name for a simple idea. Each group (or "cluster") is defined by the centroid (average position) of all the data points assigned to it. We simply alternate between assigning each point to the nearest cluster, and moving each cluster to the centroid of its assigned points. In pseudocode:
|
| 206 |
+
|
| 207 |
+
```pseudo
|
| 208 |
+
initialize k clusters at random positions
|
| 209 |
+
repeat until done:
|
| 210 |
+
assign each data point to the nearest cluster
|
| 211 |
+
move each cluster to the centroid of data assigned to it
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
Using Mini Micro, we can implement this algorithm in a very visual way, using sprites for the data points and cluster centroids. It comes out a bit longer, but it's totally worth it.
|
| 215 |
+
|
| 216 |
+
{caption:"k-means clustering program."}
|
| 217 |
+
```miniscript
|
| 218 |
+
import "mathUtil"
|
| 219 |
+
import "listUtil"
|
| 220 |
+
|
| 221 |
+
clear
|
| 222 |
+
|
| 223 |
+
Datum = new Sprite
|
| 224 |
+
Datum.image = file.loadImage("/sys/pics/shapes/Circle.png")
|
| 225 |
+
Datum.scale = 0.2
|
| 226 |
+
|
| 227 |
+
Cluster = new Sprite
|
| 228 |
+
Cluster.image = file.loadImage("/sys/pics/XO/X-white.png")
|
| 229 |
+
Cluster.scale = 0.2
|
| 230 |
+
|
| 231 |
+
// Define the number of data points (n) and centroids (k).
|
| 232 |
+
n = 40
|
| 233 |
+
k = 4
|
| 234 |
+
|
| 235 |
+
// Create some random data points.
|
| 236 |
+
data = []
|
| 237 |
+
for i in range(1, n)
|
| 238 |
+
d = new Datum
|
| 239 |
+
d.x = round(960 * rnd) // (960 is the screen width)
|
| 240 |
+
d.y = round(640 * rnd) // (640 is screen height)
|
| 241 |
+
display(4).sprites.push d // (display 4 is the sprite display)
|
| 242 |
+
data.push d
|
| 243 |
+
end for
|
| 244 |
+
|
| 245 |
+
// Create the centroids, also in random starting positions.
|
| 246 |
+
centroids = []
|
| 247 |
+
colors = [color.orange, color.aqua, color.fuchsia, color.lime]
|
| 248 |
+
for i in range(1, k)
|
| 249 |
+
c = new Cluster
|
| 250 |
+
c.tint = colors[i-1]
|
| 251 |
+
c.x = round(960) * rnd
|
| 252 |
+
c.y = round(640 * rnd)
|
| 253 |
+
display(4).sprites.push c
|
| 254 |
+
centroids.push c
|
| 255 |
+
end for
|
| 256 |
+
|
| 257 |
+
// update all data points by assigning them to the nearest centroid
|
| 258 |
+
// also update dataX and dataY lists within each centroid
|
| 259 |
+
updateData = function()
|
| 260 |
+
for c in centroids
|
| 261 |
+
c.dataX = []
|
| 262 |
+
c.dataY = []
|
| 263 |
+
end for
|
| 264 |
+
for d in data
|
| 265 |
+
bestCluster = null
|
| 266 |
+
for c in centroids
|
| 267 |
+
dist = mathUtil.distance(d, c)
|
| 268 |
+
if bestCluster == null or dist < bestDist then
|
| 269 |
+
bestCluster = c
|
| 270 |
+
bestDist = dist
|
| 271 |
+
end if
|
| 272 |
+
end for
|
| 273 |
+
d.tint = bestCluster.tint
|
| 274 |
+
bestCluster.dataX.push d.x
|
| 275 |
+
bestCluster.dataY.push d.y
|
| 276 |
+
end for
|
| 277 |
+
end function
|
| 278 |
+
|
| 279 |
+
// update the centroids by moving them to the average position
|
| 280 |
+
// of the data points assigned to them
|
| 281 |
+
updateClusters = function()
|
| 282 |
+
for c in centroids
|
| 283 |
+
if not c.dataX then continue
|
| 284 |
+
c.x = c.dataX.mean
|
| 285 |
+
c.y = c.dataY.mean
|
| 286 |
+
end for
|
| 287 |
+
end function
|
| 288 |
+
|
| 289 |
+
// Repeat those steps until done!
|
| 290 |
+
for i in range(10)
|
| 291 |
+
updateData
|
| 292 |
+
updateClusters
|
| 293 |
+
wait // slow things down enough that you can see!
|
| 294 |
+
end for
|
| 295 |
+
```
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
Notice that even though the pseudocode didn't show any functions, I chose to put each of the major update steps into its own function in the MiniScript implementation. That just helps keep things neat and organized. Also note that we're defining "done" as simply completing 10 updates. You might need more in some cases, or you might keep track of whether any of the points are actually changing their color, and stop when they are no longer changing. (This is guaranteed to happen eventually.)
|
| 299 |
+
|
| 300 |
+
{width:"75%"}
|
| 301 |
+

|
| 302 |
+
|
| 303 |
+
Run this a few times; since the data and initial cluster positions are random, you'll get a different result every time.
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
## Next Steps
|
| 307 |
+
|
| 308 |
+
The three algorithms in this chapter are pretty typical of most small, well-defined problems that you might need to solve. Now you've learned the secret every expert programmer knows: you don't have to think up a solution to every problem yourself. In many cases, a good solution (algorithm) is already known, and all you need to do is translate it into your favorite language (which is surely MiniScript in our case!).
|
| 309 |
+
|
| 310 |
+
Of course, not *every* problem has already been solved by someone else. The number of things a computer can do is infinite, and you have so much creative freedom, you will certainly run into things that no one has done before, or if they have, they failed to publish a nice neat algorithm explaining how they did it. In such cases you'll need to develop your *own* algorithm. And that's the topic of the next chapter!
|
| 311 |
+
|
| 312 |
+
A> **Chapter Review**
|
| 313 |
+
A> - You learned about algorithms, and how they relate to programming.
|
| 314 |
+
A> - You implemented algorithms for Greatest Common Divisor, Binary Search, and k-Means Clustering.
|
| 315 |
+
A> - You learned how to fix an algorithm that is incomplete or contains an error.
|
| 316 |
+
|
data/day28.txt
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 28: Snowflakes Evolution", startingPageNum:347}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Programming isn't about what you know; it's about what you can figure out.
|
| 7 |
+
Q>— Chris Pine (programmer and author)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Build the *Snowflakes Evolution* app, which lets you guide the development of an endless variety of beautiful snowflakes.
|
| 11 |
+
A> - Learn how to design a custom algorithm to tackle a complex computing problem.
|
| 12 |
+
A> - Brush up on turtle graphics.
|
| 13 |
+
|
| 14 |
+
In the previous chapter, you learned about algorithms, and how to convert a pseudocode description of an algorithm into working MiniScript code. Today we're going to learn how to design your own algorithm from scratch!
|
| 15 |
+
|
| 16 |
+
The context of this task will be a fun little program called *Snowflake Evolution*. The program begins by generating six random snowflakes, as shown in the screen shot on the next page. Then, when the user clicks one of them, it generates several variations of the selected snowflake. This process can be repeated as many times as desired, allowing you to guide snowflakes through a process of directed evolution.
|
| 17 |
+
|
| 18 |
+

|
| 19 |
+
|
| 20 |
+
But how do you write code to generate such complex shapes? And not only that, but do it in a way that lets us generate variations of a particular shape? That's not something for which you can easily find an off-the-shelf algorithm. So let's roll up our sleeves and figure it out!
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
## First Observations
|
| 24 |
+
|
| 25 |
+
Looking at the snowflakes in the figure, the first thing we should notice is the sixfold symmetry. Thinking in the step-by-step terms of algorithms, we should think of drawing the branches one at a time. But all six branches are the same, so we can just use a loop. In pseudocode, that would look something like this.
|
| 26 |
+
|
| 27 |
+
```pseudo
|
| 28 |
+
repeat 6 times
|
| 29 |
+
draw a branch
|
| 30 |
+
rotate 60°
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
This assumes that the *draw a branch* step does the same thing every time we do it, except pointed in a different direction.
|
| 34 |
+
|
| 35 |
+
Of the many ways Mini Micro has to put graphics on the screen, this assumption — that we can draw the same thing, but rotated differently — leads us directly to turtle graphics, first introduced in Chapter 18. To draw the same branch but rotated some number of degrees with only `gfx.line` and friends would take a *lot* of math! But with turtle graphics, it is easy: just rotate the turtle, and then use turtle drawing commands that work with whatever direction it is facing.
|
| 36 |
+
|
| 37 |
+
So we're already making progress on two levels: we have a very rough sketch of the algorithm, and we have made an important decision about the implementation.
|
| 38 |
+
|
| 39 |
+
## Anatomy of a Snowflake Branch
|
| 40 |
+
|
| 41 |
+
We still don't know how quite to do that *draw a branch* step. So let's look more closely. Consider the following snowflake.
|
| 42 |
+
|
| 43 |
+
{width: "50%"}
|
| 44 |
+

|
| 45 |
+
|
| 46 |
+
We've already dealt with the fact that there are six identical branches, so let's focus now on just one branch.
|
| 47 |
+
|
| 48 |
+
{width: "25%"}
|
| 49 |
+

|
| 50 |
+
|
| 51 |
+
{gap:30}
|
| 52 |
+
How can we simplify this? The first thing to notice is that there is some self-similarity going on. Each of the two side branches coming off the main trunk, when viewed in isolation, look a lot like the whole branch. And in fact if you were to break the main branch right where those two side branches come off, the smaller part of that looks a lot like the whole branch, too.
|
| 53 |
+
|
| 54 |
+
{width: "25%"}
|
| 55 |
+

|
| 56 |
+
|
| 57 |
+
And then if you were to focus on any one of those branches, you could break it down into smaller bits the exact same way: a trunk, two smaller side branches, and one smaller forward branch.
|
| 58 |
+
|
| 59 |
+
{width: "25%"}
|
| 60 |
+

|
| 61 |
+
|
| 62 |
+
## Our Custom Branch Algorithm
|
| 63 |
+
|
| 64 |
+
So we've uncovered a recursive structure here: a branch is composed of a straight line, followed by three smaller branches. In pseudocode, we might represent this as something like:
|
| 65 |
+
|
| 66 |
+
```pseudo
|
| 67 |
+
draw a branch = function(scale)
|
| 68 |
+
if scale is too small, return
|
| 69 |
+
draw a straight line proportional to scale
|
| 70 |
+
turn to the left
|
| 71 |
+
draw a branch (scale * 0.5)
|
| 72 |
+
turn to the right
|
| 73 |
+
draw a branch (scale * 0.5)
|
| 74 |
+
turn forward
|
| 75 |
+
draw a branch (scale * 0.6)
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
And now we have a detailed enough algorithm to convert this into MiniScript.
|
| 79 |
+
|
| 80 |
+
{i:"`/sys/lib`,`turtle`"}
|
| 81 |
+
{caption: "First stab at a program for drawing one branch of a snowflake."}
|
| 82 |
+
```miniscript
|
| 83 |
+
import "turtle"
|
| 84 |
+
clear
|
| 85 |
+
|
| 86 |
+
drawBranch = function(turtle, scale = 1)
|
| 87 |
+
if scale < 0.02 then return
|
| 88 |
+
// create a new turtle, so we don't move the one passed in
|
| 89 |
+
t = new turtle
|
| 90 |
+
// draw main branch
|
| 91 |
+
t.penSize = 20 * scale
|
| 92 |
+
t.forward 100 * scale
|
| 93 |
+
// draw sub-branches
|
| 94 |
+
t.left 70
|
| 95 |
+
drawBranch t, scale * 0.4
|
| 96 |
+
t.right 70 * 2
|
| 97 |
+
drawBranch t, scale * 0.4
|
| 98 |
+
t.left 70
|
| 99 |
+
drawBranch t, scale * 0.6
|
| 100 |
+
end function
|
| 101 |
+
|
| 102 |
+
drawBranch new Turtle
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
This is a pretty direct translation of the pseudocode. The only "trick" here is on line 7, where we take the Turtle object that was passed in to our `drawBranch` function and create a `new` turtle derived from it. That allows us to do whatever we like with this new turtle — move it, rotate it, change its pen size or color — without affecting the turtle that was passed in. That's very handy since the turtle that was passed in has other work to do (i.e. drawing more branches), and our job is easier if we can assume that its state has not changed after drawing a branch.
|
| 106 |
+
|
| 107 |
+
So type that in, if you haven't already, and give it a try. The result should look like this:
|
| 108 |
+
|
| 109 |
+
{width: "25%"}
|
| 110 |
+

|
| 111 |
+
|
| 112 |
+
{gap:30}
|
| 113 |
+
Looks pretty good! And now we can make an entire snowflake by just drawing it six times, turning 60 degrees each time. Just replace line 20 of the program above with:
|
| 114 |
+
|
| 115 |
+
{number-from: 20}
|
| 116 |
+
```miniscript
|
| 117 |
+
t = new Turtle
|
| 118 |
+
for i in range(1, 6)
|
| 119 |
+
drawBranch t
|
| 120 |
+
t.left 60
|
| 121 |
+
end for
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
And now you have a beautiful snowflake!
|
| 125 |
+
|
| 126 |
+
## Introducing Variation
|
| 127 |
+
|
| 128 |
+
This code, of course, will draw the same snowflake every time you run it. But there are lots of magic numbers in it, which could be varied to produce different results: the length and width of the main branch, the angle of the side branches, and the scale of the side and forward branches. We could also tweak the color. Go ahead and experiment with those numbers a while to see what you can create!
|
| 129 |
+
|
| 130 |
+
For our *Snowflake Evolution* program, we're going to wrap up all those adjustable bits into a little class called `Step`. And we'll go a little further: instead of strictly drawing the exact same branch at every level of the recursion, we'll keep a list of four different step variations, and switch to one of those when we recurse.
|
| 131 |
+
|
| 132 |
+
This will all likely be clearer in MiniScript than in English, so `reset` your program, and dive right in.
|
| 133 |
+
|
| 134 |
+
{i:"`/sys/lib`,`turtle`;`/sys/lib`,`mathUtil`"}
|
| 135 |
+
{caption: "Listing 1 (Start of Snowflake Evolution program)."}
|
| 136 |
+
```miniscript
|
| 137 |
+
import "turtle"
|
| 138 |
+
import "mathUtil"
|
| 139 |
+
clamp = @mathUtil.clamp // (we'll be using this a lot)
|
| 140 |
+
clear
|
| 141 |
+
|
| 142 |
+
// randColor: return a random (bright) color, 155-255 in RGB.
|
| 143 |
+
randColor = function()
|
| 144 |
+
return color.fromList([155+99*rnd, 155+99*rnd, 155+99*rnd])
|
| 145 |
+
end function
|
| 146 |
+
|
| 147 |
+
// Step class. Draws one branch of a snowflake
|
| 148 |
+
// (using recursion to draw sub-branches).
|
| 149 |
+
Step = {}
|
| 150 |
+
|
| 151 |
+
Step.newRandom = function()
|
| 152 |
+
result = new Step
|
| 153 |
+
result.penSize = round(5 + 10*rnd)
|
| 154 |
+
result.penColor = randColor
|
| 155 |
+
result.fwd = 25 + 50*rnd
|
| 156 |
+
result.sideAngle = 20 + 60*rnd
|
| 157 |
+
result.sideScale = 0.25 + 0.5*rnd
|
| 158 |
+
result.sideStepNum = floor(rnd * 4)
|
| 159 |
+
result.fwdScale = 0.25 + 0.5*rnd
|
| 160 |
+
result.fwdStepNum = floor(rnd * 4)
|
| 161 |
+
return result
|
| 162 |
+
end function
|
| 163 |
+
|
| 164 |
+
Step.draw = function(turtle, steps, scale=1)
|
| 165 |
+
if scale < 0.1 then return
|
| 166 |
+
t = new turtle
|
| 167 |
+
t.penSize = self.penSize * scale
|
| 168 |
+
t.color = self.penColor
|
| 169 |
+
t.forward self.fwd * scale
|
| 170 |
+
newScale = scale * self.sideScale
|
| 171 |
+
if self.sideAngle > 0 and steps.hasIndex(self.sideStepNum) then
|
| 172 |
+
t.left self.sideAngle
|
| 173 |
+
steps[self.sideStepNum].draw t, steps, newScale
|
| 174 |
+
t.right self.sideAngle * 2
|
| 175 |
+
steps[self.sideStepNum].draw t, steps, newScale
|
| 176 |
+
t.left self.sideAngle
|
| 177 |
+
end if
|
| 178 |
+
newScale = scale * self.fwdScale
|
| 179 |
+
if newScale > 0 and steps.hasIndex(self.fwdStepNum) then
|
| 180 |
+
steps[self.fwdStepNum].draw t, steps, newScale
|
| 181 |
+
end if
|
| 182 |
+
end function
|
| 183 |
+
|
| 184 |
+
// Snowflake class: keeps four Steps, and uses them to
|
| 185 |
+
// draw a complete snowflake.
|
| 186 |
+
Snowflake = {}
|
| 187 |
+
|
| 188 |
+
Snowflake.newRandom = function()
|
| 189 |
+
result = new Snowflake
|
| 190 |
+
result.steps = []
|
| 191 |
+
for i in range(1, 4)
|
| 192 |
+
result.steps.push Step.newRandom
|
| 193 |
+
end for
|
| 194 |
+
return result
|
| 195 |
+
end function
|
| 196 |
+
|
| 197 |
+
Snowflake.draw = function(x=480, y=320)
|
| 198 |
+
t = new Turtle
|
| 199 |
+
t.penDown = false
|
| 200 |
+
t.goTo x, y
|
| 201 |
+
t.penDown = true
|
| 202 |
+
for i in range(0,5)
|
| 203 |
+
self.steps[0].draw t, self.steps
|
| 204 |
+
t.left 60
|
| 205 |
+
end for
|
| 206 |
+
end function
|
| 207 |
+
|
| 208 |
+
flake = Snowflake.newRandom
|
| 209 |
+
flake.draw
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
The recursive drawing algorithm from the previous section is now implemented in the `Step.draw` method. It looks a little more complicated because the function takes a list of `Step` objects, each specifying a different set of properties for the branch. So when it is time to draw one of the angled side branches, or the forward branch, it calls `draw` on some item from that list instead of on `self`.
|
| 213 |
+
|
| 214 |
+
A `Snowflake` is just a collection of four different `Step`s. It also has the `draw` method that kicks off the branch-drawing process six times in six different directions, making a complete snowflake.
|
| 215 |
+
|
| 216 |
+
{pageBreak}
|
| 217 |
+
D> Why four different `Step` objects? I knew I wanted more than one, and ten seemed excessive, given the recursion rarely goes more than a few levels deep anyway. Four seemed to work nicely, but you should feel free to try other numbers! Be sure to change the `4`s in both `Step.newRandom`, and in `Snowflake.newRandom`. Or better yet, store this value in a well-named global variable, and get rid of the magic value!
|
| 218 |
+
|
| 219 |
+
Once you've entered the listing above, run it several times. You should get a different snowflake each time!
|
| 220 |
+
|
| 221 |
+
## Mutant Clones
|
| 222 |
+
|
| 223 |
+
Our *Snowflake Evolution* app requires creating several variations of one snowflake. So we will need some code to both *clone* a snowflake, and to *mutate* it.
|
| 224 |
+
|
| 225 |
+
clone
|
| 226 |
+
: to create a copy of an object
|
| 227 |
+
mutate
|
| 228 |
+
: to introduce (usually small) changes to an object
|
| 229 |
+
|
| 230 |
+
Clear out the last couple of lines (test code) from your program, and continue with the code below.
|
| 231 |
+
|
| 232 |
+
{caption: "Listing 2 (Cloning and mutation).", number-from: 72}
|
| 233 |
+
```miniscript
|
| 234 |
+
Step.mutate = function()
|
| 235 |
+
i = floor(rnd * 8)
|
| 236 |
+
if i == 0 then
|
| 237 |
+
self.penSize = clamp(self.penSize + rnd*2-1, 1, 15)
|
| 238 |
+
else if i == 1 then
|
| 239 |
+
self.fwd = clamp(self.fwd + rnd*20-10, 10, 100)
|
| 240 |
+
else if i == 2 then
|
| 241 |
+
self.sideAngle = clamp(self.sideAngle + rnd*20-10, 0, 170)
|
| 242 |
+
else if i == 3 then
|
| 243 |
+
self.sideScale = clamp(self.sideScale + rnd/2-0.25, 0, 0.8)
|
| 244 |
+
else if i == 4 then
|
| 245 |
+
self.sideStepNum = floor(rnd * 4)
|
| 246 |
+
else if i == 5 then
|
| 247 |
+
self.fwdScale = clamp(self.fwdScale + rnd/2-0.25, 0, 0.9)
|
| 248 |
+
else if i == 6 then
|
| 249 |
+
self.penColor = randColor
|
| 250 |
+
else
|
| 251 |
+
self.fwdStepNum = floor(rnd * 4)
|
| 252 |
+
end if
|
| 253 |
+
end function
|
| 254 |
+
|
| 255 |
+
Step.clone = function()
|
| 256 |
+
return {} + self
|
| 257 |
+
end function
|
| 258 |
+
|
| 259 |
+
Snowflake.cloneAndMutate = function()
|
| 260 |
+
result = new Snowflake
|
| 261 |
+
result.steps = []
|
| 262 |
+
for step in self.steps
|
| 263 |
+
result.steps.push step.clone
|
| 264 |
+
result.steps[-1].mutate
|
| 265 |
+
end for
|
| 266 |
+
return result
|
| 267 |
+
end function
|
| 268 |
+
|
| 269 |
+
flake = Snowflake.newRandom
|
| 270 |
+
while true
|
| 271 |
+
clear
|
| 272 |
+
flake.draw
|
| 273 |
+
if key.get == char(27) then break
|
| 274 |
+
flake = flake.cloneAndMutate
|
| 275 |
+
end while
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
This listing includes somewhat longer test code, which generates a single mutated clone every time you press a key (until you press Escape, which is `char(27)`; then it breaks the loop).
|
| 279 |
+
|
| 280 |
+
Most of the work here is being done by the `Step.mutate` method, which picks a random attribute (`i`), and then randomly changes the corresponding property. The `clamp` method being used here (imported from the `mathUtil` module) simply limits a value to a valid range. This is especially important for the `sideScale` and `fwdScale` properties, which must always be less than 1.
|
| 281 |
+
|
| 282 |
+
D> What if, say, `fwdScale` were *not* less than 1? Remember that this controls how big the next section of the branch is, relative to the last section. And also remember that the recursion stops when the branches get too small. So if the next part of the branch were actually *bigger* than the previous part, what would happen? If you're not sure, try it and see!
|
| 283 |
+
|
| 284 |
+
## Main Program
|
| 285 |
+
|
| 286 |
+
We're just about done now. The rest of the program draws six flakes at a time, waits for the user to pick one with the mouse, and then generates five new ones — mostly mutant clones of the one selected.
|
| 287 |
+
|
| 288 |
+
Delete the test code starting on line 107, and then type in the following to finish the program.
|
| 289 |
+
|
| 290 |
+
{caption: "Listing 3 (Wrapping up *Snowflake Evolution*).", number-from: 107}
|
| 291 |
+
```miniscript
|
| 292 |
+
// Helper function to wait for a click. Also watches
|
| 293 |
+
// for the Escape key, and if pressed, exits the program.
|
| 294 |
+
waitForClick = function()
|
| 295 |
+
// wait for mouse down, or escape key
|
| 296 |
+
while not mouse.button
|
| 297 |
+
if key.pressed("escape") then exit
|
| 298 |
+
yield
|
| 299 |
+
end while
|
| 300 |
+
// wait for mouse up
|
| 301 |
+
while mouse.button; yield; end while
|
| 302 |
+
end function
|
| 303 |
+
|
| 304 |
+
// Prepare six snowflakes.
|
| 305 |
+
flakes = []
|
| 306 |
+
for i in range(0,5)
|
| 307 |
+
flakes.push Snowflake.newRandom
|
| 308 |
+
end for
|
| 309 |
+
|
| 310 |
+
// Main loop.
|
| 311 |
+
while true
|
| 312 |
+
// Draw our current six snowflakes.
|
| 313 |
+
clear
|
| 314 |
+
for i in range(0,5)
|
| 315 |
+
col = i % 3
|
| 316 |
+
row = floor(i/3)
|
| 317 |
+
flakes[i].draw 160 + col * 320, 160 + row*320
|
| 318 |
+
end for
|
| 319 |
+
|
| 320 |
+
// Wait for a click, and figure out which flake was hit.
|
| 321 |
+
waitForClick
|
| 322 |
+
col = floor(mouse.x / 320)
|
| 323 |
+
row = floor(mouse.y / 320)
|
| 324 |
+
choice = row * 3 + col
|
| 325 |
+
|
| 326 |
+
// Replace all the other flakes with new ones.
|
| 327 |
+
for i in range(0, 5)
|
| 328 |
+
if i != choice then
|
| 329 |
+
// create either a mutant of the chosen one,
|
| 330 |
+
// or occasionally, a completely new one
|
| 331 |
+
if rnd < 0.8 then
|
| 332 |
+
flakes[i] = flakes[choice].cloneAndMutate
|
| 333 |
+
else
|
| 334 |
+
flakes[i] = Snowflake.newRandom
|
| 335 |
+
end if
|
| 336 |
+
end if
|
| 337 |
+
end for
|
| 338 |
+
end while
|
| 339 |
+
```
|
| 340 |
+
|
| 341 |
+
Before you call it a day, take some time to play with this program! It's really fun trying to "breed" the perfect snowflake, guiding their evolution with judicious clicks of the mouse. But don't be shy about hitting Escape and running again to get a fresh new batch of snowflakes to start from.
|
| 342 |
+
|
| 343 |
+
A> **Chapter Review**
|
| 344 |
+
A> - You developed an algorithm for drawing a snowflake, by recursively drawing the same (or similar) things at progressively smaller scales.
|
| 345 |
+
A> - You implemented that algorithm first in a small program that draws a snowflake.
|
| 346 |
+
A> - You elaborated that into a more sophisticated program that demonstrates cloning and mutation.
|
| 347 |
+
|
| 348 |
+
|
data/day29.txt
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 29: Finding Help", startingPageNum:359}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Don’t be afraid to say "I don’t know" or "I don’t understand" – no question is a dumb question.
|
| 7 |
+
Q>— Margaret Hamilton (software engineering pioneer)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
A> **Chapter Objectives**
|
| 11 |
+
A> - Learn where to look for programming help on the Internet.
|
| 12 |
+
A> - Explore some places where you can join a community and share your work.
|
| 13 |
+
A> - Learn some common ways programmers find solutions to problems.
|
| 14 |
+
|
| 15 |
+
I hope you've found this book fun and easy to follow. If you're like many readers, you began with little or no programming experience, and now you've completed an entire book, entered and debugged a large number of programs, and learned MiniScript syntax as well as most of the Mini Micro classes and functions.
|
| 16 |
+
|
| 17 |
+
Despite the considerable increase in your programming prowess, you may still find it difficult when you sit down to write a program from scratch. You may experience a form of "writer's block" where you don't even know how to begin. Or you may get partway through a project, and then run into some bug you don't know how to solve. You can certainly search this book for helpful advice, and I hope you find some! But if that doesn't work, then what do you do?
|
| 18 |
+
|
| 19 |
+
In this chapter we'll go over some places to get help at times like those. We'll also cover some communities you can join and participate in even when you don't need help — for example, when you've just coded something cool and want to share it with people who will appreciate it. The MiniScript community is friendly and supportive. Here's where you can find them.
|
| 20 |
+
|
| 21 |
+
Q> The Internet? Is that thing still around?
|
| 22 |
+
Q>— Homer Simpson
|
| 23 |
+
|
| 24 |
+
## Official MiniScript Sites
|
| 25 |
+
|
| 26 |
+
From the very beginning of the book, I've encouraged you to make use of the resources linked from the MiniScript home page. But it's worth suggesting these again.
|
| 27 |
+
|
| 28 |
+
MiniScript home page
|
| 29 |
+
: <https://miniscript.org>
|
| 30 |
+
|
| 31 |
+
This web site is the first step for all things related to MiniScript and Mini Micro. Other sites may come and go, or change their web address, but this one should always be valid and up to date.
|
| 32 |
+
|
| 33 |
+
From here you can find links to most of the other places mentioned in this chapter. You'll also find very helpful resources like the MiniScript Quick Reference.
|
| 34 |
+
|
| 35 |
+
One of these resources is the **MiniScript User's Manual**, a downloadable reference book that explains the MiniScript language and its intrinsic functions in good detail. I wouldn't recommend this book to someone who is entirely new to programming. But you're not new to programming any more! You will be able to understand pretty much everything in this book at this point. While much of it is the same material that was covered here, it's presented in a different way, and this might make you say "aha!" if you were confused on some detail of the language.
|
| 36 |
+
|
| 37 |
+
You'll also find an invitation link for the **MiniScript Discord server** here. Discord is a popular real-time chat program. People here communicate mostly by text, though you can also post pictures of your projects, and a voice channel is available when needed. Text channels are divided into topics, including `#mini-micro`, `#show-and-tell`, and `#game-ideas`, so you can focus on the areas that interest you. Many MiniScript users hang out here and are always eager to share the excitement of coding. (If you are underage, please check with a parent or caregiver before joining any online chat.)
|
| 38 |
+
|
| 39 |
+
MiniScript wiki
|
| 40 |
+
: <https://miniscript.org/wiki/>
|
| 41 |
+
|
| 42 |
+
The MiniScript wiki is a very useful reference site. Continually updated and extended by volunteers (including myself), this wiki has a page for just about every language feature and function in MiniScript and Mini Micro. Let's say you are wondering if there is some way to hide the mouse cursor in Mini Micro. Just go to the wiki, type "mouse" into the search field, and press Return. This will take you to the documentation on the `mouse` module, which includes a link to every method and property therein, including `mouse.visible`. Clicking that takes you to details on `mouse.visible`, including a simple code example you can type in (or copy and paste) to try it yourself.
|
| 43 |
+
|
| 44 |
+
The wiki is cross-referenced using tags that appear on the bottom of most pages, making it easy to explore and find related topics. It also features a large number of "how to" articles demonstrating how to solve specific problems, for example, how to move a sprite towards a target. Just type "how to" into the Search field to find the whole set of these.
|
| 45 |
+
|
| 46 |
+
MiniScript forums
|
| 47 |
+
: <https://forums.miniscript.org/>
|
| 48 |
+
|
| 49 |
+
The MiniScript forums are an online discussion board for the MiniScript community. Posts to the board are divided into topics, similar to Discord, but while Discord messages are real-time and tend to disappear quickly, posts to the forums stick around for a long time and end up indexed by search engines such as Google. So the forums are a better place for longer, more detailed discussions, or for anyone who just prefers web forums to Discord.
|
| 50 |
+
|
| 51 |
+
## Third-Party Sites
|
| 52 |
+
|
| 53 |
+
These are sites that are not directly associated with the MiniScript maintainers, but nonetheless include some useful MiniScript-related content.
|
| 54 |
+
|
| 55 |
+
YouTube
|
| 56 |
+
: <https://youtube.com>
|
| 57 |
+
|
| 58 |
+
I doubt I have to explain YouTube to anyone! The 900-pound-gorilla of video-sharing sites, YouTube includes videos about just about everything, including MiniScript. Unfortunately it can be a little hard to find, especially since a recent (and completely unrelated) scripting language related to Bitcoin has also started calling itself MiniScript (and there is apparently a children's scooter called the Mini Micro). So be careful!
|
| 59 |
+
|
| 60 |
+
There is a MiniScript channel which contains official MiniScript videos; you can find that via <http://bit.ly/miniscript-channel>. If you're a visual learner, you may find this a helpful resource.
|
| 61 |
+
|
| 62 |
+
Reddit
|
| 63 |
+
: <https://www.reddit.com/r/MiniScript/>
|
| 64 |
+
|
| 65 |
+
Reddit is a discussion site that bills itself as "the front page of the internet." It's divided into topic areas called "subreddits," and the URL above takes you directly to the subreddit for MiniScript. At the moment, this area gets less traffic than the Discord server or forums, but if you like Reddit's format or are already a user there, you should join this subreddit so you don't miss out on anything. It's also a fine place to ask questions when you need help; the community tends to be a little less formal and more forgiving than StackOverflow (below).
|
| 66 |
+
|
| 67 |
+
StackOverflow
|
| 68 |
+
: <https://stackoverflow.com/>
|
| 69 |
+
|
| 70 |
+
StackOverflow is a question/answer site for programmers. No, it's *the* question/answer site for programmers! Professionals and serious hobbyists frequently make use of this site when they have a problem. The first step is always to search for an existing question; very often if you're stuck on something, someone else was stuck on it before you, and an existing question may have a good answer.
|
| 71 |
+
|
| 72 |
+
When that fails, then you can post a new question here, and very often get a good answer within days. Other users will vote on which answers are the best, and the original questioner can mark one answer as "accepted," all of which helps later searchers find an answer likely to work.
|
| 73 |
+
|
| 74 |
+
StackOverflow can be a little intimidating to new users; it has pretty strict guidelines about what constitutes a programming question, not duplicating a previous question, etc. Don't let it scare you! Everyone there is there either to get help, or give help (or both). And everyone was a first-time user at some point. If you have a technical question about programming, this is a valid place to find or ask for expert advice. And if this book turns out to be the start of a long and productive programming career, you will definitely be making use of StackOverflow on a regular basis.
|
| 75 |
+
|
| 76 |
+
## Other places to find MiniScript code
|
| 77 |
+
|
| 78 |
+
The last two sites we'll consider in this chapter are not really discussion sites, though they do have some limited commenting features. They're really *project* sites, where people who have put a lot of work into a MiniScript or Mini Micro project have decided to share it with the world. These can be really helpful for a beginner. It's like a new architect not only driving around and looking at buildings, but getting to peek at the blueprints too!
|
| 79 |
+
|
| 80 |
+
GitHub
|
| 81 |
+
: <https://github.com>
|
| 82 |
+
|
| 83 |
+
GitHub is a very popular source code hosting site, based on the *git* version control system. Using git, you can push a copy of your project (source code, images, and other files) up to GitHub, where other people can clone your project to make their own variation, or even suggest fixes or enhancements to yours. Use of git is beyond the scope of this book, and is a bit involved, but it's something you may want to learn eventually.
|
| 84 |
+
|
| 85 |
+
In the meantime, though, you can browse other people's projects on GitHub. On the wiki under "open-source projects" you will find a list of games/apps/programs written in MiniScript; those are mostly or entirely links to GitHub. Click on any of those to go to the GitHub project, and then start clicking on file or folder names you see to drill down to the MiniScript code files. Who knows what cool coding tricks you may learn this way?
|
| 86 |
+
|
| 87 |
+
Itch.io
|
| 88 |
+
: <https://itch.io/games/tag-minimicro>
|
| 89 |
+
|
| 90 |
+
Itch.io is a project hosting site that is mostly about serving compiled, ready-to-run games and other software projects. However, in the case of Mini Micro games (which you will find using the URL above), you can usually get to the source code just by pressing Control-C during the game, and then poking around.
|
| 91 |
+
|
| 92 |
+
D> You can *usually* but not *always* do this because it is possible to package your Mini Micro game in such a way that breaking with Control-C is disabled. To learn how, go to the MiniScript Wiki and search for "bootOpts.grfon".
|
| 93 |
+
|
| 94 |
+
The itch.io community is generally very friendly and supportive. If you like any of the Mini Micro games you find here, post a comment to let the author know! And someday, when you've created something fun or interesting, consider posting it as a project here for others to enjoy. You can package your app as a web build, upload it here, and send the URL to everyone you know; they will be able to run your program right in their web browser, without having to download anything.
|
| 95 |
+
|
| 96 |
+
## The tip of the iceberg
|
| 97 |
+
|
| 98 |
+
The internet is vast, and of course we've only scratched the surface with this survey. It's also always in motion, so by the time you read this, there may be other good places to get help or find other MiniScript users. Don't be afraid to poke around, and ask the folks you meet in one place if there is anywhere else you should check out.
|
| 99 |
+
|
| 100 |
+
This has been a short chapter, if you only read it — but as always in this book, you learn more from *doing* than from merely reading! So if you haven't already, I highly recommend you go check out these sites. All of them are free to use and welcoming to newcomers.
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
A> **Chapter Review**
|
| 104 |
+
A> - You reviewed the official MiniScript sites and resources.
|
| 105 |
+
A> - You learned about some third-party sites that also have some MiniScript content.
|
| 106 |
+
A> - You discovered project-hosting sites where you may find sophisticated MiniScript programs to learn from.
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
data/day3.txt
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 3: Variables and Comments", startingPageNum:27}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
|
| 7 |
+
Q>— Martin Fowler (software developer and author)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn how *variables* are used to hold values in memory.
|
| 11 |
+
A> - Use *comments* to leave notes for your future self (or others).
|
| 12 |
+
A> - Start thinking about how to write code that is clear and easy to read.
|
| 13 |
+
|
| 14 |
+
## Keeping values for later
|
| 15 |
+
|
| 16 |
+
So far, every program you've written has created values right where they are used -- mainly on a `print` statement.
|
| 17 |
+
|
| 18 |
+
```miniscript
|
| 19 |
+
print "Hey " * 3
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
The example above multiplies `"Hey "` by three, resulting in `"Hey Hey Hey "`, and then immediately passes it to the `print` function. This is like assembling a sandwich in the kitchen, and then immediately eating it.
|
| 23 |
+
|
| 24 |
+
There's nothing wrong with that; in fact it's a perfectly fine way to eat a sandwich. But sometimes your recipe is too complex to do all at once; some steps need to be done ahead of time. Or sometimes you want to make your sandwich in the morning, and eat it at lunch.
|
| 25 |
+
|
| 26 |
+
In such cases, you need to store your intermediate results somewhere. Let's imagine you're more organized in the kitchen than most people (including me!). You have a large number of tupperware containers, and a dry-erase marker you use to label each one whenever you put something in it. So you might build a sandwich, put it in a tupperware, and write "hamOnRye" on it. Then later, when you're hungry for a ham on rye, you can easily grab the right tupperware and retrieve the sandwich you stored earlier.
|
| 27 |
+
|
| 28 |
+
In computer programming, we have a similar concept, but the tupperware containers are called *variables*. A variable has a name (the label) and stores a value, so you can easily retrieve it later. You store something in a variable by using the equals sign, called the *assignment operator* in this case.
|
| 29 |
+
|
| 30 |
+
variable
|
| 31 |
+
: a name associated with a storage location that can hold a value
|
| 32 |
+
|
| 33 |
+
assignment
|
| 34 |
+
: storing a value in a variable by use of the `=` operator
|
| 35 |
+
|
| 36 |
+
It looks like this:
|
| 37 |
+
|
| 38 |
+
```miniscript
|
| 39 |
+
greeting = "Hey " * 3
|
| 40 |
+
print greeting
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
Line 1 in this example also computes `"Hey Hey Hey "`, but then stores this result in a variable called `greeting`. Line 2 then retrieves that value, passing the value of `greeting` to the `print` function.
|
| 44 |
+
|
| 45 |
+

|
| 46 |
+
|
| 47 |
+
And that's all there is to it. Variable names can be pretty much anything, as long as they start with a letter or underscore character, and contain only letters, numbers, and underscores. In particular, this means that a variable name can't contain spaces. So `hamOnRye` would be a perfectly fine variable name, but `ham on rye` would not.
|
| 48 |
+
|
| 49 |
+
D> MiniScript uses spaces and punctuation to divide your program code into words, and expects each word to have some meaning. That's why you can't use spaces, commas, or other punctuation in a variable name; it would look like multiple words. A variable is a single thing, so it needs to be a single word as far as the computer's concerned.
|
| 50 |
+
|
| 51 |
+
E> Does "hamOnRye" look strange to you? This style of internal capital letters, known as "camel case," is common in computer programming, but not in normal English. It's a way to let us humans see it as multiple words, while still appearing to the computer as a single word.
|
| 52 |
+
|
| 53 |
+
The example above was admittedly a bit pointless. Our greeting expression was very simple and used immediately, so we didn't really need a variable there -- it was like making a simple sandwich and eating it right away. So let's look at a more realistic example.
|
| 54 |
+
|
| 55 |
+
{caption: "Always-8 number trick"}
|
| 56 |
+
```miniscript
|
| 57 |
+
num = 42
|
| 58 |
+
print "starting with: " + num
|
| 59 |
+
x = num - 1
|
| 60 |
+
print "- 1: " + x
|
| 61 |
+
x = x * 3
|
| 62 |
+
print "* 3: " + x
|
| 63 |
+
x = x + 12
|
| 64 |
+
print "+ 12: " + x
|
| 65 |
+
x = x / 3
|
| 66 |
+
print "/ 3: " + x
|
| 67 |
+
x = x + 5
|
| 68 |
+
print "+ 5: " + x
|
| 69 |
+
result = x - num
|
| 70 |
+
print "- " + num + ": " + result
|
| 71 |
+
print "...it's always 8!"
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
This program encodes a little arithmatic trick I found somewhere. You start with any number -- the listing above uses `42` -- and then do a series of simple math operations to it. At the end, no matter what you started with, you end up with 8.
|
| 75 |
+
|
| 76 |
+
Variables are handy in this program for several reasons. First, it lets us take a complex series of steps and do them one at a time, which makes the code easier to write and understand. Second, it lets us print out the result of each of those steps as we go. Without variables, we could either print the result of a calculation, or use it as part of a larger calculation, but not both. Finally, you'll notice that the last step is to subtract off the number we started with -- that would be impossible if we didn't store that original number away in `num`, keeping it intact while we did all our calculations in a different variable `x`.
|
| 77 |
+
|
| 78 |
+
{pageBreak}
|
| 79 |
+
D> Try it! Enter the program on the previous page carefully, and run it several times, changing the value assigned to `num` in the first line each time. Neat, huh?
|
| 80 |
+
|
| 81 |
+
## Assignment Is Not Math
|
| 82 |
+
|
| 83 |
+
Some mathematically-minded people may be disturbed by lines like
|
| 84 |
+
|
| 85 |
+
```miniscript
|
| 86 |
+
x = x + 12
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
from the above example. If you think of this as algebra, it makes no sense at all! In high-school math, this would be a statement that says, "there is a number x such that x is equal to x plus 12." There can be no such number; this is an equation with no solution.
|
| 90 |
+
|
| 91 |
+
But this isn't algebra, and the above line is not a declaration of equality. It's computer programming, and this is an assignment. The computer does this in two steps: first, it computes the value of whatever's on the right-hand side of the `=` sign. And second, it stores that value under the label on the left-hand side.
|
| 92 |
+
|
| 93 |
+
Going back to the kitchen analogy, this would be like having a container labeled "lunch". In the morning, you store some bread in this container. At your mid-morning break, you retrieve your "lunch" container, take out the bread, insert some ham, and then put it back into that same "lunch" container. You've simply reused the same container.
|
| 94 |
+
|
| 95 |
+
The same thing is going on with `x = x + 12`. We first take out the value of `x`, whatever it is at this point, and add 12 to it. Then we store this new value back into `x`, replacing the previous value.
|
| 96 |
+
|
| 97 |
+
## Leaving Notes For Yourself
|
| 98 |
+
|
| 99 |
+
The second (and last) concept for today is simple but important: leaving little messages in your programs, so that readers of the code (including your future self) will better understand what it's all about. These messages are called *comments*.
|
| 100 |
+
|
| 101 |
+
comment
|
| 102 |
+
: a message left in a program, ignored by the computer, meant for human readers of the code
|
| 103 |
+
|
| 104 |
+
A comment in MiniScript starts with two forward slashes, `//`, and continues until the end of the line. So anywhere you see `//` in a MiniScript program, except of course inside a string, you are looking at a note left for you by whoever wrote the code.
|
| 105 |
+
|
| 106 |
+
Here's an example program containing some comments:
|
| 107 |
+
|
| 108 |
+
{caption: "Simple dice program"}
|
| 109 |
+
```miniscript
|
| 110 |
+
// Dice program
|
| 111 |
+
// Rolls two 6-sided dice and prints the sum.
|
| 112 |
+
|
| 113 |
+
// Note: rnd returns a number between 0 and 1.
|
| 114 |
+
// So if we multiply by 6, we get a number between 0 and 6.
|
| 115 |
+
// The ceil function then "rounds" this to a whole number 1-6.
|
| 116 |
+
d1 = ceil(rnd * 6) // get the first die
|
| 117 |
+
d2 = ceil(rnd * 6) // get the second die
|
| 118 |
+
print "Rolled: " + d1 + " and " + d2
|
| 119 |
+
print "Total: " + (d1 + d2) // parens needed here!
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
The comments at the top of the listing are sometimes called *header comments*, and are generally there to provide an overview of what the program does. Those are lines 1-2 in the listing above. Lines 4-6 are providing some implementation notes, explaining the calculation that follows.
|
| 123 |
+
|
| 124 |
+
Those were all longer comments that got entire lines to themselves, but you can also put a shorter comment at the end of a line of code, as shown on lines 7, 8, and 10. In this case the computer will execute the MiniScript up until `//`, and then ignore the rest of the line. As a human, you may often do the opposite, especially when skimming the code; you'll look for the comments, and mostly ignore the code itself. (Not that this is always advisable; remember that comments are written by humans, and not checked by the computer... and humans often make mistakes!)
|
| 125 |
+
|
| 126 |
+
As a beginner, you will be tempted to skip writing comments. You are juggling a lot of things in your head, and comments feel like just one more. But this is a mistake. On the contrary, as a beginner you should write *more* comments, and you should write most of them first, before you write the actual code. Use the comments as a way to organize your thoughts and construct an outline of your program, before you get into the nitty-gritty details. In most cases, this will produce a working solution faster, and result in a better program.
|
| 127 |
+
|
| 128 |
+
## Writing Clear Code
|
| 129 |
+
|
| 130 |
+
That brings us to possibly the most important lesson in this book, and it's well put by the quote at the start of this chapter.
|
| 131 |
+
|
| 132 |
+
The computer programs you've written so far have been simple, no more than a dozen lines, and often much less. It's simple enough to read through them and understand what they're doing.
|
| 133 |
+
|
| 134 |
+
But that won't be the case much longer. Even in a high-level language like MiniScript, nontrivial programs routinely take hundreds or thousands of lines of code. Commercial games and other apps are often millions of lines of code. No human can grasp all those details at once.
|
| 135 |
+
|
| 136 |
+
Managing this complexity is the central business of programming. There are many strategies for doing so, and they work great together. But as a beginner, there are just two you should keep in mind:
|
| 137 |
+
|
| 138 |
+
1. Pick good, descriptive names for your variables and functions.
|
| 139 |
+
|
| 140 |
+
2. Write good comments.
|
| 141 |
+
|
| 142 |
+
Both of these stem from the recognition that the person reading the code in the future -- quite likely yourself -- will not be able to know everything about it at once. When reading a line of code that uses a variable, they may not see where it was assigned a value. So it's important that the name itself provide a useful clue to what it contains. And of course comments help explain what is going on when the variables and operations themselves are not obvious. They're also important for relaying the *intent* of the code, that is, the big picture of what the programmer was trying to do. This provides the context in which the details can make sense.
|
| 143 |
+
|
| 144 |
+
The importance of all this can't be overstated. Most big software projects that fail, fail not because the computer hardware or programming environment wasn't up to the task. They fail because the code got harder and harder to understand, and it reached a point where any attempt to change anything -- even just fixing a bug -- caused more problems than it fixed.
|
| 145 |
+
|
| 146 |
+
But this is not a cause for despair. We have learned a lot in the last half-century about how to write code that is clear, easy to understand, and a pleasure to maintain. Well-written code has a beauty to it that is very real, even though most people can't see it. By the end of this book, you'll be well on your way to seeing that beauty yourself.
|
| 147 |
+
|
| 148 |
+
{pageBreak}
|
| 149 |
+
Now that we've introduced variables and comments, the rest of the example programs will make use of these in ways that hopefully make the code clear. And when you write your own code from scratch (which, if you haven't already done, you will soon!), please try to do the same thing.
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
A> **Chapter Review**
|
| 153 |
+
A> - You learned how to store values in variables for future use.
|
| 154 |
+
A> - You discovered how to leave comments in the code for human readers.
|
| 155 |
+
A> - You've begun to think about how to write code that is not only correct, but clear and easy to understand.
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
|
data/day30.txt
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 30: Where to Go From Here", startingPageNum:367}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Software engineering is the closest I could come to fulfilling my lifelong dream of becoming a wizard.
|
| 7 |
+
Q>— Mel Klimushyn (software engineer)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn some fun ways to apply your programming skills.
|
| 11 |
+
A> - Find resources that will enable you to keep learning and growing as a coder.
|
| 12 |
+
A> - Get some final words of wisdom that you may find useful.
|
| 13 |
+
|
| 14 |
+
This is it. The final chapter! If you've done one chapter per day, then you set out on your programming journey a month ago. Look how far you've come!
|
| 15 |
+
|
| 16 |
+
This guide book is coming to an end, but the road to programming mastery does not. So let's finish by looking forward a bit, so you can choose your own path as you continue from here.
|
| 17 |
+
|
| 18 |
+
## Contributing to the Community
|
| 19 |
+
|
| 20 |
+
Q> When one teaches, two learn.
|
| 21 |
+
Q> — Robert Heinlein (science fiction author)
|
| 22 |
+
|
| 23 |
+
A great way to continue growing as a programmer is to help the MiniScript community, and there are several easy ways to do that. First, you can look for tasks to implement at Rosetta Code.
|
| 24 |
+
|
| 25 |
+
Rosetta Code
|
| 26 |
+
: <http://www.rosettacode.org/>
|
| 27 |
+
|
| 28 |
+
This site is a specialized wiki that has a large number of relatively simple, well-defined tasks, and for each task, implementations in a wide variety of languages. If you search for "MiniScript" you can find a page that lists all the tasks that have been already implemented in MiniScript. There are over 150 of those, and studying these is a great way to get nice, bite-sized examples of MiniScript code.
|
| 29 |
+
|
| 30 |
+
But there are literally thousands of tasks not yet implemented in MiniScript (and you can get a list of those from the MiniScript category page, too). Some of the tasks are complex, but most of them are quite simple. Most of them have dozens of implementations in other languages, too, which you can use as pseudocode if you're not sure about the algorithm.
|
| 31 |
+
|
| 32 |
+
So, my suggestion is this: create an account on Rosetta Code, browse the tasks not implemented in MiniScript, find some nice easy ones, and implement them! You will be exercising your skills, and helping visitors to Rosetta Code see how we do things in MiniScript. Then head on over to BadgeList — described in the next section — to collect your Rosetta Coder badge!
|
| 33 |
+
|
| 34 |
+
Another way to help out the community is to contribute to the MiniScript wiki. That was also mentioned in the last chapter, but it's so important that it's worth pointing out again.
|
| 35 |
+
|
| 36 |
+
MiniScript wiki
|
| 37 |
+
: <https://miniscript.org/wiki/>
|
| 38 |
+
|
| 39 |
+
Beginners often think of wikis as something they only read. But it doesn't need to be that way; you can and should *write* wiki content, too! Find some article that is short or lacking in examples, and improve it by adding your own example, or clarifying some unclear part of the text. If you poke around enough, you might even find a link to some page that does not yet exist. In that case, create it!
|
| 40 |
+
|
| 41 |
+
Here's a great way to get started when making a new page: find some similar page, click Edit, and then copy the wiki source code that appears in the editing box. Then cancel that edit, go to the page you want to create, click "create this page," and then paste in the copied text. Now you have the basic format already done, and you can just change the text and sample code to reflect the new topic. Be sure to use the Preview button to check that it all looks good before you save it. But don't worry about making mistakes — a wiki can always restore a previous version of a page if needed, and believe me, your efforts will be greatly appreciated.
|
| 42 |
+
|
| 43 |
+
Rosetta Code and the wiki are important but indirect ways of helping others: you're depositing your knowledge in a resource that future knowledge-seekers may find. But also try to help others more directly, through the forums or Discord server. Check in with these when you can, and if you see somebody posting a question you happen to know the answer to, help them out! Also, if you see someone sharing something they're working on, give them some positive feedback. Helping each other in this way makes us all stronger.
|
| 44 |
+
|
| 45 |
+
## Coding Challenges
|
| 46 |
+
|
| 47 |
+
If you're facing the "writer's block" problem where you just don't know what program to write next, then there are some fun programming challenges that might be of use. Your first stop could be Badge List:
|
| 48 |
+
|
| 49 |
+
Badge List
|
| 50 |
+
: <https://www.badgelist.com/MiniScript>
|
| 51 |
+
|
| 52 |
+
Badge List is a fun little site that awards "badges" for your accomplishments, something like merit badges in Girl Scouts and Boy Scouts. You can group the badges by tags or just browse them all, and many of them are organized into different difficulty levels. Start with the *MiniScript Neophyte* badge, which only requires you to use a `for` loop to print "Hello world!" ten times. Like Rosetta Code, you will find some of the tasks are quite easy, while others are more difficult. See how many badges you can collect!
|
| 53 |
+
|
| 54 |
+
{i:"game jam"}
|
| 55 |
+
When you're ready for a bigger challenge, you may want to dip your toes into the warm, chaotic waters of *game jams*. A game jam is a contest in which developers get together, individually or in small teams, to create a game in a short amount of time — typically a few days, sometimes several weeks. There are usually restrictions and/or a theme that is not known until the contest begins, which helps keep people from working ahead on a project before the official start date.
|
| 56 |
+
|
| 57 |
+
Most game jams are informal affairs, just for fun, though some of them do offer prizes, awarded by a panel of judges. Every game jam I've participated in has been a blast, and full of supportive, positive people all eager to share their love of coding. Here's a good place to find upcoming game jams:
|
| 58 |
+
|
| 59 |
+
Game jams on itch.io
|
| 60 |
+
: <https://itch.io/jams>
|
| 61 |
+
|
| 62 |
+
Here you'll find a "jam calendar" showing all the ongoing or upcoming jams. You can also search and filter in various ways. Note that you don't need to find a MiniScript-specific game jam; you can build your Mini Micro games for Windows, Mac, Linux, and the web, so you can enter almost any game jam that does not require a specific development tool.
|
| 63 |
+
|
| 64 |
+
{width:"75%"}
|
| 65 |
+

|
| 66 |
+
|
| 67 |
+
The game jam community is also a great place to connect with others in the hobby. In particular, it's common for programmers like yourself to team up with artists and musicians to tackle a jam together.
|
| 68 |
+
|
| 69 |
+
Note that there's a `#game-jam` channel in the MiniScript Discord server, too, so if you are thinking about participating in a jam and would like a coding partner, help with a bug, or just words of encouragement, be sure to post there.
|
| 70 |
+
|
| 71 |
+
## More Guidance
|
| 72 |
+
|
| 73 |
+
Since you've made it this far, it's clear you're a good reader and you enjoy learning this way. So you may be wondering if there are any other books to learn from?
|
| 74 |
+
|
| 75 |
+
At the time of this writing, the only other book is the *MiniScript User's Manual*, described in the last chapter. *Learn to Code in 30 Days* is the first "real" book written for MiniScript, because its whole purpose is to help people who are new to coding get up to speed.
|
| 76 |
+
|
| 77 |
+
However, there are plans for follow-on books that will be focused on different topics: games with various themes, simulations, and more. They will include program listings, and lots of explanation about how to tackle various problems that come up when writing that sort of code. As those books come out, they will be announced via the forums, Discord, and of course the MiniScript home page. Maybe by the time you're reading this, some are out already! Go have a look, and be sure to let me know what you most want to see.
|
| 78 |
+
|
| 79 |
+
## Parting Advice
|
| 80 |
+
|
| 81 |
+
You are fortunate to have begun your coding journey with MiniScript, a language that is especially simple and easy to learn, while still being powerful enough to create real programs. MiniScript is still a pretty new language, and you will find that many people have not heard of it. Those people are likely to tell you that if you want to become a programmer, you have to learn JavaScript, or C#, or C++, or whatever else their preferred language might be.
|
| 82 |
+
|
| 83 |
+
*This is not true.*
|
| 84 |
+
|
| 85 |
+
You already *are* a programmer, and there is no one language that you have to learn. Eventually you will be comfortable in many languages, but there is no rush to get there. The best tool for the job is whichever one lets you accomplish your goals in the simplest, most efficient manner. In many cases, that will be MiniScript and Mini Micro, even if the guru you're speaking to has never seriously looked at these. Just smile and nod, thank them for their advice, and then go and do it your way anyway.
|
| 86 |
+
|
| 87 |
+
At the same time, don't be afraid of learning another language when a genuine need arises. Beginners often mistake *syntax* for *programming.* Syntax is the detailed rules about how to declare variables, write loops, create classes, and so on in a particular language. That stuff is relatively easy to pick up in a new language, because the concepts are all more or less the same as any other language. The real difficulty in programming is at the conceptual level: how to break a complex problem down into smaller problems, how to design an algorithm when you need one, how to manage the complexity of your code so that you don't have to keep too many things in your head at once. These skills are universal. So you can certainly stick with MiniScript while you build these skills, and rest assured that when someday you need to pick up another language, those same skills will still apply.
|
| 88 |
+
|
| 89 |
+
Be patient with yourself as you build these skills. This book is called *Learn to Code in 30 Days*, and you've done that — but it's in the same sense that you could learn to play the piano in 30 days. You know all the basics and you can understand what the experts are doing, but that doesn't mean you can do it yourself at an expert level yet. That's OK! Like any skill, programming takes practice. Keep mind that there is no such thing as raw talent:
|
| 90 |
+
|
| 91 |
+
Q> A lot of people believe that... people have their gifts and that they should go out and look for what that gift is. That’s what you are spending your teenage and college years sifting through and sampling things and then finding your gift, but what I find with most college students is that they never find their gift... We argue that there is no gift to be found, basically that [they] are much better off picking something that they want to be good at and then use all of that [known about how] you can effectively achieve a high level of performance.
|
| 92 |
+
Q>— Anders Ericsson, Ph.D.
|
| 93 |
+
|
| 94 |
+
Talent is what you have *after* you've put in hours and hours of productive practice. In the case of programming, that means writing code. This chapter was full of suggestions on where to find programming tasks, from tiny to large, as well as where to share your own unique creations. Use them! And if you find them challenging, that is OK. That feeling of struggling, of not quite being able to see the answer, is just the feeling of your mind getting stronger. It's no different from sore muscles, which indicate your body growing stronger. It's a sign of time well spent.
|
| 95 |
+
|
| 96 |
+
You will find that this talent you build in programming spills over to other mental activities, too. Computers, as you know by now, are patient, but require precision. You have to say exactly what you mean; fuzzy thinking doesn't work. So over time you learn to think clearly and precisely, and this will serve you well in everything from schoolwork, to the workplace, to understanding the world.
|
| 97 |
+
|
| 98 |
+
So have fun! Remember "code a little, test a little." Don't try to do too much at once. And when you do get stuck — as we all do from time to time — don't be shy about asking for help. Every expert was a beginner at some point, and someday *you* will be the expert helping someone who is new.
|
| 99 |
+
|
| 100 |
+
You are now part of a web of experience passed from person to person, which stretches back to our prehistoric ancestors, and forward to who-knows-where — the stars, perhaps. With diligence, a good attitude, and a supportive community, there is nothing you can't accomplish.
|
| 101 |
+
|
| 102 |
+
Happy coding!
|
| 103 |
+
|
| 104 |
+
{gap:100}
|
| 105 |
+
{width:"25%"}
|
| 106 |
+

|
data/day4.txt
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 4: Input and Val", startingPageNum:37}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> I view computer science as a liberal art. It should be something that everybody learns.
|
| 7 |
+
Q>— Steve Jobs (co-founder, Apple Computer)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn to use `input` to get a string from the user.
|
| 11 |
+
A> - Use the `val` function to convert a string to a number.
|
| 12 |
+
|
| 13 |
+
## Getting input from the user
|
| 14 |
+
|
| 15 |
+
In the first three days of this course, you've already learned how to store values in variables, do math with them, and print them out. But those values are always set right in the program code, so your program does the same thing every time. The only exception to that is code that uses the `rnd` function, but that only gets a random value. What can a program do when it needs a little input from the user?
|
| 16 |
+
|
| 17 |
+
The answer is the `input` function. This is a built-in function in most MiniScript implementations.
|
| 18 |
+
|
| 19 |
+
{i:"`input`"}
|
| 20 |
+
{caption:"`input` intrinsic function"}
|
| 21 |
+
| `input(s="")` | displays prompt s, then returns string entered by the user |
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
{i:"prompt"}
|
| 25 |
+
prompt
|
| 26 |
+
: a string displayed to the user when the computer is waiting for input, giving them some idea of what sort of input is needed
|
| 27 |
+
|
| 28 |
+
Here's a simple example.
|
| 29 |
+
|
| 30 |
+
```miniscript
|
| 31 |
+
name = input("What is your name?")
|
| 32 |
+
print "Hello, " + name + "!"
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Go ahead and try this on the MiniScript *Try-It!* page. When you run it, you'll see the prompt — "What is your name?" — displayed in the output area, followed by a rectangular blinking cursor. That blinking cursor is your invitation to type something! Go ahead and type your name. (Or the name of your favorite celebrity, or your favorite fruit — it's your program; you can troll it if you like.)
|
| 36 |
+
|
| 37 |
+
{i:"Return key;Enter key"}
|
| 38 |
+
When you've typed something, press the Return or Enter key, which is your signal to the computer that you're done with your answer. The program then continues with line 2, printing out a personalized greeting. Now run it again, and type something else. You get a different output.
|
| 39 |
+
|
| 40 |
+
D> Pause for a moment and think about how cool that is. You can now make programs that can ask for information from the user, process that information, and produce a unique result. Every run of the program can do something new and useful based on the information the user provides. This is the power that got us to the Moon; it's the power that took the world by storm in the second half of the 20th century. And now that power is yours.
|
| 41 |
+
|
| 42 |
+
The ability to get input from the user lets you make considerably more chatty programs than you could before. Let's illustrate that with a somewhat longer example. (Remember, the fastest way to learn is to actually type these examples in and run them!)
|
| 43 |
+
|
| 44 |
+
{caption:"Cookbook suggestion program"}
|
| 45 |
+
```miniscript
|
| 46 |
+
name = input("Enter your name: ")
|
| 47 |
+
print "Hello, " + name + "."
|
| 48 |
+
food = input("What's your favorite food? ")
|
| 49 |
+
print "You like " + food + "? I can't stand the stuff."
|
| 50 |
+
print "So what region do you live in?"
|
| 51 |
+
region = input("Northern, Eastern, etc.? ")
|
| 52 |
+
print "Well, maybe you should make a cookbook:"
|
| 53 |
+
print name + "'s " + region + " " + food + "!"
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
This program uses three variables: `name`, `food`, and `region`. Each of them is assigned a value from a separate call to the `input` function. You can see that the computer works through this program, step by step, but it pauses on each `input` call, waiting for the user to type something and press return. Then it continues with the next line.
|
| 57 |
+
|
| 58 |
+
{width: "75%"}
|
| 59 |
+

|
| 60 |
+
|
| 61 |
+
## Getting a *number* from the user
|
| 62 |
+
|
| 63 |
+
Recall the difference between strings and numbers, which we covered in Chapter 1. A string is a sequence of characters, like `"Mary"`, while a number is a numeric value, like `42`. Even if the sequence of characters in a string happens to look like a number to us, like `"007"`, it's still just a bunch of characters to the computer.
|
| 64 |
+
|
| 65 |
+
The `input` function always returns a string. This is important.
|
| 66 |
+
|
| 67 |
+
A> The `input` function always returns a string!
|
| 68 |
+
|
| 69 |
+
That's important to remember, because the math operators do different things with strings than they do with numbers. With numbers, `*` is multiplication. But with strings, it is string replication (i.e. repeating). So if you try to do something like the following, it doesn't work as intended.
|
| 70 |
+
|
| 71 |
+
{caption:"Incorrect dog-years program"}
|
| 72 |
+
```miniscript
|
| 73 |
+
age = input("Enter your age: ")
|
| 74 |
+
print "That's " + age*7 + " in dog years!"
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Try that out and see what happens. The program above asks your age, so the user probably enters something like "42", which gets stored in the variable `age`. But it's still a string, so when we do `age*7`, we get "42424242424242" — that is, the string "42" repeated seven times.
|
| 78 |
+
|
| 79 |
+
The solution is the `val` function, which we briefly mentioned in Chapter 2. This takes a string argument and returns its numeric value. To fix the program above, we just need to use this to convert the user's input to a number. That could be done in several ways; we could do it in the math expression where the number is needed...
|
| 80 |
+
|
| 81 |
+
{caption:"Dog-years program, corrected version 1"}
|
| 82 |
+
```miniscript
|
| 83 |
+
age = input("Enter your age: ")
|
| 84 |
+
print "That's " + val(age)*7 + " in dog years!"
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
Or we could do it around the `input`, so we get a number right away...
|
| 88 |
+
|
| 89 |
+
{caption:"Dog-years program, corrected version 2"}
|
| 90 |
+
```miniscript
|
| 91 |
+
age = val(input("Enter your age: "))
|
| 92 |
+
print "That's " + age*7 + " in dog years!"
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
Or we could even add a new line, between where we get `age` as a string and where we use `age` as a number, that reassigns the variable with the numeric value.
|
| 96 |
+
|
| 97 |
+
{caption:"Dog-years program, corrected version 3"}
|
| 98 |
+
```miniscript
|
| 99 |
+
age = input("Enter your age: ")
|
| 100 |
+
age = val(age)
|
| 101 |
+
print "That's " + age*7 + " in dog years!"
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
All of these work just fine; you should use whichever makes the most sense to you.
|
| 105 |
+
|
| 106 |
+
Also try entering a string that does *not* look like a number. Enter "fish" for example. What result to you get?
|
| 107 |
+
|
| 108 |
+
A> If given a string that does not appear to be a number, `val` returns 0.
|
| 109 |
+
|
| 110 |
+
However, it's smart enough to correctly convert negative numbers, numbers with a decimal point, etc. Experiment with different values until you're comfortable with it. `val` is one of the most common functions you will use in all your MiniScript programming, so it's well worth spending a little time on it.
|
| 111 |
+
|
| 112 |
+
Try one more example to see how `input`, `val`, and math all work together to do handy calculations. (Remember that the rest of the line after `//` is a comment for the human reader, and ignored by the computer.)
|
| 113 |
+
|
| 114 |
+
{caption:"Yearly income calculator"}
|
| 115 |
+
```miniscript
|
| 116 |
+
// Yearly income calculator.
|
| 117 |
+
// Enter your income per hour, and hours worked per week,
|
| 118 |
+
// and this will calculate your income per month and year.
|
| 119 |
+
amountPerHour = val(input("Hourly rate? "))
|
| 120 |
+
hoursPerWeek = val(input("Hours per week? "))
|
| 121 |
+
weeksPerYear = 50 // assume 2 weeks vacation
|
| 122 |
+
amountPerYear = amountPerHour * hoursPerWeek * weeksPerYear
|
| 123 |
+
print "That's " + amountPerYear + " per year,"
|
| 124 |
+
print "or about " + round(amountPerYear/12) + " per month!"
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
{gap:40}
|
| 128 |
+
A> **Chapter Review**
|
| 129 |
+
A> - You learned how use `input` to get a string from the user.
|
| 130 |
+
A> - You used the `val` function to convert a string to a numeric value.
|
| 131 |
+
A> - You've entered programs that can be run again and again, calculating different results based on user inputs.
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
|
data/day5.txt
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 5: Comparisons and Looping", startingPageNum:43}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> You might not think that programmers are artists, but programming is an extremely creative profession.
|
| 7 |
+
Q> It's logic-based creativity.
|
| 8 |
+
Q>— John Romero (co-founder, id Software)
|
| 9 |
+
|
| 10 |
+
A> **Chapter Objectives**
|
| 11 |
+
A> - Learn how to compare two values to see if they are equal, or which one is greater.
|
| 12 |
+
A> - Learn to use `while` and `for` to make blocks of code repeat.
|
| 13 |
+
A> - Obtain and start relying on the *MiniScript Quick Reference*.
|
| 14 |
+
|
| 15 |
+
{i:"hard-coded value;value, hard-coded"}
|
| 16 |
+
By now, you know several ways to get values into your computer program. You can put them right into the code (these are known as "hard-coded" values); you can ask the user for them with `input`; or you can calculate them from other values. Doing calculations with them is great, but sometimes what you need is to make *decisions* with them. That begins by comparing two values. In a computer program, there are various *comparison operators* for just this purpose.
|
| 17 |
+
|
| 18 |
+
{i:"comparison operator"}
|
| 19 |
+
comparison operator
|
| 20 |
+
: a type of operator that compares two values in some way
|
| 21 |
+
|
| 22 |
+
For example: suppose you wonder whether your computer really understands math at all, so you decide to check whether it knows that 2 plus 2 equals 4. Write:
|
| 23 |
+
|
| 24 |
+
```miniscript
|
| 25 |
+
print 2 + 2 == 4
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
The comparison operator here is `==`, pronounced "equals." Notice that this operator is written with *two* equal signs. A single equal sign is used for assignment, as you learned on Day 3.
|
| 29 |
+
|
| 30 |
+
D> To test two values for equality, remember to use *two* equal signs: `==`
|
| 31 |
+
|
| 32 |
+
So in the example above, we are comparing the result of `2 + 2`, on the left side of `==`, to the value `4`, on the right. Run this code and you should see the value `1` in the output. In MiniScript, `1` means "true" and `0` means "false." So MiniScript here is saying that yes, indeed, two plus two is equal to four.
|
| 33 |
+
|
| 34 |
+
D> MiniScript uses the value 1 to mean true, and 0 to mean false.
|
| 35 |
+
|
| 36 |
+
But `==` is just one comparison operator. There are half a dozen:
|
| 37 |
+
|
| 38 |
+
{i:"operators, comparison;comparison operators"}
|
| 39 |
+
{caption:"Comparison operators"}
|
| 40 |
+
| `==` | equals |
|
| 41 |
+
| `!=` | not equal |
|
| 42 |
+
| `>` | greater than |
|
| 43 |
+
| `>=` | greater than or equal to |
|
| 44 |
+
| `<` | less than |
|
| 45 |
+
| `<=` | less than or equal to |
|
| 46 |
+
|
| 47 |
+
You can use any of these to compare values, wherever they might come from. Here's an example that decides if you're old enough to see a scary movie.
|
| 48 |
+
|
| 49 |
+
{caption:"Movie Decider 1"}
|
| 50 |
+
```miniscript
|
| 51 |
+
print "Now showing: Chainsaw Zombie Nightmare VII"
|
| 52 |
+
age = val(input("How old are you? "))
|
| 53 |
+
print "My decision: " + (age >= 18)
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
This program prints the name of the movie, asks for your age, and then compares your age to 17. It prints a 1 if your age is 18 or older, otherwise it prints a 0.
|
| 57 |
+
|
| 58 |
+
That works, but it's not a very elegant way of displaying the result, is it? Let's make it a little better by making use of string replication from Day 2. A string multiplied by 1 is just that string itself; but a string multiplied by 0 is nothing (an empty string). We can use that to print a custom message:
|
| 59 |
+
|
| 60 |
+
{caption:"Movie Decider 2"}
|
| 61 |
+
```miniscript
|
| 62 |
+
print "Now showing: Chainsaw Zombie Nightmare VII"
|
| 63 |
+
age = val(input("How old are you? "))
|
| 64 |
+
print "Hmm..."
|
| 65 |
+
ok = age >= 18
|
| 66 |
+
print "OK, you can go." * ok
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
Try that one a few times, entering different ages. Notice how we are storing the result of the age comparison in a variable, `ok`, on line 4, and then multiplying that by the message on line 5.
|
| 70 |
+
|
| 71 |
+
If you enter 18 or older, this program works fine. But if you enter a smaller number, it doesn't print anything after "Hmm..." Let's improve that with the help of the `not` operator.
|
| 72 |
+
|
| 73 |
+
{i:"`not` operator;operator, `not`"}
|
| 74 |
+
D> The `not` operator changes 1 to 0 (true to false), and vice versa.
|
| 75 |
+
|
| 76 |
+
This is the first operator we've seen that operates on a single value, instead of appearing between two values. You put `not` before the value you want to operate on. We can use that to finish our movie decider.
|
| 77 |
+
|
| 78 |
+
{caption:"Movie Decider 3"}
|
| 79 |
+
```miniscript
|
| 80 |
+
print "Now showing: Chainsaw Zombie Nightmare VII"
|
| 81 |
+
age = val(input("How old are you? "))
|
| 82 |
+
print "Hmm..."
|
| 83 |
+
ok = age >= 18
|
| 84 |
+
print "OK, you can go." * ok + "I'm sorry, you're too young." * (not ok)
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
D> When a line in a code listing is too long, the end of it is printed in this book on the next line, identified with "..." as shown in the last line above. But when you type it in, just keep typing — it will wrap or scroll over as needed.
|
| 88 |
+
|
| 89 |
+
This is not the only way to print out alternate messages; we'll learn a more natural way tomorrow. But it works and is a nice way to review both string replication, and the fact that `true` and `false` are represented as `1` and `0` in MiniScript.
|
| 90 |
+
|
| 91 |
+
## Looping with `while`
|
| 92 |
+
|
| 93 |
+
{i:"`while` loop"}
|
| 94 |
+
So far every program we've written has started with the first line, executed each line in order to the end, and quit. A decent start, to be sure, but computers are so much more powerful when they can do the same operation multiple times.
|
| 95 |
+
|
| 96 |
+
Now that you know how to compare values, you're ready to learn the first of two ways to make the computer repeat itself. This is the `while` statement, which defines that a group of lines should repeat while some condition is true. It looks like this:
|
| 97 |
+
|
| 98 |
+
{caption:"Doublings"}
|
| 99 |
+
```miniscript
|
| 100 |
+
x = 1
|
| 101 |
+
while x < 1000
|
| 102 |
+
print x
|
| 103 |
+
x = x * 2
|
| 104 |
+
end while
|
| 105 |
+
print "And that's high enough!"
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
Type this code into the Try-It! interface and see what it does. In plain English, this starts by assigning 1 to x. Then the loop begins. Lines 3-4 are repeated as long as (or "while") x is less than 1000. Those lines print x and then double its value.
|
| 109 |
+
|
| 110 |
+
When the `while` condition (`x < 1000`) is no longer true, then the loop exits, continuing with the line right after `end while`.
|
| 111 |
+
|
| 112 |
+
Of course this can work with any sort of condition. Try this variation:
|
| 113 |
+
|
| 114 |
+
{caption:"Doubling Spam"}
|
| 115 |
+
```miniscript
|
| 116 |
+
x = "spam "
|
| 117 |
+
while x.len < 60
|
| 118 |
+
print x
|
| 119 |
+
x = x * 2
|
| 120 |
+
end while
|
| 121 |
+
print "...that's enough spam for me!"
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
This is almost the same as the previous program, except instead of numbers, we are doubling strings; and our `while` condition now relies on `x.len` (the length of x).
|
| 125 |
+
|
| 126 |
+
Let's revisit our movie-decider program. Suppose it's your job to tell not just one youth, but a whole busload of youths, whether each of them is allowed to see the movie. Because you are becoming a programmer, you quickly think to automate this tedious process.
|
| 127 |
+
|
| 128 |
+
{caption:"Multi Movie Decider"}
|
| 129 |
+
```miniscript
|
| 130 |
+
print "Now showing: Chainsaw Zombie Nightmare VII"
|
| 131 |
+
age = val(input("How old are you? "))
|
| 132 |
+
while age > 0
|
| 133 |
+
print "Hmm..."
|
| 134 |
+
ok = age >= 18
|
| 135 |
+
print "OK, you can go." * ok + "I'm sorry, you're too young." * (not ok)
|
| 136 |
+
age = val(input("Next! How old are YOU? (0 to exit): "))
|
| 137 |
+
end while
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
{i:"indentation"}
|
| 141 |
+
I'm sure you've noticed by now that the lines inside the `while` loop are indented. In MiniScript, indentation is like comments: it's there for the human readers of the code, and ignored by the computer. But that doesn't mean it's not important! Without indenting the body of the loop, it would be much harder to see what's going on; and it's generally important that you be able to understand your code when you look at it months later. But it's not important exactly *how* you indent. Generally you should just hit the Tab key to indent a line, and your text editor will either insert an actual tab character, or some number of spaces. Either is fine, as long as the result is clear to your eyes.
|
| 142 |
+
|
| 143 |
+
## Looping with `for`
|
| 144 |
+
|
| 145 |
+
{i:"`for` loop"}
|
| 146 |
+
MiniScript has exactly two ways to repeat code; one is the `while` loop. The other is the `for` loop. It looks like this:
|
| 147 |
+
|
| 148 |
+
{caption:"For Loop"}
|
| 149 |
+
```miniscript
|
| 150 |
+
for i in range(1, 10)
|
| 151 |
+
print i
|
| 152 |
+
end for
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
Like a `while` loop, a `for` loop repeats everything in the loop body (which by convention we indent, though the computer is just looking for the line that says `end for`). But rather than looping while some condition is true, a `for` loop assigns a sequence of values to a variable, and stops when that sequence is complete.
|
| 156 |
+
|
| 157 |
+
{i:"`range` function"}
|
| 158 |
+
The example above uses the `range` function, which we haven't covered before. We'll delve into that more deeply in Chapter 8, but for now just think of it as a way to tell the `for` loop what range of numbers you want it to loop over. In the example above, `for i in range(1, 10)` makes the variable `i` go from 1 to 10. (Unlike some other languages, `range` in MiniScript includes both the start and end values specified.) Try it!
|
| 159 |
+
|
| 160 |
+
You can easily make a `for` statement count down instead of up. Try this one:
|
| 161 |
+
|
| 162 |
+
{caption:"Countdown"}
|
| 163 |
+
```miniscript
|
| 164 |
+
for i in range(10, 1)
|
| 165 |
+
print i + "..."
|
| 166 |
+
wait
|
| 167 |
+
end for
|
| 168 |
+
print "Lift-off!"
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
{i:"`wait` function"}
|
| 172 |
+
Here I have snuck in another new function, `wait`, which just tells MiniScript to pause for 1 second (unless you specify some other number of seconds as an argument). Together with `range` counting from 10 down to 1, we have a classic rocket count-down.
|
| 173 |
+
|
| 174 |
+
The `for` loop can also iterate over the characters of a string. For a trivial example:
|
| 175 |
+
|
| 176 |
+
{caption:Hello World, Letter by Letter}
|
| 177 |
+
```miniscript
|
| 178 |
+
for i in "Hello world"
|
| 179 |
+
print i
|
| 180 |
+
end for
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
This prints each character of the string on its own line.
|
| 184 |
+
|
| 185 |
+
This is a good time to point out that `for` and `while` loops can be *nested*, that is, you can put one loop inside of another, as much as you like. Here's a simple example that prints out all the squares on a Chess board.
|
| 186 |
+
|
| 187 |
+
{caption:"Chess Coordinates"}
|
| 188 |
+
```miniscript
|
| 189 |
+
for col in "ABCDEFGH"
|
| 190 |
+
for row in "12345678"
|
| 191 |
+
print col + row
|
| 192 |
+
end for
|
| 193 |
+
end for
|
| 194 |
+
```
|
| 195 |
+
|
| 196 |
+
{i:"loop, inner vs. outer;outer loop;inner loop"}
|
| 197 |
+
We call the first loop (`col` in this case) the *outer* loop, and the one nested inside it (`row` in his example) the *inner* loop. For every iteration of the outer loop, the inner loop starts over and does its whole sequence again. Here we have eight iterations for columns A through H in the outer loop, and eight iterations for rows 1 through 8 in the inner loop. How many lines will this print? Try it and see if you were right!
|
| 198 |
+
|
| 199 |
+
iteration
|
| 200 |
+
: one time through the body of a loop
|
| 201 |
+
|
| 202 |
+
Of course you don't have to stop with just two loops; you could nest these as deeply as you like, though the number of iterations adds up quickly. For example, if the outermost loop iterates 10 times, the middle loop iterates 5 times, and the innermost loop iterates 8 times, the result would be (10 \* 5 \* 8) = 400 iterations in all.
|
| 203 |
+
|
| 204 |
+
## The MiniScript Quick Reference
|
| 205 |
+
|
| 206 |
+
{i:"MiniScript Quick Reference;Quick Reference;documentation, MiniScript Quick Reference"}
|
| 207 |
+
In Chapter 2, we referred to coding as an "open-book process." It's like a test where you're allowed to use your textbook. Not only that, but you're allowed to search the web, too! These are great ways to find answers, especially to questions you haven't seen before.
|
| 208 |
+
|
| 209 |
+
However, they're not always the *fastest* way to find answers, particularly for things you've seen before but just need to double-check your spelling or punctuation. For that, a concise cheat sheet works much better. Fortunately, MiniScript comes with exactly that: the **MiniScript Quick Reference**. This is a one-page document that contains everything you need to know about the MiniScript language. That's right. One page. Everything!
|
| 210 |
+
|
| 211 |
+
If you haven't already done so, you should go to <https://miniscript.org> *right now*, scroll down to the "MiniScript Quick Reference" link, and click it. Save the file that appears to someplace handy like your desktop, and if you have a printer, print it out and tape it up next to your computer, or slip it into the cover of your notebook. Or at least leave it lying around on your desk. The point is, have it handy, so that you can quickly refer to it.
|
| 212 |
+
|
| 213 |
+
Although you're only on Day 5, you will find that you already understand much of what this page contains:
|
| 214 |
+
|
| 215 |
+
- The left column talks about general syntax, including comments; and also `while` and `for` loops, which you just learned. It also mentions `if` blocks, and `break` and `continue`, both of which we'll cover tomorrow.
|
| 216 |
+
- The middle column talks about numbers and strings, which you understand; plus lists and maps, which we'll get to on days 8 and 10.
|
| 217 |
+
- The right column includes some more advanced stuff we haven't gotten to yet, plus a list of all the important intrinsic functions, for those moments when you know there's a function to do something, but you can't quite remember what it's called.
|
| 218 |
+
|
| 219 |
+
D> There is only one important function that you won't find on this sheet, and that's `input`. That's because `input` is not actually part of the official MiniScript standard; if you use MiniScript in the context of a game, for example, it might not have this. But all the contexts we discuss in this book will have `input`. So go ahead and write it in the margin next to `yield` if you like.
|
| 220 |
+
|
| 221 |
+
So this MiniScript Quick Reference serves not only as a handy jog for your memory, but also as a map of what you've learned, and what still lies ahead. In another week or so, you will understand pretty much everything on this sheet.
|
| 222 |
+
|
| 223 |
+
In fact, you might consider making an extra printout of this sheet, and highlighting things on it as we go (starting by highlighting everything we've already covered). That will give you a very visual indicator of your progress, as well as reinforce what you've learned. If you don't have a printer, you can probably do the same thing using your PDF viewer software.
|
| 224 |
+
|
| 225 |
+
{pageBreak}
|
| 226 |
+
A> **Chapter Review**
|
| 227 |
+
A> - You learned how to use comparison operators to compare two values.
|
| 228 |
+
A> - You used `while` and `for` to repeat code multiple times.
|
| 229 |
+
A> - You acquired the MiniScript Quick Reference, which will be your favorite one-page document in the coming weeks.
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
{gap:100}
|
| 233 |
+
{width:"25%"}
|
| 234 |
+

|
| 235 |
+
|
data/day6.txt
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 6: If and Break", startingPageNum:53}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> In the end, there can be only one `else` block.
|
| 7 |
+
Q> Or none. That's cool too.
|
| 8 |
+
Q>— The Highlander
|
| 9 |
+
|
| 10 |
+
A> **Chapter Objectives**
|
| 11 |
+
A> - Learn how a computer program can do different things depending on what values it currently has.
|
| 12 |
+
A> - Explore the various forms of the `if` statement.
|
| 13 |
+
A> - Learn how to short-cut or exit a loop.
|
| 14 |
+
|
| 15 |
+
In the last chapter, we learned how to compare values, and applied that new power to the `while` loop. But, it turns out, that's a little bit like learning to cook and then only doing so for breakfast. It's a perfectly valid use of your skill, but misses the most common application. In programming, comparing values happens most often in the `if` statement.
|
| 16 |
+
|
| 17 |
+
{i:"`if`"}
|
| 18 |
+
An `if` statement does just what it sounds like: it tells the computer to do something only *if* some condition is true. Let's look at a simple example:
|
| 19 |
+
|
| 20 |
+
{caption:Our first `if` statement}
|
| 21 |
+
```miniscript
|
| 22 |
+
age = val(input("Enter your age: "))
|
| 23 |
+
if age > 23 then
|
| 24 |
+
print "Wow, you're old!"
|
| 25 |
+
end if
|
| 26 |
+
print "OK, got it."
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
Line 1 of this example should be familiar to you; it displays a prompt, waits for the user to type something and press Return, converts this to a number using `val`, and stores it in a variable called `age`.
|
| 30 |
+
|
| 31 |
+
The new bit is on line 2. It says that *if* (and *only* if!) age is greater than 23, *then* the computer should actually do line 3. If not, then the computer should just skip on down to the `end if` line.
|
| 32 |
+
|
| 33 |
+
Note how, just as with `while` and `for` loops, we indent the body of the `if` block (everything between `if` and `end if`) for clarity. But again, that indentation is like a comment; it's for the human readers of the code, and ignored by the computer. But that doesn't mean you shouldn't do it!
|
| 34 |
+
|
| 35 |
+
Also notice that there are two new keywords on line 2: `if` and `then`. An `if` statement always has both of these keywords, working together. The actual condition lies in between.
|
| 36 |
+
|
| 37 |
+
Type in the above code and run it several times, testing it with different ages. (It's totally OK to lie about your age when testing a program.)
|
| 38 |
+
|
| 39 |
+
## Doing Something Else
|
| 40 |
+
|
| 41 |
+
The above example prints an extra message when an age over 23 is entered. You may have wondered how to print a different extra message for younger users. You could do it with another `if` block, like so:
|
| 42 |
+
|
| 43 |
+
{caption:Life without `else`}
|
| 44 |
+
```miniscript
|
| 45 |
+
age = val(input("Enter your age: "))
|
| 46 |
+
if age > 23 then
|
| 47 |
+
print "Wow, you're old!"
|
| 48 |
+
end if
|
| 49 |
+
if age <= 23 then
|
| 50 |
+
print "Not so old, are you?"
|
| 51 |
+
end if
|
| 52 |
+
print "OK, got it."
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
That works, but it's a pain; we have to think about what the opposite of the original comparison is (changing `> 23` to `<= 23` in this case). Worse, if we ever change the initial `if` statement, we'll have to remember to change the second one accordingly. That's just inviting mistakes. Programming is all about making complex things easier so as to *reduce* the chance of mistakes, especially in the future.
|
| 56 |
+
|
| 57 |
+
Fortunately, there's a much better way to express what we're trying to do here, and that is the `else` statement. The word `else`, on a line all by itself, identifies code that the computer should run when the condition in the `if` statement is *not* true.
|
| 58 |
+
|
| 59 |
+
{caption:`else` to the rescue}
|
| 60 |
+
```miniscript
|
| 61 |
+
age = val(input("Enter your age: "))
|
| 62 |
+
if age > 23 then
|
| 63 |
+
print "Wow, you're old!"
|
| 64 |
+
else
|
| 65 |
+
print "Not so old, are you?"
|
| 66 |
+
end if
|
| 67 |
+
print "OK, got it."
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
This is much better! Now when the computer gets to line 2, it's going to check the age, and then print one message or the other, but never both.
|
| 71 |
+
|
| 72 |
+
## Checking Multiple Possibilities
|
| 73 |
+
|
| 74 |
+
Sometimes there are multiple possibilities you want to check for, and run code corresponding only to the one that is true. You can do this using `else if` blocks.
|
| 75 |
+
Extending the previous example, suppose we want the computer to comment on several different age ranges.
|
| 76 |
+
|
| 77 |
+
{caption:Being snarky to all ages}
|
| 78 |
+
```miniscript
|
| 79 |
+
age = val(input("Enter your age: "))
|
| 80 |
+
if age > 60 then
|
| 81 |
+
print "Distinguished indeed."
|
| 82 |
+
else if age > 23 then
|
| 83 |
+
print "Older than dirt! (Dirt's 23.)"
|
| 84 |
+
else if age > 17 then
|
| 85 |
+
print "Be sure to vote!"
|
| 86 |
+
else if age > 12 then
|
| 87 |
+
print "Ah, the teenage years."
|
| 88 |
+
else if age < 1 then
|
| 89 |
+
print "I don't think that's right."
|
| 90 |
+
else
|
| 91 |
+
print "Just a young'un!"
|
| 92 |
+
end if
|
| 93 |
+
print "Seriously though, thanks for telling me."
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
In this example there are actually four `else if` blocks, but you can have any number of these (including none at all). Here's how it works: the computer first checks the condition on the `if` statement. If that's true, then it runs the code in that very first block (line 3 in the example above), and then jumps on down to the `end if` statement, skipping the rest of the conditions. Otherwise, it goes on to check the condition in the first `else if` block. Again if the condition there is true, it runs *that* block of code and then skips to the end; otherwise it goes on checking the next `else if`, and the next, until it either finds one that applies, or reaches the `else` block (which always applies, since it doesn't have a condition).
|
| 97 |
+
|
| 98 |
+
To review, a complete `if` statement consists of:
|
| 99 |
+
|
| 100 |
+
- an `if` *condition* `then` block
|
| 101 |
+
- zero or more `else if` *condition* `then` blocks
|
| 102 |
+
- zero or one `else` block
|
| 103 |
+
- an `end if` statement
|
| 104 |
+
|
| 105 |
+
Notice that while you can have any number of `else if` blocks, you can have no more than one `else` block, and this must always come last.
|
| 106 |
+
|
| 107 |
+
Finally, be aware that just like `while` and `for` loops, `if` blocks can be nested; you can put an `if` inside another `if`. Or inside a loop. Or put a loop inside an `if`. Combine these however you like... just remember to be consistent about your indentation, so you don't get confused about what's going on.
|
| 108 |
+
|
| 109 |
+
## Single-Line If
|
| 110 |
+
{i:"single-line `if`;`if`, single-line"}
|
| 111 |
+
|
| 112 |
+
A fairly common need is to do a simple check with just one simple effect. This often comes up in input validation, that is, making maximum sense out of a human's input (humans are notoriously unreliable). Suppose you've got code that asks users for a percentage, but you just know some eager user is going to try to give you 110%, which doesn't make any sense mathematically. But you want to treat it the same as 100%. You could write:
|
| 113 |
+
|
| 114 |
+
{caption:Using three lines where one would do}
|
| 115 |
+
```miniscript
|
| 116 |
+
effort = val(input("Enter effort, in percent: "))
|
| 117 |
+
if effort > 100 then
|
| 118 |
+
effort = 100
|
| 119 |
+
end if
|
| 120 |
+
print "OK, calculating with " + effort + "%..."
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
There's nothing wrong with this. It works fine. But it will eventually become a little annoying to have to write (or read) three lines for such a simple correction. For this reason, MiniScript supports a special single-line form of the *if* statement. It looks like this (see line 2):
|
| 124 |
+
|
| 125 |
+
{caption:Single-line `if`}
|
| 126 |
+
```miniscript
|
| 127 |
+
effort = val(input("Enter effort, in percent: "))
|
| 128 |
+
if effort > 100 then effort = 100
|
| 129 |
+
print "OK, calculating with " + effort + "%..."
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
This does exactly the same thing as the previous example; it's just shorter, and easier to read and write.
|
| 133 |
+
|
| 134 |
+
To make a single-line *if* statement, simply put the (single line) of code you want to happen if the condition is true on the same line right after `then`. That's it. If you have more than one line of code to do when the condition is true, you'll need to use the standard block form instead.
|
| 135 |
+
|
| 136 |
+
You can, however, also include an `else` clause in the single-line *if*. This is less commonly needed, but might come up for example when finding the right way to pluralize a word:
|
| 137 |
+
|
| 138 |
+
{caption:Counting geese}
|
| 139 |
+
```miniscript
|
| 140 |
+
count = val(input("How many geese? "))
|
| 141 |
+
if count == 1 then n = "goose" else n = "geese"
|
| 142 |
+
print "Thanks for the " + count + " " + n + "!"
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
Type that in and try entering different numbers — in particular, be sure to try both 1 and any value other than 1. You'll see that the print statement at the end always selects the right form of the word "goose." You could certainly do the same thing with a block-form `if`/`else` statement, but it would take five lines of code instead of one. That would require more brain power to process when reading the code, whereas the single-line form is much easier to scan and say "oh, we're just picking the right form of the noun here" and move on. Minimizing the brain power needed to read the code is one of the keys of good programming.
|
| 146 |
+
|
| 147 |
+
## Breaking a Loop
|
| 148 |
+
|
| 149 |
+
Let's return now to the subject of loops, introduced yesterday. Once a loop begins, must it carry through mindlessly to completion? Is it a slave to its `for` sequence or `while` condition, condemned, like Bill Murray in *Groundhog Day*, to repeat itself over and over until the loop is fully satisfied?
|
| 150 |
+
|
| 151 |
+
{i:"`break`"}
|
| 152 |
+
Well, no. There is a way out: the `break` statement. This statement tells MiniScript to break out of the current loop, jumping to the next line past the closest `end for` or `end while` statement.
|
| 153 |
+
|
| 154 |
+
{caption:"C'mon, 1!"}
|
| 155 |
+
```miniscript
|
| 156 |
+
while true
|
| 157 |
+
roll = 1 + floor(rnd * 6)
|
| 158 |
+
print "I rolled: " + roll
|
| 159 |
+
if roll == 1 then break
|
| 160 |
+
end while
|
| 161 |
+
print "Finally rolled a 1!"
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
Look at the funny condition on this `while` statement — `while true`. That would be an infinite loop, because of course `true` can never be `false`.
|
| 165 |
+
|
| 166 |
+
{i:"infinite loop"}
|
| 167 |
+
{i:"loop, infinite"}
|
| 168 |
+
infinite loop
|
| 169 |
+
: a loop that repeats forever, or until something forcibly halts the program
|
| 170 |
+
|
| 171 |
+
But this loop does not actually repeat forever, because we've provided an escape clause in line 4: `if roll == 1 then break`. This is using the single-line `if` statement you just learned about to check whether the randomly selected value is a 1. If it is, then we execute the `break` statement, which jumps past the nearest `end while` or `end for` statement, exiting the loop.
|
| 172 |
+
|
| 173 |
+
{i:"`continue`"}
|
| 174 |
+
There is another, related statement called `continue`. Instead of skipping past the nearest `end while` or `end for` statement, it skips to the next iteration of the loop, as if that `end` line had been reached normally. For example, suppose you're writing code for a user who's afraid of the number 13, and whatever processing you do with all the other numbers, you want to skip it entirely for that one.
|
| 175 |
+
|
| 176 |
+
{caption:Triskaidekaphobia}
|
| 177 |
+
```miniscript
|
| 178 |
+
sum = 0
|
| 179 |
+
for i in range(1,20)
|
| 180 |
+
if i == 13 then continue
|
| 181 |
+
print i + ". " + "*" * i
|
| 182 |
+
sum = sum + i
|
| 183 |
+
end for
|
| 184 |
+
print "That's a total of: " + sum
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
This is an ordinary `for` loop, but on line 13, we check for the special case of `i == 13`, and when that's true, we `continue` — that is, we skip the rest of the loop body and continue with the next iteration of the loop (when `i` is 14 in this case).
|
| 188 |
+
|
| 189 |
+
This is a pretty silly example, but in real code the need for this sort of thing occurs fairly often. You might have a long `while` loop that does a lot of processing, but starts by asking the user for an input. You could check this input and if it's no good, skip the rest of the loop and continue with the next iteration. You could also check for a special input that means "I'm done" and bail out.
|
| 190 |
+
|
| 191 |
+
{caption:Common while-loop input handling}
|
| 192 |
+
```miniscript
|
| 193 |
+
while true
|
| 194 |
+
inp = input("Enter a value (0 to exit): ")
|
| 195 |
+
if inp == "0" then break
|
| 196 |
+
if val(inp) < 1 or val(inp) > 100 then
|
| 197 |
+
print "Please keep your values between 1 and 100."
|
| 198 |
+
continue
|
| 199 |
+
end if
|
| 200 |
+
print "...OK... doing big complex processing with " + inp + "..."
|
| 201 |
+
end while
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
Just imagine that line 8 in the example above is actually a couple dozen lines long, and you may see why bailing out at the top of the loop is better than putting all that code inside a giant `if` block. (Remember, the goal isn't to write code the computer can understand... it's to write code a *human* can understand, and with as little effort as possible!)
|
| 205 |
+
|
| 206 |
+
As a final example, here's a program that may actually be useful. It allows you to encode and decode messages in a cipher called "ROT-13." In this cipher, every letter in the alphabet is rotated 13 places, so A maps to N, B maps to O, etc. Because the alphabet is exactly 26 letters long, a 13-letter rotation also does the inverse mapping (N maps to A, O maps to B, and so on). So, with this one program, you can either enter a plain-text message and get back the encoded version, or enter an encoded message to decode it.
|
| 207 |
+
|
| 208 |
+
{width:"75%"}
|
| 209 |
+

|
| 210 |
+
|
| 211 |
+
{caption:ROT-13 secret message encoder/decoder}
|
| 212 |
+
```miniscript
|
| 213 |
+
while true
|
| 214 |
+
msg = input("Enter your message: ")
|
| 215 |
+
if msg == "" then break
|
| 216 |
+
result = ""
|
| 217 |
+
for i in range(0, msg.len - 1)
|
| 218 |
+
c = msg[i] // gets the i'th letter of msg, starting at 0.
|
| 219 |
+
if c >= "A" and c <= "Z" then
|
| 220 |
+
letterNum = c.code - "A".code // A=0, B=1, etc.
|
| 221 |
+
letterNum = (letterNum + 13) % 26 // 1->14, 2->15...
|
| 222 |
+
result = result + char("A".code + letterNum) // 0->A...
|
| 223 |
+
else if c >= "a" and c <= "z" then
|
| 224 |
+
letterNum = c.code - "a".code // a=0, b=1, etc.
|
| 225 |
+
letterNum = (letterNum + 13) % 26 // 1->14, 2->15...
|
| 226 |
+
result = result + char("a".code + letterNum) // 0->a...
|
| 227 |
+
else
|
| 228 |
+
// not a letter; copy to the output as-is
|
| 229 |
+
result = result + c
|
| 230 |
+
end if
|
| 231 |
+
end for
|
| 232 |
+
print result
|
| 233 |
+
end while
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
Notice how there is a main `while` loop that runs forever, but we break out of it (on line 3) if the user enters an empty string. Then within the `for` loop that iterates over each character of the message, we have an `if`/`else if`/`else` block that checks for several possibilities: the character is an upper-case letter (lines 7-10), or a lower-case letter (lines 11-14), or anything else (lines 15-17).
|
| 237 |
+
|
| 238 |
+
Enter this code carefully, and confirm that it works by entering a message, and then copying the encoded message and pasting it back as your next input, which should produce the original message. Use this to send secret messages over email or social media! And then when you're done, just press Return without typing in anything, and the program will neatly exit.
|
| 239 |
+
|
| 240 |
+
{pageBreak}
|
| 241 |
+
A> **Chapter Review**
|
| 242 |
+
A> - You learned how to use `if`, with optional `else if` and `else` blocks, to make a program do different things depending on the data.
|
| 243 |
+
A> - You can use a single-line `if` or `if`/`else` for very short checks.
|
| 244 |
+
A> - You learned how to break out of a loop with `break`, or skip to the next iteration with `continue`.
|
| 245 |
+
|
data/day7.txt
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 7: Three Small Games", startingPageNum:63}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> The only way to learn a new programming language is by writing programs in it.
|
| 7 |
+
Q>— Dennis Ritchie (creator of C programming language)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Rest and recouperate.
|
| 11 |
+
A> - Enter and play with some simple-but-fun MiniScript games.
|
| 12 |
+
A> - Review and synthesize what you've learned so far.
|
| 13 |
+
|
| 14 |
+
If you've been doing one chapter a day, then it's been a week since you started on your journey to programming mastery. If you've been doing the chapters faster or slower than that, that's fine too. In any case, it's time to pause and let it sink in.
|
| 15 |
+
|
| 16 |
+
A great way to help it sink in is to type in some short programs. In our modern world of scrolling through social media posts and picking responses from suggestions made by AI, you will be tempted to skip this exercise. Don't! Typing in code is crucial to learning how to write your own code. It's like having an expert trainer help you to move your body correctly as you learn dance or martial arts. But in this case, the muscles being moved are in your brain.
|
| 17 |
+
|
| 18 |
+
So in this chapter are three small games. Why games? First, games are fun. But more importantly, games like these are *easy*; they represent a world of simplified, well-defined rules that can be converted into code. With only six chapters behind us, our toolset is still a bit limited. We haven't learned about lists, maps, or functions yet, so we have to keep things simple. In a few more weeks, you'll be able to create simulations that provide deep insight into science or business, analysis programs that crunch numbers or graph data, programs that create music or art, and much more. So if games aren't your cup of tea, be patient — the skills you practice here will be useful for other kinds of coding too.
|
| 19 |
+
|
| 20 |
+
## The Matchstick Game
|
| 21 |
+
|
| 22 |
+
First up is the matchstick game. This is a classic numbers game for two players. You start with a pile of matchsticks between you, and then take turns removing one, two, or three matchsticks from the pile. Whoever takes the last matchstick loses. The skill in this game is to think ahead and try to force your opponent to take the last matchstick.
|
| 23 |
+
|
| 24 |
+
Our implementation here pits you, the human player, against the computer! Here's the code — only 40 lines long. Type it in and take it for a spin. If you get any errors, compare your code carefully to the code below. If you are still getting errors, check the troubleshooting section at the end of this chapter.
|
| 25 |
+
|
| 26 |
+
{caption:Matchstick Game}
|
| 27 |
+
```miniscript
|
| 28 |
+
// Matchstick Game
|
| 29 |
+
qty = 15
|
| 30 |
+
while qty > 0
|
| 31 |
+
// Human player's turn.
|
| 32 |
+
// Print how many matchsticks there are.
|
| 33 |
+
if qty == 1 then
|
| 34 |
+
print "There is one matchstick left."
|
| 35 |
+
else
|
| 36 |
+
print "There are " + qty + " matchsticks."
|
| 37 |
+
end if
|
| 38 |
+
// Ask the player how many to take.
|
| 39 |
+
take = 0
|
| 40 |
+
while take < 1 or take > 3 or qty - take < 0
|
| 41 |
+
take = round(val(input("How many do you take? ")))
|
| 42 |
+
end while
|
| 43 |
+
// Update the quantity left, and check for game-over.
|
| 44 |
+
qty = qty - take
|
| 45 |
+
if qty == 0 then
|
| 46 |
+
print "You took the last matchstick. I win! :)"
|
| 47 |
+
break
|
| 48 |
+
end if
|
| 49 |
+
|
| 50 |
+
// Computer player's turn.
|
| 51 |
+
// Print how many matchsticks there are now.
|
| 52 |
+
if qty == 1 then
|
| 53 |
+
print "That leaves just one matchstick."
|
| 54 |
+
print "I guess I have to take it. You win!"
|
| 55 |
+
break
|
| 56 |
+
else
|
| 57 |
+
print "That leaves " + qty + " matchsticks."
|
| 58 |
+
end if
|
| 59 |
+
// Calculate how many the computer should take.
|
| 60 |
+
take = (qty - 1) % 4
|
| 61 |
+
if take == 0 then take = 3
|
| 62 |
+
if rnd < 0.2 then take = ceil(rnd * 3) // occasional mistake
|
| 63 |
+
print "I'll take " + take + "."
|
| 64 |
+
// Update the quantity.
|
| 65 |
+
qty = qty - take
|
| 66 |
+
if qty == 0 then print "Oops. You win!"
|
| 67 |
+
end while
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
Most of this code should be pretty clear to you by now. There's a main `while` loop, as in most interactive programs. This begins by printing out the current state of the game on lines 6-10. Then we ask (with `input`) how many matchsticks you want to take. Notice how we use a little `while` loop around that to keep asking until we get a valid input (lines 12-15).
|
| 71 |
+
|
| 72 |
+
The second half of the main loop does the computer's turn. It begins by again printing the current state. Then on lines 33-35, we do a bit of mathematical wizardry to figure out how many matchsticks the computer should take. Let's pause and study how that works.
|
| 73 |
+
|
| 74 |
+
The computer's goal is to leave only 1 matchstick, forcing the player to take it. So if there are 2 sticks left, the computer should take 1; if there are 3 it should take 2, etc. In general, if `qty` (the number of matchsticks left) is a small number, the computer should take `qty - 1`. That explains the first part of line 33.
|
| 75 |
+
|
| 76 |
+
This works up to 4, since 4 - 3 is 1, a valid number of matchsticks to take. What if there's more than that? Well, if there are 5 matchsticks left, then the computer is out of luck. No matter how many it takes, the human can take all but one of the remainder. But this works both ways; if the computer can stick the human with 5, then it can win no matter what the human does. So the computer should take 1 when `qty = 6`, 2 when `qty = 7`, etc. If you keep working this out, the correct number of matchsticks to take repeats every 4 numbers.
|
| 77 |
+
|
| 78 |
+
Whenever you have a sequence that repeats every so-many numbers, it's a hint to use the mod (`%`) operator. Mod is the remainder after division. In this case, we want the remainder after dividing by 4. Let's work through an example: if `qty = 6`, then `qty - 1` is 5, and `5 % 4`, the remainder after dividing 5 by 4, is 1. So the computer takes 1 matchstick, leaving the player with 5, from which the player cannot win. It works!
|
| 79 |
+
|
| 80 |
+
The only hitch in this formula is that sometimes the remainder after dividing by 4 is 0. This is true when `qty - 1` is 4, 8, 12, etc. Taking 0 sticks is not a legal move. These are the no-win situations for the computer; it doesn't really matter what we do in this case, but to keep the game moving along, we have the computer take 3 matchsticks in this case (line 34).
|
| 81 |
+
|
| 82 |
+
If all this math is still unclear, don't worry about it. It's not the programming that's tricky; it's the math! And eventually, programming will make math easier. For now it's OK to just take these formulas on authority and enjoy the game.
|
| 83 |
+
|
| 84 |
+
Finally, note that the computer would play a perfect game if not for line 35. That generates a random number between 0 and 1, and if this is less than 0.2 (i.e., 20% of the time), it makes a random move instead of the ideal move. This causes the computer to make occasional mistakes, giving the poor human a chance to win. Feel free to change that 0.2 to other values, to make the computer smarter or dumber.
|
| 85 |
+
|
| 86 |
+
**Challenge:** Change line 34 so that when the computer is in a tight spot, instead of always taking 3 matchsticks, it randomly takes 1, 2, or 3. This makes the game less predictable and more interesting for a good human player.
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
## The Bit-Flip Game
|
| 90 |
+
|
| 91 |
+
Next up is a fun little logic puzzle. Nine bits are arranged in three rows and three columns. You can think of these as coins, or Othello pieces that are black on one side and white on the other, or cards that are face up or down. But since we're doing this on a computer, they're just bits, each with a value of 0 or 1.
|
| 92 |
+
|
| 93 |
+
The bits start out all 0, and your goal is to change them all to 1. On each move, you pick a row and column. All the bits that match your row or column are flipped: 1 becomes 0, and 0 becomes 1. Can you find a sequence of moves that gets all the bits to be 1?
|
| 94 |
+
|
| 95 |
+
{caption:Bit-Flip Game}
|
| 96 |
+
```miniscript
|
| 97 |
+
b0A = 0 // bit in column 0, row A
|
| 98 |
+
b0B = 0 // bit in column 0, row B
|
| 99 |
+
b0C = 0 // (etc.)
|
| 100 |
+
b1A = 0
|
| 101 |
+
b1B = 0
|
| 102 |
+
b1C = 0
|
| 103 |
+
b2A = 0
|
| 104 |
+
b2B = 0
|
| 105 |
+
b2C = 0
|
| 106 |
+
print "Can you flip the all bits to 1?"
|
| 107 |
+
print
|
| 108 |
+
while true
|
| 109 |
+
print "Bit: "
|
| 110 |
+
print " A: " + b0A + " " + b1A + " " + b2A
|
| 111 |
+
print " B: " + b0B + " " + b1B + " " + b2B
|
| 112 |
+
print " C: " + b0C + " " + b1C + " " + b2C
|
| 113 |
+
print " - - -"
|
| 114 |
+
print " 0 1 2"
|
| 115 |
+
print
|
| 116 |
+
if b0A + b0B + b0C + b1A + b1B + b1C + b2A + b2B + b2C == 9 then
|
| 117 |
+
print "You win!"
|
| 118 |
+
break
|
| 119 |
+
end if
|
| 120 |
+
cmd = input("Which row and column to flip (e.g. A0)? ").upper
|
| 121 |
+
if cmd.len != 2 then continue
|
| 122 |
+
row = cmd[0]
|
| 123 |
+
col = val(cmd[1])
|
| 124 |
+
if col == 0 then
|
| 125 |
+
b0A = 1 - b0A
|
| 126 |
+
b0B = 1 - b0B
|
| 127 |
+
b0C = 1 - b0C
|
| 128 |
+
else if col == 1 then
|
| 129 |
+
b1A = 1 - b1A
|
| 130 |
+
b1B = 1 - b1B
|
| 131 |
+
b1C = 1 - b1C
|
| 132 |
+
else if col == 2 then
|
| 133 |
+
b2A = 1 - b2A
|
| 134 |
+
b2B = 1 - b2B
|
| 135 |
+
b2C = 1 - b2C
|
| 136 |
+
end if
|
| 137 |
+
if row == "A" then
|
| 138 |
+
if col != 0 then b0A = 1 - b0A
|
| 139 |
+
if col != 1 then b1A = 1 - b1A
|
| 140 |
+
if col != 2 then b2A = 1 - b2A
|
| 141 |
+
else if row == "B" then
|
| 142 |
+
if col != 0 then b0B = 1 - b0B
|
| 143 |
+
if col != 1 then b1B = 1 - b1B
|
| 144 |
+
if col != 2 then b2B = 1 - b2B
|
| 145 |
+
else if row == "C" then
|
| 146 |
+
if col != 0 then b0C = 1 - b0C
|
| 147 |
+
if col != 1 then b1C = 1 - b1C
|
| 148 |
+
if col != 2 then b2C = 1 - b2C
|
| 149 |
+
end if
|
| 150 |
+
end while
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
The logic in this game is straightforward. Notice that our main loop in this program is using `while true`, with a `break` when the game is over (line 22). We get the user's input on line 24, and if it's not 2 characters long, use `continue` to jump back to the top of the loop.
|
| 154 |
+
|
| 155 |
+
The rest of the main loop flips the appropriate set of bits. There is an `if`/`else if` structure for the column (lines 28-40), and another one for the row (lines 41-53). Note that there is one bit that matches the column *and* the row — i.e., the one at the exact coordinates you enter. We don't want to flip that one twice. So as we're working on the row, we also check (using single-line `if` statements) to be sure we skip the entered column.
|
| 156 |
+
|
| 157 |
+
**Challenge:** The code given above gets the job done and exercises some important variations on the `if` statement. But there is another way to do it. Lines 28-53 could be replaced with nine lines, each checking for a particular row and column, like this:
|
| 158 |
+
|
| 159 |
+
```miniscript
|
| 160 |
+
if row == "A" or col == 0 then b0A = 1 - b0A
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
Delete lines 28-53, and replace them with the line above, which handles position A0, and eight similar lines to handle the other eight positions. Verify that the game still works!
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
## Pig Dice Game
|
| 167 |
+
|
| 168 |
+
The last game for this chapter is another computer-versus-human game. This one involves rolling dice. On each player's turn, a six-sided die is rolled. If the player rolls a 1, their turn is over and they get no points for that turn. If they roll 2 to 6, they get that many points added to their total for the turn. At this point they face a choice: end their turn and add their current total to their score; or roll again, potentially getting even more points, but risk getting a 1 and losing all their points for the turn. This continues until the player either chooses to stop, or rolls a 1.
|
| 169 |
+
|
| 170 |
+
In either case, play then passes to the other player. The first player to reach the goal (32 points in this version) wins the game.
|
| 171 |
+
|
| 172 |
+
{width:"50%"}
|
| 173 |
+

|
| 174 |
+
|
| 175 |
+
{caption:Pig Dice Game}
|
| 176 |
+
```miniscript
|
| 177 |
+
// Pig Dice game
|
| 178 |
+
human = 0
|
| 179 |
+
computer = 0
|
| 180 |
+
goal = 32
|
| 181 |
+
print "Let's play Pig to " + goal + " points!"
|
| 182 |
+
while human < goal and computer < goal
|
| 183 |
+
// Human player's turn
|
| 184 |
+
print
|
| 185 |
+
print "Your turn! (You: " + human + " Me: " + computer + ")"
|
| 186 |
+
rollTotal = 0
|
| 187 |
+
choice = "R"
|
| 188 |
+
while choice != "D"
|
| 189 |
+
if choice == "R" then // roll!
|
| 190 |
+
wait
|
| 191 |
+
roll = ceil(rnd * 6)
|
| 192 |
+
if roll == 1 then
|
| 193 |
+
print "You roll a 1. No points for you!"
|
| 194 |
+
rollTotal = 0
|
| 195 |
+
break
|
| 196 |
+
end if
|
| 197 |
+
rollTotal = rollTotal + roll
|
| 198 |
+
print "Your roll: " + roll + ", total: " + rollTotal
|
| 199 |
+
end if
|
| 200 |
+
choice = input("[R]oll again, or [D]one? ")
|
| 201 |
+
choice = choice.upper
|
| 202 |
+
end while
|
| 203 |
+
human = human + rollTotal
|
| 204 |
+
print "You gain " + rollTotal + " points, and now have: " + human
|
| 205 |
+
if human >= goal then break
|
| 206 |
+
|
| 207 |
+
// Computer's turn
|
| 208 |
+
print
|
| 209 |
+
print "My turn! (You: " + human + " Me: " + computer + ")"
|
| 210 |
+
rollTotal = 0
|
| 211 |
+
while true
|
| 212 |
+
wait
|
| 213 |
+
roll = ceil(rnd * 6)
|
| 214 |
+
if roll == 1 then
|
| 215 |
+
print "I roll a 1. Darn!"
|
| 216 |
+
rollTotal = 0
|
| 217 |
+
break
|
| 218 |
+
end if
|
| 219 |
+
rollTotal = rollTotal + roll
|
| 220 |
+
print "My roll: " + roll + ", total: " + rollTotal
|
| 221 |
+
if rnd * 20 < rollTotal then
|
| 222 |
+
print "That's enough for me."
|
| 223 |
+
break
|
| 224 |
+
end if
|
| 225 |
+
print "I'll roll again."
|
| 226 |
+
end while
|
| 227 |
+
computer = computer + rollTotal
|
| 228 |
+
print "I gain " + rollTotal + " points, and now have: " + computer
|
| 229 |
+
|
| 230 |
+
end while
|
| 231 |
+
|
| 232 |
+
print
|
| 233 |
+
print "Final scores: You: " + human + " Me: " + computer
|
| 234 |
+
if human > computer then
|
| 235 |
+
print "You win. Well played!"
|
| 236 |
+
else
|
| 237 |
+
print "I win. Good game!"
|
| 238 |
+
end if
|
| 239 |
+
```
|
| 240 |
+
|
| 241 |
+
As usual, there's a main `while` loop here. Within that, we have a section of code for the human player, using another `while` loop to let the player roll as many times as they like until they stop or get a 1. Notice how the `break` statement on line 19 breaks out of this inner loop.
|
| 242 |
+
|
| 243 |
+
Then we have a similar section of code for the computer player. The AI (artificial intelligence) here is on line 45: the computer decides to stop when `rnd * 20 < rollTotal`. The formula `rnd * 20` picks a random number between 0 and 20. So when the computer's total roll is rather small, it's likely to roll again. When the total for the turn is 10, it has a 50% chance of stopping. And once the roll total is 20 or more, the computer is guaranteed to stop.
|
| 244 |
+
|
| 245 |
+
Play the game a few times and see how often you can win. It's not easy!
|
| 246 |
+
|
| 247 |
+
**Challenge:** the rule used on line 45 is certainly not optimal; it always plays the same, regardless of whether it's ahead or behind. A smarter player might play more aggressively when behind, and more conservatively when ahead. Change the code so that it first picks a `target` value, equal to 10 if `computer > human`, or 25 otherwise. Then use `rnd * target` instead of `rnd * 20` when deciding whether to roll again.
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
## Troubleshooting
|
| 251 |
+
|
| 252 |
+
If you got errors or incorrect behavior in any of the programs above, start by comparing your code carefully to what's in the book. Here are some common mistakes to watch out for:
|
| 253 |
+
|
| 254 |
+
- Be sure you've used the correct capitalization. Remember that MiniScript is case-sensitive. So check for places you may have typed `RollTotal` or `rolltotal` rather than `rollTotal`, for example.
|
| 255 |
+
|
| 256 |
+
- Check that every `if` statement has a `then`, and unless it's a single-line `if`, it should also have a matching `end if` statement.
|
| 257 |
+
|
| 258 |
+
- Check that every `while` has a matching `end while`.
|
| 259 |
+
|
| 260 |
+
- Be sure every open parenthesis `(` has a matching close parenthesis `)`.
|
| 261 |
+
|
| 262 |
+
- Make sure your quotation marks are balanced. Every string must have quotation marks at the beginning, and quotation marks at the end.
|
| 263 |
+
|
| 264 |
+
- Some text editors may try to apply "smart quotes," that is, quotation marks that curl towards the text they enclose. Those will not work with MiniScript (or any other programming language I've used). You need to use the straight kind, like `"`. If you're running into this problem, find the option to turn off smart quotes, or use a different text editor.
|
| 265 |
+
|
| 266 |
+
- Make sure any tests for equality are using two equal signs, `==` instead of `=`. If you get an error like "got OpAssign where Keyword(then) is required", you made this mistake (and now you know how to fix it).
|
| 267 |
+
|
| 268 |
+
- The Bit-Flip Game uses some square brackets on lines 26 and 27, to get to the first and second characters of the player's input. Double-check that you're using square brackets and parentheses exactly as shown.
|
| 269 |
+
|
| 270 |
+
{pageBreak}
|
| 271 |
+
A> **Chapter Review**
|
| 272 |
+
A> - You entered and debugged several real programs that do interesting things.
|
| 273 |
+
A> - You practiced using variables, assignment, `if` blocks, and `while` loops.
|
| 274 |
+
A> - You exercised your coding muscles, laying down brain pathways through which magic will one day flow. Savor this accomplishment. You are well on your way!
|
| 275 |
+
|
| 276 |
+
|
data/day8.txt
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 8: Command-Line MiniScript", startingPageNum:75}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> Ah, the command line. This is the interface of a Programmer.
|
| 7 |
+
Q> Not as clumsy or random as a GUI...
|
| 8 |
+
Q> An elegant interface for a more civilized age.
|
| 9 |
+
Q>— Obi-wan Codonly
|
| 10 |
+
|
| 11 |
+
A> **Chapter Objectives**
|
| 12 |
+
A> - Install command-line MiniScript on your computer.
|
| 13 |
+
A> - Learn about a Read-Eval-Print Loop, and how it makes coding even more fun and interactive.
|
| 14 |
+
A> - Learn how to represent and work with a list of data.
|
| 15 |
+
A> - Realize that a programming language may be used in different environments, but your knowledge still applies.
|
| 16 |
+
|
| 17 |
+
For many readers, all code written this point has been run in the MiniScript *Try-It!* web page. However, that is only one way to run MiniScript code; there are many others.
|
| 18 |
+
|
| 19 |
+
In the beginning it is very easy to confuse the *programming language* with the *development environment* you are using.
|
| 20 |
+
|
| 21 |
+
programming language
|
| 22 |
+
: A formal language used to specify a computer program, e.g., MiniScript
|
| 23 |
+
|
| 24 |
+
development environment
|
| 25 |
+
: A software application that provides a programming language and related tools, such as a code editor and libraries of extra intrinsic functions. E.g., the Try-It! web page, command-line MiniScript, and Mini Micro
|
| 26 |
+
|
| 27 |
+
The great thing is, your knowledge of the language from one environment applies equally well in other environments. Yet each one provides unique new capabilities. Today you're going to add a second MiniScript environment to your tool set.
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
## Command-Line MiniScript
|
| 31 |
+
|
| 32 |
+
{i: "MiniScript, command-line;command-line MiniScript"}
|
| 33 |
+
Today's computers use a graphical user interface (GUI) of buttons, menus, and other widgets, manipulated more with a mouse or touch screen than by typing. However, on desktop computers at least, there is still a command line available to power users such as yourself.
|
| 34 |
+
|
| 35 |
+
command line
|
| 36 |
+
: a user interface based around typing commands and getting interactive results
|
| 37 |
+
|
| 38 |
+
To someone raised on a GUI, the command line might seem old-fashioned. But there are many power users today who rely on it heavily. With practice, complex operations can be carried out efficiently with a command line that would take much longer (or in some cases be impossible to do at all) with pointing and clicking. The command line is especially important (and useful) to a programmer. So this week, let's install and explore the command-line version of MiniScript.
|
| 39 |
+
|
| 40 |
+
Unfortunately, the details of how to find and use the command line are a bit different depending on what kind of computer you use. We'll cover here the three main varieties of desktop platforms: Windows, Mac OS, and Linux.
|
| 41 |
+
|
| 42 |
+
{pageBreak}
|
| 43 |
+
### Windows
|
| 44 |
+
|
| 45 |
+
On a Windows computer, the standard command line is called `cmd` (short for "Command Prompt"). The easiest way to get to it is probably: (1) click on `Start` in the lower-left corner of your screen; (2) type `cmd` and press Enter.
|
| 46 |
+
|
| 47 |
+
If you type "Windows command line" or "how to use Windows cmd" into your favorite web search engine, you will probably find some great introductory resources. The main commands you should pay attention to are `dir` (directory, i.e. list files for the folder you are in) and `cd` (change directory, i.e. move to a different folder).
|
| 48 |
+
|
| 49 |
+
Once you have mastered those, you are ready to download and use command-line MiniScript. Point your web browser to <https://miniscript.org/cmdline/>, and click the link for "miniscript-win.zip". This should download the zip archive, probably into your Downloads folder. Find that file in Windows Explorer, select it, and press the "Extract All" button. This should result in a file called `miniscript.exe` (though in Explorer, file extensions are normally hidden, so it may appear as simply "miniscript").
|
| 50 |
+
|
| 51 |
+
Now go back to Command Prompt, navigate to that directory using the "cd" command, and run miniscript by typing `miniscript.exe` and pressing Enter. If all goes well, you should see the word "MiniScript" followed by some version information, and a ">" prompt, as shown in the image below.
|
| 52 |
+
|
| 53 |
+
{width:"75%"}
|
| 54 |
+

|
| 55 |
+
|
| 56 |
+
Chances are good, however, that all will *not* go well, and Windows will instead decide that MiniScript is a "threat" (because it can execute commands), and quarantine the file, removing it from the folder where you had it and tucking it away in some hidden location. The exact steps you follow to fix this may vary slightly depending on what version of Windows you're running, but here's the procedure for Windows 10:
|
| 57 |
+
|
| 58 |
+
1. Open **Windows Security** (again from the Start menu).
|
| 59 |
+
2. Click on **Virus & threat protection**, and then on **Protection history** (or **Threat history**).
|
| 60 |
+
3. In the filter pop-up, select **Quarantined items**.
|
| 61 |
+
4. Click miniscript.exe, and then click **Restore**.
|
| 62 |
+
|
| 63 |
+
This should both restore the file, and tell Windows that this particular file is OK and not actually a threat.
|
| 64 |
+
|
| 65 |
+
Once you've done all that, you should be able to run `miniscript.exe`, and get a result like the above. Once you see that MiniScript header and version info, you're ready to go!
|
| 66 |
+
|
| 67 |
+
Finally, it should be noted that there are alternatives to the built-in Command Line app for Windows. Terminal is a popular one, as is the somewhat older PowerShell; both are from Microsoft and available in the Microsoft Store. If you're already using one of these alternatives, feel free to continue using it with MiniScript. Otherwise, Command Line is perfectly adequate for now, and you can always move to something else if you feel the need later.
|
| 68 |
+
|
| 69 |
+
### MacOS
|
| 70 |
+
|
| 71 |
+
The procedure on a Mac is similar to on Windows. The app you'll want to use is called Terminal, and can be launched via Spotlight, or directly from Applications/Utilities. If you're new to Terminal, do a search for "mac useful terminal commands," and read an article or two. There are plenty of good resources on this very useful tool.
|
| 72 |
+
|
| 73 |
+
Now you're ready to download and use command-line MiniScript. Point your web browser to <https://miniscript.org/cmdline/>, and click the link for "miniscript-mac.zip". This should download the zip archive, probably into your Downloads folder. Find that file in Finder, and double-click it to unzip. This should result in a file called `MiniScript`. Finally, double-click that new MiniScript file to launch it in Terminal.
|
| 74 |
+
|
| 75 |
+
At this point, chances are Finder is going to get cranky, with a message along the lines of "MiniScript can't be opened because it is from an unidentified developer." If that happens, click OK to dismiss the alert, then right-click MiniScript and choose "Open" from the contextual menu. You'll get a similar alert, but this time there will be an "Open" button. Click that, and Finder will remember that it's OK to run this program.
|
| 76 |
+
|
| 77 |
+
The result should look similar to the image below.
|
| 78 |
+
|
| 79 |
+
{width:"75%"}
|
| 80 |
+

|
| 81 |
+
|
| 82 |
+
Note that double-clicking the executable is not the only way to launch it; you can also open a Terminal window yourself, use `cd` to navigate to the folder containing MiniScript, and then enter `./MiniScript` to run it. This does essentially the same thing.
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
### Linux
|
| 86 |
+
|
| 87 |
+
If you're a Linux user, chances are extremely high that you don't need me telling you how to use the command line — you probably know more about it than I do! Just download the gzipped Linux binary from <https://miniscript.org/cmdline/>, unpack it, and put it somewhere in your search path. Then invoke it by name, like any other command-line tool.
|
| 88 |
+
|
| 89 |
+
Some Linux users prefer to build their software from the source code. If that describes you, you can find a link on the MiniScript home page to the source code repository. The build process is pretty straightforward, and explained in the README file in the MiniScript-cpp directory.
|
| 90 |
+
|
| 91 |
+
### Trouble-Shooting
|
| 92 |
+
|
| 93 |
+
For many readers, this will be the first time you have ever tried to install and run a command-line program. With all the variations on operating systems out there, and these systems' (quite justified) concern for security, doing this can be tricky, and it's possible something has gone wrong. But this is an important step, so if you've run into a roadblock, don't give up!
|
| 94 |
+
|
| 95 |
+
You may have someone in your home or office who has more experience with this sort of thing; show them what you're trying to do, and they may be able to help. Or, failing that, come to the MiniScript forums or Discord server (both reachable via <https://miniscript.org/>). We'll work together to get you unstuck. Command-line MiniScript, and for that matter the command line itself, are powerful tools you will want in your toolbox.
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
## The Read-Eval-Print Loop
|
| 99 |
+
|
| 100 |
+
{i:"prompt"}
|
| 101 |
+
Once you've got MiniScript running, you should be looking at a blinky cursor next to a ">" prompt. Now what? ...Now the fun begins!
|
| 102 |
+
|
| 103 |
+
{i:"REPL, defined"}
|
| 104 |
+
That prompt and cursor represent something called a read-eval-print loop, or REPL for short. That's a fancy way of saying that you can type and run code here interactively, as MiniScript itself will
|
| 105 |
+
|
| 106 |
+
- **Read** input from the user,
|
| 107 |
+
- **Evaluate** the expression or command entered,
|
| 108 |
+
- **Print** the results, and
|
| 109 |
+
- repeat (i.e. **Loop**) until told to quit.
|
| 110 |
+
|
| 111 |
+
Try it! At the prompt, type
|
| 112 |
+
|
| 113 |
+
```terminal
|
| 114 |
+
> 6*7
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
and press Return or Enter. (Note that when examples are shown with a faint REPL prompt, like the `>` above, you don't type that; only type what comes after.) MiniScript immediately responds with
|
| 118 |
+
|
| 119 |
+
```repl
|
| 120 |
+
42
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
and then displays the ">" prompt again, waiting for your next command. That `6*7` you typed in was MiniScript code. You didn't need to use `print` here because that's a built-in function of the read-eval-print loop; it evaluated your MiniScript expression, `6*7`, and printed the result automatically.
|
| 124 |
+
|
| 125 |
+
Prove that this is more than just a calculator by trying something a little more complex:
|
| 126 |
+
|
| 127 |
+
```terminal
|
| 128 |
+
> ceil(6*rnd) + ceil(6*rnd)
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
This simulates rolling two dice. I can't say exactly what the output will be, except that it will be between 2 and 12, and most likely closer to 7! Here's your first power-user trick on the command line: *press the up-arrow key*, and the previous command should reappear on the prompt, with the cursor at the end. You can just press Enter or Return at this point to execute the same command again. Do this up-arrow/return trick several times, rolling the dice multiple times to confirm that the result really is random (and more importantly, to learn how to repeat previous commands).
|
| 132 |
+
|
| 133 |
+
The command-line environment supports all the same MiniScript powers you know from the Try-It page, and then some. This includes variables, `print` and `input`, `wait`, loops, and so on. Carefully type in the following:
|
| 134 |
+
|
| 135 |
+
```miniscript
|
| 136 |
+
for i in range(10, 1)
|
| 137 |
+
print i + "..."
|
| 138 |
+
wait
|
| 139 |
+
end for
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
But hold on — something different happened after the "for" line, didn't it? The prompt changed from ">" to ">>>". This is the REPL's way of acknowledging that your input is not yet finished (because you have started a `for` loop, but not yet ended it). As you're typing this code, it actually looks like this:
|
| 143 |
+
|
| 144 |
+
```terminal
|
| 145 |
+
> for i in range(10, 1)
|
| 146 |
+
>>> print i + "..."
|
| 147 |
+
>>> wait
|
| 148 |
+
>>> end for
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
You may also notice that the statements inside the loop, `print` and `wait` in this example, don't do anything as soon as you type them. Only after you finish with the `end for` does the whole loop run and do whatever it does.
|
| 152 |
+
|
| 153 |
+
Now, let's see what happens if things get out of control. Here's an infinite loop. Don't panic!
|
| 154 |
+
|
| 155 |
+
```miniscript
|
| 156 |
+
i = 0
|
| 157 |
+
while true
|
| 158 |
+
i = i + 1
|
| 159 |
+
print i
|
| 160 |
+
end while
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
{i:"control-C"}
|
| 164 |
+
Woo! MiniScript starts printing numbers very fast, with no sign of stopping. Fortunately *you* are the programmer; you are in charge! Hold the Control key down and then press the C key (i.e., the key combination called control-C). MiniScript stops and exits. This leaves you either at the command prompt, or (if you launched MiniScript directly from Finder) back in Finder. Just relaunch it the same way you did before, and you'll have a fresh clean REPL, ready to continue.
|
| 165 |
+
|
| 166 |
+
It can sometimes happen that you make a mistake in entering some code in the REPL, and don't catch it until you've already pressed Return. There's no going back to edit something already entered; but you can often just replace a previous result with a new one (i.e., assign a new value to a variable if you made a mistake on a previous assignment). If you make a mistake inside a `for`, `while`, or `if` block, you can usually just enter the corresponding `end` statement to finish the block and get back to a ">" prompt where you can try again. But if all else fails, Control-C will always bail out and let you start over.
|
| 167 |
+
|
| 168 |
+
Obviously the REPL is not a great way to enter long programs. We'll be learning tomorrow how to use command-line MiniScript with programs stored in text files, which is better for writing more than a few lines of code. What's great about a REPL is that it is a very fast, very *interactive* way of experimenting with code. When you put this book down, stretch your wings, and start to fly on your own, you will very often pause and say, "I *think* I know how to do that, but does that actually work?" At those times, if you have the MiniScript REPL at hand, you can very quickly try out your idea and see if it works. If it does not, you can try a slightly different variation, often using up-arrow to recall and modify a previous command. This process is extremely fast, even more so than the Try-It! page... and it is also a lot of fun.
|
| 169 |
+
|
| 170 |
+
So, for the rest of this chapter, let's work exclusively in the REPL, while we learn about lists.
|
| 171 |
+
|
| 172 |
+
## Lists
|
| 173 |
+
|
| 174 |
+
You know that there are several different types of data in MiniScript. So far, we've talked about numbers (e.g. 42) and strings (e.g. "Hello World"). It's time to introduce a third data type: lists.
|
| 175 |
+
|
| 176 |
+
{i:"data type, list"}
|
| 177 |
+
list
|
| 178 |
+
: a data type that is an ordered sequence of other data
|
| 179 |
+
|
| 180 |
+
Lists in MiniScript appear in square brackets, with their elements separated with commas. You can assign these to variables, pass them into functions, and generally handle them just like you would numbers and strings.
|
| 181 |
+
|
| 182 |
+
{caption:"List Example 1"}
|
| 183 |
+
```terminal
|
| 184 |
+
> a = [1, 2, "x"]
|
| 185 |
+
> b = ["foo", 42]
|
| 186 |
+
> c = a + b
|
| 187 |
+
> print c
|
| 188 |
+
[1, 2, "x", "foo", 42]
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
In this example, line 1 creates a list with three elements — the numbers 1 and 2, and the string "x" — and assigns this to variable `a`. Line 2 creates a similar list `b` with two elements. Then line 3 adds these together and stores the result in `c`. Lists support addition (`+`), replication (`*`), and division (`/`) in the same way as strings. That is, `+` joins two lists together; `*` repeats a list some number of times; and `\\` cuts a list down to some fraction of its former length.
|
| 192 |
+
|
| 193 |
+
At this point, you should put the book down for a moment and go play with this using the command-line REPL. Experiment! Can you put a list inside another list? Does it matter whether you put a space after each comma? Can you make a list with no elements at all? Lists are a really important type of data that will come up again and again in your programming, so it's worth making sure you understand them.
|
| 194 |
+
|
| 195 |
+
Of course just being able to create a list and print it isn't very useful. You also need to be able to pull an element out of a list. We can do this with *list indexing*.
|
| 196 |
+
|
| 197 |
+
list index
|
| 198 |
+
: a numeric value, starting at 0, that indicates a particular element of a list
|
| 199 |
+
|
| 200 |
+
You use a list index by simply putting it in square brackets after a variable that contains a list. The first element is index 0, so you can print just the first element of a list this way:
|
| 201 |
+
|
| 202 |
+
{i:"list indexing;indexing, list"}
|
| 203 |
+
{caption:"List Indexing"}
|
| 204 |
+
```miniscript
|
| 205 |
+
a = ["foo", 42, "XYZZY"]
|
| 206 |
+
print a[0]
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
D> Counting in MiniScript, and most other modern languages, generally starts at 0. Just think of the index as "how many elements come *before* the one I want" and you'll be fine.
|
| 210 |
+
|
| 211 |
+
Experiment with that last example, too. Make sure you can print out any element you want. If you try to use an index that doesn't exist, such as 7 when there are only three elements, MiniScript will report the problem as a "MiniScript::IndexException".
|
| 212 |
+
|
| 213 |
+
There's one more trick with list indexing that is super handy: by using negative numbers, you can count backwards from the end of the list. The last element is -1, the second-to-last is -2, and so on.
|
| 214 |
+
|
| 215 |
+
{caption:"List Indexing, Backwards!"}
|
| 216 |
+
```miniscript
|
| 217 |
+
a = ["foo", 42, "XYZZY"]
|
| 218 |
+
print a[-1]
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
Again, experiment with this, and see that if you go too far, you get an `IndexException`.
|
| 222 |
+
|
| 223 |
+
Just as there are a number of intrinsic (built-in) functions for working with numbers and strings, there are intrinsic functions for lists, too. These are shown in the table on the next page.
|
| 224 |
+
{gap:12}
|
| 225 |
+
|
| 226 |
+
{i:"functions, list;list functions"}
|
| 227 |
+
{caption:"Intrinsic list functions", colWidths:"170,*"}
|
| 228 |
+
| `.hasIndex(i)` | 1 if i is a valid list index; otherwise 0 |
|
| 229 |
+
| `.indexes` | a list with numbers from 0 to `self.len-1` |
|
| 230 |
+
| `.indexOf(x, after=null)` | 0-based position of first element matching x in `self`, or null if not found; optionally begins the search after the given position |
|
| 231 |
+
| `.insert index, value` | inserts value into `self` at the given index (in place) |
|
| 232 |
+
| `.join(delimiter=" ")` | builds a string by joining elements by the given delimiter |
|
| 233 |
+
| `.len` | length (number of elements) of `self` |
|
| 234 |
+
| `.pop` | removes and returns the last element of `self` (like a stack) |
|
| 235 |
+
| `.pull` | removes and returns the first element of `self` (like a queue) |
|
| 236 |
+
| `.push x` | appends the given value to the end of `self`; often used with pop or pull |
|
| 237 |
+
| `.shuffle` | randomly rearranges the elements of `self` (in place) |
|
| 238 |
+
| `.sort key=null` | sorts list in place, optionally by value of the given key (e.g. in a list of maps) |
|
| 239 |
+
| `.sum` | total of all numeric elements of `self` |
|
| 240 |
+
| `.remove i` | removes element at index i from `self` (in place) |
|
| 241 |
+
| `.replace oldval, newval, maxCount=null` | replaces (in place) up to maxCount occurrences of oldval in the list with newval (if maxCount not specified, then all occurrences are replaced) |
|
| 242 |
+
| `slice(list, from, to)` | equivalent to list[from:to] |
|
| 243 |
+
|
| 244 |
+
This is the complete set of list intrinsics, and it includes some stuff we haven't talked about yet. So just as on Day 2, please don't worry about understanding everything in this table today. Let's just highlight a few of the most important functions:
|
| 245 |
+
|
| 246 |
+
- `a.len` gives you the length (number of elements) in list a.
|
| 247 |
+
- `a.push "x"` adds a new element "x" to the end of the list.
|
| 248 |
+
- `a.insert 2, "y"` inserts a new element "y" after the first 2 elements in the list.
|
| 249 |
+
- `a.remove 1` removes element 1 (that is, the item with 1 element to its left).
|
| 250 |
+
|
| 251 |
+
With these four functions, you have ways to find out how big a list is, and modify it in various ways: add a new item to the end, insert a new item at any position, and remove any item. You're probably beginning to see why lists are so important in programming; they let you hold and work with any amount of data.
|
| 252 |
+
|
| 253 |
+
{pageBreak}
|
| 254 |
+
Let's exercise these important list functions with an example.
|
| 255 |
+
|
| 256 |
+
{caption:"List Example 2"}
|
| 257 |
+
```miniscript
|
| 258 |
+
a = []
|
| 259 |
+
while a.len < 5
|
| 260 |
+
a.push input("Next item?")
|
| 261 |
+
end while
|
| 262 |
+
print "You entered: " + a
|
| 263 |
+
print "Element 2 is " + a[2]
|
| 264 |
+
print "But I can change that..."
|
| 265 |
+
a[2] = "HAHA!"
|
| 266 |
+
print "Now we have: " + a
|
| 267 |
+
print "But I feel bad. Let's just get rid of it."
|
| 268 |
+
a.remove 2
|
| 269 |
+
print "Now it's just: " + a
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
That's one of the longer examples, but go ahead and type it in. It's going to ask you to enter five strings; enter the names of the numbers in Spanish, or your favorite pizza toppings, or whatever. The program then does some shenanigans with the middle element (which, in list of length 5, is element 2). As always, play with the code to gain deep understanding. See if you can make it change the first element instead, or the last one.
|
| 273 |
+
|
| 274 |
+
{i:"string indexing;indexing, string;immutable"}
|
| 275 |
+
D> You can index into strings, too! The elements of a string are characters. `s[2]` is a perfectly cromulent way to get character 2 (the one with 2 characters to its left) of a string. The main difference is, strings are *immutable*, which means you can't assign a new value to an element of a string, nor can you insert or remove characters, the way you can with lists. We'll explore this more in the next chapter.
|
| 276 |
+
|
| 277 |
+
## `range` and `for` revisited
|
| 278 |
+
|
| 279 |
+
A `for` loop assigns a variable — often called `i` in our examples — to each element of a list or string, in turn. It stops looping after it has done this with all elements. It's equivalent to:
|
| 280 |
+
|
| 281 |
+
{caption:Life in a world without `for` loops}
|
| 282 |
+
```miniscript
|
| 283 |
+
myList = [1, 2, "hey", "you"]
|
| 284 |
+
index = 0
|
| 285 |
+
while index < myList.len
|
| 286 |
+
i = myList[index]
|
| 287 |
+
print i
|
| 288 |
+
index = index + 1
|
| 289 |
+
end while
|
| 290 |
+
```
|
| 291 |
+
...but as you can see, the `for` loop is considerably shorter and easier:
|
| 292 |
+
|
| 293 |
+
{i:"`for` loop"}
|
| 294 |
+
{caption:"`for` loops make life easy"}
|
| 295 |
+
```miniscript
|
| 296 |
+
myList = [1, 2, "hey", "you"]
|
| 297 |
+
for i in myList
|
| 298 |
+
print i
|
| 299 |
+
end for
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
{i:"`range` function"}
|
| 303 |
+
In previous chapters, we used `for` loops with the `range` function, which I glossed over without properly explaining. But now it's time to revisit that. `range` is an intrinsic function that takes three parameters: a starting value, an ending value (which defaults to zero), and a step size (which defaults to one). It returns a list with elements that begin at the start value, and count towards the end value, in increments of the given step.
|
| 304 |
+
|
| 305 |
+
{caption:"Examples of the `range` function", hpad:8}
|
| 306 |
+
| `range(1, 10)` | `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]` |
|
| 307 |
+
| `range(10, 1)` | `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]` |
|
| 308 |
+
| `range(1,10,3)` | `[1, 4, 7, 10]` |
|
| 309 |
+
| `range(1,10,4)` | `[1, 5, 9]` |
|
| 310 |
+
| `range(10,1,4)` | `Runtime Exception: range() error` |
|
| 311 |
+
| `range(10,1,-4)` | `[10, 6, 2]` |
|
| 312 |
+
| `range(10)` | `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]` |
|
| 313 |
+
|
| 314 |
+
It's quite possibly the most commonly used function in MiniScript, apart from print, and in some code it surpasses even that. So take some time with the REPL to play with it. Type in each of the examples in the left column on the previous page, and you should see the output shown on the right.
|
| 315 |
+
|
| 316 |
+
Notice that `range` can count both ways: if the start value is less than the end, it counts up; otherwise it counts down. Also notice that the start value is always included as the first element of the resulting list, but the end value might not be included at all, if it is not hit by the combination of start and step. Finally, notice that the step size, if given, must be negative if counting down, or positive if counting up; otherwise you get an error.
|
| 317 |
+
|
| 318 |
+
Experiment a bit more and make sure that `range` is a tool you are comfortable using. Now that you understand this, you can really understand all those `for` loops we glossed over before. When we write something like
|
| 319 |
+
|
| 320 |
+
```miniscript
|
| 321 |
+
for i in range(10, 1)
|
| 322 |
+
print i + "..."
|
| 323 |
+
wait
|
| 324 |
+
end for
|
| 325 |
+
```
|
| 326 |
+
|
| 327 |
+
...that `for` statement is really just iterating over the list returned by `range`. We could have instead written
|
| 328 |
+
|
| 329 |
+
```miniscript
|
| 330 |
+
for i in [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
|
| 331 |
+
print i + "..."
|
| 332 |
+
wait
|
| 333 |
+
end for
|
| 334 |
+
```
|
| 335 |
+
|
| 336 |
+
and this would do the exact same thing.
|
| 337 |
+
|
| 338 |
+
D> In programming, there are often many ways to do the same thing. You should always pick whichever way seems clearest and easiest to read and understand. This is usually (but not always) the way that is shortest.
|
| 339 |
+
|
| 340 |
+
{i:`indexes`}
|
| 341 |
+
We'll end the day with one more tip related to lists and `for` loops. It sometimes happens that you need to iterate over not the elements of a list, but the indexes of those elements. For example, suppose you want to write a loop that converts every element of a list of strings to upper case. You might do it like this:
|
| 342 |
+
|
| 343 |
+
{caption:"Uppercasing a list, the slightly less easy way"}
|
| 344 |
+
```miniscript
|
| 345 |
+
data = ["Billy", "and", "the", "boingers"]
|
| 346 |
+
for i in range(0, data.len - 1)
|
| 347 |
+
data[i] = data[i].upper
|
| 348 |
+
end for
|
| 349 |
+
data
|
| 350 |
+
```
|
| 351 |
+
|
| 352 |
+
(We left out `print` on the last line because I assume you're typing this into a REPL, where simply naming a variable is enough to print its contents.) So this isn't too bad; `i` here will go from 0 to the last index (which is one less than the length of the list), and then we use that to reassign `data[i]` with the uppercase version.
|
| 353 |
+
|
| 354 |
+
But there is a better way to do it, and that is the `.indexes` method. This returns a list of all the valid indexes for a list or string (or map, which you'll learn about in a couple days). If you did the above in your REPL, then type `data.indexes` now to see what it returns in this case. The `.indexes` method is commonly used with `for`, like this:
|
| 355 |
+
|
| 356 |
+
{caption:"Uppercasing a list, the slightly easier way"}
|
| 357 |
+
```miniscript
|
| 358 |
+
data = ["Billy", "and", "the", "boingers"]
|
| 359 |
+
for i in data.indexes
|
| 360 |
+
data[i] = data[i].upper
|
| 361 |
+
end for
|
| 362 |
+
data
|
| 363 |
+
```
|
| 364 |
+
|
| 365 |
+
Same loop, but slightly shorter and clearer code.
|
| 366 |
+
|
| 367 |
+
{pageBreak}
|
| 368 |
+
A> **Chapter Review**
|
| 369 |
+
A> - You installed command-line MiniScript for your platform.
|
| 370 |
+
A> - You learned how to do use a REPL to work with code interactively.
|
| 371 |
+
A> - You discovered that your knowledge of the MiniScript language may apply in very different environments.
|
| 372 |
+
A> - You explored the list datatype, and in the process, gained deeper understanding of `for` loops.
|
data/day9.txt
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{chapterHead: "Day 9: Slice and Scripts", startingPageNum:93}
|
| 2 |
+
|
| 3 |
+
{width: "50%"}
|
| 4 |
+

|
| 5 |
+
|
| 6 |
+
Q> If you do not have courage, you may not have the opportunity to use any of your other virtues.
|
| 7 |
+
Q>— Samuel L. Jackson (actor and producer)
|
| 8 |
+
|
| 9 |
+
A> **Chapter Objectives**
|
| 10 |
+
A> - Learn how to extract a section of a list or a string.
|
| 11 |
+
A> - See the many ways in which this "slicing" can be useful.
|
| 12 |
+
A> - Learn to write a longer script as a file, so you can run it again and again.
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
We saw in the last chapter how you could access any element of a list or string by putting its 0-based index in square brackets. We're going to build on that in some really cool ways, so let's start with a quick review. Fire up command-line MiniScript, and try the following at the REPL:
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
s = "Howdy world!"
|
| 19 |
+
s[0]
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
That should print "H", since the character in `s` with 0 letters to its left is "H". What would `s[3]` print? What about `s[-1]`, recalling that negative indexes count from the end of the string? Check each of these in the REPL to make sure you're right.
|
| 23 |
+
|
| 24 |
+
D> If you're not at a computer, following along with these examples in the REPL, they are unlikely to stick. Don't waste your time! No runner ever got fast by watching other people run.
|
| 25 |
+
|
| 26 |
+
Now the coolness begins.
|
| 27 |
+
|
| 28 |
+
## Slicing
|
| 29 |
+
|
| 30 |
+
In MiniScript, as well as some other languages (e.g. Python), you can index into a string or list with *two* indexes instead of just one. When you do, you get back the subset that starts at the first index, and goes up to (but not including) the second one. This operation is known as *slicing*, and what you get back is called a *slice*.
|
| 31 |
+
|
| 32 |
+
slice
|
| 33 |
+
: a substring or sublist defined by start and end indexes in a larger string or list
|
| 34 |
+
|
| 35 |
+
slicing
|
| 36 |
+
: the operation of getting a slice: `seq[a:b]`, where `seq` is a string or list, and `a` and `b` are numbers
|
| 37 |
+
|
| 38 |
+
You get a slice by putting the two indexes together within the square brackets, separated by a colon. Try it:
|
| 39 |
+
|
| 40 |
+
```
|
| 41 |
+
s[0:3]
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
This should print "How", which is the substring starting at `s[0]`, and going up to but not including `s[3]`. Now see if you can get the slice "world", starting with "w" and going up to but not including "!". Go on. I'll wait.
|
| 45 |
+
|
| 46 |
+
D> At times like this, the REPL is your dearest friend. Even when you are an experienced programmer with decades of skillful code-craft under your belt, when you need to quickly confirm your understanding of some language feature like slicing, there is no better way than launching a REPL and trying a few quick examples.
|
| 47 |
+
|
| 48 |
+
Did you come up with `s[6:11]`? That gets the job done! But to get that you probably either had to try several times, or count carefully from the beginning of the string. There is another way, using the trick that negative indices count from the end of the string. `s[-1]` is the exclamation point of our string, so you could write:
|
| 49 |
+
|
| 50 |
+
```
|
| 51 |
+
s[6:-1]
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
This returns the substring starting at character 6, and going up to but not including the last character of the string. You can use a negative number with either index, or both, as needed.
|
| 55 |
+
|
| 56 |
+
In addition to a numeric index (whether negative or not), you can also *omit* either index. If you leave out the first index, the slice starts at the beginning of the string; if you leave out the second index, the slice extends to the end of the string. These are very commonly needed, so this is a convenient shortcut. Suppose you want to get the first five letters of string `s`. You could of course write:
|
| 57 |
+
|
| 58 |
+
```
|
| 59 |
+
s[0:5]
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
but you can also write:
|
| 63 |
+
|
| 64 |
+
```
|
| 65 |
+
s[:5]
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
which you might read out loud as "s (up to 5)". These are equivalent, though the second form is slightly shorter, and makes your intent slightly more clear. The benefit is a bit greater when you omit the second index. Suppose we want to get the slice "world!" from our "Howdy world!" string... but we are too lazy to count how long the string is (or, in a more realistic setting, we can't know how long it is because it may be different on each run). You could do:
|
| 69 |
+
|
| 70 |
+
```
|
| 71 |
+
s[6:s.len]
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
but it's shorter, easier, and faster to do
|
| 75 |
+
|
| 76 |
+
```
|
| 77 |
+
s[6:]
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
which you might read as "s (from 6 to the end)".
|
| 81 |
+
|
| 82 |
+
These sorts of string operations come up in programming a lot more than you might think. Suppose you had a filename with a three-letter extension, which is something like ".txt" or ".png" or ".jpg". You might want to get the name without the extension, to display a nice name to the user; or you might want to get the extension itself, to figure out what sort of file it is. Both of these are easy, thanks to slicing.
|
| 83 |
+
|
| 84 |
+
{caption:"Getting the name and file extension from a file name"}
|
| 85 |
+
```miniscript
|
| 86 |
+
filename = "My Recipes.txt"
|
| 87 |
+
name = filename[:-4]
|
| 88 |
+
ext = filename[-3:]
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
Enter that in the REPL, and then enter `name` and `ext` by themselves to see what values they have. `filename[:-4]` gets the original string up to (but not including) the 4th character from the end, or in other words, it strips off the last four characters. Conversely, `filename[-3:]` gets the last three characters of the string.
|
| 92 |
+
|
| 93 |
+
All our examples so far have been with strings, but slicing works with lists, too. For this next batch of examples, let's work with a list of the first ten prime numbers.
|
| 94 |
+
|
| 95 |
+
```
|
| 96 |
+
p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
Now, because we know this list is already sorted, you can use `p[0]` to find the smallest number, and `p[-1]` to find the largest. (Try it!) That much you knew yesterday. But now you can get, say, the *three* smallest prime numbers:
|
| 100 |
+
|
| 101 |
+
```
|
| 102 |
+
p[:3]
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
Similarly, suppose you wanted the list of all primes *except* for the first and last. You only want the ones in the middle. Again with slicing, this is easy:
|
| 106 |
+
|
| 107 |
+
```
|
| 108 |
+
p[1:-1]
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
This gets the slice starting at element 1 (i.e., the one with 1 to its left), and going up to but not including the last one.
|
| 112 |
+
|
| 113 |
+
## Attack of the Mutant Lists
|
| 114 |
+
|
| 115 |
+
One important difference between strings and lists is that strings are immutable, while lists are mutable. "Mutable" means "able to be mutated," and "mutated" is just a fancy word for "changed."
|
| 116 |
+
|
| 117 |
+
mutable
|
| 118 |
+
: describes an object with data that can be changed: in MiniScript, lists and maps
|
| 119 |
+
immutable
|
| 120 |
+
: describes an object that can't be changed, but only replaced: strings and numbers
|
| 121 |
+
|
| 122 |
+
You've been mutating lists since you first saw them (i.e. yesterday), with methods like `.push`. Here's another way to mutate a list: replace any element with a new value.
|
| 123 |
+
|
| 124 |
+
```
|
| 125 |
+
p[3] = 42
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
Try that, and then examine `p` to see what it contains. It looks the same as before, except element 3 (the one with 3 items to its left) has been replaced with 42. However, it's important to note that you can *not* replace a slice this way.
|
| 129 |
+
|
| 130 |
+
{caption:"This doesn't work."}
|
| 131 |
+
```miniscript
|
| 132 |
+
p[3:6] = [1,2,3]
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Try it. At the time of this writing, at least, it doesn't work.
|
| 136 |
+
|
| 137 |
+
D> It's possible that this feature will be added to MiniScript someday. It's a sensible thing to want, and wouldn't break any existing code.
|
| 138 |
+
|
| 139 |
+
And you also can't mutate a string.
|
| 140 |
+
|
| 141 |
+
{caption:"This also doesn't work (with strings)."}
|
| 142 |
+
```miniscript
|
| 143 |
+
s[2] = "x"
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
Of course you can always assign a *new* string to a string variable. When you do something like `s = s.upper`, that is exactly what you're doing. That's not mutating the string; it's just replacing it with a different one. It's the same with numbers, for that matter; there is no way to *change* a number, but you can always assign a variable a new number, replacing its previous value, as in `x = x + 1`.
|
| 147 |
+
|
| 148 |
+
Because lists are mutable, you have to be a little careful sometimes. When you do something like `q = p`, it is not creating a new list; it is simply making `q` refer to the same list that `p` already referred to. The list itself lives off in the computer's memory somewhere, and has variables like `p` and `q` that refer to it. The list is actually deleted only when there are no more references to it. So, of course, it doesn't matter what variable you use to mutate the list; all references point to the same thing. Try this:
|
| 149 |
+
|
| 150 |
+
```
|
| 151 |
+
q = p
|
| 152 |
+
q[0] = "hey"
|
| 153 |
+
p
|
| 154 |
+
p.push "ho!"
|
| 155 |
+
q
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
{pageBreak}
|
| 159 |
+
The results will not be surprising, as long as you remember that `p` and `q` do not *contain* a list; they only *refer* to a list. Assignment copies the reference, but does not make a new list.
|
| 160 |
+
|
| 161 |
+
{width:"50%"}
|
| 162 |
+

|
| 163 |
+
|
| 164 |
+
So what do you do when you need to make a copy of a list? For example, suppose you want to keep your original list, but also make a copy that is slightly different. Here slicing comes to the rescue again. It turns out that slicing *always* gets you a new list, even if the range of the slice covers the entirety of the original list. So, you could create a complete copy of list `p` by using
|
| 165 |
+
|
| 166 |
+
```
|
| 167 |
+
q = p[0:p.len]
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
...but, as you learned above, you can omit the first index when it is 0 and omit the last one when it is the length of the list or string. So the standard solution looks like this:
|
| 171 |
+
|
| 172 |
+
```
|
| 173 |
+
q = p[:]
|
| 174 |
+
q.push "I'm unique!"
|
| 175 |
+
p
|
| 176 |
+
q
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
{gap:20}
|
| 180 |
+
{width:"62.37%"}
|
| 181 |
+

|
| 182 |
+
|
| 183 |
+
Think of `p[:]` as an idiom — a standard way of phrasing a concept in a language. The concept in this case is making a complete copy. You might even read this out loud as "copy of p", though if you forget and need to work it out at first, "p (from the beginning to the end)" is fine too.
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
## Programs as Text Files
|
| 187 |
+
|
| 188 |
+
So far in this book, we've written MiniScript code in two contexts: in the Try-It! page on the web, and in the REPL of command-line MiniScript. Both of these are great for short bits of code, but not so great for larger programs. The Try-It! page has a code limit (currently about 2000 characters), and of course typing in a REPL gets to be pretty difficult for loops or `if` blocks that are more than a few lines long.
|
| 189 |
+
|
| 190 |
+
So it's time to learn to code the way professional programmers do: using a separate code editor! In our case, any text editor will do. But this being the modern world, let's make sure we are clear on the difference between a text editor and a word processor.
|
| 191 |
+
|
| 192 |
+
text editor
|
| 193 |
+
: a program that edits plain text (.txt) files. Examples on Windows include Notepad, Notepad++, and GEdit; examples on Mac include TextEdit and BBEdit
|
| 194 |
+
|
| 195 |
+
word processor
|
| 196 |
+
: a program that edits formatted documents. Microsoft Word is the most widely known word processor, but Apple Pages is another example
|
| 197 |
+
|
| 198 |
+
While both kinds of applications are superficially similar in how they look and work, what they do is fundamentally different. Text files are fairly universal, but word processors all have their own proprietary format, and their documents are generally not usable in any other program. So, when programming, you will need to use a text editor.
|
| 199 |
+
|
| 200 |
+
A few examples of text editors are given above. If you're on Windows, Microsoft Notepad is a simple text editor that comes with the operating system, and is perfectly adequate. Many people prefer Notepad++, which is a free replacement that has some more powerful features. The situation on Mac is similar: the built-in TextEdit app will do, though I recommend BBEdit, which is powerful and free (though it has some additional for-pay features you probably won't need). On Linux, your distribution probably came with a graphical text editor, and command-line editors (vi, vim, emacs, nano, etc.) also work fine. There are many other text editors for all platforms, and any of them will work fine, so don't worry too much about which to choose.
|
| 201 |
+
|
| 202 |
+
Pick one, and create a new file. Enter the following text.
|
| 203 |
+
|
| 204 |
+
{caption:"Our first MiniScript source file!"}
|
| 205 |
+
```miniscript
|
| 206 |
+
print "MiniScript is"
|
| 207 |
+
for i in range(1, 5)
|
| 208 |
+
print "really " * i
|
| 209 |
+
end for
|
| 210 |
+
print "COOL!"
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
Save this file to disk as "cool.ms" (though the file extension is arbitrary, it's common practice to use ".ms" for MiniScript files). Pay attention to where you save it; you're going to need to know its file path for the next step.
|
| 214 |
+
|
| 215 |
+
Now the fun part. Open up a new terminal or shell window, or if you are already running command-line MiniScript, enter `exit` (or press control-C) to exit. Now you're back at the shell prompt. As before, enter the path to your command-line MiniScript executable; but before you press Enter or Return, hit the spacebar, and then enter the path to your *cool.ms* text file. (On some systems, you can drag the file icon from Finder or File Explorer right into the terminal/shell window, and it will enter the path for you — try that and see if it works!) Then hit Enter/Return. The result should look something like this.
|
| 216 |
+
|
| 217 |
+
```terminal
|
| 218 |
+
$ ./miniscript ~/DailyPurge/cool.ms
|
| 219 |
+
MiniScript is
|
| 220 |
+
really
|
| 221 |
+
really really
|
| 222 |
+
really really really
|
| 223 |
+
really really really really
|
| 224 |
+
really really really really really
|
| 225 |
+
COOL!
|
| 226 |
+
$
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
The `$` above is my Unix shell prompt; yours will probably be something different, but that's OK. The line `./miniscript ~/DailyPurge/cool.ms` is the Unix command I typed in to launch command-line MiniScript, and give it the path to my *cool.ms* file. MiniScript read that file, executed the code in it, and then exited (returning me to my `$` shell prompt).
|
| 230 |
+
|
| 231 |
+
If you see the program output above, then well done! You wrote your very first program in a file, and then ran that program on the command line. Now you have the ability to make your programs as long as they need to be, with the full power of whatever text editor you like, the ability to store them with your backup system, mail them to collaborators, and all those other great things you can do with disk files.
|
| 232 |
+
|
| 233 |
+
If you didn't see that output, then let's get to the bottom of it before moving on. If MiniScript didn't launch at all (i.e., you got only an error in response to your command), then you probably got the path to MiniScript incorrect. Review and reproduce the work you did yesterday, until you're able to get command-line MiniScript to run. It's also possible you forgot to put a space between the path to MiniScript and the path to your program; make sure to hit the spacebar in between these.
|
| 234 |
+
|
| 235 |
+
If it launched, printed its version info, and then immediately exited without printing anything else, then you probably got the path to your *cool.ms* file incorrect. Double-check each part of the path. Remember that Windows uses backslashes (`\\`) to separate each part; Mac and Linux use forward slashes (`/`). Also try the trick of dragging the file icon into your shell/terminal window, if you didn't already.
|
| 236 |
+
|
| 237 |
+
D> You may want to use the `cd` (change directory) shell command to change your current working directory to wherever you stored your *cool.ms* file. Then, after the path to miniscript and a space, you can simply enter *cool.ms*, or the name of any other script in that directory, without having to type the full path.
|
| 238 |
+
|
| 239 |
+
{pageBreak}
|
| 240 |
+
A> **Chapter Review**
|
| 241 |
+
A> - You learned how to get a slice of a list or string.
|
| 242 |
+
A> - You noticed that lists can be mutated, and found a way to make a copy of a list when you need one.
|
| 243 |
+
A> - You created a MiniScript program using a text editor, and ran it using command-line MiniScript.
|
| 244 |
+
|
| 245 |
+
{gap:340}
|
| 246 |
+
{width:"25%"}
|
| 247 |
+

|
| 248 |
+
|
| 249 |
+
|