diff --git a/lessons/02-conditionals/README.md b/lessons/02-conditionals/README.md index 06180f0..4485103 100644 --- a/lessons/02-conditionals/README.md +++ b/lessons/02-conditionals/README.md @@ -29,8 +29,8 @@ asks `a > b?` — that's `true` here (`7 > 4`) — so the program follows the Press **▶ Run step by step**. Watch the diamond answer `true` and the program head down the `true` arrow — while the other branch **grays out and gets -skipped**. Those blocks never run. This fork is exactly what Java writes as -`if / else` — you'll type it yourself in [lesson {n}](#/lesson/09-if-statements). +skipped**. Those blocks never run. This fork is exactly what Python writes as +`if / else`, and you'll type it yourself in [lesson {n}](#/lesson/09-if-statements). ```blocks preset: cond-demo diff --git a/lessons/05-what-is-java/README.md b/lessons/05-what-is-java/README.md index f4ec8ab..c4011fd 100644 --- a/lessons/05-what-is-java/README.md +++ b/lessons/05-what-is-java/README.md @@ -1,93 +1,60 @@ --- -title: "What is Java?" -goal: "Recognize Java's basic punctuation and program shape before writing or running any code." +title: "What is Python?" +goal: "Recognize Python's basic punctuation, indentation, and program shape before writing or running any code." order: 50 -section: "Java Fundamentals" +section: "Python Fundamentals" --- # A language, not a magic spell -You've been building programs already — as flowcharts of blocks -([lesson {n}](#/lesson/01-flowcharts) onward). From here on we write those same -ideas as **text**, in a language called **Java**. It's the language FRC robot -code is written in, and one of the most widely used languages in the world. +You've been building programs already, as flowcharts of blocks ([lesson {n}](#/lesson/01-flowcharts) onward). From here on we write those same ideas as **text**, in a language called **Python**. -A programming language is just a very strict set of grammar rules. English is -forgiving — "computer the on it run" is garbled but a person can still guess -what you meant. Java isn't. Every instruction has to be spelled and punctuated -exactly one way, or the computer refuses to run any of it and reports back -exactly what confused it. That's not the computer being difficult — it's the -computer being honest about not understanding you yet. +Why does FRC 2713 teach software fundamentals in Python? Python reads close to plain English and keeps extra boilerplate out of your way, so you can focus on the core ideas: variables, decisions, loops, functions, objects, and state machines. Those concepts carry straight over to any language you use on the team later, including Java for robot code, and Python itself is useful for scripts, data analysis, and team tools. -Two habits fall out of that strictness, right from the start: +A programming language is a strict set of grammar rules. English is forgiving. "Computer the on it run" is garbled, yet a person can still guess what you meant. Python won't guess. Every instruction has to follow the rules, or Python stops and points to the exact line that confused it. That isn't the computer being difficult; it's the computer telling you what it needs fixed. -- **Java is case-sensitive.** `System` and `system` are different words to - Java, the same way "Rex" and "rex" are different words if one's a dog's name - and the other isn't. Spelling has to match exactly, capital letters included. -- **Whitespace mostly doesn't matter.** Spaces, blank lines, and indentation - make code easier for *you* to read, but Java doesn't require them to be any - particular way. What *does* matter is a small set of punctuation marks that - show up in almost every line you'll write. That's the rest of this lesson. +Two habits matter right from the start: + +- **Python is case-sensitive.** `Print` and `print` are different words to Python, just like "Rex" and "rex" are different if one is a name and the other isn't. Spelling has to match, capital letters included. +- **Indentation matters.** Python uses spaces at the start of a line to group steps that belong together. Lining code up isn't just for neatness here; it's part of the grammar. # The punctuation you'll see everywhere -Before you write a single instruction, it helps to recognize the marks Java -uses to hold instructions together — the same way knowing what a period or a -comma does helps you read a sentence you've never seen before. +Before you write a single instruction, it helps to recognize the symbols Python uses to hold instructions together, the same way knowing what a period or a comma does helps you read a new sentence. ```text -{ } curly braces - group a bunch of steps into one block -( ) parentheses - hold the "ingredients" an instruction needs -, comma - separates ingredients when there's more than one -; semicolon - marks the end of one instruction +: colon - starts an indented block of steps +( ) parentheses - hold the "ingredients" a function needs +, comma - separates ingredients when there is more than one " " quotes - mark exact text, called a "string" +# hash - starts a comment (a note for humans) ``` -- **Curly braces `{ }`** group steps that belong together, the way a folder - groups pages. Everything between a `{` and its matching `}` is treated as one - bundle — you already saw this idea as the box drawn around the steps inside - an `if` or a repeat block. -- **Parentheses `( )`** hold what an instruction needs to do its job. Some - instructions need nothing (empty parentheses, `()`), some need one thing, - some need several. -- **Commas `,`** separate those things when an instruction needs more than - one — the same job a comma does in "eggs, milk, and flour." -- **Semicolons `;`** mark where one instruction ends, like a period at the end - of a sentence. Forget one and Java will tell you it expected to see it. -- **Quotes `" "`** mark exact text for Java to use as-is — a run of characters - called a **string**. Anything inside the quotes is data, not instructions; - Java won't try to run it. +- **Colons `:`** sit at the end of a header line to say "an indented block of steps comes next." You'll see them on `if` statements, loops, and functions. +- **Parentheses `( )`** hold what an instruction needs to do its job. Some instructions need nothing (`()`), some need one thing, and some need several. +- **Commas `,`** separate those things when an instruction needs more than one, the same job a comma does in "eggs, milk, and flour." +- **Quotes `" "`** mark exact text for Python to use as-is, called a **string**. Anything inside the quotes is data, not instructions, so Python won't try to run it. +- **Hash `#`** starts a **comment**. Anything after `#` on a line is a note for humans, and Python skips right over it. # Reading a program's shape -Every Java program you run needs to live inside a shell like this one: +Here is a tiny Python program so you can see those symbols working together: ```text -public class Main { - public static void main(String[] args) { - // your instructions go here - } -} +# a short Python program +def greet(name): + print("Hello, " + name) + +greet("Ada") ``` -Don't worry about memorizing this — the playground writes it for you for now, -and you'll learn to write it yourself in -[lesson {n}](#/lesson/11-writing-methods). For today, just recognize the shapes -in it with the vocabulary from above: - -- `public class Main { ... }` — a **class** named `Main`, with everything it - owns held between its curly braces. -- `public static void main(String[] args) { ... }` — inside that class, a - block named `main`. This is the one Java looks for first and runs — every - program's very first instruction lives inside `main`'s braces. The - parentheses hold what `main` needs to do its job, but you can ignore - `String[] args` for now. -- `// your instructions go here` — a **comment**. Anything after `//` on a - line is a note for humans; Java skips right over it. - -Notice the braces nest: `main`'s `{ }` sits inside `Main`'s `{ }`, like a small -folder inside a bigger one. That nesting is how Java knows what belongs to -what — you'll see it again every time a block sits inside another block. - -You now know enough vocabulary to read Java without panicking at the -punctuation. Next lesson, you'll write and run your first real instruction. +Don't worry about memorizing this yet. You'll learn to write your own functions in [lesson {n}](#/lesson/11-writing-methods). For today, just spot the pieces using the vocabulary above: + +- `# a short Python program` is a comment that Python ignores. +- `def greet(name):` defines a reusable block named `greet` that expects one input, `name`. The colon at the end tells Python an indented block is coming next. +- ` print("Hello, " + name)` is indented by four spaces, so it belongs *inside* `greet`. +- `greet("Ada")` is back at the left edge, outside `greet`, so Python runs it and hands `"Ada"` into the function. + +Notice how indentation shows what belongs to what, just like a box drawn around steps in a flowchart. Python doesn't require an outer wrapper class to start running code, so a one-line script is already a valid program. + +You now know enough vocabulary to read Python without getting tripped up by the syntax. Next lesson, you'll write and run your first real instruction. diff --git a/lessons/06-hello-world/README.md b/lessons/06-hello-world/README.md index 80a7f36..47a085f 100644 --- a/lessons/06-hello-world/README.md +++ b/lessons/06-hello-world/README.md @@ -2,72 +2,44 @@ title: "Hello, World!" goal: "Explain what a program actually is, then write and run your first one." order: 60 -section: "Java Fundamentals" +section: "Python Fundamentals" --- # What is a program? -You've already been building programs — as flowcharts of blocks. Everything you -did there carries over: doing steps in order ([lesson {n}](#/lesson/01-flowcharts)), making decisions -([lesson {n}](#/lesson/02-conditionals)), repeating steps ([lesson {n}](#/lesson/03-loops)), and packaging steps into reusable pieces -([lesson {n}](#/lesson/04-functions)). From here on we write those same ideas as **text** instead of wiring -boxes together. The concepts don't change; only the notation does — and -[last lesson](#/lesson/05-what-is-java) you already met that notation: braces, -parentheses, commas, semicolons, quotes. +You've already been building programs as flowcharts of blocks. Everything you did there carries over: doing steps in order ([lesson {n}](#/lesson/01-flowcharts)), making decisions ([lesson {n}](#/lesson/02-conditionals)), repeating steps ([lesson {n}](#/lesson/03-loops)), and packaging steps into reusable pieces ([lesson {n}](#/lesson/04-functions)). From here on we write those same ideas as **text** instead of wiring boxes together. The concepts don't change, only the notation does, and [last lesson](#/lesson/05-what-is-java) you met that notation: colons, indentation, parentheses, commas, and quotes. -A **program** is just a list of instructions, written in a language a computer -can follow exactly, step by step, in order. +A **program** is a list of instructions, written in a language a computer can follow step by step, in order. -That's it. Not magic — a recipe. "Crack two eggs. Whisk them. Pour into a hot -pan." A computer program is the same idea, except the "kitchen" is the -computer's memory and screen, and the "chef" is the computer itself, which -will follow your instructions *exactly* as written, including your mistakes. +That's it. Not magic, just a recipe: "Crack two eggs. Whisk them. Pour into a hot pan." A computer program is the same idea, except the kitchen is the computer's memory and screen, and the chef is the computer itself, which follows your instructions *exactly* as written, including your mistakes. -The robot framework we use, **WPILib**, is a big library of Java code, so -everything you learn here is exactly what you'll use to make a real robot -move. +Everything you learn here builds the foundation you'll use for FRC robot software, simulations, and team tools. # Your first program -Here is a complete, one-line Java instruction: +Here is a complete, one-line Python program: -```java -System.out.println("Hello, world!"); +```python +print("Hello, world!") ``` -`System.out.println` is an instruction that means "show this on the screen." -The text in quotes is exactly what gets shown — computers don't know that -`Hello, world!` is a greeting, they just do what they're told with the data -they're given. The semicolon at the end marks where the instruction stops, -like a period at the end of a sentence — every Java instruction needs one. +`print` is a function that means "show this on the screen." The text in quotes is exactly what gets shown. Computers don't know that `Hello, world!` is a greeting; they just do what they're told with the data they're given. Each instruction sits on its own line, with no semicolon needed at the end. Two things to know about the playground before you press Run: -- The **first Run downloads a real Java compiler** into your browser, so it - takes a few extra seconds. After that, runs are quick. -- Java instructions normally live inside a small "program shell" of wrapper - code. The playground writes that shell for you so you can focus on the - instructions themselves — you'll learn to write the shell yourself in - [lesson {n}](#/lesson/11-writing-methods). +- The **first Run loads Python** in your browser, so it can take a few extra seconds. After that, runs are quick. +- A single `print(...)` line is already a complete Python program. Later, in [lesson {n}](#/lesson/11-writing-methods), you'll learn how to package instructions into your own functions. Press **Run** and watch the output panel below the code. -Now break it on purpose. Try changing the text between the quotes, or deleting -the semicolon, or removing a parenthesis, and hit Run again each time. Reading -error messages without panicking is one of the most useful skills in -programming — you'll see a lot of them, and every one is the computer telling -you exactly what it didn't understand. +Now break it on purpose. Try changing the text between the quotes, removing a quote, or deleting a parenthesis, and hit Run again each time. Reading error messages without panicking is one of the most useful skills in programming. You'll see plenty of them, and every one is Python telling you what it didn't understand. # Your turn -Edit the code below so it prints a greeting with **your own name** in it, -instead of `world`. Run it to check. +Edit the code below so it prints a greeting with **your own name** in it, instead of `world`. Run it to check. -```java -System.out.println("Hello, world!"); +```python +print("Hello, world!") ``` -Once that works, try adding a second line that prints something else about -yourself — your favorite subject, a hobby, anything. Each -`System.out.println(...)` line runs in order, top to bottom, and produces its -own line of output. +Once that works, add a second line that prints something else about yourself, like your favorite subject or a hobby. Each `print(...)` line runs in order, top to bottom, and produces its own line of output. diff --git a/lessons/07-variables/README.md b/lessons/07-variables/README.md index 331a8d4..4e4bd94 100644 --- a/lessons/07-variables/README.md +++ b/lessons/07-variables/README.md @@ -1,94 +1,59 @@ --- title: "Naming things" -goal: "Store a value under a typed name so you can reuse it and change it in one place." +goal: "Store a value under a name so you can reuse it and change it in one place." order: 70 -section: "Java Fundamentals" +section: "Python Fundamentals" --- # A name for a value -Back in [the very first lesson](#/lesson/01-flowcharts), every **number block** held a value, and arrows -carried that value forward to the blocks that needed it. In Java we do the -same thing with a **variable**: a name that stands for a value. +Back in [the very first lesson](#/lesson/01-flowcharts), every **number block** held a value, and arrows carried that value forward to the blocks that needed it. In Python we do the same thing with a **variable**: a name that stands for a value. -```java -String name = "Ada"; -System.out.println("Hello, " + name); +```python +name = "Ada" +print("Hello, " + name) ``` -Read the `=` as "gets" or "is set to," **not** as "equals" from math. It means: -take the value on the right, and store it under the name on the left. After that -line runs, the name `name` holds the text `"Ada"`, and anywhere you write `name` -the computer reaches in and uses that value. +Read the `=` as "gets" or "is set to," **not** as "equals" from math. It means: take the value on the right, and store it under the name on the left. After that line runs, the name `name` holds the text `"Ada"`, and anywhere you write `name` Python reaches in and uses that value. -The word in front of the name — `String` — is the variable's **type**: what -*kind* of value it holds. `String` means text. Java makes you say the type up -front, and in exchange it will catch you the moment you try to put the wrong -kind of value in — more on this in [lesson {n}](#/lesson/08-numbers-and-text). +Every value in Python has a **type**, which is the *kind* of value it is. `"Ada"` is a `str` (short for *string*, meaning text). Python figures out the type from the value you assign, so you don't have to write `str` in front of `name`, and it still tracks the type behind the scenes. More on types in [lesson {n}](#/lesson/08-numbers-and-text). -The `+` between `"Hello, "` and `name` **joins** text together into one string, -so this program prints `Hello, Ada`. +The `+` between `"Hello, "` and `name` **joins** text together into one string, so this program prints `Hello, Ada`. -Press **Run**. Then change `"Ada"` to your own name and run again. Notice you -only had to change it in **one place**, even though the name gets *used* on the -next line. That's the whole point of giving a value a name. +Press **Run**. Then change `"Ada"` to your own name and run again. Notice you only had to change it in **one place**, even though the name gets *used* on the next line. That's the whole point of giving a value a name. # Use a name as many times as you like -A variable earns its keep when you use it more than once. Because the value -lives in one place, you write it once and reuse the name everywhere. Whole -numbers get the type **`int`** (short for *integer*): +A variable earns its keep when you use it more than once. Because the value lives in one place, you write it once and reuse the name everywhere. Whole numbers have the type **`int`** (short for *integer*): -```java -int team = 2713; -System.out.println("We are FRC " + team); -System.out.println("Go " + team + "!"); -System.out.println(team + " is the best number"); +```python +team = 2713 +print(f"We are FRC {team}") +print(f"Go {team}!") +print(f"{team} is the best number") ``` -Every line reaches for the same stored value. Change `2713` to any number and -run it — all three lines update together, because they all point at the same -variable. Imagine if you'd typed the number out by hand three times instead: -you'd have to find and fix every copy. One name, one place to change. +Every line reaches for the same stored value. Change `2713` to any number and run it. All three lines update together, because they all point at the same variable. Imagine if you'd typed the number out by hand three times instead; you'd have to find and fix every copy. One name, one place to change. -(Notice `+` again: joining a number onto text turns the whole thing into one -printed line. Java converts the number to text for you when you glue it to a -string.) +Notice the `f` right before the opening quote, like `f"Go {team}!"`. That is an **f-string** (formatted string). Putting a variable inside `{ }` tells Python to drop its value straight into the text, whether it's a string or a number. -You can name a value anything you like, as long as it starts with a letter and -has no spaces. Good names describe what the value *is* — `team`, `score`, -`name` — so the program reads almost like English. `x` works too, but future-you -will thank present-you for `score`. +You can name a variable almost anything, as long as it starts with a letter or underscore and has no spaces. Good names describe what the value *is*, like `team`, `score`, or `name`, so the program reads close to English. For multi-word names, Python uses `snake_case` with underscores, like `team_number`. `x` works too, but future-you will thank present-you for `score`. # A variable can vary -Here's where the name earns the word *variable*: the value it holds can -**change** while the program runs. Assigning to a name a second time replaces -what was there before. +Here's where the name earns the word *variable*: the value it holds can **change** while the program runs. Assigning to a name a second time replaces what was there before. -```java -int score = 0; -System.out.println("Starting score: " + score); +```python +score = 0 +print(f"Starting score: {score}") -score = 10; -System.out.println("After scoring: " + score); +score = 10 +print(f"After scoring: {score}") -score = score + 5; -System.out.println("After a bonus: " + score); +score = score + 5 +print(f"After a bonus: {score}") ``` -One rule to spot: the type appears only on the **first** line, where the -variable is *declared*. You tell Java the type once — `int score = 0;` — and -after that you just use the name. Writing `int score = 10;` a second time would -be an error: Java would think you're trying to create a second variable with -the same name. - -Read those last two assignments carefully. `score = 10` throws away the old `0` -and stores `10`. Then `score = score + 5` looks confusing until you remember `=` -means "gets set to," not "equals": the computer works out the right side first -(`10 + 5 = 15`), then stores that back into `score`. This "take the value, change -it, put it back" pattern is exactly the running total the **repeat** block kept -in [lesson {n}](#/lesson/03-loops) — a value that updates itself, one step at a time. - -Your turn: add a line that gives a `10` penalty (subtract, don't add), then -print the score again. Predict the final number before you run it. +Read those last two assignments carefully. `score = 10` throws away the old `0` and stores `10`. Then `score = score + 5` looks strange until you remember `=` means "gets set to," not "equals." Python works out the right side first (`10 + 5 = 15`), then stores that back into `score`. This "take the value, change it, put it back" pattern is the same running total the **repeat** block kept in [lesson {n}](#/lesson/03-loops), a value that updates itself one step at a time. + +Your turn: add a line that gives a `10` point penalty (subtract, don't add), then print the score again. Predict the final number before you run it. diff --git a/lessons/08-numbers-and-text/README.md b/lessons/08-numbers-and-text/README.md index d1e5f2c..fc9be27 100644 --- a/lessons/08-numbers-and-text/README.md +++ b/lessons/08-numbers-and-text/README.md @@ -1,83 +1,49 @@ --- -title: "Types — numbers and text" +title: "Types: numbers and text" goal: "Tell the basic kinds of data apart, and convert between them." order: 80 -section: "Java Fundamentals" +section: "Python Fundamentals" --- # Numbers are not text -The block editor quietly hid something from you: it only ever dealt with -numbers. Real programs juggle different **kinds** of data — [lesson {n}](#/lesson/07-variables) already -made you name the kind every time you declared a variable. That kind is the -**type**, and the two you'll meet first are: +The block editor quietly hid something from you: it only ever dealt with numbers. Real programs juggle different **kinds** of data. Every value in Python has a **type** ([lesson {n}](#/lesson/07-variables)), and the two you'll meet first are: -- **`int`** — a whole number you can do math with: `7`, `42`, `-3`. -- **`String`** — text: a run of characters wrapped in quotes: `"7"`, `"hello"`, - `"FRC 2713"`. +- **`int`**: a whole number you can do math with, like `7`, `42`, `-3`. +- **`str`**: text, a run of characters wrapped in quotes, like `"7"`, `"hello"`, `"FRC 2713"`. -They look similar but behave completely differently. Watch: +They look similar but behave differently. Watch: -```java -System.out.println(3 + 4); -System.out.println("3" + "4"); +```python +print(3 + 4) +print("3" + "4") ``` -The first line prints `7` — that's math. The second prints `34`, because with -text, `+` means **stick these together** (you used it that way in [lesson {n}](#/lesson/07-variables)), -not "add." `"3"` and `"4"` aren't numbers to Java; they're just characters that -happen to look like digits, so it glues them into `"34"`. +The first line prints `7`, which is math. The second prints `34`, because with text, `+` means **stick these together** (you used it that way in [lesson {n}](#/lesson/07-variables)), not "add." `"3"` and `"4"` aren't numbers to Python; they're characters that happen to look like digits, so Python glues them into `"34"`. -Run it. The lesson: the *quotes* decide everything. `7` is a number you can add; -`"7"` is text you can only join. Getting these mixed up is one of the most -common early bugs, so whenever something misbehaves, ask: *is this a number, or -text that looks like a number?* +Run it. The lesson: the *quotes* decide everything. `7` is a number you can add; `"7"` is text you can join. Getting these mixed up is one of the most common early bugs, so whenever something misbehaves, ask: *is this a number, or text that looks like a number?* # Text that looks like a number -Sometimes a value *looks* like a number but is really text — because it's -wrapped in quotes. Here's the trap, and it's sneakier than a crash: +Sometimes a value *looks* like a number but is really text because it's wrapped in quotes, like `"24"`. If you try `"24" + 1` in Python, it stops with a `TypeError` because Python refuses to guess whether you meant `"241"` or `25`. -```java -String age = "24"; -System.out.println(age + 1); -``` - -Run that. It doesn't fail — it prints `241`. Java saw text on the left of the -`+`, so it treated the `1` as text too and **glued** instead of adding. No -error, no warning, just a silently wrong answer — which in a program is far -more dangerous than a crash, because nothing tells you to go looking for it. - -The fix is to **convert** the text into a real number with -`Integer.parseInt(...)`: +The fix is to **convert** the text into a real number with `int(...)`: -```java -String ageText = "24"; -int age = Integer.parseInt(ageText); -System.out.println("Next year you will be " + (age + 1)); +```python +age_text = "24" +age = int(age_text) +print(f"Next year you will be {age + 1}") ``` -Notice we needed a **second variable**. `ageText` is a `String` and its type -can never change — that's the deal Java made with you in [lesson {n}](#/lesson/07-variables). So the -converted number gets its own name, `age`, with its own type, `int`. One name -per kind of thing keeps the program honest: you can always tell what's text -and what's a number just by reading the declarations. (The parentheses around -`(age + 1)` make the math happen *before* the joining — remember inner-first -from [lesson {n}](#/lesson/01-flowcharts).) +Using a separate name for the converted number (`age_text` for the `str`, `age` for the `int`) keeps the program easy to read. You can tell at a glance what is text and what is a number, building on the naming habit from [lesson {n}](#/lesson/07-variables). Inside the f-string, Python evaluates `age + 1` first before inserting the result, just like inner-first evaluation in [lesson {n}](#/lesson/01-flowcharts). -Conversion goes the other way too: `String.valueOf(42)` turns a number into -text — though as you saw, gluing a number onto a string with `+` usually does -that for you. +Conversion goes the other way too: `str(42)` turns a number into the text `"42"`, which is handy whenever you want to join a number onto a string with `+` instead of an f-string. -One more type while we're here: numbers with a decimal point, like a motor -voltage of `12.5`, use the type **`double`**: +One more type while we're here: numbers with a decimal point, like a motor voltage of `12.5`, use the type **`float`** (short for *floating-point number*): -```java -double voltage = 12.5; -System.out.println("Battery: " + voltage + " volts"); +```python +voltage = 12.5 +print(f"Battery: {voltage} volts") ``` -Your turn: start with the text `"9"`, convert it with `Integer.parseInt`, and -print that number **plus 5**. If you see `95` instead of `14`, you've just -met the glue-instead-of-add bug from the top of this page — look at where the -conversion happens. +Your turn: start with the text `"9"`, convert it with `int(...)`, and print that number **plus 5**. Then try removing `int(...)` for a moment and running it to see the `TypeError` Python gives when you mix text and numbers. diff --git a/lessons/09-if-statements/README.md b/lessons/09-if-statements/README.md index 45242aa..a10c873 100644 --- a/lessons/09-if-statements/README.md +++ b/lessons/09-if-statements/README.md @@ -1,89 +1,63 @@ --- title: "Decisions in code" -goal: "Use if, else if, and else to make a program choose between paths." +goal: "Use if, elif, and else to make a program choose between paths." order: 90 -section: "Java Fundamentals" +section: "Python Fundamentals" --- # The decision diamond, in text -Remember the **decision diamond** from [lesson {n}](#/lesson/02-conditionals)? It asked a true/false question and then -took one path or the other, skipping the branch it didn't take. Java writes -that same idea with the word **`if`**: +Remember the **decision diamond** from [lesson {n}](#/lesson/02-conditionals)? It asked a true/false question and then took one path or the other, skipping the branch it didn't take. Python writes that same idea with the word **`if`**: -```java -int temperature = 5; -if (temperature < 10) { - System.out.println("Bring a jacket!"); -} -System.out.println("Have a good day."); +```python +temperature = 5 +if temperature < 10: + print("Bring a jacket!") +print("Have a good day.") ``` Three things to notice: -- **The question** goes in parentheses: `(temperature < 10)` — a comparison - that works out to `true` or `false`, just like the question in the diamond. -- **The curly braces `{ }`** wrap the `true` branch — everything between - them runs *only* when the question is true. (The indentation is for human - eyes; Java only cares about the braces.) -- **The last line** runs no matter what, because it's outside the braces — not - part of the `if`. +- **The question** follows `if` and ends with a colon `:`. `temperature < 10` works out to `True` or `False`, just like the question in the diamond. +- **The indented lines** form the `True` branch. Everything indented under the `if` runs *only* when the question is true. +- **The last line** is back at the left edge, outside the `if`, so it runs no matter what. -The braces replace the arrows leaving the diamond. Run it, -then change `temperature` to `20` and run again — the jacket line vanishes, -but the "good day" line always prints. +Indentation replaces the arrows leaving the diamond. Run it, then change `temperature` to `20` and run again. The jacket line vanishes, while the "good day" line always prints. # Both paths: else -[Lesson {n}'s](#/lesson/02-conditionals) diamond always had *two* arrows — a `true` arrow and a `false` arrow. -Java spells the second one **`else`**: +[Lesson {n}'s](#/lesson/02-conditionals) diamond always had *two* arrows, a `true` arrow and a `false` arrow. Python spells the second one **`else:`**: -```java -int score = 7; -if (score >= 6) { - System.out.println("You passed!"); -} else { - System.out.println("Not yet — try again."); -} +```python +score = 7 +if score >= 6: + print("You passed!") +else: + print("Not yet, try again.") ``` -Exactly one of those two blocks runs, every time. If the question is true, you -get the first; otherwise you get the second. The other is skipped — "the road -not taken" from [lesson {n}](#/lesson/02-conditionals), in text form. - -One thing to watch closely: that's `>=` ("greater than or equal to"), and the -"is it equal?" test is `==` with **two** equals signs. A single `=` means -"store a value" ([lesson {n}](#/lesson/07-variables)), so Java uses `==` to *ask* about equality. Mixing -them up is the code version of the `>` vs `≥` bug [lesson {n}](#/lesson/02-conditionals) warned about. - -Change `score` to `6`, then `5`, and run each time. Convince yourself `>= 6` -lets a `6` pass but a `5` doesn't. - -# More than two paths: else if - -Sometimes there are more than two outcomes. `else if` lets you ask another -question when the previous one was false: - -```java -int score = 95; -if (score >= 90) { - System.out.println("Grade: A"); -} else if (score >= 80) { - System.out.println("Grade: B"); -} else if (score >= 70) { - System.out.println("Grade: C"); -} else { - System.out.println("Grade: F"); -} +Exactly one of those two blocks runs, every time. If the question is true, you get the first; otherwise you get the second. The other is skipped, "the road not taken" from [lesson {n}](#/lesson/02-conditionals), in text form. + +One thing to watch closely: `>=` means "greater than or equal to," and the "is it equal?" test is `==` with **two** equals signs. A single `=` means "store a value" ([lesson {n}](#/lesson/07-variables)), so Python uses `==` to *ask* about equality. Mixing them up is the code version of the `>` vs `≥` bug [lesson {n}](#/lesson/02-conditionals) warned about. + +Change `score` to `6`, then `5`, and run each time. Convince yourself `>= 6` lets a `6` pass while a `5` doesn't. + +# More than two paths: elif + +Sometimes there are more than two outcomes. `elif` (short for "else if") lets you ask another question when the previous one was false: + +```python +score = 95 +if score >= 90: + print("Grade: A") +elif score >= 80: + print("Grade: B") +elif score >= 70: + print("Grade: C") +else: + print("Grade: F") ``` -Java checks each question **top to bottom** and takes the **first** one that's -true — then skips all the rest. That order matters: a score of `95` is also -`>= 80`, but because `>= 90` is checked first and wins, you never reach the B -line. This is the same "inputs before the things that use them, one step at a -time" discipline from [lesson {n}](#/lesson/01-flowcharts). +Python checks each question **top to bottom** and takes the **first** one that's true, then skips all the rest. That order matters: a score of `95` is also `>= 80`, but because `>= 90` is checked first and wins, you never reach the B line. This is the same "one step at a time, in order" discipline from [lesson {n}](#/lesson/01-flowcharts). -Run it, then change `score` to `85`, `72`, and `40` and run each time to see a -different branch win. Then your challenge: build a program that sets a number -in a variable and prints whether it's `"negative"`, `"zero"`, or `"positive"` -— three paths, so you'll need an `if`, an `else if`, and an `else`. +Run it, then change `score` to `85`, `72`, and `40` and run each time to see a different branch win. Then your challenge: build a program that sets a number in a variable and prints whether it's `"negative"`, `"zero"`, or `"positive"`. That's three paths, so you'll need an `if`, an `elif`, and an `else`. diff --git a/lessons/10-loops/README.md b/lessons/10-loops/README.md index 722ed1e..6d6a40a 100644 --- a/lessons/10-loops/README.md +++ b/lessons/10-loops/README.md @@ -1,94 +1,59 @@ --- title: "Loops in code" -goal: "Repeat steps in Java with for and while instead of copying lines." +goal: "Repeat steps in Python with for and while instead of copying lines." order: 100 -section: "Java Fundamentals" +section: "Python Fundamentals" --- # Repeat, in text -In [lesson {n}](#/lesson/03-loops) the **repeat** block did a step over and over so you didn't have to -copy it out by hand. Java's version is the **`for` loop**, and it comes with a -built-in counter. Meet the counter first: +In [lesson {n}](#/lesson/03-loops) the **repeat** block did a step over and over so you didn't have to copy it out by hand. Python's version is the **`for` loop**, and it comes with a built-in counter. Meet the counter first: -```java -for (int i = 0; i < 5; i++) { - System.out.println("This is loop number " + i); -} +```python +for i in range(5): + print(f"This is loop number {i}") ``` -The header has **three slots**, separated by semicolons: +Read the header in three pieces: -- `int i = 0` — **start**: create a counter variable `i` holding `0`. -- `i < 5` — **keep going while**: before each pass, check this question; the - loop runs only while it's true. -- `i++` — **step**: after each pass, bump `i` up by one (`i++` is shorthand - for `i = i + 1`). +- **`range(5)`** generates five numbers starting at `0`: `0`, `1`, `2`, `3`, `4`. +- **`i`** is the counter variable. On each pass, Python puts the next number from `range(5)` into `i`. +- **The colon `:` and indented lines** hold the steps that repeat, just like `if` in [lesson {n}](#/lesson/09-if-statements). -Those are the same three ideas the repeat block had — a start, a count, and a -step. The braces hold the step that repeats, just like `if` in [lesson {n}](#/lesson/09-if-statements). +Run it and watch `i` climb: `0`, `1`, `2`, `3`, `4`. That's five passes, and the loop hands you the "which time around am I?" number on every one. Programmers start counting at zero; you'll see why it's handy in [lesson {n}](#/lesson/12-arrays). -Run it and watch `i` climb: `0`, `1`, `2`, `3`, `4` — five passes, and the loop -hands you the "which time around am I?" number on every one, free of charge. -(Programmers start counting at zero; you'll see why it's handy in [lesson {n}](#/lesson/12-arrays).) - -Once the counting makes sense, put the loop to work: change the middle slot to -`i < 3`, then `i < 10`, and watch the count follow. Then swap the print line -for `System.out.println("Go team!");` — same loop, but now it just repeats a -step five times. You don't have to *use* `i` for the loop to do its job of -repeating. +Once the counting makes sense, put the loop to work: change `range(5)` to `range(3)`, then `range(10)`, and watch the count follow. Then swap the print line for `print("Go team!")`. Same loop, only now it repeats a message five times. You don't have to *use* `i` for the loop to do its job of repeating. # A running total -The real power of [lesson {n}'s](#/lesson/03-loops) repeat block was the **running total** — a value it -remembered and updated each time around. You build that yourself in a `for` -loop by combining it with a variable ([lesson {n}](#/lesson/07-variables)): - -```java -int total = 0; -for (int i = 0; i < 5; i++) { - total = total + 3; - System.out.println("So far: " + total); -} -System.out.println("Final total: " + total); +The real power of [lesson {n}'s](#/lesson/03-loops) repeat block was the **running total**, a value it remembered and updated each time around. You build that yourself in a `for` loop by combining it with a variable ([lesson {n}](#/lesson/07-variables)): + +```python +total = 0 +for i in range(5): + total = total + 3 + print(f"So far: {total}") +print(f"Final total: {total}") ``` -Trace it: `total` starts at `0`, and each pass adds `3`, so it climbs `3`, `6`, -`9`, `12`, `15` — the exact sequence the "repeat +" block produced. The pattern -is *declare a starting value before the loop, update it inside the loop.* -That's how many identical steps add up to one answer. +Trace it: `total` starts at `0`, and each pass adds `3`, so it climbs `3`, `6`, `9`, `12`, `15`, the exact sequence the "repeat +" block produced. The pattern is *set a starting value before the loop, then update it inside the loop.* Notice `print(f"Final total: {total}")` is not indented, so it runs once after the loop finishes. -Try it yourself: change the starting value, the loop count, or the amount you -add. Then make a **multiplying** total — start at `1` and do -`total = total * 2` each pass — and check you get `2`, `4`, `8`, `16`, `32`, -just like the "repeat ×" block. +Try it yourself: change the starting value, the loop count, or the amount you add. Then make a **multiplying** total. Start at `1` and do `total = total * 2` each pass, and check that you get `2`, `4`, `8`, `16`, `32`, just like the "repeat ×" block. # When you don't know the count: while -A `for` loop repeats a **known** number of times. But sometimes you need to -keep going *until something happens*, and you don't know how many steps that'll -take. That's a **`while` loop**: it repeats as long as a question stays true. - -```java -int countdown = 5; -while (countdown > 0) { - System.out.println(countdown); - countdown = countdown - 1; -} -System.out.println("Liftoff!"); +A `for` loop repeats a **known** number of times. Sometimes you need to keep going *until something happens*, and you don't know how many steps that will take. That's a **`while` loop**: it repeats as long as a question stays true. + +```python +countdown = 5 +while countdown > 0: + print(countdown) + countdown = countdown - 1 +print("Liftoff!") ``` -Each time around, Java re-checks `(countdown > 0)`. As long as it's true, it -runs the braced steps; the moment it's false, the loop stops and the program -moves on. Here we count `5, 4, 3, 2, 1` and then lift off. Notice the loop -**changes the thing it's checking** (`countdown` shrinks each pass) — that's -essential. +Each time around, Python re-checks `countdown > 0`. As long as it's true, Python runs the indented steps; the moment it's false, the loop stops and the program moves on. Here we count `5, 4, 3, 2, 1` and then lift off. Notice the loop **changes the thing it's checking** (`countdown` shrinks each pass). That part is essential. -If a `while` loop never changes its condition, it runs **forever** — an -"infinite loop," the most common beginner bug. Delete the -`countdown = countdown - 1;` line in your head and you'll see why: `countdown` -would stay `5` and the question would never turn false. +If a `while` loop never changes its condition, it runs **forever**, an "infinite loop," which is the most common beginner bug. Picture deleting `countdown = countdown - 1`: `countdown` would stay `5` and the question would never turn false. -Your turn: write a `while` loop that starts a `total` at `1`, **doubles** it -each pass, and keeps going *while* `total < 100`. Print `total` each time. -What's the first value it prints that's past 100? +Your turn: write a `while` loop that starts a `total` at `1`, **doubles** it each pass, and keeps going *while* `total < 100`. Print `total` each time. What's the first value it prints that's past 100? diff --git a/lessons/11-writing-methods/README.md b/lessons/11-writing-methods/README.md index 8c0224e..004a114 100644 --- a/lessons/11-writing-methods/README.md +++ b/lessons/11-writing-methods/README.md @@ -1,114 +1,78 @@ --- -title: "Writing your own methods" -goal: "Package steps into a named method and hand back a result with return." +title: "Writing your own functions" +goal: "Package steps into a named function and hand back a result with return." order: 110 -section: "Java Fundamentals" +section: "Python Fundamentals" --- -# The program shell, revealed +# Packaging steps with def -Since [lesson {n}](#/lesson/06-hello-world), the playground has been quietly wrapping your code in a small -"program shell." Time to see it, because the thing you're about to build — a -reusable block of your own — has to live inside it. Here is what a complete -Java program really looks like: +Since [lesson {n}](#/lesson/06-hello-world), every script you wrote ran straight from top to bottom. Now you're ready to build reusable blocks of your own, just like the custom blocks in [lesson {n}](#/lesson/04-functions). In Python, a reusable block of code is called a **function**, and you create one with **`def`**: -```java -public class Main { - public static void main(String[] args) { - System.out.println("Hello from inside the shell!"); - } -} +```python +def say_hello(): + print("Hello from inside a function!") + +say_hello() +say_hello() ``` -Two layers, outside-in: +Two parts to spot: + +- **`def say_hello():`** defines a function named `say_hello`. The indented lines underneath are the steps inside it. +- **`say_hello()`** calls the function, telling Python to run those indented steps. -- `public class Main { ... }` — every Java program is a **class**, a named - container for code. (Much more on classes in [lesson {n}](#/lesson/17-classes-and-objects).) -- `public static void main(String[] args) { ... }` — the **main method**: - the agreed-upon starting point. When a Java program runs, the computer finds - `main` and follows its instructions top to bottom. Every line you've written - so far was living here. +Defining a function doesn't run it; it just teaches Python the block exists. It only does its work when you *call* it, and you can call it as many times as you need. Later, in [lesson {n}](#/lesson/17-classes-and-objects), you'll also put functions inside classes, where they're called methods. -Run it — it behaves exactly like [lesson {n}](#/lesson/06-hello-world)'s one-liner, because it *is* that -program, shell and all. From now on, when a snippet shows the full shell, the -playground runs it exactly as written; you're seeing the whole truth. +Run it and notice the message prints twice from one function definition. # Define a block of your own -[Lesson {n}](#/lesson/04-functions) gave you reusable blocks — a **double** block with a little flowchart -hidden inside, that you could drop in wherever you needed it. In Java, a -reusable block is called a **method**, and now you can build one yourself: +[Lesson {n}](#/lesson/04-functions) gave you a **double** block with a little flowchart hidden inside that you could drop in wherever you needed it. Here is that same block in Python: -```java -public class Main { - static int doubleIt(int n) { - return n * 2; - } +```python +def double_it(n): + return n * 2 - public static void main(String[] args) { - System.out.println(doubleIt(5)); - } -} +print(double_it(5)) ``` -Read the new method piece by piece: - -- `static int doubleIt(int n)` — names a new method `doubleIt` that takes one - input, `int n` (the arrow feeding into the block), and promises to hand back - an `int` — that first `int` is the **return type**. Even a method's output - has a type in Java. -- `return n * 2;` is the flowchart *inside* the block: it works out the answer - and **hands it back** with `return`. -- `doubleIt(5)` **calls** the method — it runs those inner steps with `n` set - to `5`, and the whole `doubleIt(5)` becomes the value `10`. - -Methods live inside the class, *next to* `main` — not inside it. Defining one -doesn't run it; it just teaches Java the block exists. It only does its work -when you *call* it. Run this, then change `5` and run again — same block, -different input, just like [lesson {n}](#/lesson/04-functions). - -The `n` is called a **parameter** — a placeholder that gets filled in with -whatever value you pass when you call. A method can take more than one: - -```java -static int add(int a, int b) { - return a + b; -} +Read the function piece by piece: + +- `def double_it(n):` names a new function `double_it` that takes one input, `n` (the arrow feeding into the block). +- `return n * 2` is the flowchart *inside* the block: it works out the answer and **hands it back** with `return`. +- `double_it(5)` **calls** the function. Python runs those inner steps with `n` set to `5`, and `double_it(5)` evaluates to `10`. + +Run this, then change `5` and run again: same block, different input, just like [lesson {n}](#/lesson/04-functions). + +The `n` is called a **parameter**, a placeholder that gets filled in with whatever value you pass when you call the function. A function can take more than one: + +```python +def add(a, b): + return a + b + +print(add(2, 3)) ``` -Add that next to `doubleIt` and call `add(2, 3)` from `main`. +Add `add` next to `double_it` in the editor above and call `add(2, 3)` inside `print(...)`. # Order matters (again) -[Lesson {n}](#/lesson/04-functions) ended with the big idea that **order matters**: `add 1` then `double` -gave a different answer than `double` then `add 1`. Let's prove it in code with -two methods of your own: - -```java -public class Main { - static int addOne(int n) { - return n + 1; - } - - static int doubleIt(int n) { - return n * 2; - } - - public static void main(String[] args) { - System.out.println(doubleIt(addOne(4))); - System.out.println(addOne(doubleIt(4))); - } -} +[Lesson {n}](#/lesson/04-functions) ended with the big idea that **order matters**: `add 1` then `double` gave a different answer than `double` then `add 1`. Let's prove it in code with two functions of your own: + +```python +def add_one(n): + return n + 1 + +def double_it(n): + return n * 2 + +print(double_it(add_one(4))) +print(add_one(double_it(4))) ``` -Trace the first line from the inside out: `addOne(4)` is `5`, then `doubleIt(5)` -is `10`. The second line: `doubleIt(4)` is `8`, then `addOne(8)` is `9`. Same -two blocks, same starting number, **different order, different answer** — -exactly the [lesson-4](#/lesson/04-functions) result, now in text. +Trace the first print line from the inside out: `add_one(4)` is `5`, then `double_it(5)` is `10`. The second line: `double_it(4)` is `8`, then `add_one(8)` is `9`. Same two blocks, same starting number, **different order, different answer**, matching the [lesson-4](#/lesson/04-functions) result. Run it and confirm you get `10` then `9`. -Your challenge: write a method `square(int n)` that returns `n * n`, then use -it together with `addOne` to compute **`(4 + 1)` squared**. Predict the answer -before you run — and watch your call order, because `square(addOne(4))` and -`addOne(square(4))` are *not* the same. +Your challenge: write a function `square(n)` that returns `n * n`, then use it together with `add_one` to compute **`(4 + 1)` squared**. Predict the answer before you run, and watch your call order, because `square(add_one(4))` and `add_one(square(4))` are *not* the same. diff --git a/lessons/12-arrays/README.md b/lessons/12-arrays/README.md index 848ef4a..f54e768 100644 --- a/lessons/12-arrays/README.md +++ b/lessons/12-arrays/README.md @@ -1,5 +1,5 @@ --- -title: "Arrays" +title: "Lists" goal: "Hold many values in one place, reach any of them by position, and walk through them with a loop." order: 120 section: "Data Structures" @@ -7,100 +7,101 @@ section: "Data Structures" # One name, many values -Every variable so far has held a *single* value: one number, one string. But -real programs deal in **groups** — the six sensor readings on a robot, the names -of everyone on the drive team, the points scored in each match. Java holds a -group in an **array**: values in curly braces, separated by commas. +Every variable so far has held a *single* value: one number, one string. Real +programs deal in **groups**, like the six sensor readings on a robot, the names +of everyone on the drive team, or the points scored in each match. Python holds +a group in a **list**: values inside square brackets, separated by commas. -```java -int[] readings = {12, 47, 3, 88, 21}; -System.out.println(readings.length); -System.out.println(Arrays.toString(readings)); +```python +readings = [12, 47, 3, 88, 21] +print(len(readings)) +print(readings) ``` -`readings` is *one* variable holding *five* numbers. Its type, `int[]`, reads -as "array of int" — the square brackets mean "many of these." `.length` tells -you how many are in there — run it and you'll see `5`. An array can hold text -too — `String[] sides = {"front", "back", "left", "right"};` — and every slot -has the type the array declared: an `int[]` holds ints, and nothing else. +`readings` is *one* variable holding *five* numbers. `len(readings)` tells you +how many items are inside. Run it and you will see `5`, followed by the full +list `[12, 47, 3, 88, 21]`. A list can hold text too, like +`sides = ["front", "back", "left", "right"]`. -(`Arrays.toString(...)` is a helper that prints the whole array nicely; -printing an array directly shows a cryptic id instead of the values.) - -The point: instead of `reading1`, `reading2`, `reading3`, `reading4`, -`reading5` — five names to keep straight — you have one name for the whole -batch. That's the whole idea of an array. +Instead of juggling five separate names like `reading1`, `reading2`, `reading3`, +`reading4`, and `reading5`, you keep one name for the whole batch. That is the +whole idea of a list. # Reaching one item -You pull a single value out of an array by its **position**, written in square -brackets after the name. And here's the catch that trips up everyone: Java -counts positions starting from **0**, not 1 — the same "programmers start at -zero" rule the loop counter followed back in [lesson {n}](#/lesson/10-loops). +You pull a single value out of a list by its **position**, written in square +brackets after the name. Python counts positions starting from **0**, not 1, +following the same "programmers start at zero" rule from +[lesson {n}](#/lesson/10-loops). -```java -int[] readings = {12, 47, 3, 88, 21}; -System.out.println(readings[0]); -System.out.println(readings[1]); -System.out.println(readings[4]); +```python +readings = [12, 47, 3, 88, 21] +print(readings[0]) +print(readings[1]) +print(readings[4]) ``` So `readings[0]` is the **first** item (`12`), `readings[1]` is the second (`47`), and `readings[4]` is the fifth and last (`21`). That number in brackets -is called the **index**. +is called the **index**. Python also lets you count backward from the end with +negative numbers, so `readings[-1]` grabs the last item (`21`). -Because counting starts at zero, the last index is always `length - 1`, never -`length`. Ask for `readings[5]` and the program fails with an -`ArrayIndexOutOfBoundsException` — there's no sixth item. Try it and read the -error: "exception" is Java's word for "something went wrong while running," -and this one tells you exactly what — the index was out of the array's bounds. -Then fix it back. +Because forward counting starts at zero, the last positive index is always +`len(readings) - 1`, never `len(readings)`. Ask for `readings[5]` and Python +stops with an `IndexError: list index out of range`. There is no sixth item. +Try it, read the error message, and then change it back. -You can also *change* an item by assigning to its position, exactly like a +You can also *change* an item by assigning to its position, just like a regular variable: -```java -int[] readings = {12, 47, 3, 88, 21}; -readings[0] = 99; -System.out.println(Arrays.toString(readings)); +```python +readings = [12, 47, 3, 88, 21] +readings[0] = 99 +print(readings) ``` -# Walking the whole array +# Walking the whole list -[Lesson {n}'s](#/lesson/10-loops) `for` loop counted with `i`. There's a second form of `for` whose -real job is walking an array — handing you each item, one per pass. It's -called the **for-each** loop: +[Lesson {n}'s](#/lesson/10-loops) `for` loop counted with `range(...)`. A `for` +loop can also walk straight through a list, handing you each item one pass at a +time: -```java -int[] scores = {10, 25, 5, 40}; -for (int score : scores) { - System.out.println("We scored " + score); -} +```python +scores = [10, 25, 5, 40] +for score in scores: + print(f"We scored {score}") ``` -No indexes, no counting — the loop takes care of visiting every item in order. -Read the colon as "in": "for each `score` in `scores`, print it." Run it and -you get one line per match. +No indexes, no manual counting. The loop visits every item in order. Read the +header like English: "for each `score` in `scores`, print it." Run it and you +get one line per match. -Now combine it with the **running total** from [lesson {n}](#/lesson/10-loops) to add an array up: +Now combine it with the **running total** from [lesson {n}](#/lesson/10-loops) +to add a list up: -```java -int[] scores = {10, 25, 5, 40}; -int total = 0; -for (int score : scores) { - total = total + score; -} -System.out.println("Total points: " + total); +```python +scores = [10, 25, 5, 40] +total = 0 +for score in scores: + total = total + score +print(f"Total points: {total}") ``` -Same pattern as always — declare a total *before* the loop, update it *inside*. +Same pattern as before. Start a total *before* the loop and update it *inside*. + +## Fixed sequences: tuples + +Sometimes you have a small group of values that should never change, like an +`(x, y)` field position or an RGB color. Python calls that a **tuple**, written +with parentheses instead of square brackets: `position = (3.5, 1.2)`. You can +index it with `position[0]` and check `len(position)` just like a list, but +trying to change a slot with `position[0] = 5.0` raises a `TypeError`. Use a +list when the items can change, and a tuple when they are fixed. -One thing an array **can't** do is grow: it's created with a fixed number of -slots and keeps them forever. [Next lesson](#/lesson/13-arraylists) covers -`ArrayList`, Java's group that grows and shrinks — but nail down arrays first: -a fixed row of numbered slots. +[Next lesson](#/lesson/13-arraylists) shows how to grow, shrink, and slice lists +while a program runs. -Your turn: make an array of five sensor `readings`, then loop through and print -only the ones **above 20** (you'll need an `if` inside the `for` — [lesson {n}](#/lesson/09-if-statements) -meets [lesson {n}](#/lesson/12-arrays)). Then use the running-total pattern and `.length` to print the -**average**. Predict it first, then check. +Your turn: make a list of five sensor `readings`, then loop through and print +only the ones **above 20** (combining [lesson {n}](#/lesson/09-if-statements) +and [lesson {n}](#/lesson/12-arrays)). Then use the running-total pattern and +`len()` to print the **average**. Predict the answer first, then check. diff --git a/lessons/13-arraylists/README.md b/lessons/13-arraylists/README.md index 4635941..c3a6fdb 100644 --- a/lessons/13-arraylists/README.md +++ b/lessons/13-arraylists/README.md @@ -1,122 +1,108 @@ --- -title: "ArrayLists" -goal: "Hold a group that grows and shrinks while the program runs, instead of a fixed number of slots." +title: "Growing and changing lists" +goal: "Build lists while a program runs, add and remove items, and pull out slices." order: 130 section: "Data Structures" --- -# A row that can grow +# Building a list as you go -[Last lesson's](#/lesson/12-arrays) array is great, but it commits to a size up -front: the five values you write between the braces are five slots, forever. -That's a problem the moment you -don't know the count ahead of time — how many game pieces will you score this -match? You don't know until the match is over. +In [last lesson](#/lesson/12-arrays) you wrote every value in the list up front. +That breaks down the moment you do not know the count ahead of time. How many +game pieces will your robot score this match? You do not know until the match is +over. -Java's answer is `ArrayList`: a list that grows one slot at a time as you add -to it. +Python lists can start **empty** (`[]`) and grow one item at a time with +`.append(...)`: -```java -ArrayList scores = new ArrayList<>(); -scores.add(10); -scores.add(25); -scores.add(15); -System.out.println(scores); -System.out.println(scores.size()); +```python +scores = [] +scores.append(10) +scores.append(25) +scores.append(15) +print(scores) +print(len(scores)) ``` -Run it. `scores` starts **empty** — no size decided up front — and each -`.add(...)` grows it by one. `System.out.println(scores)` prints the whole -list at once: `[10, 25, 15]`. And instead of the array's `.length` -*property*, a list has a `.size()` *method* — one of those small differences -that trips people up, so it's worth saying out loud: arrays use `.length`, no -parentheses; lists use `.size()`, with parentheses. - -Notice the type in the brackets is `Integer`, capitalized — not the lowercase -`int` from every lesson before this one. An `ArrayList` can only hold -**objects**, not raw numbers, so Java uses a boxed stand-in type for each -primitive (`Integer` for `int`, `Double` for `double`, and so on). You'll -mostly just write `Integer` where you mean "a group of `int`s" and Java quietly -boxes and unboxes the values for you — `scores.add(10)` just works even -though `10` is a plain `int`. - -# Reaching, changing, removing - -Like an array, you reach one item by index with square brackets — except an -`ArrayList` uses a method instead of brackets: - -```java -ArrayList scores = new ArrayList<>(); -scores.add(10); -scores.add(25); -scores.add(15); -System.out.println(scores.get(1)); +Run it. `scores` starts with zero items, and each `.append(...)` tacks a new +value onto the end. `print(scores)` shows `[10, 25, 15]`, and `len(scores)` is +`3`. + +This shines inside a loop. You can walk through one list and build a brand-new +list with only the values you want to keep: + +```python +readings = [12, 47, 3, 88, 21] +high_readings = [] +for reading in readings: + if reading > 20: + high_readings.append(reading) +print(high_readings) ``` -`.get(1)` is the second item (`25`) — indexes still start at **0**, same rule -as [lesson {n}](#/lesson/12-arrays). To change a slot without touching the -others, use `.set(index, value)`: - -```java -ArrayList scores = new ArrayList<>(); -scores.add(10); -scores.add(25); -scores.add(15); -scores.set(0, 99); -System.out.println(scores); +Start with an empty list before the loop, then append inside the `if`. You will +use this pattern all the time to filter sensor data or collect match events. + +# Removing items with pop and remove + +Python gives you two main ways to take items out of a list. When you know the +**position** you want to remove, use `.pop(index)`. It deletes that slot, shifts +everything after it down, and hands the removed value back to you: + +```python +scores = [10, 25, 15] +dropped = scores.pop(1) +print(dropped) +print(scores) ``` -And to shrink the list, `.remove(index)` deletes a slot entirely — everything -after it shifts down to fill the gap, and `.size()` drops by one: +That prints `25`, then `[10, 15]`. Indexes still start at **0**, same rule as +[lesson {n}](#/lesson/12-arrays). If you call `scores.pop()` with nothing inside +the parentheses, it removes and returns the **last** item. -```java -ArrayList scores = new ArrayList<>(); -scores.add(10); -scores.add(25); -scores.add(15); -scores.remove(1); -System.out.println(scores); +When you know the **value** you want gone instead of its position, use +`.remove(value)`: + +```python +sides = ["front", "left", "back", "right"] +sides.remove("back") +print(sides) ``` -That prints `[10, 15]` — `25` is gone and `15` slid into its place. This is -the move an array simply cannot make: an array's size never changes, but a -list's does, on demand. - -# Looping and checking membership - -A for-each loop ([lesson {n}](#/lesson/12-arrays)) walks a list exactly like it -walks an array: - -```java -ArrayList scores = new ArrayList<>(); -scores.add(10); -scores.add(25); -scores.add(15); -int total = 0; -for (int score : scores) { - total = total + score; -} -System.out.println("Total points: " + total); +`.remove(...)` finds the first matching item and deletes it. If the value is not +in the list, Python stops with a `ValueError`, so make sure it is there first. + +# Slicing and checking membership + +Sometimes you want a chunk of a list rather than a single item. **Slicing** uses +a colon inside the brackets, `scores[start:stop]`, to copy from `start` up to +(but not including) `stop`, just like `range` in +[lesson {n}](#/lesson/10-loops): + +```python +scores = [10, 25, 15, 40, 30] +print(scores[1:4]) +print(scores[:2]) +print(scores[3:]) ``` -One more list-only trick: `.contains(...)` asks "is this value in here -anywhere?" without you writing a loop yourself. +`scores[1:4]` grabs indexes `1`, `2`, and `3`, giving `[25, 15, 40]`. Leave out +the first number (`scores[:2]`) to start from the beginning. Leave out the +second number (`scores[3:]`) to go all the way to the end. Slicing always makes +a new list and leaves `scores` untouched. + +One more handy check: `in` asks whether a value appears anywhere in the list, +without writing a loop yourself: -```java -ArrayList scores = new ArrayList<>(); -scores.add(10); -scores.add(25); -System.out.println(scores.contains(25)); -System.out.println(scores.contains(99)); +```python +scores = [10, 25, 15] +print(25 in scores) +print(99 in scores) ``` -That's `true` then `false`. Between arrays and `ArrayList`, the choice comes -down to one question: do you know the count before the program runs? If yes, -an array is simpler. If the count depends on what happens while the program -runs — scoring events, sensor hits, robots you've seen this match — reach for -`ArrayList`. +That prints `True`, then `False`. -Your turn: build an empty `ArrayList` called `climbTimes`, then -`.add(...)` four made-up times in seconds. Remove the **slowest** one by -index (look at the printed list and pick its position), then loop over what's -left and print the **average** of the remaining times. +Your turn: start with an empty list called `climb_times`, then use `.append(...)` +to add four made-up times in seconds. Remove the **slowest** one using +`.remove(...)` or `.pop(...)`, then loop over what is left and print the +**average** of the remaining times. diff --git a/lessons/14-maps/README.md b/lessons/14-maps/README.md index 7359844..450eca1 100644 --- a/lessons/14-maps/README.md +++ b/lessons/14-maps/README.md @@ -1,5 +1,5 @@ --- -title: "Maps" +title: "Dictionaries" goal: "Store values under names you choose instead of numbered positions, and look them up by those names." order: 140 section: "Data Structures" @@ -7,104 +7,94 @@ section: "Data Structures" # Labels instead of positions -An array is great when order is all you need. But `motors[2]` doesn't tell you -*what* motor that is — you just have to remember that position 2 is the intake. -Wouldn't it be nicer to say `motors.get("intake")`? - -That's a **map**: a group of values where each one is filed under a **label you -pick** (called a **key**) instead of a numbered position. Java's everyday map -is the **`HashMap`**, and you put entries in with `put` and read them back -with `get`: - -```java -HashMap motorSpeeds = new HashMap<>(); -motorSpeeds.put("intake", 0.8); -motorSpeeds.put("shooter", 1.0); -motorSpeeds.put("climber", 0.5); -System.out.println(motorSpeeds.get("shooter")); -System.out.println(motorSpeeds.get("intake")); -``` +A list is great when order is all you need. But `motors[2]` does not tell you +*which* motor that is. You just have to remember that position 2 is the intake. +It is much clearer to write `motor_speeds["intake"]`. -The type `HashMap` names both halves: keys are `String`s, -values are `Double`s (that's `double` from [lesson {n}](#/lesson/08-numbers-and-text), dressed up so it can -live in a collection — same idea as `ArrayList` in [lesson {n}](#/lesson/13-arraylists)). -`motorSpeeds.get("shooter")` hands back `1.0`. It reads like plain English, and -you never have to remember which position is which. A map is perfect for -**robot configuration**: settings filed under names you'll recognize six -months from now. +That is a **dictionary** (`dict`): a group of values where each one is filed +under a **label you pick**, called a **key**, instead of a numbered position. +You write a dictionary with curly braces and `key: value` pairs: -Ask for a key that isn't there — `motorSpeeds.get("drive")` — and you get back -**`null`**, Java's word for "no value here." It doesn't crash on the spot, -which is a mixed blessing: the `null` travels onward and blows up *later* if -you try to use it, so check your spelling of keys carefully. +```python +motor_speeds = { + "intake": 0.8, + "shooter": 1.0, + "climber": 0.5, +} +print(motor_speeds["shooter"]) +print(motor_speeds["intake"]) +``` -One housekeeping note: `HashMap` and `ArrayList` live in Java's utility -toolbox, which real programs bring in with a line at the top of the file — -`import java.util.*;`. The playground adds that line to its shell for you, so -these snippets just work. +Here the keys are strings (`"intake"`, `"shooter"`, `"climber"`) and the values +are floats from [lesson {n}](#/lesson/08-numbers-and-text). Looking up +`motor_speeds["shooter"]` hands back `1.0`. It reads like plain English, and you +never have to memorize which slot is which. Dictionaries are a natural fit for +**robot configuration**, where settings live under names you will still +recognize six months later. -# Reading, changing, adding +Ask for a key that does not exist with square brackets, like +`motor_speeds["drive"]`, and Python stops with a `KeyError`. If a key might be +missing, use `.get(...)` instead: `motor_speeds.get("drive")` returns `None`, +Python's value for "nothing here." You can also pass a fallback value, like +`motor_speeds.get("drive", 0.0)`, which returns `0.0` when `"drive"` is missing. -You change a value the same way you added it — `put` to the same key replaces -what was there: +# Reading, changing, adding -```java -HashMap config = new HashMap<>(); -config.put("maxSpeed", 3.0); -config.put("rampTime", 0.25); +You change a value the same way you update a list slot, using its key in square +brackets: -config.put("maxSpeed", 4.5); -System.out.println(config.get("maxSpeed")); +```python +config = {"max_speed": 3.0, "ramp_time": 0.25} +config["max_speed"] = 4.5 +print(config["max_speed"]) ``` -And `put` on a key that **doesn't exist yet** *adds* a new entry — the same -call does double duty: +Assigning to a key that **does not exist yet** adds a new entry. The same syntax +does both jobs: -```java -HashMap config = new HashMap<>(); -config.put("maxSpeed", 3.0); -config.put("shooterSpeed", 1.0); -System.out.println(config); +```python +config = {"max_speed": 3.0} +config["shooter_speed"] = 1.0 +print(config) ``` `config` started with one entry and now has two. To check whether a key exists -before you reach for it — avoiding that sneaky `null` — ask with -`containsKey`: - -```java -HashMap config = new HashMap<>(); -config.put("maxSpeed", 3.0); -System.out.println(config.containsKey("maxSpeed")); -System.out.println(config.containsKey("shooter")); -``` +before you look it up, use `in` or `.get(...)`: -That prints `true` then `false`. It's the safe way to look before you leap. +```python +config = {"max_speed": 3.0} +print("max_speed" in config) +print("shooter" in config) +print(config.get("shooter", 0.0)) +``` -# Looping over a map +That prints `True`, `False`, and `0.0`. Checking with `in` or providing a +default with `.get(...)` keeps missing keys from crashing your program. -Like an array, a map can be walked with a for-each loop ([lesson {n}](#/lesson/12-arrays)). Loop -over its `keySet()` — the collection of every key — and use each key to fetch -its value: +# Looping over a dictionary -```java -HashMap motorSpeeds = new HashMap<>(); -motorSpeeds.put("intake", 0.8); -motorSpeeds.put("shooter", 1.0); -motorSpeeds.put("climber", 0.5); +Like a list in [lesson {n}](#/lesson/12-arrays), you can walk through a +dictionary with a `for` loop. Call `.items()` to get each key and its matching +value together: -for (String name : motorSpeeds.keySet()) { - System.out.println(name + " runs at " + motorSpeeds.get(name)); +```python +motor_speeds = { + "intake": 0.8, + "shooter": 1.0, + "climber": 0.5, } + +for name, speed in motor_speeds.items(): + print(f"{name} runs at {speed}") ``` -Each pass fills `name` with one key, and `get(name)` fetches the matching -value — a tidy report of the whole config in a few lines. This is how you'd -dump every setting on the robot to the console to check it before a match. -(One heads-up: a `HashMap` doesn't promise to keep entries in the order you -added them — it files things for fast lookup, not for tidy printing.) - -Your turn: build a map called `sensors` with three named readings — `"front"` -→ `12.0`, `"left"` → `30.0`, `"back"` → `8.0`. Then loop over its keys and -print a warning line only for sensors reading **below 10** (an `if` inside the -`for` again). Which combination from the last few lessons is this? A map, a -loop, and a condition working together — that's what real programs look like. +Each pass fills `name` with the key and `speed` with the value, giving you a +clean report of the whole config in two lines. This is how you dump every +setting on a robot to the console before a match. Python dictionaries also +remember the order you added keys, so the output stays predictable. + +Your turn: build a dictionary called `sensors` with three named readings: +`"front"` at `12.0`, `"left"` at `30.0`, and `"back"` at `8.0`. Loop over +`sensors.items()` and print a warning line only for sensors reading **below 10** +(an `if` inside the `for` again). A dictionary, a loop, and a condition working +together is what real programs look like. diff --git a/lessons/15-sets/README.md b/lessons/15-sets/README.md index 67d4ee4..930aff3 100644 --- a/lessons/15-sets/README.md +++ b/lessons/15-sets/README.md @@ -7,82 +7,78 @@ section: "Data Structures" # Just "is it in here?" -Three data structures in, and each one answers a different question. An array -or `ArrayList` ([lessons {n}](#/lesson/12-arrays)–[{n}](#/lesson/13-arraylists)) -answers "what's at position `i`?" A map ([lesson {n}](#/lesson/14-maps)) -answers "what's filed under this key?" A **set** throws position and keys out -entirely and answers just one question: **"is this value in the group, or -not?"** - -Java's everyday set is `HashSet`, and it behaves like an `ArrayList` that -refuses duplicates: - -```java -HashSet visited = new HashSet<>(); -visited.add("red"); -visited.add("blue"); -visited.add("red"); -System.out.println(visited); -System.out.println(visited.size()); +Three data structures in, and each one answers a different question. Lists +([lesson {n}](#/lesson/12-arrays) and [lesson {n}](#/lesson/13-arraylists)) +answer "what is at position `i`?" Dictionaries +([lesson {n}](#/lesson/14-maps)) answer "what is filed under this key?" A +**set** throws out positions and keys and answers just one question: **"is this +value in the group, or not?"** + +Python's `set` acts like a collection that refuses duplicates: + +```python +visited = set() +visited.add("red") +visited.add("blue") +visited.add("red") +print(visited) +print(len(visited)) ``` -Run it. Even though `"red"` was added twice, it only appears **once** — the -second `.add("red")` is silently ignored because it's already there. `.size()` -prints `2`, not `3`. That's the entire point of a set: it enforces "no -duplicates" for you, so you never have to check yourself before adding. +Run it. Even though `"red"` was added twice, it only appears **once**. The +second `.add("red")` does nothing because `"red"` is already there, and +`len(visited)` prints `2`, not `3`. That is the point of a set: it enforces "no +duplicates" for you so you never have to check yourself before adding. + +You can also create a non-empty set with curly braces, like +`visited = {"red", "blue"}`. Notice that `{}` on its own makes an empty +dictionary, so always write `set()` when you want an empty set. # Checking membership -The move you'll use constantly is `.contains(...)` — same method name as -`ArrayList` ([lesson {n}](#/lesson/13-arraylists)), but here it's the *reason -the type exists*, not an extra trick: +The check you will use most often is `in`, the same operator you saw with lists +in [lesson {n}](#/lesson/13-arraylists). With a set, membership checks are the +main reason the type exists, and Python can answer them fast even when the set +holds thousands of items: -```java -HashSet visited = new HashSet<>(); -visited.add("red"); -visited.add("blue"); -System.out.println(visited.contains("red")); -System.out.println(visited.contains("green")); +```python +visited = {"red", "blue"} +print("red" in visited) +print("green" in visited) ``` -`true`, then `false`. Think of a set as a robot's memory of "places I've -already been" or "alliance colors I've already faced" — you don't care what -order you saw them in, and you don't want the same one counted twice. Add -with `.add(...)`, ask with `.contains(...)`, remove with `.remove(...)`: - -```java -HashSet visited = new HashSet<>(); -visited.add("red"); -visited.add("blue"); -visited.remove("red"); -System.out.println(visited.contains("red")); +`True`, then `False`. Think of a set as a robot's memory of places it has +already visited or alliance colors it has faced. You do not care about the +order, and you do not want the same one counted twice. Add with `.add(...)`, +check with `in`, and delete with `.remove(...)`: + +```python +visited = {"red", "blue"} +visited.remove("red") +print("red" in visited) ``` -# Looping, and why order isn't promised +If you want to remove an item without risking an error when it is already gone, +use `.discard(...)` instead of `.remove(...)`. -A for-each loop walks a set just like an array, `ArrayList`, or a map's -`keySet()`: +# Looping, and why order isn't promised -```java -HashSet alliances = new HashSet<>(); -alliances.add("red"); -alliances.add("blue"); -alliances.add("green"); +A `for` loop walks a set just like a list or dictionary: -for (String alliance : alliances) { - System.out.println("Faced: " + alliance); -} +```python +alliances = {"red", "blue", "green"} +for alliance in alliances: + print(f"Faced: {alliance}") ``` -Run it a couple of times. The three lines always appear, but not necessarily -in the order you added them — same warning as `HashMap` in -[lesson {n}](#/lesson/14-maps): a `HashSet` files things for fast lookup, not -for tidy printing. If you need "no duplicates" *and* "keeps the order I added -them," Java has `LinkedHashSet` — same methods, different filing system — but -plain `HashSet` is the one you'll reach for first. - -Your turn: loop over this array of scouted robot numbers — -`int[] seen = {254, 1114, 254, 118, 1114, 33};` — adding each one to a -`HashSet` called `uniqueTeams`. Print `uniqueTeams.size()` to see how -many *distinct* teams were actually scouted, then print the set itself to -check which numbers survived. +All three lines always appear, but not necessarily in the order you wrote them. +Unlike lists and dictionaries ([lesson {n}](#/lesson/14-maps)), a `set` does not +preserve insertion order. It organizes values for fast `in` lookups, not for +tidy printing. If you need them in alphabetical or numeric order, loop over +`sorted(alliances)` instead. + +Your turn: start with this list of scouted robot numbers, +`seen = [254, 1114, 254, 118, 1114, 33]`. Loop over `seen` and add each one to +an empty set called `unique_teams`. Print `len(unique_teams)` to see how many +*distinct* teams were scouted, then print `unique_teams` itself to check which +numbers survived. diff --git a/lessons/16-booleans/README.md b/lessons/16-booleans/README.md index bed62ba..867524a 100644 --- a/lessons/16-booleans/README.md +++ b/lessons/16-booleans/README.md @@ -1,122 +1,117 @@ --- -title: "true, false, and combining conditions" -goal: "Treat yes/no answers as real values and combine them with &&, ||, and ! to make safe decisions." +title: "True, False, and combining conditions" +goal: "Treat yes/no answers as real values and combine them with and, or, and not to make safe decisions." order: 160 -section: "Java Fundamentals" +section: "Python Fundamentals" --- # Yes and no are values too -Back in [lesson {n}](#/lesson/09-if-statements), an `if` asked a question like `score > 10` and acted on the -answer. That answer is a real value with a type of its own: a **`boolean`**, -which is either `true` or `false` — the only two it can ever be. Every -comparison *produces* one: - -```java -int score = 15; -System.out.println(score > 10); -System.out.println(score == 20); -System.out.println(score < 5); +Back in [lesson {n}](#/lesson/09-if-statements), an `if` asked a question like +`score > 10` and acted on the answer. That answer is a real value with a type of +its own: a **`bool`**, which is either `True` or `False`. Those are the only two +boolean values in Python, and both start with a capital letter. Every comparison +*produces* one: + +```python +score = 15 +print(score > 10) +print(score == 20) +print(score < 5) ``` -Run it: `true`, `false`, `false`. So `score > 10` isn't magic that only works -inside an `if` — it's an expression that evaluates to `true` or `false`, and -you can store it in a variable just like a number: +Run it: `True`, `False`, `False`. So `score > 10` is not magic that only works +inside an `if`. It is an expression that evaluates to `True` or `False`, and you +can store it in a variable just like a number: -```java -boolean enabled = true; -boolean atLimit = false; -System.out.println(enabled); +```python +enabled = True +at_limit = False +print(enabled) ``` -Booleans are how a robot represents every yes/no fact about itself: *is the -robot enabled? is the arm at its limit? is the button pressed?* Each is one -`true`/`false` value. An `if` simply runs its block when the boolean is `true`. +Booleans are how a robot represents every yes/no fact about itself. Is the robot +enabled? Is the arm at its limit? Is the button pressed? Each is one +`True`/`False` value, and an `if` runs its block when the boolean is `True`. -# Two questions at once: && / || +# Two questions at once: and / or -Real decisions rarely hinge on a single fact. "Run the shooter **only if** it's -spun up **and** we have a game piece." Java joins conditions with **`&&`** -(and) and **`||`** (or): +Real decisions rarely hinge on a single fact. "Run the shooter **only if** it is +spun up **and** we have a game piece." Python joins conditions with the words +**`and`** and **`or`**: -- `a && b` is `true` only when **both** are true. -- `a || b` is `true` when **at least one** is true. +- `a and b` is `True` only when **both** are true. +- `a or b` is `True` when **at least one** is true. -```java -boolean spunUp = true; -boolean hasPiece = true; -System.out.println(spunUp && hasPiece); +```python +spun_up = True +has_piece = True +print(spun_up and has_piece) -double battery = 11.5; -System.out.println(battery > 12 || battery > 11); +battery = 11.5 +print(battery > 12 or battery > 11) ``` -The first prints `true` — both facts hold, so the shooter's clear to fire. In -the second, the battery isn't above 12, but it *is* above 11, and `||` only -needs one side to be true, so you get `true`. - -Put it to work in a real safety check — a motor that should only run when the -system is enabled **and** hasn't hit its limit: - -```java -boolean enabled = true; -boolean atLimit = false; -if (enabled && atLimit == false) { - System.out.println("Motor running"); -} else { - System.out.println("Motor held"); -} +The first prints `True` because both facts hold, so the shooter is clear to +fire. In the second, the battery is not above 12, but it *is* above 11, and `or` +only needs one side to be true, so you get `True`. + +Put it to work in a real safety check: a motor that should only run when the +system is enabled **and** has not hit its limit: + +```python +enabled = True +at_limit = False +if enabled and at_limit == False: + print("Motor running") +else: + print("Motor held") ``` -# !: flipping an answer +# not: flipping an answer -`atLimit == false` works, but there's a cleaner way to say "the opposite of -this." **`!`** (read it as "not") flips a boolean: `!true` is `false`, and -`!false` is `true`. +`at_limit == False` works, but there is a cleaner way to say "the opposite of +this." **`not`** flips a boolean: `not True` is `False`, and `not False` is +`True`. -```java -boolean atLimit = false; -System.out.println(!atLimit); +```python +at_limit = False +print(not at_limit) ``` -So `!atLimit` reads as "not at the limit" — which is exactly the English you +So `not at_limit` reads as "not at the limit," which is the exact English you meant. Rewrite the safety check with it and it reads like a sentence: -```java -boolean enabled = true; -boolean atLimit = false; -if (enabled && !atLimit) { - System.out.println("Motor running"); -} else { - System.out.println("Motor held"); -} +```python +enabled = True +at_limit = False +if enabled and not at_limit: + print("Motor running") +else: + print("Motor held") ``` -"If enabled and not at the limit, run." That's the goal of good conditions: -code that says what it means. Flip `enabled` to `false`, or `atLimit` to -`true`, and confirm the motor is held every time either safety fails. +"If enabled and not at the limit, run." That is the goal of good conditions: +code that says what it means. Flip `enabled` to `False`, or `at_limit` to +`True`, and confirm the motor is held every time either safety fails. -## Comparing text: use .equals, not == +## Comparing text -One trap to disarm before the next lessons, where programs start making -decisions based on text. `==` is for comparing **numbers and booleans**. For -**Strings**, always ask with **`.equals(...)`**: +In Python, `==` compares **strings** the same way it compares numbers and +booleans: -```java -String mode = "climb"; -System.out.println(mode.equals("climb")); -System.out.println(mode.equals("shoot")); +```python +mode = "climb" +print(mode == "climb") +print(mode == "shoot") +print(mode == "Climb") ``` -That prints `true` then `false`. Writing `mode == "climb"` will sometimes -*look* like it works and then silently fail in a real program, because `==` on -Strings asks "are these the exact same object in memory?" rather than "do -these spell the same thing?" — a distinction you don't want your robot's -behavior hanging on. The habit to build now: **numbers use `==`, text uses -`.equals`**. - -Your turn: a climber should only extend when `enabled` is true, `atLimit` is -false, **and** the match timer `timeLeft` is under 30 seconds. Write the single -`if` (using `&&` and `!`) that prints `"Climb!"` only when all three hold. Set -up variables and test it with a few combinations — especially the ones that -should *refuse* to climb. +That prints `True`, `False`, `False`. Watch that last line: string comparisons +are case-sensitive, so `"climb"` and `"Climb"` do not match. + +Your turn: a climber should only extend when `enabled` is `True`, `at_limit` is +`False`, **and** the match timer `time_left` is under 30 seconds. Write the +single `if` (using `and` and `not`) that prints `"Climb!"` only when all three +hold. Set up variables and test it with a few combinations, especially the ones +that should *refuse* to climb. diff --git a/lessons/17-classes-and-objects/README.md b/lessons/17-classes-and-objects/README.md index 22ca8a3..a988890 100644 --- a/lessons/17-classes-and-objects/README.md +++ b/lessons/17-classes-and-objects/README.md @@ -1,139 +1,80 @@ --- title: "Classes and objects" -goal: "Bundle related data and the actions on it into one thing you can create with new." +goal: "Bundle related data and the actions on it into one class you can create instances from." order: 170 section: "Objects" --- # When data and actions belong together -Picture the robot's intake. It has **data** — a motor speed, whether it's -currently holding a game piece — and **actions** — start, stop, check if it's -loaded. So far you'd scatter that across loose variables and static methods -and hope you kept them straight. As a robot grows to a dozen mechanisms, that -falls apart fast. - -A **class** is Java's way to bundle related data and actions into one thing. -It's a **blueprint**; from it you stamp out **objects** (also called -*instances*). This is not an obscure feature — it is how essentially all real -robot code is written. WPILib, the library FRC robots run on, gives you a -`SubsystemBase` class for each mechanism: an `Intake`, an `Elevator`, a -`Drivetrain`. Learn this and you're reading the shape of actual robot code. - -```java -class Intake { - double speed; - boolean hasPiece; -} - -public class Main { - public static void main(String[] args) { - Intake intake = new Intake(); - System.out.println(intake.speed); - System.out.println(intake.hasPiece); - } -} +Picture the robot's intake. It has **data**, like a motor speed and whether it is holding a game piece, and **actions**, like start, stop, and check if it is loaded. So far you would scatter that across loose variables and standalone functions and hope you kept them straight. As a robot grows to a dozen mechanisms, that falls apart fast. + +A **class** is Python's way to bundle related data and actions into one thing. It is a **blueprint**. From it you stamp out **objects** (also called *instances*). This is how real robot code is written. WPILib gives you a `Subsystem` class for each mechanism: an `Intake`, an `Elevator`, a `Drivetrain`. Learn this and you are reading the shape of actual robot code. + +```python +class Intake: + speed = 0.0 + has_piece = False + +intake = Intake() +print(intake.speed) +print(intake.has_piece) ``` -`class Intake { ... }` declares the blueprint — a `double` and a `boolean` -**field** for the data it will hold. `new Intake()` stamps out one actual -intake object. And `intake.speed` reaches inside it for a value stored on -that object. Run it — you've built your first object, and its fields start at -Java's defaults: `0.0` and `false`. +`class Intake:` declares the blueprint with two attributes for the data it holds. `Intake()` stamps out one actual intake object. `intake.speed` reaches inside that object for a stored value. Run it and you have built your first object, starting at `0.0` and `False`. # The constructor: giving a new object its starting values -Defaults are a coincidence, not a plan — the next field you add might not have -a sensible default, and relying on it is a bug waiting to happen. A -**constructor** runs automatically the moment you create an object with `new`, -and its job is to set the starting values on purpose: - -```java -class Intake { - double speed; - boolean hasPiece; - - Intake() { - this.speed = 0.0; - this.hasPiece = false; - } -} - -public class Main { - public static void main(String[] args) { - Intake intake = new Intake(); - System.out.println(intake.speed); - System.out.println(intake.hasPiece); - } -} +Relying on shared class defaults is a trap. If two intakes exist, each one needs its own starting values set on purpose. A **constructor**, named `__init__` in Python, runs automatically the moment you create an object with `Intake()`, and its job is to set those starting values: + +```python +class Intake: + def __init__(self): + self.speed = 0.0 + self.has_piece = False + +intake = Intake() +print(intake.speed) +print(intake.has_piece) ``` -Two pieces worth naming: +Two pieces are worth naming: -- **`Intake() { ... }`** — a method with no return type, sharing its name with - the class. That's what makes it the constructor; `new Intake()` calls it. -- **`this`** is *the object being built, right now*. `this.speed = 0.0` means - "*this particular intake's* speed starts at `0.0`." Every value filed on - `this` becomes part of the object and sticks around after the constructor - finishes. +- **`def __init__(self):`** is the constructor. Calling `Intake()` runs it automatically. +- **`self`** is *the object being built right now*. `self.speed = 0.0` means "*this particular intake's* speed starts at `0.0`." Every value stored on `self` becomes part of that object and sticks around after `__init__` finishes. -Same output as before, but now it's guaranteed — not a default you got lucky -with. +Same output as before, but now every intake gets its own clean starting state. # Methods: the actions -Data on its own is only half of it. A method defined **inside** a class, -without `static`, is an action the object performs **on its own data**, reached -through `this`: - -```java -class Intake { - double speed; - boolean hasPiece; - - Intake() { - this.speed = 0.0; - this.hasPiece = false; - } - - void start() { - this.speed = 0.8; - this.hasPiece = true; - } - - void stop() { - this.speed = 0.0; - } - - void report() { - System.out.println("speed: " + this.speed + " | holding: " + this.hasPiece); - } -} - -public class Main { - public static void main(String[] args) { - Intake intake = new Intake(); - intake.report(); - intake.start(); - intake.report(); - intake.stop(); - intake.report(); - } -} +Data on its own is only half of it. A function defined **inside** a class, with `self` as its first parameter, is a **method**. It is an action the object performs **on its own data**, reached through `self`: + +```python +class Intake: + def __init__(self): + self.speed = 0.0 + self.has_piece = False + + def start(self): + self.speed = 0.8 + self.has_piece = True + + def stop(self): + self.speed = 0.0 + + def report(self): + print(f"speed: {self.speed} | holding: {self.has_piece}") + +intake = Intake() +intake.report() +intake.start() +intake.report() +intake.stop() +intake.report() ``` -You call a method with `intake.start()` — same dot as a field, now with -parentheses because it's an action. Trace the output: speed `0.0` and not -holding, then `start()` flips both, then `stop()` zeroes the speed. The object -carries its own state between calls; you're just telling it what to do. - -That's the whole idea: **an object is data and the actions on that data, kept -together.** `intake.start()` reads like a command to a real mechanism — which -is exactly why robot code is built this way. - -Your turn: write a `Shooter` class. In its constructor set `this.rpm = 0` and -`this.ready = false`. Add a `spinUp()` method that sets `rpm` to `5000` and -`ready` to `true`, and a `fire()` method that prints `"Fired!"` **only if** -`this.ready` is true (an `if` inside a method — [lesson {n}](#/lesson/09-if-statements) lives here too). -Make one, try to `fire()` before spinning up, then `spinUp()` and fire for -real. +You call a method with `intake.start()`, using the same dot as an attribute, now with parentheses because it is an action. Python passes `intake` in as `self` for you. Trace the output: speed `0.0` and not holding, then `start()` flips both, then `stop()` zeroes the speed. The object carries its own state between calls while you tell it what to do. + +That is the whole idea: **an object is data and the actions on that data, kept together.** `intake.start()` reads like a command to a real mechanism, which is why robot code is built this way. + +Your turn: write a `Shooter` class. In `__init__`, set `self.rpm = 0` and `self.ready = False`. Add a `spin_up(self)` method that sets `self.rpm` to `5000` and `self.ready` to `True`, and a `fire(self)` method that prints `"Fired!"` **only if** `self.ready` is `True` (an `if` inside a method, from [lesson {n}](#/lesson/09-if-statements), works here too). Make one, try calling `fire()` before spinning up, then call `spin_up()` and `fire()` for real. diff --git a/lessons/18-multiple-objects/README.md b/lessons/18-multiple-objects/README.md index e32ed37..81e8c18 100644 --- a/lessons/18-multiple-objects/README.md +++ b/lessons/18-multiple-objects/README.md @@ -7,124 +7,70 @@ section: "Objects" # One blueprint, many objects -A class is a blueprint, not a thing by itself — and a robot rarely has just -one of anything. Make two objects from the same `Intake` blueprint and each -gets its **own copy** of the fields: - -```java -class Intake { - String name; - double speed; - - Intake(String name) { - this.name = name; - this.speed = 0.0; - } - - void start() { - this.speed = 0.8; - } -} - -public class Main { - public static void main(String[] args) { - Intake left = new Intake("left"); - Intake right = new Intake("right"); - left.start(); - System.out.println(left.name + " " + left.speed); - System.out.println(right.name + " " + right.speed); - } -} +A class is a blueprint, not a thing by itself, and a robot rarely has just one of anything. Make two objects from the same `Intake` blueprint and each gets its **own copy** of the attributes: + +```python +class Intake: + def __init__(self, name): + self.name = name + self.speed = 0.0 + + def start(self): + self.speed = 0.8 + +left = Intake("left") +right = Intake("right") +left.start() +print(left.name, left.speed) +print(right.name, right.speed) ``` -`Intake(String name)` takes a value in, exactly like a method parameter -([lesson {n}](#/lesson/11-writing-methods)) — `new Intake("left")` fills it in. Run it: `left.start()` sets -`left`'s speed to `0.8` and leaves `right` completely untouched, at `0.0`. One -blueprint, two independent objects, no way for one to reach into the other's -fields by accident. +`__init__(self, name)` takes a value in, just like a function parameter ([lesson {n}](#/lesson/11-writing-methods)), and `Intake("left")` fills it in. Run it: `left.start()` sets `left`'s speed to `0.8` and leaves `right` completely untouched at `0.0`. One blueprint, two independent objects, with no way for one to reach into the other's attributes by accident. -# static vs. instance: who does a method belong to? +# Functions vs. methods: who does it belong to? -Every method you wrote before [lesson {n}](#/lesson/17-classes-and-objects) had `static` in front of it, and -you probably didn't think twice about it — there was nothing yet for a method -to belong to. Now that objects exist, the difference matters: +Every function you wrote before [lesson {n}](#/lesson/17-classes-and-objects) stood on its own outside a class. Now that objects exist, the difference between a standalone function and a method matters: -```java -class Intake { - double speed; +```python +class Intake: + def __init__(self): + self.speed = 0.0 - void start() { - this.speed = 0.8; - } -} + def start(self): + self.speed = 0.8 -public class Main { - static int doubleIt(int n) { - return n * 2; - } +def double_it(n): + return n * 2 - public static void main(String[] args) { - System.out.println(doubleIt(5)); +print(double_it(5)) - Intake intake = new Intake(); - intake.start(); - System.out.println(intake.speed); - } -} +intake = Intake() +intake.start() +print(intake.speed) ``` -`doubleIt(5)` is called by name alone — a `static` method belongs to the -**program**, not to any object, so there's nothing to attach it to (that's -also why `main` itself is `static`: the program needs somewhere to start -before a single object exists). `intake.start()` is different — `start` has -no `static`, so it belongs to **one object**, and you must have that object -(`intake`) to call it. Inside, `this` means exactly that object. That's the -whole rule: no `static` and no object, no call. +`double_it(5)` is called by name alone. It is a standalone function, so it does not belong to any object and has no `self`. `intake.start()` is different: `start` is defined inside `Intake` with `self`, so it belongs to **one object**, and you must have that object (`intake`) to call it. Inside `start`, `self` means that exact object. # A list of objects -Real robots don't have one intake — they have a handful of mechanisms, all -built from a small number of classes. An `ArrayList` ([lesson {n}](#/lesson/13-arraylists)) -holds objects exactly the way it holds numbers or strings: - -```java -import java.util.ArrayList; - -class Intake { - String name; - double speed; - - Intake(String name) { - this.name = name; - this.speed = 0.0; - } - - void start() { - this.speed = 0.8; - } -} - -public class Main { - public static void main(String[] args) { - ArrayList intakes = new ArrayList<>(); - intakes.add(new Intake("front")); - intakes.add(new Intake("back")); - - for (Intake intake : intakes) { - intake.start(); - System.out.println(intake.name + " " + intake.speed); - } - } -} +Real robots do not have just one intake. They have a handful of mechanisms, all built from a small number of classes. A Python `list` ([lesson {n}](#/lesson/13-arraylists)) holds objects the same way it holds numbers or strings: + +```python +class Intake: + def __init__(self, name): + self.name = name + self.speed = 0.0 + + def start(self): + self.speed = 0.8 + +intakes = [Intake("front"), Intake("back")] + +for intake in intakes: + intake.start() + print(intake.name, intake.speed) ``` -`ArrayList` says exactly what it holds: not numbers this time, but -whole `Intake` objects. The for-each loop ([lesson {n}](#/lesson/12-arrays)) hands you one object at -a time — `intake` is a real object each pass, so `intake.start()` and -`intake.name` work exactly as they did above. Run it and watch both mechanisms -start independently. +`intakes` holds whole `Intake` objects instead of numbers. The `for` loop ([lesson {n}](#/lesson/12-arrays)) hands you one object at a time. Each pass, `intake` is a real object, so `intake.start()` and `intake.name` work just as they did above. Run it and watch both mechanisms start independently. -Your turn: give `Intake` a `hasPiece` field and a `report()` method that -prints `name`, `speed`, and `hasPiece`. Build an `ArrayList` of three intakes, -`start()` only the second one, then loop over the list calling `report()` on -each — confirm only one shows a nonzero speed. +Your turn: give `Intake` a `has_piece` attribute and a `report(self)` method that prints `name`, `speed`, and `has_piece`. Build a list of three intakes, call `start()` on only the second one, then loop over the list calling `report()` on each. Confirm only one shows a nonzero speed. diff --git a/lessons/19-encapsulation/README.md b/lessons/19-encapsulation/README.md index c2bd371..eaa3e06 100644 --- a/lessons/19-encapsulation/README.md +++ b/lessons/19-encapsulation/README.md @@ -1,136 +1,80 @@ --- title: "Encapsulation" -goal: "Hide an object's fields behind public methods so outside code can't force it into a broken state." +goal: "Hide an object's internal attributes behind public methods so outside code cannot force it into a broken state." order: 190 section: "Objects" --- -# The problem with public fields - -Every field you've written so far has been reachable from anywhere, just by -naming it: `intake.speed = ...`. That's convenient, and also a trap. Nothing -stops outside code from setting a field to something the object was never -designed to hold: - -```java -class Flywheel { - double rpm; - - Flywheel() { - this.rpm = 0.0; - } -} - -public class Main { - public static void main(String[] args) { - Flywheel flywheel = new Flywheel(); - flywheel.rpm = -500.0; - System.out.println(flywheel.rpm); - } -} +# The problem with public attributes + +Every attribute you have written so far has been reachable from anywhere, just by naming it: `intake.speed = ...`. That is convenient, and also a trap. Nothing stops outside code from setting an attribute to something the object was never designed to hold: + +```python +class Flywheel: + def __init__(self): + self.rpm = 0.0 + +flywheel = Flywheel() +flywheel.rpm = -500.0 +print(flywheel.rpm) ``` -Run it — Java lets `rpm` go negative without a complaint, because nothing -about the field says it shouldn't. A real flywheel can't spin at `-500` RPM; -that's not a value, it's a bug waiting to reach the motor controller. The -object's own methods would never *do* that to it — the danger is code -**outside** the class reaching in directly. - -# private fields, public methods - -The fix: mark the field **`private`**, so only code inside the class can -touch it, and offer a public method as the *only* door in: - -```java -class Flywheel { - private double rpm; - - Flywheel() { - this.rpm = 0.0; - } - - void setRpm(double target) { - if (target < 0.0) { - this.rpm = 0.0; - } else { - this.rpm = target; - } - } - - double getRpm() { - return this.rpm; - } -} - -public class Main { - public static void main(String[] args) { - Flywheel flywheel = new Flywheel(); - flywheel.setRpm(-500.0); - System.out.println(flywheel.getRpm()); - flywheel.setRpm(4500.0); - System.out.println(flywheel.getRpm()); - } -} +Run it. Python lets `rpm` go negative without a complaint, because nothing about the attribute says it cannot. A real flywheel cannot spin at `-500` RPM. That is not a valid setting, it is a bug waiting to reach the motor controller. The object's own methods would never do that to it. The danger is code **outside** the class reaching in directly. + +# Private attributes, public methods + +The fix is to mark the attribute as **private** by starting its name with an underscore (`_rpm`), and offer public methods as the *only* door in: + +```python +class Flywheel: + def __init__(self): + self._rpm = 0.0 + + def set_rpm(self, target): + if target < 0.0: + self._rpm = 0.0 + else: + self._rpm = target + + def get_rpm(self): + return self._rpm + +flywheel = Flywheel() +flywheel.set_rpm(-500.0) +print(flywheel.get_rpm()) +flywheel.set_rpm(4500.0) +print(flywheel.get_rpm()) ``` -Try `flywheel.rpm = -500.0;` now and it won't even compile — `rpm` is -`private`, so `Main` isn't allowed to see it at all. The only way in is -`setRpm`, and `setRpm` **refuses** the bad value instead of storing it. Run it: -the first call clamps to `0.0`, the second sets a real value. The object is -now in charge of protecting its own rules — that's the whole point of -`private`. +In Python, a leading underscore like `_rpm` tells every reader and tool: "this belongs to `Flywheel` alone, do not touch it from outside." The intended way in is `set_rpm`, and `set_rpm` **refuses** the bad value instead of storing it. Run it: the first call clamps to `0.0`, and the second sets a real value. The object is now in charge of protecting its own rules. # Designing the public interface -Every class you write is really a decision about **what's public and what's -private** — what the rest of the program is allowed to do to this object, -versus the bookkeeping it never needs to see. A good rule of thumb: fields are -almost always `private`; methods are public **only** if calling code actually -needs them. - -```java -class Flywheel { - private double rpm; - private boolean spinning; - - Flywheel() { - this.rpm = 0.0; - this.spinning = false; - } - - void spinUp() { - this.rpm = 5000.0; - this.spinning = true; - } - - void stop() { - this.rpm = 0.0; - this.spinning = false; - } - - boolean isReady() { - return this.spinning && this.rpm >= 4500.0; - } -} - -public class Main { - public static void main(String[] args) { - Flywheel flywheel = new Flywheel(); - System.out.println(flywheel.isReady()); - flywheel.spinUp(); - System.out.println(flywheel.isReady()); - } -} +Every class you write is a decision about **what is public and what is private**, meaning what the rest of the program is allowed to do to this object versus the bookkeeping it never needs to see. A good rule of thumb: attributes are almost always private (prefixed with `_`), and methods are public **only** if calling code actually needs them. + +```python +class Flywheel: + def __init__(self): + self._rpm = 0.0 + self._spinning = False + + def spin_up(self): + self._rpm = 5000.0 + self._spinning = True + + def stop(self): + self._rpm = 0.0 + self._spinning = False + + def is_ready(self): + return self._spinning and self._rpm >= 4500.0 + +flywheel = Flywheel() +print(flywheel.is_ready()) +flywheel.spin_up() +print(flywheel.is_ready()) ``` -Nothing outside `Flywheel` ever touches `rpm` or `spinning` directly — it asks -for `spinUp()`, `stop()`, or `isReady()` and lets the object worry about its -own numbers. That's exactly the shape of real WPILib subsystem code: a small, -honest set of public actions guarding a pile of private details. - -Your turn: write a `Climber` class with `private` fields `heightInches` and -`atTop`. Give it a public `extend(double amount)` method that adds `amount` to -`heightInches` but never lets it go **above `60.0`** (clamp it, the way -`setRpm` did), setting `atTop` to `true` exactly when it reaches `60.0`. Try -extending past the top in one big jump and confirm it stops at `60.0` instead -of sailing over. +Nothing outside `Flywheel` touches `_rpm` or `_spinning` directly. Calling code asks for `spin_up()`, `stop()`, or `is_ready()` and lets the object manage its own numbers. That is the shape of real WPILib subsystem code: a small, honest set of public actions guarding private details. + +Your turn: write a `Climber` class with private attributes `_height_inches` and `_at_top`. Give it a public `extend(self, amount)` method that adds `amount` to `_height_inches` but never lets it go **above `60.0`** (clamp it, the way `set_rpm` did), setting `_at_top` to `True` when it reaches `60.0`. Add a `get_height(self)` method, try extending past the top in one big jump, and confirm it stops at `60.0` instead of sailing over. diff --git a/lessons/20-state-machines/README.md b/lessons/20-state-machines/README.md index 940fa76..9c6a99b 100644 --- a/lessons/20-state-machines/README.md +++ b/lessons/20-state-machines/README.md @@ -1,6 +1,6 @@ --- title: "State machines as diagrams" -goal: "See a machine that's always in exactly one state and moves between states when events happen — before writing a line of code." +goal: "See a machine that's always in exactly one state and moves between states when events happen, before writing a line of code." order: 200 section: "State Machines" --- @@ -10,34 +10,34 @@ section: "State Machines" Back in [the first lessons](#/lesson/01-flowcharts) you built flowcharts and watched the computer walk them one step at a time. Now we meet the idea the whole rest of the season is built on: the **state machine**. It's how our robots will think this year, so -we'll learn it the same way we learned everything else — **as a diagram first**, +we'll learn it the same way we learned everything else, **as a diagram first**, then in code. A state machine is simple to say: the machine is **always in exactly one state**, and it **moves to another state when an event happens**. That's it. -Here's the classic example — a traffic light. Each rounded box is a **state**; -each arrow is a **transition**, labelled with the **event** that triggers it. +Here's the classic example, a traffic light. Each rounded box is a **state**, +and each arrow is a **transition**, labelled with the **event** that triggers it. ```blocks preset: sm-demo ``` -The light is glowing on its current state. There's one event here — the timer -finishing — so press **timer done** and watch the machine move: `RED → GREEN → +The light is glowing on its current state. There's one event here, the timer +finishing, so press **timer done** and watch the machine move: `RED → GREEN → YELLOW → RED`, forever. Notice what you *can't* do: the light can't be red and green at once, and it can't jump from red straight to yellow. One state at a time, and it only moves the way an arrow allows. That restriction is the whole -point — it's what makes the behavior predictable. +point. It's what makes the behavior predictable. # Events, and what gets ignored A traffic light only had one event. A real mechanism has several, and here's the -key idea: **a state only reacts to the events it has an arrow for — everything +key idea: **a state only reacts to the events it has an arrow for. Everything else, it ignores.** This machine is a **game-piece handler**, the kind of thing our robot runs: it starts `EMPTY`, takes a piece in, holds it, and shoots. It listens for three -events — the driver's button, a sensor seeing a piece, and a shot finishing. +events: the driver's button, a sensor seeing a piece, and a shot finishing. ```blocks preset: sm-edit @@ -47,12 +47,12 @@ Drive it the "happy path" first: `EMPTY` → press **driver button** → `INTAKI → press **piece detected** → `LOADED` → press **driver button** → `SHOOTING` → press **shot done** → back to `EMPTY`. -Now try to break it. While it's `EMPTY`, press **shot done**. Nothing happens — +Now try to break it. While it's `EMPTY`, press **shot done**. Nothing happens. `EMPTY` has no arrow for that event, so the machine simply ignores it. Press -**piece detected** while `LOADED`; ignored again. This is the safety you get for -free: the machine *can't* shoot when it's empty, because there's no path to -`SHOOTING` from `EMPTY`. You don't write code to forbid the bad cases — you just -don't draw those arrows. +**piece detected** while `LOADED`, and it is ignored again. This is the safety +you get for free: the machine *can't* shoot when it's empty, because there's no +path to `SHOOTING` from `EMPTY`. You don't write code to forbid the bad cases. +You just don't draw those arrows. Watch the status line under the canvas as you press things; it tells you each move it makes, or that an event was ignored. @@ -60,8 +60,8 @@ move it makes, or that an event was ignored. # Build one yourself Your turn to design a machine. This one's a **climber**: it stows, extends up, -sits extended, then retracts back down. The four states are already placed — -your job is to draw the **arrows** between them, because *the transitions are the +sits extended, then retracts back down. The four states are already placed. +Your job is to draw the **arrows** between them, because *the transitions are the machine.* ```blocks @@ -83,6 +83,7 @@ Then make it your own: add a state with **+ state** (say, an `EMERGENCY STOP` everything can fall into), or a real mechanism from this year's robot. Sketch its states, decide what event moves between each, and wire it up. -Everything you just did by hand — states, events, transitions, ignoring the -events that don't apply — is exactly what we'll write in Java [next lesson](#/lesson/21-state-machines-in-code). The -diagram *is* the program; the code just spells it out. +Everything you just did by hand, including states, events, transitions, and +ignoring the events that don't apply, is exactly what we'll write in Python +[next lesson](#/lesson/21-state-machines-in-code). The diagram *is* the program; +the code just spells it out. diff --git a/lessons/21-state-machines-in-code/README.md b/lessons/21-state-machines-in-code/README.md index 960e504..32e96f6 100644 --- a/lessons/21-state-machines-in-code/README.md +++ b/lessons/21-state-machines-in-code/README.md @@ -1,6 +1,6 @@ --- title: "State machines in code" -goal: "Turn the state diagram from last lesson into Java — a state variable, transitions, and the loop that drives them." +goal: "Turn the state diagram from last lesson into Python with an Enum, transitions, and the loop that drives them." order: 210 section: "State Machines" --- @@ -8,103 +8,115 @@ section: "State Machines" # The current state is just a variable [Last lesson](#/lesson/20-state-machines) you drove state machines as diagrams: a machine sits in one state and -moves along an arrow when an event happens. Now we write that in Java — and the +moves along an arrow when an event happens. Now we write that in Python, and the first piece is something you already know cold. **The current state is just a variable.** -```java -String state = "red"; +To list the allowed states clearly, Python gives us `Enum` from the standard +library: -if (state.equals("red")) { - System.out.println("STOP"); -} else if (state.equals("green")) { - System.out.println("GO"); -} else if (state.equals("yellow")) { - System.out.println("SLOW DOWN"); -} +```python +from enum import Enum + +class LightState(Enum): + RED = "red" + GREEN = "green" + YELLOW = "yellow" + +state = LightState.RED + +match state: + case LightState.RED: + print("STOP") + case LightState.GREEN: + print("GO") + case LightState.YELLOW: + print("SLOW DOWN") ``` -That's the traffic light from [lesson {n}](#/lesson/20-state-machines). One variable, `state`, holds which state -the machine is in right now; an `if/else if` ([lesson {n}](#/lesson/09-if-statements)) picks the behavior for -that state. The glowing box in the diagram *is* this variable — nothing more. -(The states are text, so we ask with `.equals`, the habit from [lesson {n}](#/lesson/16-booleans).) +That's the traffic light from [lesson {n}](#/lesson/20-state-machines). `LightState` lists the three +legal states, one variable `state` holds which state the machine is in right +now, and `match` picks the behavior for that state (you can also write the same +checks with `if` and `elif` from [lesson {n}](#/lesson/09-if-statements) and `==` from [lesson {n}](#/lesson/16-booleans)). +The glowing box in the diagram *is* this variable, nothing more. -Run it, then change `state` to `"green"` and run again. Same code, different -state, different behavior. Notice you can only be in one state at a time, -because a variable holds one value — exactly the rule the diagram enforced. +Run it, then change `state` to `LightState.GREEN` and run again. Same code, +different state, different behavior. Notice you can only be in one state at a +time, because a variable holds one value, which is the exact rule the diagram +enforced. # Moving between states A diagram's arrows said how to move. In code, a transition is just **changing -the variable**. Let's package "what comes next" as a method ([lesson {n}](#/lesson/11-writing-methods)) — -and since methods live in the shell, from here on the snippets show the whole -program: - -```java -public class Main { - static String nextState(String state) { - if (state.equals("red")) { - return "green"; - } else if (state.equals("green")) { - return "yellow"; - } else { - return "red"; - } - } - - public static void main(String[] args) { - String state = "red"; - System.out.println(state); - state = nextState(state); - System.out.println(state); - state = nextState(state); - System.out.println(state); - } -} +the variable**. Let's package "what comes next" as a function ([lesson {n}](#/lesson/11-writing-methods)): + +```python +from enum import Enum + +class LightState(Enum): + RED = "red" + GREEN = "green" + YELLOW = "yellow" + +def next_state(state): + match state: + case LightState.RED: + return LightState.GREEN + case LightState.GREEN: + return LightState.YELLOW + case LightState.YELLOW: + return LightState.RED + +state = LightState.RED +print(state.name) +state = next_state(state) +print(state.name) +state = next_state(state) +print(state.name) ``` -Each `state = nextState(state)` is one press of **timer done** from the +Each `state = next_state(state)` is one press of **timer done** from the diagram: it looks at where we are and hands back where we go. Run it and watch -`red → green → yellow`. The reassignment trick from [lesson {n}](#/lesson/07-variables) is doing the -real work — the machine "moves" because we overwrite `state` with its next -value. +`RED → GREEN → YELLOW`. The reassignment trick from [lesson {n}](#/lesson/07-variables) is doing the +real work. The machine "moves" because we overwrite `state` with its next value. # The loop that drives it Here's the idea the whole season rests on: a robot doesn't run its code once and stop. It runs the same update **over and over, many times a second**. -That's a loop ([lesson {n}](#/lesson/10-loops)) — and dropping our machine inside one makes it *go*: - -```java -public class Main { - static String nextState(String state) { - if (state.equals("red")) { - return "green"; - } else if (state.equals("green")) { - return "yellow"; - } else { - return "red"; - } - } - - public static void main(String[] args) { - String state = "red"; - for (int tick = 0; tick < 6; tick++) { - System.out.println(tick + " " + state); - state = nextState(state); - } - } -} +That's a loop ([lesson {n}](#/lesson/10-loops)), and dropping our machine inside one makes it *go*: + +```python +from enum import Enum + +class LightState(Enum): + RED = "red" + GREEN = "green" + YELLOW = "yellow" + +def next_state(state): + match state: + case LightState.RED: + return LightState.GREEN + case LightState.GREEN: + return LightState.YELLOW + case LightState.YELLOW: + return LightState.RED + +state = LightState.RED +for tick in range(6): + print(tick, state.name) + state = next_state(state) ``` Each time around the loop is one **tick**: print where we are, then advance. -Run it and watch the light cycle `red → green → yellow → red → green …`, +Run it and watch the light cycle `RED → GREEN → YELLOW → RED → GREEN …`, driven entirely by that one repeating step. A real robot's loop is this exact shape, just running 50 times a second instead of 6. -Your turn: add a fourth state, `"flashing"`, that the light enters after -`yellow` and leaves back to `red`. You'll change `nextState` in two spots — -make `"yellow"` return `"flashing"` instead of falling through to `"red"`, and -add a new `else if` for `"flashing"` that returns `"red"`. That's exactly -adding a box and rerouting the arrows in the diagram. Run the loop and confirm -your new state shows up in the cycle. +Your turn: add a fourth state, `FLASHING = "flashing"`, that the light enters +after `YELLOW` and leaves back to `RED`. You'll change `next_state` in two +spots: make `case LightState.YELLOW:` return `LightState.FLASHING`, and add a +new `case LightState.FLASHING:` that returns `LightState.RED`. That's the same +as adding a box and rerouting the arrows in the diagram. Run the loop and +confirm your new state shows up in the cycle. diff --git a/lessons/22-events-and-transitions/README.md b/lessons/22-events-and-transitions/README.md index 5da258f..cd02d7c 100644 --- a/lessons/22-events-and-transitions/README.md +++ b/lessons/22-events-and-transitions/README.md @@ -7,7 +7,7 @@ section: "State Machines" # Transitions depend on an event -The traffic light moved on its own — one event, `timer done`, always advanced +The traffic light moved on its own. One event, `timer done`, always advanced it. Real mechanisms wait for **specific events**: a button press, a sensor tripping, a shot finishing. So a transition depends on **two things**: which state you're in, *and* which event just happened. @@ -15,101 +15,87 @@ state you're in, *and* which event just happened. This is the game-piece handler you drove in [lesson {n}](#/lesson/20-state-machines). Here's a single transition from it: -```java -String state = "empty"; -String event = "button"; +```python +state = "empty" +event = "button" -if (state.equals("empty") && event.equals("button")) { - state = "intaking"; -} +if state == "empty" and event == "button": + state = "intaking" -System.out.println(state); +print(state) ``` -The `&&` ([lesson {n}](#/lesson/16-booleans)) is the key: the machine only moves when it's in `empty` -**and** the driver's `button` event happened. Run it — `empty` becomes +The `and` ([lesson {n}](#/lesson/16-booleans)) is the key: the machine only moves when it's in `empty` +**and** the driver's `button` event happened. Run it, and `empty` becomes `intaking`. Change `event` to `"sensor"` and run again: nothing changes, because `empty` has no transition for `sensor`. That's the diagram's "ignore" behavior, falling straight out of an `if` that doesn't match. -# The whole machine — and what it ignores +# The whole machine, and what it ignores -Now the full handler, as an `update` method that takes the current state and +Now the full handler, as an `update` function that takes the current state and an event and returns the new state: -```java -public class Main { - static String update(String state, String event) { - if (state.equals("empty") && event.equals("button")) { - return "intaking"; - } else if (state.equals("intaking") && event.equals("sensor")) { - return "loaded"; - } else if (state.equals("loaded") && event.equals("button")) { - return "shooting"; - } else if (state.equals("shooting") && event.equals("done")) { - return "empty"; - } - return state; - } - - public static void main(String[] args) { - System.out.println(update("empty", "done")); - System.out.println(update("empty", "button")); - System.out.println(update("loaded", "sensor")); - } -} +```python +def update(state, event): + if state == "empty" and event == "button": + return "intaking" + elif state == "intaking" and event == "sensor": + return "loaded" + elif state == "loaded" and event == "button": + return "shooting" + elif state == "shooting" and event == "done": + return "empty" + return state + +print(update("empty", "done")) +print(update("empty", "button")) +print(update("loaded", "sensor")) ``` Look hard at that **last line, `return state`**. If none of the transitions -matched, the machine stays exactly where it was. That one line *is* "a state -ignores events it has no arrow for" — the safety you got for free in the +matched, the machine stays right where it was. That one line *is* "a state +ignores events it has no arrow for," the safety you got for free in the diagram. -Run it: `update("empty", "done")` returns `empty` (ignored — you can't finish -a shot you never took), `update("empty", "button")` returns `intaking`, and -`update("loaded", "sensor")` returns `loaded` (ignored — a piece can't load -twice). The machine simply *cannot* reach a bad state, because no path leads -there. +Run it: `update("empty", "done")` returns `empty` (ignored, since you can't +finish a shot you never took), `update("empty", "button")` returns `intaking`, +and `update("loaded", "sensor")` returns `loaded` (ignored, since a piece can't +load twice). The machine simply *cannot* reach a bad state, because no path +leads there. # Feeding it a stream of events A robot gets a new event every tick. We can simulate a whole match by putting -events in an **array** ([lesson {n}](#/lesson/12-arrays)) and running them through the machine one -at a time with a for-each loop: - -```java -public class Main { - static String update(String state, String event) { - if (state.equals("empty") && event.equals("button")) { - return "intaking"; - } else if (state.equals("intaking") && event.equals("sensor")) { - return "loaded"; - } else if (state.equals("loaded") && event.equals("button")) { - return "shooting"; - } else if (state.equals("shooting") && event.equals("done")) { - return "empty"; - } - return state; - } - - public static void main(String[] args) { - String[] events = {"done", "button", "sensor", "button", "done", "sensor"}; - String state = "empty"; - for (String event : events) { - state = update(state, event); - System.out.println(event + " -> " + state); - } - } -} +events in a **list** ([lesson {n}](#/lesson/12-arrays)) and running them through the machine one +at a time with a `for` loop: + +```python +def update(state, event): + if state == "empty" and event == "button": + return "intaking" + elif state == "intaking" and event == "sensor": + return "loaded" + elif state == "loaded" and event == "button": + return "shooting" + elif state == "shooting" and event == "done": + return "empty" + return state + +events = ["done", "button", "sensor", "button", "done", "sensor"] +state = "empty" +for event in events: + state = update(state, event) + print(f"{event} -> {state}") ``` -Trace the output. That first `"done"` while `empty` does nothing — the machine -shrugs it off — then the real sequence walks `empty → intaking → loaded → +Trace the output. That first `"done"` while `empty` does nothing. The machine +shrugs it off, then the real sequence walks `empty → intaking → loaded → shooting → empty`. This is the loop from [last lesson](#/lesson/21-state-machines-in-code), now fed real events instead of a timer. -Your turn: write the events array that takes the handler through **two full +Your turn: write the `events` list that takes the handler through **two full cycles** (load and shoot a piece, then do it again). Then slip an out-of-place -event like `"sensor"` in at the start — a real event, just not one `empty` has -a transition for — and confirm the machine ignores it and still ends where you +event like `"sensor"` in at the start, a real event that `empty` has no +transition for, and confirm the machine ignores it and still ends where you expect. diff --git a/lessons/23-organizing-a-machine/README.md b/lessons/23-organizing-a-machine/README.md index f5f9ac2..563e7b7 100644 --- a/lessons/23-organizing-a-machine/README.md +++ b/lessons/23-organizing-a-machine/README.md @@ -7,140 +7,136 @@ section: "State Machines" # Name your states with an enum -Our machines used bare strings like `"shooting"` for state names. That works -until you make a typo — and typos in strings are a nasty, silent bug: - -```java -String state = "loaded"; -if (state.equals("loded")) { - System.out.println("this never runs, and Java never warns you"); -} -System.out.println("done"); +In the last lesson we used bare strings like `"shooting"` for state names. That +works until you make a typo, and typos in strings are a nasty, silent bug: + +```python +state = "loaded" +if state == "loded": + print("this never runs, and Python never warns you") +print("done") ``` -Run it. Java happily compares `"loaded"` to the misspelled `"loded"`, decides -they're not equal, and moves on — no error, just a branch that mysteriously -never fires. In a robot, that's a mechanism that silently refuses to shoot. +Run it. Python happily compares `"loaded"` to the misspelled `"loded"`, decides +they're not equal, and moves on. There's no error, just a branch that +mysteriously never fires. In a robot, that's a mechanism that silently refuses +to shoot. -Java has a purpose-built fix: an **`enum`** — a type you define yourself, whose -only possible values are the ones you list: +You saw the fix back in [lesson {n}](#/lesson/21-state-machines-in-code): an **`Enum`**, a type you define +yourself whose only possible values are the ones you list: -```java -enum HandlerState { EMPTY, INTAKING, LOADED, SHOOTING } +```python +from enum import Enum -public class Main { - public static void main(String[] args) { - HandlerState state = HandlerState.LOADED; - if (state == HandlerState.LODED) { - System.out.println("ready to shoot!"); - } - } -} +class HandlerState(Enum): + EMPTY = "empty" + INTAKING = "intaking" + LOADED = "loaded" + SHOOTING = "shooting" + +state = HandlerState.LOADED +if state == HandlerState.LOADED: + print("ready to shoot!") ``` -Run *that* and it doesn't even compile — the error points straight at the -misspelled `LODED` before the program takes a single step. That's the whole -point: a misspelled string fails silently at the worst possible moment, but a -misspelled **enum value** fails loudly before the code can run at all. Fix -`LODED` to `LOADED` and it works. +Run it, then change `HandlerState.LOADED` in the `if` line to +`HandlerState.LODED` and run it again. Python stops right away with an +`AttributeError` pointing straight at the misspelled `LODED`. That's the whole +point: a misspelled string fails silently at the worst possible moment, while a +misspelled **enum value** fails loudly right where the typo is. Fix `LODED` +back to `LOADED` and it works. Two details worth noticing: -- `HandlerState` is a **type**, like `int` or `String` — but one *you* - invented, and a variable of that type can only ever hold one of the four - listed values. The machine's rule "you're always in exactly one of these - states" is now enforced by the compiler. -- Enums are compared with `==` — the one place text-like values get to use it - safely, because there's exactly one `HandlerState.LOADED` in the whole - program. (Strings still need `.equals`, as [lesson {n}](#/lesson/16-booleans) warned.) +- `HandlerState` is a **type** you invented, and its members are the only legal + states. The machine's rule "you're always in one of these states" is spelled + out in one place. +- Enums are compared with `==` (from [lesson {n}](#/lesson/16-booleans)), or matched with `match`, + so your conditions stay short and readable. -This is exactly how real FRC robot code names its states, so everything from -here on is the real-world shape. +This is how real robot code names its states, so everything from here on uses +this shape. # Do something the moment you enter a state -Often a state needs an action to happen **once, right as you enter it** — spin -the shooter up, start the intake motor, reset a timer. That's an **enter -action**. Keep it separate from the transition logic: - -```java -enum HandlerState { EMPTY, INTAKING, LOADED, SHOOTING } - -public class Main { - static void onEnter(HandlerState state) { - if (state == HandlerState.INTAKING) { - System.out.println(" -> intake motor ON"); - } else if (state == HandlerState.SHOOTING) { - System.out.println(" -> shooter spinning up!"); - } else if (state == HandlerState.EMPTY) { - System.out.println(" -> motors off, waiting"); - } - } - - public static void main(String[] args) { - // When a transition happens, run the enter action for the new state: - HandlerState newState = HandlerState.SHOOTING; - onEnter(newState); - } -} +Often a state needs an action to happen **once, right as you enter it**, like +spinning the shooter up, starting the intake motor, or resetting a timer. +That's an **enter action**. Keep it separate from the transition logic: + +```python +from enum import Enum + +class HandlerState(Enum): + EMPTY = "empty" + INTAKING = "intaking" + LOADED = "loaded" + SHOOTING = "shooting" + +def on_enter(state): + if state == HandlerState.INTAKING: + print(" -> intake motor ON") + elif state == HandlerState.SHOOTING: + print(" -> shooter spinning up!") + elif state == HandlerState.EMPTY: + print(" -> motors off, waiting") + +# When a transition happens, run the enter action for the new state: +new_state = HandlerState.SHOOTING +on_enter(new_state) ``` Run it and you'll see the shooter spin-up message. The idea: transitions decide *where* you go; enter actions decide *what fires* when you get there. Doing the -spin-up on **enter** means it happens exactly once per shot, not every tick -while you sit in `SHOOTING` — a distinction that matters a lot on a real robot. +spin-up on **enter** means it happens once per shot, not every tick while you +sit in `SHOOTING`. That distinction matters a lot on a real robot. # Bundle it into a class -Right now the state lives in a loose variable and the logic in loose methods. -You already know the fix for that from [the Objects lessons](#/lesson/17-classes-and-objects): a -**field** for the data, a **constructor** to set its starting value, and -**methods** that read and write it through `this`. Applied to a state -machine, it looks like this: - -```java -enum HandlerState { EMPTY, INTAKING, LOADED, SHOOTING } - -class GamePieceHandler { - HandlerState state; - - GamePieceHandler() { - this.state = HandlerState.EMPTY; - } - - void update(String event) { - if (this.state == HandlerState.EMPTY && event.equals("button")) { - this.state = HandlerState.INTAKING; - } else if (this.state == HandlerState.INTAKING && event.equals("sensor")) { - this.state = HandlerState.LOADED; - } else if (this.state == HandlerState.LOADED && event.equals("button")) { - this.state = HandlerState.SHOOTING; - } else if (this.state == HandlerState.SHOOTING && event.equals("done")) { - this.state = HandlerState.EMPTY; - } - } -} - -public class Main { - public static void main(String[] args) { - GamePieceHandler handler = new GamePieceHandler(); - System.out.println(handler.state); - handler.update("button"); - handler.update("sensor"); - System.out.println(handler.state); - } -} +Right now the state lives in a loose variable and the logic in loose functions. +You already know the fix for that from [the Objects lessons](#/lesson/17-classes-and-objects): an +**attribute** for the data, an `__init__` method to set its starting value, and +**methods** that read and write it through `self`. Applied to a state machine, +it looks like this: + +```python +from enum import Enum + +class HandlerState(Enum): + EMPTY = "empty" + INTAKING = "intaking" + LOADED = "loaded" + SHOOTING = "shooting" + +class GamePieceHandler: + def __init__(self): + self.state = HandlerState.EMPTY + + def update(self, event): + if self.state == HandlerState.EMPTY and event == "button": + self.state = HandlerState.INTAKING + elif self.state == HandlerState.INTAKING and event == "sensor": + self.state = HandlerState.LOADED + elif self.state == HandlerState.LOADED and event == "button": + self.state = HandlerState.SHOOTING + elif self.state == HandlerState.SHOOTING and event == "done": + self.state = HandlerState.EMPTY + +handler = GamePieceHandler() +print(handler.state.name) +handler.update("button") +handler.update("sensor") +print(handler.state.name) ``` -Nothing here is new — `HandlerState state;` is a field, `GamePieceHandler()` -is a constructor, `this.state` reads and writes that field — just aimed at an -enum instead of the plain data you practiced on earlier. Run it: the handler -starts `EMPTY`, and after a `button` then a `sensor` it's `LOADED` — and it -stayed `LOADED` between the two calls because the object remembers its own -state. That memory is why a class beats loose variables once you have more -than one machine — which is exactly where we go next. - -Your turn: add a `report()` method to the class that prints the current state -with a friendly label (an `if/else if` over `this.state`). Create a handler -and drive it through a full load-and-shoot cycle, calling `report()` after -each event. +Nothing here is new. `self.state` is an attribute, `__init__` sets its starting +value, and `update` reads and writes `self.state`. We just aimed it at an enum +instead of the plain data you practiced on earlier. Run it: the handler starts +`EMPTY`, and after a `button` then a `sensor` it's `LOADED`. It stayed `LOADED` +between the two calls because the object remembers its own state. That memory +is why a class beats loose variables once you have more than one machine, which +is where we go next. + +Your turn: add a `report(self)` method to the class that prints the current +state with a friendly label (an `if`/`elif` over `self.state`). Create a +handler and drive it through a full load-and-shoot cycle, calling `report()` +after each event. diff --git a/lessons/24-coordinating-machines/README.md b/lessons/24-coordinating-machines/README.md index 99e746a..3893c83 100644 --- a/lessons/24-coordinating-machines/README.md +++ b/lessons/24-coordinating-machines/README.md @@ -8,95 +8,96 @@ section: "State Machines" # A robot is many small machines One giant state machine for a whole robot would be a tangle. Real robot code -uses **several small machines** — one per mechanism — each an object +uses **several small machines**, one per mechanism, each an object ([lesson {n}](#/lesson/18-multiple-objects)) with its own state. Because a class remembers its own state -field, you can make as many as you want and they don't interfere: - -```java -enum IntakeState { CLEAR, HOLDING } -enum ShooterState { IDLE, FIRING } - -class Intake { - IntakeState state = IntakeState.CLEAR; - - void update(String event) { - if (this.state == IntakeState.CLEAR && event.equals("grab")) { - this.state = IntakeState.HOLDING; - } else if (this.state == IntakeState.HOLDING && event.equals("release")) { - this.state = IntakeState.CLEAR; - } - } -} - -class Shooter { - ShooterState state = ShooterState.IDLE; - - void update(String event) { - if (this.state == ShooterState.IDLE && event.equals("shoot")) { - this.state = ShooterState.FIRING; - } else if (this.state == ShooterState.FIRING && event.equals("done")) { - this.state = ShooterState.IDLE; - } - } -} - -public class Main { - public static void main(String[] args) { - Intake intake = new Intake(); - Shooter shooter = new Shooter(); - System.out.println(intake.state + " " + shooter.state); - } -} +attribute, you can make as many as you want and they don't interfere: + +```python +from enum import Enum + +class IntakeState(Enum): + CLEAR = "clear" + HOLDING = "holding" + +class ShooterState(Enum): + IDLE = "idle" + FIRING = "firing" + +class Intake: + def __init__(self): + self.state = IntakeState.CLEAR + + def update(self, event): + if self.state == IntakeState.CLEAR and event == "grab": + self.state = IntakeState.HOLDING + elif self.state == IntakeState.HOLDING and event == "release": + self.state = IntakeState.CLEAR + +class Shooter: + def __init__(self): + self.state = ShooterState.IDLE + + def update(self, event): + if self.state == ShooterState.IDLE and event == "shoot": + self.state = ShooterState.FIRING + elif self.state == ShooterState.FIRING and event == "done": + self.state = ShooterState.IDLE + +intake = Intake() +shooter = Shooter() +print(intake.state.name, shooter.state.name) ``` -Two machines, two independent states — and two enums, because each mechanism -has its *own* set of legal states. Run it: `CLEAR IDLE`. Each machine is small -and easy to reason about on its own — that's the point of splitting them up. +Two machines, two independent states, and two enums, because each mechanism has +its *own* set of legal states. Run it: `CLEAR IDLE`. Each machine is small and +easy to reason about on its own. That's the point of splitting them up. -(One shorthand to spot: `IntakeState state = IntakeState.CLEAR;` sets the -field's starting value right where it's declared, so these little classes -don't need a constructor. [Lesson {n}'s](#/lesson/17-classes-and-objects) constructor form is what you'll -want when starting up takes real work.) +Each class sets its starting `self.state` inside `__init__` (from +[lesson {n}](#/lesson/17-classes-and-objects)), so every new object starts in a known state. # Machines that watch each other Mechanisms aren't really independent, though. You shouldn't fire the shooter while the intake is still holding a piece in the way. One machine can make a -decision based on **another machine's state** — just pass it in: - -```java -enum IntakeState { CLEAR, HOLDING } -enum ShooterState { IDLE, FIRING } - -class Shooter { - ShooterState state = ShooterState.IDLE; - - void update(String event, IntakeState intakeState) { - if (this.state == ShooterState.IDLE && event.equals("shoot") - && intakeState == IntakeState.CLEAR) { - this.state = ShooterState.FIRING; - } else if (this.state == ShooterState.FIRING && event.equals("done")) { - this.state = ShooterState.IDLE; - } - } -} - -public class Main { - public static void main(String[] args) { - Shooter shooter = new Shooter(); - shooter.update("shoot", IntakeState.HOLDING); - System.out.println("tried to shoot while holding: " + shooter.state); - shooter.update("shoot", IntakeState.CLEAR); - System.out.println("shot while clear: " + shooter.state); - } -} +decision based on **another machine's state**. Just pass it in: + +```python +from enum import Enum + +class IntakeState(Enum): + CLEAR = "clear" + HOLDING = "holding" + +class ShooterState(Enum): + IDLE = "idle" + FIRING = "firing" + +class Shooter: + def __init__(self): + self.state = ShooterState.IDLE + + def update(self, event, intake_state): + if ( + self.state == ShooterState.IDLE + and event == "shoot" + and intake_state == IntakeState.CLEAR + ): + self.state = ShooterState.FIRING + elif self.state == ShooterState.FIRING and event == "done": + self.state = ShooterState.IDLE + +shooter = Shooter() +shooter.update("shoot", IntakeState.HOLDING) +print("tried to shoot while holding:", shooter.state.name) +shooter.update("shoot", IntakeState.CLEAR) +print("shot while clear:", shooter.state.name) ``` -The extra `&& intakeState == IntakeState.CLEAR` ([lesson {n}](#/lesson/16-booleans) again) is a +The extra `and intake_state == IntakeState.CLEAR` ([lesson {n}](#/lesson/16-booleans) again) is a **guard**: the shooter refuses to fire unless the intake reports it's out of -the way. Run it — the first attempt is ignored because the intake was -`HOLDING`; the second works. This cross-machine guard is how you keep two -mechanisms from fighting each other. +the way. Run it. The first attempt is ignored because the intake was `HOLDING`; +the second works. This cross-machine guard is how you keep two mechanisms from +fighting each other. # The shared robot loop @@ -104,58 +105,58 @@ Now the payoff: one loop drives **both** machines every tick, feeding the shooter whatever the intake's state currently is. This is, in miniature, the loop that runs the whole robot. -```java -enum IntakeState { CLEAR, HOLDING } -enum ShooterState { IDLE, FIRING } - -class Intake { - IntakeState state = IntakeState.CLEAR; - - void update(String event) { - if (this.state == IntakeState.CLEAR && event.equals("grab")) { - this.state = IntakeState.HOLDING; - } else if (this.state == IntakeState.HOLDING && event.equals("release")) { - this.state = IntakeState.CLEAR; - } - } -} - -class Shooter { - ShooterState state = ShooterState.IDLE; - - void update(String event, IntakeState intakeState) { - if (this.state == ShooterState.IDLE && event.equals("shoot") - && intakeState == IntakeState.CLEAR) { - this.state = ShooterState.FIRING; - } else if (this.state == ShooterState.FIRING && event.equals("done")) { - this.state = ShooterState.IDLE; - } - } -} - -public class Main { - public static void main(String[] args) { - Intake intake = new Intake(); - Shooter shooter = new Shooter(); - String[] events = {"grab", "shoot", "release", "shoot", "done"}; - - for (String event : events) { - intake.update(event); - shooter.update(event, intake.state); - System.out.println(event + " -> intake: " + intake.state - + " shooter: " + shooter.state); - } - } -} +```python +from enum import Enum + +class IntakeState(Enum): + CLEAR = "clear" + HOLDING = "holding" + +class ShooterState(Enum): + IDLE = "idle" + FIRING = "firing" + +class Intake: + def __init__(self): + self.state = IntakeState.CLEAR + + def update(self, event): + if self.state == IntakeState.CLEAR and event == "grab": + self.state = IntakeState.HOLDING + elif self.state == IntakeState.HOLDING and event == "release": + self.state = IntakeState.CLEAR + +class Shooter: + def __init__(self): + self.state = ShooterState.IDLE + + def update(self, event, intake_state): + if ( + self.state == ShooterState.IDLE + and event == "shoot" + and intake_state == IntakeState.CLEAR + ): + self.state = ShooterState.FIRING + elif self.state == ShooterState.FIRING and event == "done": + self.state = ShooterState.IDLE + +intake = Intake() +shooter = Shooter() +events = ["grab", "shoot", "release", "shoot", "done"] + +for event in events: + intake.update(event) + shooter.update(event, intake.state) + print(f"{event} -> intake: {intake.state.name} shooter: {shooter.state.name}") ``` Trace it: `grab` makes the intake `HOLDING`; the `shoot` that follows is blocked because the intake is in the way; `release` clears it; the next `shoot` fires; and `done` resets. Two machines, one loop, coordinating through -their states — every tick, both get a chance to update. Run it and confirm the +their states. Every tick, both get a chance to update. Run it and confirm the blocked shot. -Your turn: add a third machine — a `Climber` with its own enum and states +Your turn: add a third machine, a `Climber` with its own enum and states `STOWED → EXTENDING → EXTENDED`. Update it in the same loop, and give it a guard so it only starts extending when the shooter is `IDLE` (you don't want to climb mid-shot). Add the events it needs and watch all three states march diff --git a/lessons/25-capstone-state-machine/README.md b/lessons/25-capstone-state-machine/README.md index 85bb155..70680db 100644 --- a/lessons/25-capstone-state-machine/README.md +++ b/lessons/25-capstone-state-machine/README.md @@ -1,5 +1,5 @@ --- -title: "Capstone 1 — design a state machine" +title: "Capstone 1: design a state machine" goal: "Take a real mechanism from words to a diagram to working code you can simulate." order: 250 section: "State Machines" @@ -7,8 +7,8 @@ section: "State Machines" # From a mechanism to a diagram -Everything so far handed you the states and transitions. The real skill — the -one you'll use all season — is **designing** them yourself. It's a repeatable +Everything so far handed you the states and transitions. The real skill, the +one you'll use all season, is **designing** them yourself. It's a repeatable process, and it starts on paper, not in code. Take a **climber**: it stows flat, extends a hook up to the bar, hangs there, @@ -26,119 +26,111 @@ EXTENDED --button---> RETRACTING RETRACTING --at_bottom-> STOWED ``` -That's the exact diagram you'd build with blocks in [lesson {n}](#/lesson/20-state-machines) — states, events, -arrows, and (just as important) *no* arrow for anything unsafe. Notice there's -no way to go straight from `STOWED` to `EXTENDED`: you must pass through -`EXTENDING`. The design forbids the dangerous shortcut. +That's the exact diagram you'd build with blocks in [lesson {n}](#/lesson/20-state-machines): states, +events, arrows, and (just as important) *no* arrow for anything unsafe. Notice +there's no way to go straight from `STOWED` to `EXTENDED`. You must pass +through `EXTENDING`. The design forbids the dangerous shortcut. # Translate the diagram to code -Now it's mechanical — the diagram maps straight onto the class shape from -[lesson {n}](#/lesson/23-organizing-a-machine): an enum for the states, a constructor for the start, an `update` -with one branch per arrow, and enter actions for what should fire once. - -```java -enum ClimberState { STOWED, EXTENDING, EXTENDED, RETRACTING } - -class Climber { - ClimberState state; - - Climber() { - this.state = ClimberState.STOWED; - } - - void update(String event) { - ClimberState old = this.state; - if (this.state == ClimberState.STOWED && event.equals("button")) { - this.state = ClimberState.EXTENDING; - } else if (this.state == ClimberState.EXTENDING && event.equals("at_top")) { - this.state = ClimberState.EXTENDED; - } else if (this.state == ClimberState.EXTENDED && event.equals("button")) { - this.state = ClimberState.RETRACTING; - } else if (this.state == ClimberState.RETRACTING && event.equals("at_bottom")) { - this.state = ClimberState.STOWED; - } - if (this.state != old) { - onEnter(); - } - } - - void onEnter() { - if (this.state == ClimberState.EXTENDING) { - System.out.println(" -> motor up"); - } else if (this.state == ClimberState.RETRACTING) { - System.out.println(" -> motor down, hang on!"); - } - } -} - -public class Main { - public static void main(String[] args) { - Climber climber = new Climber(); - climber.update("button"); - System.out.println(climber.state); - } -} +Now it's mechanical. The diagram maps straight onto the class shape from +[lesson {n}](#/lesson/23-organizing-a-machine): an enum for the states, an `__init__` for the start, an +`update` with one branch per arrow, and enter actions for what should fire once. + +```python +from enum import Enum + +class ClimberState(Enum): + STOWED = "stowed" + EXTENDING = "extending" + EXTENDED = "extended" + RETRACTING = "retracting" + +class Climber: + def __init__(self): + self.state = ClimberState.STOWED + + def update(self, event): + old = self.state + if self.state == ClimberState.STOWED and event == "button": + self.state = ClimberState.EXTENDING + elif self.state == ClimberState.EXTENDING and event == "at_top": + self.state = ClimberState.EXTENDED + elif self.state == ClimberState.EXTENDED and event == "button": + self.state = ClimberState.RETRACTING + elif self.state == ClimberState.RETRACTING and event == "at_bottom": + self.state = ClimberState.STOWED + if self.state != old: + self.on_enter() + + def on_enter(self): + if self.state == ClimberState.EXTENDING: + print(" -> motor up") + elif self.state == ClimberState.RETRACTING: + print(" -> motor down, hang on!") + +climber = Climber() +climber.update("button") +print(climber.state.name) ``` Read `update`: it remembers the `old` state, tries each transition, and if the -state actually changed, fires `onEnter` for the new one. Every line traces back -to a piece of the diagram. Run it — one `button` moves `STOWED → EXTENDING` +state actually changed, fires `on_enter` for the new one. Every line traces +back to a piece of the diagram. Run it: one `button` moves `STOWED → EXTENDING` and prints the motor-up action. # Simulate it, then build your own -Drive your machine with an array of events, the way a match would, and print +Drive your machine with a list of events, the way a match would, and print each step: -```java -enum ClimberState { STOWED, EXTENDING, EXTENDED, RETRACTING } - -class Climber { - ClimberState state = ClimberState.STOWED; - - void update(String event) { - if (this.state == ClimberState.STOWED && event.equals("button")) { - this.state = ClimberState.EXTENDING; - } else if (this.state == ClimberState.EXTENDING && event.equals("at_top")) { - this.state = ClimberState.EXTENDED; - } else if (this.state == ClimberState.EXTENDED && event.equals("button")) { - this.state = ClimberState.RETRACTING; - } else if (this.state == ClimberState.RETRACTING && event.equals("at_bottom")) { - this.state = ClimberState.STOWED; - } - } -} - -public class Main { - public static void main(String[] args) { - Climber climber = new Climber(); - String[] events = {"button", "button", "at_top", "button", "at_bottom"}; - for (String event : events) { - climber.update(event); - System.out.println(event + " -> " + climber.state); - } - } -} +```python +from enum import Enum + +class ClimberState(Enum): + STOWED = "stowed" + EXTENDING = "extending" + EXTENDED = "extended" + RETRACTING = "retracting" + +class Climber: + def __init__(self): + self.state = ClimberState.STOWED + + def update(self, event): + if self.state == ClimberState.STOWED and event == "button": + self.state = ClimberState.EXTENDING + elif self.state == ClimberState.EXTENDING and event == "at_top": + self.state = ClimberState.EXTENDED + elif self.state == ClimberState.EXTENDED and event == "button": + self.state = ClimberState.RETRACTING + elif self.state == ClimberState.RETRACTING and event == "at_bottom": + self.state = ClimberState.STOWED + +climber = Climber() +events = ["button", "button", "at_top", "button", "at_bottom"] +for event in events: + climber.update(event) + print(f"{event} -> {climber.state.name}") ``` -Watch the second `"button"` do nothing — while `EXTENDING`, the climber -ignores the button and waits for `at_top`, just like the diagram says. That's -the safety you designed in, running in code. +Watch the second `"button"` do nothing. While `EXTENDING`, the climber ignores +the button and waits for `at_top`, just like the diagram says. That's the +safety you designed in, running in code. -**Your Capstone 1.** Pick a real mechanism from this year's robot — an arm, a -turret, an indexer, whatever your team is building. Then: +**Your Capstone 1.** Pick a real mechanism from this year's robot, like an arm, +a turret, or an indexer. Then: 1. Write its states, its events, and its arrows as a diagram (page 1's three questions). 2. Turn it into an enum and a class with an `update` and at least one enter action. -3. Simulate it with an event array and confirm it does the right thing — - including *ignoring* the events that would be unsafe. +3. Simulate it with an event list and confirm it does the right thing, including + *ignoring* the events that would be unsafe. -Do that, and you haven't just finished the lessons — you've written the kind of +Do that, and you haven't just finished the lessons. You've written the kind of code your robot will actually run this season. Keep this mechanism around. Once you've picked up a few more tools in the -Advanced Java section, Capstone 2 will have you come back and upgrade this +Advanced Python section, Capstone 2 will have you come back and upgrade this exact class. diff --git a/lessons/26-decisions-in-code-revisited/README.md b/lessons/26-decisions-in-code-revisited/README.md index 2820cc4..b5377d6 100644 --- a/lessons/26-decisions-in-code-revisited/README.md +++ b/lessons/26-decisions-in-code-revisited/README.md @@ -1,129 +1,104 @@ --- title: "Decisions in code, revisited" -goal: "Rewrite if/else-if chains as switch statements — including over an enum — and use the ternary operator for one-line decisions." +goal: "Rewrite if/elif chains as match/case statements, including over an Enum, and use conditional expressions for one-line decisions." order: 260 -section: "Advanced Java" +section: "Advanced Python" --- -# switch: one question, many answers +# match: one question, many answers -[Lesson {n}](#/lesson/22-events-and-transitions) dispatched on an event string with `if`/`else if`. That works, but -when every branch is testing the *same* variable against different exact -values, Java has a shape built for exactly that: **`switch`**. +[Lesson {n}](#/lesson/22-events-and-transitions) dispatched on an event string with `if`/`elif`. That works, but when every branch tests the *same* variable against different exact values, Python 3.10+ has a cleaner shape built for it: **`match`** and **`case`**. -```java -String event = "button"; +```python +event = "button" -if (event.equals("button")) { - System.out.println("driver pressed the button"); -} else if (event.equals("sensor")) { - System.out.println("sensor tripped"); -} else if (event.equals("done")) { - System.out.println("shot finished"); -} else { - System.out.println("unknown event"); -} +if event == "button": + print("driver pressed the button") +elif event == "sensor": + print("sensor tripped") +elif event == "done": + print("shot finished") +else: + print("unknown event") ``` -Same behavior, as a `switch`: +Same behavior, written with `match`: -```java -String event = "button"; +```python +event = "button" -switch (event) { +match event: case "button": - System.out.println("driver pressed the button"); - break; + print("driver pressed the button") case "sensor": - System.out.println("sensor tripped"); - break; + print("sensor tripped") case "done": - System.out.println("shot finished"); - break; - default: - System.out.println("unknown event"); -} + print("shot finished") + case _: + print("unknown event") ``` -Run it, then change `event` to `"sensor"` and `"nonsense"` and run again. Three -things to notice: - -- **`case value:`** replaces `else if (x.equals(value))` — Java checks `event` - against each case in order and runs the matching one. -- **`default:`** replaces the final `else` — it catches anything that matched - no case. -- **`break;`** stops the switch after that case runs. Leave it off and Java - keeps going into the *next* case regardless of whether it matches — a real - bug called "fall-through." Try deleting the `break;` after `"button"` and - run with `event = "button"` again: you'll get both the button message *and* - the sensor message. Put the `break;` back before moving on. - -# switch on an enum - -`switch` gets even better once the thing you're checking is an -**`enum`**, because Java already knows every value it could possibly be. -Here's [lesson {n}'s](#/lesson/23-organizing-a-machine) `onEnter`, rewritten: - -```java -enum HandlerState { EMPTY, INTAKING, LOADED, SHOOTING } - -public class Main { - static void onEnter(HandlerState state) { - switch (state) { - case INTAKING: - System.out.println(" -> intake motor ON"); - break; - case SHOOTING: - System.out.println(" -> shooter spinning up!"); - break; - case EMPTY: - System.out.println(" -> motors off, waiting"); - break; - default: - break; - } - } - - public static void main(String[] args) { - onEnter(HandlerState.SHOOTING); - onEnter(HandlerState.LOADED); - } -} +Run it, then change `event` to `"sensor"` and `"nonsense"` and run again. Three things to notice: + +- **`case value:`** replaces `elif event == value:`. Python checks `event` against each case in order and runs the first one that matches. +- **`case _:`** replaces the final `else`. The underscore is a wildcard that catches anything that did not match an earlier case. +- **No `break` needed.** Once a case runs, Python exits the `match` block automatically. It never falls through into the next case. + +# match on an enum + +`match` shines when the value you're checking is an **`Enum`**, because every legal value is listed in one place. Here is [lesson {n}'s](#/lesson/23-organizing-a-machine) `on_enter`, rewritten: + +```python +from enum import Enum + + +class HandlerState(Enum): + EMPTY = "empty" + INTAKING = "intaking" + LOADED = "loaded" + SHOOTING = "shooting" + + +def on_enter(state: HandlerState) -> None: + match state: + case HandlerState.INTAKING: + print(" -> intake motor ON") + case HandlerState.SHOOTING: + print(" -> shooter spinning up!") + case HandlerState.EMPTY: + print(" -> motors off, waiting") + case _: + pass + + +on_enter(HandlerState.SHOOTING) +on_enter(HandlerState.LOADED) ``` -Run it: `SHOOTING` prints the spin-up message, and `LOADED` prints nothing — -it falls to `default`, which does nothing on purpose. Notice the case labels -are just `INTAKING`, not `HandlerState.INTAKING` — once you `switch (state)`, -Java already knows the type, so the enum name would be redundant. Compare -this to the `if (state == HandlerState.INTAKING)` chain from [lesson {n}](#/lesson/23-organizing-a-machine): same -logic, less repetition, and far easier to scan when a state list grows long. +Run it. `SHOOTING` prints the spin-up message, and `LOADED` prints nothing because it hits `case _:` and does `pass` on purpose. + +Notice that each case writes the full dotted name, `HandlerState.INTAKING`, not just `INTAKING`. In Python's `match` statement, a bare name without a dot tells Python to *capture* the value into a new variable instead of comparing against a constant. Always include the enum class name with the dot. -# The ternary operator: a decision in one line +Compare this to the `if state == HandlerState.INTAKING:` chain from [lesson {n}](#/lesson/23-organizing-a-machine). Same logic, less repetition, and easier to scan when a state list grows long. -Some decisions are too small to deserve a whole `if`/`else` — just picking -one of two values. The **ternary operator**, `? :`, does that in one line: +# Conditional expressions: a decision in one line -```java -boolean ready = true; -String status = ready ? "GO" : "WAIT"; -System.out.println(status); +Some decisions are too small for a four-line `if`/`else`. When you only need to pick one of two values, Python's **conditional expression** does it on one line: + +```python +ready = True +status = "GO" if ready else "WAIT" +print(status) ``` -Read it as *"ready? then `"GO"`, otherwise `"WAIT"`."* Change `ready` to -`false` and run again — `status` flips. It's exactly the two-branch `if`/`else` -from [lesson {n}](#/lesson/09-if-statements), just squeezed onto one line -because both branches are a single value, not a block of statements. A -realistic use — the ready check from [lesson {n}'s](#/lesson/19-encapsulation) -`Flywheel`: - -```java -double rpm = 4800.0; -String message = rpm >= 4500.0 ? "shooter ready" : "still spinning up"; -System.out.println(message); +Read it almost like English: *"`"GO"` if `ready`, else `"WAIT"`."* Change `ready` to `False` and run again to see `status` flip. It is the exact same two-branch `if`/`else` from [lesson {n}](#/lesson/09-if-statements), squeezed onto one line because both branches produce a single value rather than running a block of statements. + +Here is a realistic use based on the ready check from [lesson {n}'s](#/lesson/19-encapsulation) `Flywheel`: + +```python +rpm = 4800.0 +message = "shooter ready" if rpm >= 4500.0 else "still spinning up" +print(message) ``` -Your turn: write a method `describe(HandlerState state)` that returns a -`String` using a `switch` — one case per state, plus a `default`. Then, in -`main`, call it for `HandlerState.EMPTY` and print the result with a ternary -tacked on: append `" (idle)"` if the state is `HandlerState.EMPTY`, or -`""` otherwise. +Your turn: write a function `describe(state: HandlerState) -> str` that returns a description using `match`, with one case per state plus `case _:`. Call it for `HandlerState.EMPTY` and print the result with a conditional expression tacked on: append `" (idle)"` if the state is `HandlerState.EMPTY`, or `""` otherwise. diff --git a/lessons/27-enums-revisited/README.md b/lessons/27-enums-revisited/README.md index 5f887b4..05a70b6 100644 --- a/lessons/27-enums-revisited/README.md +++ b/lessons/27-enums-revisited/README.md @@ -1,99 +1,88 @@ --- title: "Enums, revisited" -goal: "Loop over every value an enum can hold, and give an enum a field so each state carries its own number." +goal: "Loop over every member of an Enum, and give each member its own attributes and methods." order: 270 -section: "Advanced Java" +section: "Advanced Python" --- # Every value an enum can hold -You've had `HandlerState` since [lesson {n}](#/lesson/23-organizing-a-machine) -— four fixed values, nothing else legal. Here's a trick you haven't seen yet: -an enum can hand you **every value it has**, with `.values()`. +You've had `HandlerState` since [lesson {n}](#/lesson/23-organizing-a-machine), four fixed states and nothing else legal. Here is a trick you haven't seen yet: in Python, an `Enum` class is directly iterable, so you can loop over **every member it has**. -```java -enum HandlerState { EMPTY, INTAKING, LOADED, SHOOTING } +```python +from enum import Enum -public class Main { - public static void main(String[] args) { - for (HandlerState state : HandlerState.values()) { - System.out.println(state); - } - } -} + +class HandlerState(Enum): + EMPTY = "empty" + INTAKING = "intaking" + LOADED = "loaded" + SHOOTING = "shooting" + + +for state in HandlerState: + print(state.name) +``` + +Run it. All four states print in the order they were declared. Looping directly over `HandlerState` works just like looping over a list from [lesson {n}](#/lesson/12-arrays), and you can even write `list(HandlerState)` if you need an actual list. If you add a fifth state to the enum later, this loop picks it up automatically. A hand-written list would silently miss it. + +# Giving an enum attributes and methods + +So far an enum member has only been a name and a simple value. Because a Python `Enum` is a real class, each member can also carry its **own attributes** and **methods**, just like `Flywheel` in [lesson {n}](#/lesson/17-classes-and-objects). + +Suppose every `HandlerState` knows the motor speed it should run at, plus a method that reports whether the motor is spinning: + +```python +from enum import Enum + + +class HandlerState(Enum): + EMPTY = 0.0 + INTAKING = 0.5 + LOADED = 0.0 + SHOOTING = 1.0 + + def __init__(self, motor_speed: float) -> None: + self.motor_speed = motor_speed + + def is_spinning(self) -> bool: + return self.motor_speed > 0.0 + + +for state in HandlerState: + print(f"{state.name} -> speed={state.motor_speed}, spinning={state.is_spinning()}") ``` -Run it — all four states print, in the order they were declared. `.values()` -returns an array of every constant ([lesson {n}'s](#/lesson/12-arrays) array -and for-each) — handy anywhere you'd otherwise -have to list the states yourself and hope you didn't forget one. If you add a -fifth state to the enum, this loop picks it up automatically; a hand-written -list would silently miss it. - -# Giving an enum a field - -So far an enum constant has only ever been a name. But a constant can also -carry its **own data** — say, the motor speed each state should run at. Give -`HandlerState` a field and a constructor, the same way [lesson {n}](#/lesson/17-classes-and-objects) -gave `Flywheel` one: - -```java -enum HandlerState { - EMPTY(0.0), - INTAKING(0.5), - LOADED(0.0), - SHOOTING(1.0); - - final double motorSpeed; - - HandlerState(double motorSpeed) { - this.motorSpeed = motorSpeed; - } -} - -public class Main { - public static void main(String[] args) { - for (HandlerState state : HandlerState.values()) { - System.out.println(state + " -> " + state.motorSpeed); - } - } -} +Run it. Each member passes its value into `__init__` when the class is defined. `INTAKING = 0.5` sets `self.motor_speed = 0.5` on `HandlerState.INTAKING`, and `SHOOTING = 1.0` sets `self.motor_speed = 1.0` on `HandlerState.SHOOTING`. Wait, look closely at `EMPTY` and `LOADED` in that output! + +Did `LOADED` disappear from the loop? Yes! In Python, if two enum members have the exact same value (`0.0`), Python treats the second one (`LOADED`) as an **alias** for the first (`EMPTY`) instead of a distinct state. When two states share a speed, give each member a tuple with a unique name or ID, or a second field: + +```python +from enum import Enum + + +class HandlerState(Enum): + EMPTY = ("empty", 0.0) + INTAKING = ("intaking", 0.5) + LOADED = ("loaded", 0.0) + SHOOTING = ("shooting", 1.0) + + def __init__(self, label: str, motor_speed: float) -> None: + self.label = label + self.motor_speed = motor_speed + + def is_spinning(self) -> bool: + return self.motor_speed > 0.0 + + +for state in HandlerState: + print(f"{state.name} -> speed={state.motor_speed}, spinning={state.is_spinning()}") ``` -Run it. Each constant now calls the constructor with its own number — -`INTAKING(0.5)` means "build the `INTAKING` constant, passing `0.5` to its -constructor" — exactly like `new Flywheel(0.5)` would, just written before the -semicolon that ends the constant list. `this.motorSpeed = motorSpeed;` inside -the constructor is the same assignment pattern from [lesson {n}](#/lesson/17-classes-and-objects); it just runs -once per constant instead of once per `new`. - -Two details worth naming: - -- The **semicolon after `SHOOTING(1.0)`** is required — it's what separates - "here are the constants" from "here's everything else in the enum" (the - field and constructor). -- **`final`** means `motorSpeed` is set once, in the constructor, and can - never change after — appropriate here, since `HandlerState.SHOOTING` - shouldn't be able to quietly mean a different speed partway through a - match. - -This is exactly the real shape of state-specific setpoints in FRC code: one -enum, one number per state, no separate lookup table to keep in sync. - -**A word of caution, though.** An enum's whole job is to name a **small, -closed set of options** for a decision — `HandlerState` works because there -are exactly four states, and every one of them matters to `update()`. One -field like `motorSpeed` still serves that job. But it's tempting to keep -piling more fields onto an enum once you've seen it hold one — a second -number, then a third, then a `String` label — and that's a trap. The moment -a constant needs several fields, or the list of constants grows past what you -can hold in your head at once, you've stopped modeling *a choice* and started -modeling *a small database*, and a `class` ([lesson {n}](#/lesson/17-classes-and-objects)) -or a `Map` ([lesson {n}](#/lesson/14-maps)) usually fits that better. Keep an -enum's values doing what they're for — naming the options — and keep what -they carry small enough that the set of options is still the point. - -Your turn: add a fifth state, `JAMMED(0.0)`, to `HandlerState`. Then loop over -`.values()` again and print each state's name next to its `motorSpeed` — -confirm your new state shows up automatically, with no other line of the loop -needing to change. +Run that second snippet. Now all four states are distinct, Python unpacks the tuple into `__init__(self, label, motor_speed)` automatically, and every state carries both its own speed and the `is_spinning()` method. + +This is the real shape of state-specific setpoints in FRC code: one enum, one speed per state, and no separate lookup table to keep in sync. + +**A word of caution, though.** An enum's job is to name a **small, closed set of options** for a decision. `HandlerState` works because there are four clear states and every one of them matters to `update()`. One or two fields like `motor_speed` still serve that job. It is tempting to keep piling more attributes onto an enum once you see it hold one, like a third number, a timeout, and a sensor flag. The moment a member needs a pile of fields, or the list grows past what you can hold in your head at once, you have stopped modeling *a choice* and started modeling *a small database*. A regular `class` ([lesson {n}](#/lesson/17-classes-and-objects)) or a `dict` ([lesson {n}](#/lesson/14-maps)) fits that much better. Keep enum members focused on naming the options. + +Your turn: add a fifth state, `JAMMED = ("jammed", 0.0)`, to `HandlerState`. Loop over `HandlerState` again and print each state's name, `motor_speed`, and `is_spinning()`. Confirm your new state shows up automatically without changing a single line of the loop. diff --git a/lessons/28-interfaces-as-diagrams/README.md b/lessons/28-interfaces-as-diagrams/README.md index 09bbf8e..ee61e0d 100644 --- a/lessons/28-interfaces-as-diagrams/README.md +++ b/lessons/28-interfaces-as-diagrams/README.md @@ -1,76 +1,44 @@ --- title: "Interfaces, as diagrams" -goal: "See that a contract can have more than one implementation, and that plugging in something that isn't one shows up as a visible, broken wire — before writing a line of Java." +goal: "See that a contract can have more than one implementation, and that plugging in something that isn't one shows up as a visible broken wire, before writing a line of Python." order: 280 -section: "Advanced Java" +section: "Advanced Python" --- # One contract, two implementations -Every class you've built so far was one specific thing: one `Flywheel`, one -`Climber`. Now meet a different idea: a **contract** — a promise that -"whatever this is, it can do *this one thing*" — with more than one thing -willing to keep that promise. +Every class you've built so far was one specific thing: one `Flywheel`, one `Climber`. Now meet a different idea: a **contract**, a promise that "whatever this is, it can do *this one thing*", with more than one thing willing to keep that promise. -Here's `MotorIO`: a contract for one action, `getSpeed()`. Below it sit two -things that could keep that promise — a **SIM** block and a **REAL** block — -and a **declare** block that holds exactly one of them. +Here is `MotorIO`: a contract for one action, `getSpeed()`. Below it sit two things that could keep that promise, a **SIM** block and a **REAL** block, plus a **declare** block that holds one of them. ```blocks preset: iface-demo ``` -Notice the SIM and REAL blocks each show a `getSpeed()` field with a number in -it — but only because a wire runs down from `MotorIO` into each one. That -wire is what grants them the field in the first place; an implementation -without it would have nothing to offer. `declare` holds the SIM block right -now, so the result is SIM's number. Run it and watch that value flow all the -way down. +Notice the SIM and REAL blocks each show a `getSpeed()` field with a number in it, but only because a wire runs down from `MotorIO` into each one. That wire is what grants them the field in the first place. An implementation without it would have nothing to offer. `declare` holds the SIM block right now, so the result is SIM's number. Run it and watch that value flow all the way down. # Same question, different answer -To get REAL's answer instead, you don't flip a switch — you change **which -wire** feeds `declare`. Here the same graph is wired to REAL instead, with -different numbers on each implementation: +To get REAL's answer instead, you don't flip a switch. You change **which wire** feeds `declare`. Here the same graph is wired to REAL instead, with different numbers on each implementation: ```blocks preset: iface-edit ``` -Edit the SIM and REAL numbers and re-run. Whichever one `declare` is wired to -is the one whose number reaches the result — same question, same `declare` -block, different answer, entirely because of which implementation is plugged -in underneath it. +Edit the SIM and REAL numbers and re-run. Whichever one `declare` is wired to is the one whose number reaches the result. Same question, same `declare` block, different answer, entirely because of which implementation is plugged in underneath it. -This is the whole idea of an interface, in one sentence: **code that asks the -question doesn't need to know which implementation is answering — it only -needs whatever's plugged in to have kept the promise.** A robot running in -simulation and a robot running on real motors can execute the *exact same* -logic, as long as both sides keep the same promise. +This is the whole idea of an interface in one sentence: **code that asks the question doesn't need to know which implementation is answering, only that whatever is plugged in kept the promise.** A robot running in simulation and a robot running on real motors can execute the *exact same* logic, as long as both sides keep the same promise. # Build one yourself -Your turn. Place an **interface**, two implementations — one **SIM**, one -**REAL** — and a **declare object**, then wire `MotorIO` into both -implementations (watch their `getSpeed()` fields appear) and wire *one* of -them into `declare`. +Your turn. Place an **interface**, two implementations (one **SIM**, one **REAL**), and a **declare object**. Wire `MotorIO` into both implementations so their `getSpeed()` fields appear, then wire *one* of them into `declare`. ```blocks preset: iface-build ``` -Now try to break it: drag out a plain **number** block and wire it into -`declare` instead. The wire *does* connect — but it turns dashed with a red -**✕** on it, because `declare` can tell this isn't a real `MotorIO`. Click -**Run step by step** anyway and the result comes back `error`: a wire is not -the same thing as a valid answer. This is exactly what a real -`MotorIO io = someNumber;` line would do in Java — refuse to compile, because -a plain number was never anything the interface promised. Reconnect a real -implementation, confirm the result comes back clean, then try swapping which -implementation feeds `declare` and watch the result change to match. - -Everything you just built by hand — a contract, two things that fulfill it, -and a declaration that can tell the difference between a real implementation -and a broken wire — is exactly what we'll write in Java -[next lesson](#/lesson/29-interfaces-in-code). The diagram *is* the pattern; -the code just spells it out. +Now try to break it: drag out a plain **number** block and wire it into `declare` instead. The wire connects, but it turns dashed with a red **✕** on it because `declare` can tell this isn't a real `MotorIO`. Click **Run step by step** anyway and the result comes back `error`. A wire is not the same thing as a valid answer. + +In Python, writing `io: MotorIO = 42` causes the exact same kind of mismatch: a type checker flags the broken contract immediately, and calling `io.get_speed()` at runtime crashes because a plain number never promised to act like a motor. Reconnect a real implementation, confirm the result comes back clean, then swap which implementation feeds `declare` and watch the result change to match. + +Everything you just built by hand, a contract, two things that fulfill it, and a slot that expects something matching the contract, is what we'll write in Python [next lesson](#/lesson/29-interfaces-in-code). The diagram *is* the pattern. The code just spells it out. diff --git a/lessons/29-interfaces-in-code/README.md b/lessons/29-interfaces-in-code/README.md index 2fcccea..6af72c0 100644 --- a/lessons/29-interfaces-in-code/README.md +++ b/lessons/29-interfaces-in-code/README.md @@ -1,137 +1,100 @@ --- title: "Interfaces, in code" -goal: "Write an interface as a contract with no body, implement it two ways, and see one method work unchanged against either implementation." +goal: "Write a Protocol as a contract with no body, implement it two ways, and see one function work unchanged against either implementation." order: 290 -section: "Advanced Java" +section: "Advanced Python" --- # A contract with no body -[Last lesson](#/lesson/28-interfaces-as-diagrams) you dragged a contract and -two implementations around by hand. In Java, the contract is an -**`interface`** — it lists a method's name and return type, but never says -*how*: +[Last lesson](#/lesson/28-interfaces-as-diagrams) you dragged a contract and two implementations around by hand. In Python, you write that contract with **`Protocol`** from the `typing` module. It lists a method's name, parameters, and return type, without saying *how* it works: -```java -interface MotorIO { - double getSpeed(); -} +```python +from typing import Protocol -public class Main { - public static void main(String[] args) { - } -} + +class MotorIO(Protocol): + def get_speed(self) -> float: ... ``` -(Nothing to run yet — an interface alone has no behavior. `main` is here -empty on purpose; the first real output shows up once something -`implements` it, below.) +Nothing prints when you run this, because a protocol alone has no behavior. The first real output shows up once a class satisfies it below. -That's it — no `{ }` body on `getSpeed()`, just a signature ending in a -semicolon, like a method header from [lesson {n}](#/lesson/11-writing-methods) -with the body torn off. `MotorIO` is a promise: "whatever `implements` me can -answer `getSpeed()`" — nothing about *how* it answers. +Notice the `...` (three dots) in place of a method body. Like a function header from [lesson {n}](#/lesson/11-writing-methods) with the body torn off, `MotorIO` is purely a promise: "whatever matches me has a `get_speed()` method that returns a `float`." It says nothing about *how* that speed is measured. # Two things that keep the promise -A class **implements** an interface with the `implements` keyword, and then -*must* provide a body for every method the interface listed: - -```java -interface MotorIO { - double getSpeed(); -} - -class MotorIOSim implements MotorIO { - public double getSpeed() { - System.out.println("SIM: getSpeed()"); - return 0.4; - } -} - -class MotorIOReal implements MotorIO { - public double getSpeed() { - System.out.println("REAL: getSpeed()"); - return 0.55; - } -} - -public class Main { - public static void main(String[] args) { - MotorIO io = new MotorIOSim(); - System.out.println(io.getSpeed()); - } -} +In Python, a class satisfies a `Protocol` simply by having methods with the right names and types. You don't even need a special `implements` keyword. Here are two classes that both keep `MotorIO`'s promise, `SimMotorIO` and `RealMotorIO`: + +```python +from typing import Protocol + + +class MotorIO(Protocol): + def get_speed(self) -> float: ... + + +class SimMotorIO: + def get_speed(self) -> float: + print("SIM: get_speed()") + return 0.4 + + +class RealMotorIO: + def get_speed(self) -> float: + print("REAL: get_speed()") + return 0.55 + + +io: MotorIO = SimMotorIO() +print(io.get_speed()) ``` -Run it — you'll see `SIM: getSpeed()` printed by the method itself, then -`0.4` printed by `main`. Now change `new MotorIOSim()` to `new MotorIOReal()` -and run again: same variable type, same `io.getSpeed()` call, completely -different implementation running underneath. `MotorIO io = ...` is the key -line — `io`'s **type** is the interface, so anything implementing `MotorIO` -can be stored in it and called through it, exactly the declare block from -last lesson. +Run it. You'll see `SIM: get_speed()` printed by the method itself, then `0.4` printed below it. Now change `SimMotorIO()` to `RealMotorIO()` and run again: same type annotation, same `io.get_speed()` call, completely different implementation running underneath. + +`io: MotorIO = ...` is the key line. It declares that `io` must satisfy `MotorIO`, so anything with a matching `get_speed` method fits right in, just like the `declare` block from last lesson. # The pattern real robot code uses -An interface isn't limited to one method — add a second, `setSpeed`, and -every implementation has to answer for both. Watch what happens when a method -also takes the *interface* as its parameter type, not a specific class: - -```java -interface MotorIO { - double getSpeed(); - void setSpeed(double target); -} - -class MotorIOSim implements MotorIO { - public double getSpeed() { - System.out.println("SIM: getSpeed()"); - return 0.4; - } - - public void setSpeed(double target) { - System.out.println("SIM: setSpeed(" + target + ")"); - } -} - -class MotorIOReal implements MotorIO { - public double getSpeed() { - System.out.println("REAL: getSpeed()"); - return 0.55; - } - - public void setSpeed(double target) { - System.out.println("REAL: setSpeed(" + target + ")"); - } -} - -public class Main { - static void report(MotorIO io) { - io.setSpeed(0.8); - System.out.println("current speed: " + io.getSpeed()); - } - - public static void main(String[] args) { - report(new MotorIOSim()); - report(new MotorIOReal()); - } -} +A `Protocol` isn't limited to one method. Add a second, `set_speed`, and every implementation must answer for both. Watch what happens when a function takes the *protocol* as its parameter type instead of a specific class: + +```python +from typing import Protocol + + +class MotorIO(Protocol): + def get_speed(self) -> float: ... + def set_speed(self, target: float) -> None: ... + + +class SimMotorIO: + def get_speed(self) -> float: + print("SIM: get_speed()") + return 0.4 + + def set_speed(self, target: float) -> None: + print(f"SIM: set_speed({target})") + + +class RealMotorIO: + def get_speed(self) -> float: + print("REAL: get_speed()") + return 0.55 + + def set_speed(self, target: float) -> None: + print(f"REAL: set_speed({target})") + + +def report(io: MotorIO) -> None: + io.set_speed(0.8) + print(f"current speed: {io.get_speed()}") + + +report(SimMotorIO()) +report(RealMotorIO()) ``` -`report` never mentions `MotorIOSim` or `MotorIOReal` by name — it only knows -about `MotorIO`. Run it: both calls print a `SIM:`/`REAL:` pair from inside -`setSpeed()` and `getSpeed()`, then `report`'s own line, unchanged either way. - -This is the **exact** pattern AdvantageKit uses for every subsystem: an -`XxxIO` interface plus an `XxxIOSim` and an `XxxIOReal`. The subsystem code — -the stuff that decides *when* to spin a motor or check its speed — is written -once against the interface, and never has to change depending on whether the -robot is a physical machine on the field or a simulation running on a -laptop. Swapping `new MotorIOSim()` for `new MotorIOReal()` in one place -(usually `RobotContainer`) is the only thing that changes. - -Your turn: add a third method to `MotorIO`, `boolean isStalled()`, and -implement it in both classes — `MotorIOSim` should always return `false`, -`MotorIOReal` should always return `true` (just to tell them apart). Call it -from `report` and print its result alongside the speed. +`report` never mentions `SimMotorIO` or `RealMotorIO` by name. It only knows about `MotorIO`. Run it: both calls print a `SIM:`/`REAL:` pair from inside `set_speed()` and `get_speed()`, then `report`'s own line, unchanged either way. + +This is the **exact** AdvantageKit IO pattern used in FRC subsystems: an `XxxIO` contract plus a `SimXxxIO` and a `RealXxxIO`. The subsystem code that decides *when* to spin a motor or check its speed is written once against the protocol, and never has to change depending on whether the robot is physical hardware on the field or a simulation running on a laptop. Swapping `SimMotorIO()` for `RealMotorIO()` in one place (usually `RobotContainer`) is the only thing that changes. + +Your turn: add a third method to `MotorIO`, `def is_stalled(self) -> bool: ...`, and implement it in both classes. `SimMotorIO` should return `False`, and `RealMotorIO` should return `True` just to tell them apart. Call it from `report` and print its result alongside the speed. diff --git a/lessons/30-encapsulation-revisited/README.md b/lessons/30-encapsulation-revisited/README.md index 0a4bc60..926ae15 100644 --- a/lessons/30-encapsulation-revisited/README.md +++ b/lessons/30-encapsulation-revisited/README.md @@ -1,86 +1,55 @@ --- title: "Encapsulation, revisited" -goal: "Add the default (package-private) access level to private and public, and see how a real robot project uses all three." +goal: "Use leading-underscore conventions and @property for read-only attributes so every class has a clear public contract." order: 300 -section: "Advanced Java" +section: "Advanced Python" --- -# A third option: no modifier at all - -[Lesson {n}](#/lesson/19-encapsulation) gave you two access levels: `private` -(only this class can see it) and `public` (anything can see it). There's a -third, and you've actually been writing it by accident — leave the modifier -off entirely, and you get **default** access, also called **package-private**: -visible to any class in the same **package**, invisible to everything outside -it. - -A real robot project isn't one file — it's dozens, organized into packages -like `frc.robot.subsystems` and `frc.robot.commands`, one folder per package. -`public` means "any package can use this." `private` means "not even other -classes in my own file." Package-private sits in between: "anything in my -own folder can use this, but nothing outside it." - -```java -interface MotorIO { - double getSpeed(); - void setSpeed(double target); -} - -class MotorIOSim implements MotorIO { - private double speed; - - double clampSpeed(double value) { - if (value > 1.0) return 1.0; - if (value < -1.0) return -1.0; - return value; - } - - public double getSpeed() { - return this.speed; - } - - public void setSpeed(double target) { - this.speed = clampSpeed(target); - } -} - -public class Main { - public static void main(String[] args) { - MotorIOSim sim = new MotorIOSim(); - sim.setSpeed(1.5); - System.out.println(sim.getSpeed()); - } -} +# Leading underscores and @property + +[Lesson {n}](#/lesson/19-encapsulation) showed why outside code shouldn't reach straight into an object's internal state. Unlike languages with a `private` keyword that locks fields at compile time, Python relies on two clean tools: **leading underscores** for internals, and **`@property`** for controlled, read-only access. + +A single leading underscore, like `_speed` or `_clamp_speed`, tells every other programmer (and your editor): "this is internal bookkeeping for this class, don't reach in and touch it." Meanwhile, `@property` lets callers read `sim.speed` like a normal attribute without letting them overwrite it directly: + +```python +class SimMotorIO: + def __init__(self) -> None: + self._speed = 0.0 + + def _clamp_speed(self, value: float) -> float: + if value > 1.0: + return 1.0 + if value < -1.0: + return -1.0 + return value + + @property + def speed(self) -> float: + return self._speed + + def set_speed(self, target: float) -> None: + self._speed = self._clamp_speed(target) + + +sim = SimMotorIO() +sim.set_speed(1.5) +print(sim.speed) ``` -`clampSpeed` has **no modifier** — that's package-private. Run it: `setSpeed` -still calls `clampSpeed` just fine, because they're in the same class (and -therefore certainly the same package). The site's playground compiles -everything as one file, so there's no *other* package here to actually be -kept out — but picture `clampSpeed` living in `frc.robot.subsystems` -alongside a few other motor-wrapper classes that also need to clamp a speed: -they could all share it, while a class over in `frc.robot.commands` — a -different package — couldn't call it even by accident. That's the whole -point of package-private: a helper meant for "the other classes right next -to me," not the entire codebase. - -# Choosing a level for every member - -Every field or method you write is really a decision among three doors: - -- **`private`** — only this class. The default choice for fields - ([lesson {n}](#/lesson/19-encapsulation)). -- **(no modifier)** — this class, plus anything else in the same package. Use - it for helpers that other closely-related classes legitimately need, but - that have no business being called from anywhere else in the robot. -- **`public`** — anyone. Reserve it for the small set of actions or values - outside code genuinely needs — `getSpeed()`, `setSpeed()`, not - `clampSpeed()`. - -Your turn: go back to [lesson {n}'s](#/lesson/23-organizing-a-machine) -`GamePieceHandler`. Make its `state` field `private` with a public -`getState()` method, keep `update(String event)` `public` (outside code needs -to drive it), and add a package-private helper method, -`boolean isSafeToShoot()`, that returns `true` only when `state` is `LOADED` -— a check another class in the same package (say, a shooter-arming routine) -could call, but nothing outside it should. +Run it. `set_speed(1.5)` clamps the value through `_clamp_speed` and stores `1.0` in `_speed`. Then `print(sim.speed)` runs the `@property` method behind the scenes and hands back `1.0`. + +Now try adding `sim.speed = 999.0` at the bottom and running again. Python raises `AttributeError: property 'speed' of 'SimMotorIO' object has no setter`. Because `speed` has a `@property` without a setter, it is **read-only**. Callers can inspect the speed cleanly with `sim.speed`, but the only legal way to change it is through `set_speed()`, where clamping is guaranteed. + +# Clear contracts over locked doors + +You might notice that Python wouldn't physically stop someone from writing `sim._speed = 999.0`. Python's philosophy is often summed up as "we're all consenting adults here." Encapsulation isn't about building a vault to fight off hackers; it's about drawing a **clear contract** between a class and the rest of the robot code. + +When you write a class in Python, every attribute or method falls into one of three buckets: + +- **Public methods and `@property` attributes** (`speed`, `set_speed`). This is the contract outside code depends on. Keep it small and predictable. +- **Read-only `@property`** (`@property def speed`). Use it when outside code needs to *read* a value, or a computed value like `is_at_speed`, without being able to assign to it directly. +- **Leading underscore (`_name`)** (`_speed`, `_clamp_speed`). Internal state and helper methods. Anything with a leading underscore is free to be renamed or rewritten later without breaking other files, because no outside code should be calling it. + +Clear boundaries make a big robot codebase much easier to change. If `SimMotorIO` changes how it clamps or stores `_speed` next week, nothing in the commands or subsystems breaks as long as `speed` and `set_speed()` keep their promise. + +Your turn: go back to [lesson {n}'s](#/lesson/23-organizing-a-machine) `GamePieceHandler`. Store its state in `self._state`, expose a read-only `@property` named `state`, keep `update(self, event: str)` public, and add an internal helper method `_is_safe_to_shoot(self) -> bool` that returns `True` only when `self._state == HandlerState.LOADED`. diff --git a/lessons/31-lambdas/README.md b/lessons/31-lambdas/README.md index e6ba9a0..d95a79a 100644 --- a/lessons/31-lambdas/README.md +++ b/lessons/31-lambdas/README.md @@ -1,177 +1,126 @@ --- title: "Lambdas" -goal: "Write a lambda that hands back a value, then one that just does something, and pass either into a method as a parameter." +goal: "Write one-line lambda functions, pass functions as key arguments and callbacks, and know when to use def instead." order: 310 -section: "Advanced Java" +section: "Advanced Python" --- -# A lambda that returns something +# A lambda: a one-line function -A **lambda** is a tiny, unnamed chunk of behavior you can store in a -variable. Here's the simplest one — it just answers a yes/no question: +A **`lambda`** is a tiny, unnamed function you can write inline on a single line. Here is the simplest kind, one that answers a yes/no question: -```java -interface Check { - boolean isReady(); -} - -public class Main { - public static void main(String[] args) { - Check ready = () -> true; - System.out.println(ready.isReady()); - } -} +```python +ready = lambda: True +print(ready()) ``` -Run it — `true` prints. Read `() -> true` as *"takes no arguments, returns -`true`"*: the `()` is `isReady()`'s empty parameter list, `->` separates "the -inputs" from "what happens," and `true` is what gets returned. Don't worry -yet about *why* `Check` has to exist — for now, just read `Check ready = () -> true;` -as "make a thing called `ready` whose answer is always `true`." - -The part after `->` is a real expression, evaluated fresh every time it's -called, not just a fixed value: - -```java -interface Check { - boolean isReady(); -} - -public class Main { - public static void main(String[] args) { - Check ready = () -> true; - Check notReady = () -> false; - Check bigEnough = () -> 12 > 10; - - System.out.println(ready.isReady()); - System.out.println(notReady.isReady()); - System.out.println(bigEnough.isReady()); - } -} +Run it and `True` prints. Read `lambda: True` as *"takes no arguments, returns `True`"*. The part before the colon lists the parameters (empty here), and the expression after the colon is what gets returned. No `return` keyword is needed. + +The expression after the colon runs fresh every time you call the lambda, and lambdas can take parameters just like a normal function: + +```python +ready = lambda: True +not_ready = lambda: False +fast_enough = lambda rpm: rpm >= 4500.0 + +print(ready()) +print(not_ready()) +print(fast_enough(4800.0)) +print(fast_enough(2000.0)) ``` -Run it — `true`, `false`, `true`. Three completely different lambdas, each -answering `isReady()` its own way. +Run it: `True`, `False`, `True`, `False`. -# Runnable: a lambda that just does something +In practice, you rarely assign a `lambda` to a variable name like `fast_enough = ...` in real Python code. If a function deserves a name, `def` is cleaner and easier to debug. Lambdas exist for the places where you want to pass a tiny throwaway function directly into *another* function. -A lambda doesn't have to answer a question — sometimes you just want it to -**do** something. Java ships a ready-made type for exactly that, called -`Runnable`, with one method, `run()`, that takes nothing and returns nothing. -You don't have to declare it yourself — it's already part of Java: +# Passing functions as arguments: key=... -```java -public class Main { - public static void main(String[] args) { - Runnable sayHi = () -> System.out.println("intake spinning"); - sayHi.run(); - } -} +In Python, functions are ordinary values, just like numbers or strings. That means you can pass a function into another function as an argument. + +One of the most common places you'll see this is sorting with `key=`. Suppose you have a list of robot motors as `(name, rpm)` tuples and want to sort them by RPM instead of alphabetically by name: + +```python +motors = [("intake", 1200), ("shooter", 4800), ("climber", 600)] + +by_rpm = sorted(motors, key=lambda motor: motor[1]) +print(by_rpm) ``` -Run it — the message prints. `sayHi` is a lambda implementing `Runnable`, -the exact same way `ready` above was a lambda implementing `Check` — the only -difference is `Runnable` came from Java itself instead of a line you wrote. -More examples, same shape: - -```java -public class Main { - public static void main(String[] args) { - Runnable spinIntake = () -> System.out.println("intake spinning"); - Runnable spinShooter = () -> System.out.println("shooter spinning"); - - spinIntake.run(); - spinShooter.run(); - spinIntake.run(); - } -} +Run it. `sorted()` calls your lambda once for each item in `motors`, gets back `motor[1]` (the RPM), and sorts the list by those numbers. Without `lambda`, you'd have to write a separate `def get_rpm(motor): ...` just to use it once. + +The same `key=` pattern works with `min()` and `max()`, and you can pass a regular `def` function whenever the logic is clearer with a name: + +```python +motors = [ + {"name": "intake", "rpm": 1200}, + {"name": "shooter", "rpm": 4800}, + {"name": "climber", "rpm": 600}, +] + +fastest = max(motors, key=lambda motor: motor["rpm"]) +print(fastest["name"], fastest["rpm"]) ``` -Run it — each `.run()` prints whatever that particular lambda says, in -whatever order you call them. - -# Passing a lambda into a method - -Since a lambda is just a value like any other, you can hand one to a method -as a parameter — which means you're handing over **behavior**, not just a -number or a `String`: - -```java -interface Check { - boolean isReady(); -} - -public class Main { - static void checkSensor(Check sensor) { - if (sensor.isReady()) { - System.out.println("piece detected!"); - } else { - System.out.println("nothing there"); - } - } - - public static void main(String[] args) { - checkSensor(() -> true); - checkSensor(() -> false); - checkSensor(() -> 12 > 10); - } -} +Run it and `shooter 4800` prints. `max()` doesn't know what a motor dictionary looks like; your lambda tells it which number to compare. + +# Callbacks: handing behavior to another function + +You can write your own functions that accept other functions as parameters, often called **callbacks**. Instead of handing a function a number or a string, you hand it *behavior*: + +```python +from collections.abc import Callable + + +def check_sensor(sensor: Callable[[], bool]) -> None: + if sensor(): + print("piece detected!") + else: + print("nothing there") + + +check_sensor(lambda: True) +check_sensor(lambda: False) +check_sensor(lambda: 12 > 10) ``` -`checkSensor` doesn't know or care *how* its `sensor` decides — it just calls -`.isReady()` once and reacts to whatever comes back ([lesson {n}'s](#/lesson/09-if-statements) -`if`, doing exactly what it always does). Three calls, three different -lambdas, and `checkSensor` itself never changes. A method can take a -`Runnable` the same way: - -```java -public class Main { - static void doTwice(Runnable action) { - action.run(); - action.run(); - } - - public static void main(String[] args) { - doTwice(() -> System.out.println("intake spinning")); - doTwice(() -> System.out.println("shooter spinning")); - } -} +`Callable[[], bool]` is the type hint for "a function that takes no arguments and returns a `bool`." `check_sensor` doesn't know or care *how* `sensor` decides. It just calls `sensor()` once and reacts with the `if` from [lesson {n}](#/lesson/09-if-statements). + +A function can also take a callback that just *does* something, returning `None`: + +```python +from collections.abc import Callable + + +def do_twice(action: Callable[[], None]) -> None: + action() + action() + + +do_twice(lambda: print("intake spinning")) +do_twice(lambda: print("shooter spinning")) ``` -Run it — each lambda's line prints twice. `doTwice` doesn't know what its -`action` actually does, only that it can `.run()` it. - -One more, combining both ideas: - -```java -interface Check { - boolean isReady(); -} - -public class Main { - static void runIfReady(Check ready, Runnable action) { - if (ready.isReady()) { - action.run(); - } else { - System.out.println("not ready yet"); - } - } - - public static void main(String[] args) { - runIfReady(() -> true, () -> System.out.println("fire!")); - runIfReady(() -> false, () -> System.out.println("fire!")); - } -} +Run it, and each line prints twice. `do_twice` doesn't know what `action` does, only that it can call `action()`. + +Now combine both ideas, a condition callback and an action callback: + +```python +from collections.abc import Callable + + +def run_if_ready(ready: Callable[[], bool], action: Callable[[], None]) -> None: + if ready(): + action() + else: + print("not ready yet") + + +run_if_ready(lambda: True, lambda: print("fire!")) +run_if_ready(lambda: False, lambda: print("fire!")) ``` -Run it: the first call is ready, so `action` runs and prints `fire!`; the -second isn't, so `action` never runs at all — the exact same lambda, simply -never called. This is the same shape WPILib's `Trigger` and -`Commands.run(() -> ...)` use under the hood: a lambda standing in for "the -thing to check" or "the thing to do," handed to code that doesn't need to -know any more about it than that. - -Your turn: write a method `describe(Check c)` that prints `"ready"` or -`"not ready"` depending on `c.isReady()`. Call it three times with three -different lambdas — one always `true`, one always `false`, and one that -computes its answer from a comparison you make up (like `7 > 3`). +Run it. The first call is ready, so `action()` runs and prints `fire!`. The second isn't, so `action` never runs at all. This is the exact shape WPILib's `Trigger` and `cmd.run(lambda: ...)` use in FRC robot code: a short lambda standing in for "the thing to check" or "the thing to do," handed to code that decides *when* to run it. + +One rule of thumb: reach for `lambda` when the body is a single short expression. The moment it needs two steps, an `if` statement, or a descriptive name, write a regular `def` function and pass its name (without parentheses) as the callback instead. + +Your turn: write a function `describe(check: Callable[[], bool]) -> None` that prints `"ready"` or `"not ready"` depending on `check()`. Call it three times with three different lambdas: one always `True`, one always `False`, and one that computes its answer from a comparison you make up (like `7 > 3`). diff --git a/lessons/32-builder-pattern-as-diagrams/README.md b/lessons/32-builder-pattern-as-diagrams/README.md index ed76283..5ac0991 100644 --- a/lessons/32-builder-pattern-as-diagrams/README.md +++ b/lessons/32-builder-pattern-as-diagrams/README.md @@ -2,16 +2,16 @@ title: "The builder pattern, as diagrams" goal: "See a configuration accumulate one field at a time through a chain of steps, before writing a line of code." order: 320 -section: "Advanced Java" +section: "Advanced Python" --- # Building a config, one step at a time -A real motor needs a pile of settings — a max speed, a current limit, and -more — decided once, up front. Instead of one block that takes every setting -at once, here's a different shape: a **chain**. Each block adds exactly one -setting to whatever configuration flowed in, then passes the whole thing -along to the next block. +A real motor needs a pile of settings, like a max speed, a current limit, and +more, decided once up front. Instead of one block that takes every setting at +once, here's a different shape: a **chain**. Each block adds exactly one +setting to whatever configuration flowed in, then passes the whole thing along +to the next block. ```blocks preset: builder-demo @@ -19,24 +19,23 @@ preset: builder-demo Run it step by step and watch the **result** grow: empty config, then `{ maxSpeed: 80 }`, then `{ maxSpeed: 80, currentLimit: 40 }`. Nothing gets -overwritten — every step keeps everything the steps before it set, and adds -its own field on top. +overwritten. Every step keeps everything the steps before it set, and adds its +own field on top. # Edit the chain Change the numbers on each step and re-run. Notice the *shape* of the chain -never changes — configStart, then step, then step, then result — only the -values flowing through it do. +never changes. It always goes configStart, then step, then step, then result. +Only the values flowing through it change. ```blocks preset: builder-edit ``` -This is the whole idea of the builder pattern: instead of one giant block -(or one giant constructor call) that takes every setting as a pile of -arguments in a fixed order, you get a **chain of small, named steps**, each -responsible for exactly one setting, that reads top to bottom like a -sentence. +This is the whole idea of the builder pattern. Instead of one giant block (or +one giant constructor call) that takes every setting as a pile of arguments in +a fixed order, you get a **chain of small, named steps**, each responsible for +exactly one setting, that reads top to bottom like a sentence. # Build one yourself @@ -47,12 +46,12 @@ steps of your choice, and connect the last one to the **result**. preset: builder-build ``` -Try wiring the steps in a different order than you first thought of them — -confirm the final config comes out the same regardless of which order you +Try wiring the steps in a different order than you first thought of them. +Confirm the final config comes out the same regardless of which order you chained them in, as long as each field is only set once. Then run it step by step and watch the result accumulate one field at a time. -Everything you just built here — a chain of small steps, each adding one -setting and handing the rest along — is exactly what we'll write in Java +Everything you just built here, a chain of small steps where each adds one +setting and hands the rest along, is exactly what we'll write in Python in the [next lesson](#/lesson/33-builder-pattern-in-code). The diagram *is* the pattern; the code just spells it out. diff --git a/lessons/33-builder-pattern-in-code/README.md b/lessons/33-builder-pattern-in-code/README.md index f4d0750..b1baf67 100644 --- a/lessons/33-builder-pattern-in-code/README.md +++ b/lessons/33-builder-pattern-in-code/README.md @@ -1,104 +1,105 @@ --- title: "The builder pattern, in code" -goal: "Write a chain of fluent setters that each return this, in the exact shape PhoenixLib uses to configure a motor." +goal: "Write a chain of fluent setters that each return self, in the exact shape PhoenixLib uses to configure a motor." order: 330 -section: "Advanced Java" +section: "Advanced Python" --- # The problem with plain setters -A motor controller needs several settings at once — a max speed, a current -limit, a gear ratio. A `void` setter, one per line, works, but it's clunky: - -```java -class MotorConfig { - double maxSpeed; - double currentLimit; - - void withMaxSpeed(double value) { - this.maxSpeed = value; - } - - void withCurrentLimit(double value) { - this.currentLimit = value; - } -} - -public class Main { - public static void main(String[] args) { - MotorConfig config = new MotorConfig(); - config.withMaxSpeed(80); - config.withCurrentLimit(40); - System.out.println(config.maxSpeed + " " + config.currentLimit); - } -} +A motor controller needs several settings at once: a max speed, a current +limit, a gear ratio. A plain setter that returns `None`, called one per line, +works, but it's clunky: + +```python +class MotorConfig: + def __init__(self) -> None: + self.max_speed = 0.0 + self.current_limit = 0.0 + + def with_max_speed(self, value: float) -> None: + self.max_speed = value + + def with_current_limit(self, value: float) -> None: + self.current_limit = value + + +config = MotorConfig() +config.with_max_speed(80) +config.with_current_limit(40) +print(config.max_speed, config.current_limit) ``` -Run it — it works, but every setting is its own statement, repeating -`config.` each time. [Last lesson's](#/lesson/32-builder-pattern-as-diagrams) -diagram chained steps together instead. Here's how to make that legal Java. - -# Setters that return this - -The fix is one word: instead of `void`, a setter returns **`this`** — *the -object it was just called on* ([lesson {n}](#/lesson/17-classes-and-objects)). -That lets you call the *next* method directly on what the last one handed -back: - -```java -class MotorConfig { - private double maxSpeed; - private double currentLimit; - private double gearRatio; - - MotorConfig withMaxSpeed(double value) { - this.maxSpeed = value; - return this; - } - - MotorConfig withCurrentLimit(double value) { - this.currentLimit = value; - return this; - } - - MotorConfig withGearRatio(double value) { - this.gearRatio = value; - return this; - } - - void report() { - System.out.println("maxSpeed=" + maxSpeed + " currentLimit=" + currentLimit + " gearRatio=" + gearRatio); - } -} - -public class Main { - public static void main(String[] args) { - MotorConfig config = new MotorConfig() - .withMaxSpeed(80) - .withCurrentLimit(40) - .withGearRatio(4); - config.report(); - } -} +Run it. It works, but every setting is its own statement, repeating `config.` +each time. [Last lesson's](#/lesson/32-builder-pattern-as-diagrams) diagram +chained steps together instead. Here's how to make that valid Python. + +# Setters that return self + +The fix is one line: instead of returning `None`, each setter returns +**`self`**, *the object it was just called on* +([lesson {n}](#/lesson/17-classes-and-objects)). That lets you call the *next* +method directly on what the last one handed back: + +```python +from __future__ import annotations + + +class MotorConfig: + def __init__(self) -> None: + self._max_speed = 0.0 + self._current_limit = 0.0 + self._gear_ratio = 1.0 + + def with_max_speed(self, value: float) -> MotorConfig: + self._max_speed = value + return self + + def with_current_limit(self, value: float) -> MotorConfig: + self._current_limit = value + return self + + def with_gear_ratio(self, value: float) -> MotorConfig: + self._gear_ratio = value + return self + + def report(self) -> None: + print( + f"max_speed={self._max_speed} " + f"current_limit={self._current_limit} " + f"gear_ratio={self._gear_ratio}" + ) + + +config = ( + MotorConfig() + .with_max_speed(80) + .with_current_limit(40) + .with_gear_ratio(4) +) +config.report() ``` -Run it — all three settings land in one chained expression. Read -`new MotorConfig().withMaxSpeed(80)` as "build a config, then call -`withMaxSpeed` on it" — and because `withMaxSpeed` **returns that very -object**, `.withCurrentLimit(40)` can be called directly on whatever it just -returned, and so on. The fields stay `private` ([lesson {n}](#/lesson/19-encapsulation)) -— nothing outside `MotorConfig` ever touches `maxSpeed` directly, only -through a `with*` method that sets it on purpose. +Run it, and all three settings land in one chained expression. The outer +parentheses let Python split one chained expression across multiple lines. Read +`MotorConfig().with_max_speed(80)` as "build a config, then call +`with_max_speed` on it." Because `with_max_speed` **returns that very object**, +`.with_current_limit(40)` can be called directly on whatever it just returned, +and so on. The fields stay internal with a leading underscore +([lesson {n}](#/lesson/19-encapsulation)), so nothing outside `MotorConfig` +touches `_max_speed` directly, only through a `with_*` method that sets it on +purpose. This is the **exact** pattern PhoenixLib uses to configure a real motor -controller — a chain of `.with...(...)` calls, each setting one thing and -handing back the same config object so the next call can land right on top -of it. Real motor configs aren't just speed and current limit — they cover -dozens of settings — but every one of them is set the same way: one -`with*` method, one field, `return this;`. - -Your turn: go back to your capstone mechanism from [lesson {n}](#/lesson/25-capstone-state-machine). -Write a fluent config class for it with at least three `with*` methods (pick -settings that make sense for your mechanism — a max height, a hold current, a -speed, whatever fits) and a `report()` method. Build one with a chained call -and confirm `report()` prints all three values you set. +controller: a chain of `.with_...(...)` calls, each setting one thing and +handing back the same config object so the next call lands right on top of it. +Real motor configs cover dozens of settings, not just speed and current limit, +but every one of them works the same way: one `with_*` method, one field, +`return self`. + +Your turn: go back to your capstone mechanism from +[lesson {n}](#/lesson/25-capstone-state-machine). Write a fluent config class +for it with at least three `with_*` methods (pick settings that make sense for +your mechanism, like a max height, a hold current, or a speed) and a `report()` +method. Build one with a chained call and confirm `report()` prints all three +values you set. diff --git a/lessons/34-capstone-2/README.md b/lessons/34-capstone-2/README.md index 8e3a486..7ff34c2 100644 --- a/lessons/34-capstone-2/README.md +++ b/lessons/34-capstone-2/README.md @@ -1,333 +1,348 @@ --- -title: "Capstone 2 — an advanced mechanism" -goal: "Return to your Capstone 1 mechanism and upgrade it with enums with fields, switch, interfaces, access modifiers, and the builder pattern — so it runs identically in simulation and on real hardware." +title: "Capstone 2: an advanced mechanism" +goal: "Return to your Capstone 1 mechanism and upgrade it with enums with fields, match, Protocol interfaces, @property, lambdas, and the builder pattern so it runs identically in simulation and on real hardware." order: 340 -section: "Advanced Java" +section: "Advanced Python" --- # Picking up where Capstone 1 left off [Capstone 1](#/lesson/25-capstone-state-machine) ended with you designing and -coding a real mechanism of your own — not `Climber`, something from this +coding a real mechanism of your own, not `Climber`, but something from this year's robot. Go find that file now and open it next to this lesson. Everything below walks through upgrading `Climber` with every tool from this -Advanced Java section, one piece at a time. Your job is to make the same -upgrade to **your own mechanism** right alongside it — don't wait until the -end. When a page adds a field to `ClimberState`, add one to your enum. When a -page gives `Climber` an interface, give yours one too. By the last page, +Advanced Python section, one piece at a time. Your job is to make the same +upgrade to **your own mechanism** right alongside it. Don't wait until the end. +When a page adds a field to `ClimberState`, add one to your enum. When a page +gives `Climber` a `Protocol` interface, give yours one too. By the last page, `Climber` and your mechanism should have grown up together. Start with [lesson {n}'s](#/lesson/27-enums-revisited) trick, applied to the states from Capstone 1: give every state its own motor speed, right on the -enum. - -```java -enum ClimberState { - STOWED(0.0), - EXTENDING(0.6), - EXTENDED(0.0), - RETRACTING(-0.6); - - final double motorSpeed; - - ClimberState(double motorSpeed) { - this.motorSpeed = motorSpeed; - } -} - -public class Main { - public static void main(String[] args) { - for (ClimberState state : ClimberState.values()) { - System.out.println(state + " -> " + state.motorSpeed); - } - } -} +enum. Each member starts with a unique label so `STOWED` and `EXTENDED` stay +distinct states even though both use a speed of `0.0`: + +```python +from enum import Enum + + +class ClimberState(Enum): + STOWED = ("stowed", 0.0) + EXTENDING = ("extending", 0.6) + EXTENDED = ("extended", 0.0) + RETRACTING = ("retracting", -0.6) + + def __init__(self, label: str, motor_speed: float) -> None: + self.label = label + self.motor_speed = motor_speed + + +for state in ClimberState: + print(f"{state.name} -> {state.motor_speed}") ``` -Run it — the four states from Capstone 1 print out, each now carrying the -number the motor should run at while the climber is in that state. No new -behavior otherwise, just [lesson {n}'s](#/lesson/27-enums-revisited) trick -applied a second time. Go add a field to your own enum before moving on. +Run it. The four states from Capstone 1 print out, each now carrying the number +the motor should run at while the climber is in that state. No new behavior +otherwise, just [lesson {n}'s](#/lesson/27-enums-revisited) trick applied a +second time. Go add a field to your own enum before moving on. # Give it real and simulated hardware -Next, [lesson {n}'s](#/lesson/29-interfaces-in-code) pattern: a contract for -"whatever moves the actual motor," plus a `Sim` and a `Real` that both keep -it. - -```java -interface ClimberIO { - void setSpeed(double speed); -} - -class ClimberIOSim implements ClimberIO { - public void setSpeed(double speed) { - System.out.println("SIM: setSpeed(" + speed + ")"); - } -} - -class ClimberIOReal implements ClimberIO { - public void setSpeed(double speed) { - System.out.println("REAL: setSpeed(" + speed + ")"); - } -} - -public class Main { - public static void main(String[] args) { - ClimberIO io = new ClimberIOSim(); - io.setSpeed(0.6); - } -} +Next, [lesson {n}'s](#/lesson/29-interfaces-in-code) pattern: a `Protocol` +contract for "whatever moves the actual motor," plus a `Sim` and a `Real` class +that both keep it. + +```python +from typing import Protocol + + +class ClimberIO(Protocol): + def set_speed(self, speed: float) -> None: ... + + +class ClimberIOSim: + def set_speed(self, speed: float) -> None: + print(f"SIM: set_speed({speed})") + + +class ClimberIOReal: + def set_speed(self, speed: float) -> None: + print(f"REAL: set_speed({speed})") + + +io: ClimberIO = ClimberIOSim() +io.set_speed(0.6) ``` -Run it — `SIM: setSpeed(0.6)` prints. Neither implementation talks to actual -hardware — they're stand-ins, exactly like [lesson {n}](#/lesson/29-interfaces-in-code)'s `MotorIO`, so you can -see which one ran without needing a real motor controller plugged in. Write -the same `-IO` interface, plus `Sim` and `Real`, for your own mechanism now. +Run it, and `SIM: set_speed(0.6)` prints. Neither class talks to actual +hardware. They are stand-ins, exactly like +[lesson {n}'s](#/lesson/29-interfaces-in-code) `MotorIO`, so you can see which +one ran without needing a real motor controller plugged in. Write the same +`-IO` protocol, plus `Sim` and `Real`, for your own mechanism now. # Recap: the config builder Before combining everything, rebuild one more piece on its own: [lesson {n}'s](#/lesson/33-builder-pattern-in-code) fluent config, this time -guarding the climber's speed instead of a generic motor's. - -```java -class ClimberConfig { - private double maxSpeed; - - ClimberConfig withMaxSpeed(double value) { - this.maxSpeed = value; - return this; - } - - double clamp(double requested) { - if (requested > maxSpeed) return maxSpeed; - if (requested < -maxSpeed) return -maxSpeed; - return requested; - } -} - -public class Main { - public static void main(String[] args) { - ClimberConfig config = new ClimberConfig().withMaxSpeed(0.5); - System.out.println(config.clamp(0.6)); - System.out.println(config.clamp(-0.6)); - System.out.println(config.clamp(0.2)); - } -} +guarding the climber's speed instead of a generic motor's. We can also give it +a spot for an optional callback function, which is where a `lambda` will plug +in shortly. + +```python +from __future__ import annotations +from typing import Callable + + +class ClimberConfig: + def __init__(self) -> None: + self._max_speed = 1.0 + self._on_change: Callable[[str], None] | None = None + + def with_max_speed(self, value: float) -> ClimberConfig: + self._max_speed = value + return self + + def with_on_change(self, callback: Callable[[str], None]) -> ClimberConfig: + self._on_change = callback + return self + + @property + def on_change(self) -> Callable[[str], None] | None: + return self._on_change + + def clamp(self, requested: float) -> float: + if requested > self._max_speed: + return self._max_speed + if requested < -self._max_speed: + return -self._max_speed + return requested + + +config = ( + ClimberConfig() + .with_max_speed(0.5) + .with_on_change(lambda label: print(f"changed -> {label}")) +) +print(config.clamp(0.6)) +print(config.clamp(-0.6)) +print(config.clamp(0.2)) +if config.on_change is not None: + config.on_change("EXTENDING") ``` -Run it: `0.5`, `-0.5`, `0.2` — the first two get reined in to `maxSpeed`, -the third was already safely inside it and passes through untouched. -`private double maxSpeed` plus one `with*` method that returns `this` is the -whole builder — nothing new here, just the exact class from [lesson {n}](#/lesson/33-builder-pattern-in-code), -renamed for this mechanism. Keep this shape in mind; it's about to plug -straight into the next piece. - -# Put state, switch, and hardware together - -Now combine the pieces from the first two pages — the enum with a field, and -the `Sim`/`Real` hardware — into an actual state-machine class, using -[lesson {n}'s](#/lesson/26-decisions-in-code-revisited) `switch` for the -transitions and [lesson {n}'s](#/lesson/30-encapsulation-revisited) access -modifiers for the fields. No config yet — `update` hands the enum's speed -straight to `io`: - -```java -enum ClimberState { - STOWED(0.0), EXTENDING(0.6), EXTENDED(0.0), RETRACTING(-0.6); - - final double motorSpeed; - - ClimberState(double motorSpeed) { - this.motorSpeed = motorSpeed; - } -} - -interface ClimberIO { - void setSpeed(double speed); -} - -class ClimberIOSim implements ClimberIO { - public void setSpeed(double speed) { - System.out.println("SIM: setSpeed(" + speed + ")"); - } -} - -class Climber { - private ClimberState state; - private final ClimberIO io; - - Climber(ClimberIO io) { - this.io = io; - this.state = ClimberState.STOWED; - } - - ClimberState getState() { - return this.state; - } - - void update(String event) { - switch (state) { - case STOWED: - if (event.equals("button")) state = ClimberState.EXTENDING; - break; - case EXTENDING: - if (event.equals("at_top")) state = ClimberState.EXTENDED; - break; - case EXTENDED: - if (event.equals("button")) state = ClimberState.RETRACTING; - break; - case RETRACTING: - if (event.equals("at_bottom")) state = ClimberState.STOWED; - break; - default: - break; - } - io.setSpeed(state.motorSpeed); - } -} - -public class Main { - public static void main(String[] args) { - Climber climber = new Climber(new ClimberIOSim()); - climber.update("button"); - System.out.println(climber.getState()); - } -} +Run it: `0.5`, `-0.5`, `0.2`, followed by `changed -> EXTENDING`. The first two +speeds get reined in to `_max_speed`, while the third was already safely inside +it and passes through untouched. Internal fields plus `with_*` methods that +return `self` make up the whole builder, just like +[lesson {n}](#/lesson/33-builder-pattern-in-code), renamed for this mechanism. +Keep this shape in mind; it's about to plug straight into the next piece. + +# Put state, match, and hardware together + +Now combine the pieces from the first two pages, the enum with a field and the +`Sim`/`Real` hardware, into an actual state-machine class. Use +[lesson {n}'s](#/lesson/26-decisions-in-code-revisited) `match` for the +transitions and [lesson {n}'s](#/lesson/30-encapsulation-revisited) `@property` +to expose the state as read-only. No config yet, so `update` hands the enum's +speed straight to `io`: + +```python +from enum import Enum +from typing import Protocol + + +class ClimberState(Enum): + STOWED = ("stowed", 0.0) + EXTENDING = ("extending", 0.6) + EXTENDED = ("extended", 0.0) + RETRACTING = ("retracting", -0.6) + + def __init__(self, label: str, motor_speed: float) -> None: + self.label = label + self.motor_speed = motor_speed + + +class ClimberIO(Protocol): + def set_speed(self, speed: float) -> None: ... + + +class ClimberIOSim: + def set_speed(self, speed: float) -> None: + print(f"SIM: set_speed({speed})") + + +class Climber: + def __init__(self, io: ClimberIO) -> None: + self._io = io + self._state = ClimberState.STOWED + + @property + def state(self) -> ClimberState: + return self._state + + def update(self, event: str) -> None: + match self._state: + case ClimberState.STOWED: + if event == "button": + self._state = ClimberState.EXTENDING + case ClimberState.EXTENDING: + if event == "at_top": + self._state = ClimberState.EXTENDED + case ClimberState.EXTENDED: + if event == "button": + self._state = ClimberState.RETRACTING + case ClimberState.RETRACTING: + if event == "at_bottom": + self._state = ClimberState.STOWED + self._io.set_speed(self._state.motor_speed) + + +climber = Climber(ClimberIOSim()) +climber.update("button") +print(climber.state.name) ``` -Run it — `SIM: setSpeed(0.6)` prints, then `EXTENDING`. Read it back to where -each piece came from: `state` is `private` with a public `getState()` (30); -`update` dispatches with a `switch` (26); each state already knows its own -speed (27); that speed goes straight to whichever `ClimberIO` was built in -(29). Everything here is a piece you've already seen — this page just wires -them into one class. The only thing missing is the config from the last -page, guarding that speed before it reaches `io`. Bring your own mechanism's -`update` method up to the same shape before continuing. +Run it. `SIM: set_speed(0.6)` prints, then `EXTENDING`. Trace each piece back +to where it came from: `_state` is internal with a read-only `@property` (30), +`update` dispatches with `match` (26), each state knows its own speed (27), and +that speed goes straight to whichever `ClimberIO` was passed in (29). +Everything here is a piece you've already seen; this page just wires them into +one class. The only thing missing is the config from the last page, guarding +that speed before it reaches `io` and firing the callback when the state +changes. Bring your own mechanism's `update` method up to the same shape before +continuing. # Assemble the whole mechanism -One more piece: bring the `ClimberConfig` from two pages ago in, and clamp -the speed before it reaches `io`. - -```java -enum ClimberState { - STOWED(0.0), EXTENDING(0.6), EXTENDED(0.0), RETRACTING(-0.6); - - final double motorSpeed; - - ClimberState(double motorSpeed) { - this.motorSpeed = motorSpeed; - } -} - -interface ClimberIO { - void setSpeed(double speed); -} - -class ClimberIOSim implements ClimberIO { - public void setSpeed(double speed) { - System.out.println("SIM: setSpeed(" + speed + ")"); - } -} - -class ClimberIOReal implements ClimberIO { - public void setSpeed(double speed) { - System.out.println("REAL: setSpeed(" + speed + ")"); - } -} - -class ClimberConfig { - private double maxSpeed; - - ClimberConfig withMaxSpeed(double value) { - this.maxSpeed = value; - return this; - } - - double clamp(double requested) { - if (requested > maxSpeed) return maxSpeed; - if (requested < -maxSpeed) return -maxSpeed; - return requested; - } -} - -class Climber { - private ClimberState state; - private final ClimberIO io; - private final ClimberConfig config; - - Climber(ClimberIO io, ClimberConfig config) { - this.io = io; - this.config = config; - this.state = ClimberState.STOWED; - } - - ClimberState getState() { - return this.state; - } - - void update(String event) { - switch (state) { - case STOWED: - if (event.equals("button")) state = ClimberState.EXTENDING; - break; - case EXTENDING: - if (event.equals("at_top")) state = ClimberState.EXTENDED; - break; - case EXTENDED: - if (event.equals("button")) state = ClimberState.RETRACTING; - break; - case RETRACTING: - if (event.equals("at_bottom")) state = ClimberState.STOWED; - break; - default: - break; - } - io.setSpeed(config.clamp(state.motorSpeed)); - } -} - -public class Main { - public static void main(String[] args) { - ClimberConfig config = new ClimberConfig().withMaxSpeed(0.5); - Climber climber = new Climber(new ClimberIOSim(), config); - - String[] events = {"button", "at_top", "button", "at_bottom"}; - for (String event : events) { - climber.update(event); - System.out.println(climber.getState()); - } - } -} +One more piece: bring `ClimberConfig` in, clamp the speed before it reaches +`io`, and pass a `lambda` to log every state transition. + +```python +from __future__ import annotations +from enum import Enum +from typing import Callable, Protocol + + +class ClimberState(Enum): + STOWED = ("stowed", 0.0) + EXTENDING = ("extending", 0.6) + EXTENDED = ("extended", 0.0) + RETRACTING = ("retracting", -0.6) + + def __init__(self, label: str, motor_speed: float) -> None: + self.label = label + self.motor_speed = motor_speed + + +class ClimberIO(Protocol): + def set_speed(self, speed: float) -> None: ... + + +class ClimberIOSim: + def set_speed(self, speed: float) -> None: + print(f"SIM: set_speed({speed})") + + +class ClimberIOReal: + def set_speed(self, speed: float) -> None: + print(f"REAL: set_speed({speed})") + + +class ClimberConfig: + def __init__(self) -> None: + self._max_speed = 1.0 + self._on_change: Callable[[ClimberState], None] | None = None + + def with_max_speed(self, value: float) -> ClimberConfig: + self._max_speed = value + return self + + def with_on_change( + self, callback: Callable[[ClimberState], None] + ) -> ClimberConfig: + self._on_change = callback + return self + + @property + def on_change(self) -> Callable[[ClimberState], None] | None: + return self._on_change + + def clamp(self, requested: float) -> float: + if requested > self._max_speed: + return self._max_speed + if requested < -self._max_speed: + return -self._max_speed + return requested + + +class Climber: + def __init__(self, io: ClimberIO, config: ClimberConfig) -> None: + self._io = io + self._config = config + self._state = ClimberState.STOWED + + @property + def state(self) -> ClimberState: + return self._state + + def update(self, event: str) -> None: + previous = self._state + match self._state: + case ClimberState.STOWED: + if event == "button": + self._state = ClimberState.EXTENDING + case ClimberState.EXTENDING: + if event == "at_top": + self._state = ClimberState.EXTENDED + case ClimberState.EXTENDED: + if event == "button": + self._state = ClimberState.RETRACTING + case ClimberState.RETRACTING: + if event == "at_bottom": + self._state = ClimberState.STOWED + if self._state != previous and self._config.on_change is not None: + self._config.on_change(self._state) + self._io.set_speed(self._config.clamp(self._state.motor_speed)) + + +config = ( + ClimberConfig() + .with_max_speed(0.5) + .with_on_change(lambda state: print(f"transition -> {state.name}")) +) +climber = Climber(ClimberIOSim(), config) + +events = ["button", "at_top", "button", "at_bottom"] +for event in events: + climber.update(event) + print(climber.state.name) ``` -Run it. The only new line versus last page is `io.setSpeed(config.clamp(state.motorSpeed))` -instead of `io.setSpeed(state.motorSpeed)` — everything else is exactly what -you already built. Notice `EXTENDING`'s `0.6` comes out as `0.5` in the -printed `setSpeed` calls — `config.clamp(...)` is doing real work, not just -sitting there. - -Change `new ClimberIOSim()` to `new ClimberIOReal()` and run again: every -`state` printed is identical, and only the `SIM:`/`REAL:` label on each -`setSpeed` line changes. That's the entire payoff of the interface pattern — -the state machine itself never had to know which one it was talking to. - -**This is your Capstone 2.** Bring your own mechanism from Capstone 1 the -rest of the way to this exact shape: - -1. Give its enum a field for whatever number matters most (a speed, a - height rate, whatever fits). -2. Write an `-IO` interface for it, plus a `Sim` and a `Real` that print - `"SIM: ..."` / `"REAL: ..."`. -3. Make its state field `private` with a public getter, and dispatch its - transitions with a `switch`. -4. Build it through a fluent config with at least one `with*` setting. -5. Swap its `Sim` for a `Real` and confirm every state transition still - happens exactly the same way. +Run it. Notice two things versus the last page: `EXTENDING`'s `0.6` comes out +as `0.5` in the printed `set_speed` call because `config.clamp(...)` caps it, +and the `lambda` passed to `with_on_change` prints each transition as it +happens. + +Change `ClimberIOSim()` to `ClimberIOReal()` and run again. Every `state` +printed is identical, and only the `SIM:`/`REAL:` label on each `set_speed` +line changes. That's the entire payoff of the `Protocol` pattern: the state +machine itself never had to know which one it was talking to. + +**This is your Capstone 2.** Bring your own mechanism from Capstone 1 the rest +of the way to this exact shape: + +1. Give its `Enum` a field for whatever number matters most (a speed, a height + rate, whatever fits). +2. Write an `-IO` `Protocol` for it, plus `Sim` and `Real` classes that print + `"SIM: ..."` and `"REAL: ..."`. +3. Keep its `_state` field internal with a read-only `@property`, and dispatch + its transitions with `match`. +4. Build it through a fluent config with at least one `with_*` setting and a + `lambda` callback. +5. Swap `Sim` for `Real` and confirm every state transition still happens + exactly the same way. Do that, and the mechanism you designed back in Capstone 1 is now written in -the same shape — enum, interface, access modifiers, builder — as a real -subsystem in this year's robot. +the same shape (enum, protocol, property, lambda, and builder) as a real +subsystem in a modern robot codebase. diff --git a/lessons/35-a-star/README.md b/lessons/35-a-star/README.md index 905653d..c8cd202 100644 --- a/lessons/35-a-star/README.md +++ b/lessons/35-a-star/README.md @@ -1,29 +1,30 @@ --- title: "Finding the shortest path (A*)" -goal: "Meet A* — the algorithm that finds the shortest path, not just any path. Model the maze as a graph, score each step with cost-so-far plus a heuristic, drive a real PriorityQueue frontier, and watch your own A* beat the wall follower out of a freshly generated maze." +goal: "Use A* to find the shortest path through a maze by modeling it as a graph, scoring steps with cost-so-far plus a heuristic, and driving a heapq priority queue." order: 350 -section: "Advanced Java" +section: "Advanced Python" --- # When "it works" isn't good enough Back in the Algorithms section you wrote a **wall follower**: keep your right -hand on the wall, and you'll eventually stumble out of any maze. It works — but -watch it run and you'll see it do a lot of *wandering*. It ducks into dead ends, -backs out, hugs walls that lead nowhere, and only reaches the goal because it -refuses to give up. It finds *a* path. It does not find the *shortest* one. +hand on the wall, and you'll eventually stumble out of any maze. It works, but +watch it run and you'll see it do a lot of *wandering*. It ducks into dead +ends, backs out, hugs walls that lead nowhere, and only reaches the goal +because it refuses to give up. It finds *a* path. It does not find the +*shortest* one. For a robot on a field with a shot clock, the difference matters. "Reaches the -goal" and "reaches the goal in the fewest moves" are two different problems, and -the second one needs a smarter idea. +goal" and "reaches the goal in the fewest moves" are two different problems, +and the second one needs a smarter idea. That idea is **A\*** (say "A-star"), one of the most widely used pathfinding -algorithms there is — it's behind the routes in navigation apps and the enemies -in video games. The wall follower was *reactive*: it only ever looked at the one +algorithms in software. It powers routes in navigation apps and enemies in +video games. The wall follower was *reactive*: it only ever looked at the one cell it was standing in. A\* is a **planner**: it studies the whole map first, works out the shortest route from start to goal, and only then starts driving. -The core trick is simple to say. At every moment A\* is holding a set of +The core trick is simple to say. At every moment A\* holds a set of partly-explored routes, and it always extends **the one that looks most promising**. "Most promising" is the whole game, and A\* scores it with two numbers added together: @@ -31,164 +32,166 @@ numbers added together: ```text f = g + h -g = the cost to get HERE from the start (steps we've actually taken — a fact) -h = a guess of the cost from HERE to goal (the "heuristic" — an estimate) +g = the cost to get HERE from the start (steps we've actually taken, a fact) +h = a guess of the cost from HERE to goal (the "heuristic", an estimate) ``` -`g` is what a route has already cost. `h` is a hunch about what's left. Their sum -`f` is A\*'s best estimate of the *total* length of a route that goes through this -cell. Always expanding the smallest `f` means A\* pours its effort into routes -that are both cheap so far **and** heading the right way — never wasting time -exploring backwards, the way the wall follower does. +`g` is what a route has already cost. `h` is a hunch about what's left. Their +sum `f` is A\*'s best estimate of the *total* length of a route that goes +through this cell. Always expanding the smallest `f` means A\* pours its effort +into routes that are both cheap so far **and** heading the right way, instead +of wasting time exploring backwards the way the wall follower does. -Over the next two pages we'll turn each piece into Java: the map into a graph, -`h` into a formula, and "always take the smallest `f`" into a `PriorityQueue`. -Then you'll write A\* yourself and race it against the wall follower. +Over the next two pages we'll turn each piece into Python: the map into a +graph, `h` into a formula, and "always take the smallest `f`" into a `heapq` +priority queue. Then you'll write A\* yourself and race it against the wall +follower. # The maze as a graph -To *plan* a route, A\* needs to see the whole map at once — not just the cell the -robot is standing in. So the first move is to stop thinking about the maze as a -picture and start thinking about it as a **graph**: a set of **nodes** connected -by **edges**. +To *plan* a route, A\* needs to see the whole map at once, not just the cell +the robot is standing in. So the first move is to stop thinking about the maze +as a picture and start thinking about it as a **graph**: a set of **nodes** +connected by **edges**. - Each **cell** is a node. - Wherever two neighbouring cells have **no wall** between them, there's an - **edge** — a legal one-cell step. + **edge**, a legal one-cell step. - Every edge costs the same: **1 step**. That's it. "Find the shortest path through the maze" becomes "find the fewest -edges from the start node to the goal node." And unlike the wall follower's robot, -which could only feel the walls of its current cell, a planner gets random access -to the entire map. In this lesson's playground your method is handed the whole -`Maze`: +edges from the start node to the goal node." Unlike the wall follower's robot, +which could only feel the walls of its current cell, a planner gets random +access to the entire map. In this lesson's playground your function is handed +the whole `maze`: ```text -maze.rows(), maze.cols() → the grid size -maze.cellAt(row, col) → any cell you want, by coordinates -maze.cellAt(r, c).wall(dir) → is there a wall on that side? (true = wall) +maze.rows, maze.cols -> the grid size +maze.cell_at(row, col) -> any cell you want, by coordinates +maze.cell_at(r, c).wall(dir) -> is there a wall on that side? (True = wall) +dir.delta() -> (dr, dc) step for that direction ``` -`maze.cellAt(r, c).wall(Direction.UP)` is how you discover the edges: if that's -`false`, there's no wall, so `(r, c)` connects to the cell above it. +`maze.cell_at(r, c).wall(Direction.UP)` is how you discover the edges: if +that's `False`, there's no wall, so `(r, c)` connects to the cell above it. ### The heuristic: a good guess about what's left -The `g` in `f = g + h` is easy — it's just how many steps you've counted so far. -The interesting half is `h`, the guess about the distance still to go. In a grid -the natural guess is the **Manhattan distance**: how many rows plus how many -columns away the goal is, *pretending the walls aren't there.* +The `g` in `f = g + h` is easy, because it's just how many steps you've counted +so far. The interesting half is `h`, the guess about the distance still to go. +In a grid the natural guess is the **Manhattan distance**: how many rows plus +how many columns away the goal is, *pretending the walls aren't there.* ```text -h(r, c) = |r - goalRow| + |c - goalCol| +h(r, c) = abs(r - goal_r) + abs(c - goal_c) ``` -Why pretend there are no walls? Because a heuristic has one job: it must **never -over-estimate** the real distance. Walls can only ever make the true path -*longer* than the wall-free guess, so Manhattan distance is always a safe +Why pretend there are no walls? Because a heuristic has one job: it must +**never over-estimate** the real distance. Walls can only ever make the true +path *longer* than the wall-free guess, so Manhattan distance is always a safe under-estimate. A heuristic that never over-estimates is called **admissible**, -and admissibility is exactly the property that guarantees A\* returns a genuinely +and admissibility is the property that guarantees A\* returns a genuinely shortest path rather than a merely-pretty-good one. ### The frontier is a priority queue "Always expand the route with the smallest `f`" is a job for a data structure -that hands you its smallest element on demand: a **`PriorityQueue`**. You add -cells to it in any order; when you `poll()`, you always get the one with the best -(lowest) `f`. That's the beating heart of A\*, and you can watch it work on its -own right here: - -```java -// A* keeps a "frontier" of cells it could explore next, and always takes the -// most promising one first: the smallest f = g + h. -// g = steps already taken to reach a cell -// h = the heuristic — a guess of how many steps are still to go -// Here each cell is just an {g, h} pair; the queue orders them by f = g + h. -PriorityQueue frontier = - new PriorityQueue<>((a, b) -> (a[0] + a[1]) - (b[0] + b[1])); - -frontier.add(new int[] { 3, 5 }); // f = 8 -frontier.add(new int[] { 1, 2 }); // f = 3 <-- most promising -frontier.add(new int[] { 2, 4 }); // f = 6 - -// They come back out cheapest-f first, no matter what order they went in. -while (!frontier.isEmpty()) { - int[] cell = frontier.poll(); - System.out.println("explore a cell with f = " + (cell[0] + cell[1])); -} +that hands you its smallest element on demand: a **priority queue**. In Python, +the standard library module **`heapq`** turns a regular list into one. You push +tuples with `heapq.heappush(frontier, item)`, and `heapq.heappop(frontier)` +always hands back the smallest tuple. Because Python compares tuples by their +first element, putting `f = g + h` first means `heappop` always picks the +lowest `f`. Watch it work on its own right here: + +```python +import heapq + +# A* keeps a "frontier" of cells it could explore next, and always takes the +# most promising one first: the smallest f = g + h. +# g = steps already taken to reach a cell +# h = the heuristic, a guess of how many steps are still to go +# Putting f first in each (f, g, h) tuple makes heapq return the smallest f. +frontier: list[tuple[int, int, int]] = [] + +for g, h in [(3, 5), (1, 2), (2, 4)]: + heapq.heappush(frontier, (g + h, g, h)) + +# They come back out cheapest-f first, no matter what order they went in. +while frontier: + f, g, h = heapq.heappop(frontier) + print(f"explore a cell with f = {f} (g={g}, h={h})") ``` -Run it: even though `f = 3` went in second, it comes out first, then `6`, then -`8`. A\* will lean on exactly this — a frontier that always surrenders its most -promising cell — to march toward the goal without wandering. On the next page you -wire it into the real maze. +Run it. Even though `f = 3` went in second, it comes out first, then `6`, then +`8`. A\* leans on this exact trick, a frontier that always hands over its most +promising cell, to march toward the goal without wandering. On the next page +you wire it into the real maze. # A* in code -Here's the whole algorithm. It's longer than the wall follower, but every line is -one of the pieces you just met: a `g` score per cell, a `cameFrom` trail so you -can rebuild the route, a `PriorityQueue` frontier ordered by `f = g + h`, and the +Here's the whole algorithm. It's longer than the wall follower, but every line +is one of the pieces you just met: a `g` score per cell, a `came_from` trail so +you can rebuild the route, a `heapq` frontier ordered by `f = g + h`, and the Manhattan heuristic. Read it top to bottom before you run it. ```text -void solve(Maze maze, Robot robot) { - int rows = maze.rows(), cols = maze.cols(); - int goalR = rows - 1, goalC = cols - 1; // goal is the bottom-right cell - - int[][] g = new int[rows][cols]; // cheapest steps to reach each cell - int[][] cameFrom = new int[rows][cols]; // which cell we arrived from - for (int[] row : g) Arrays.fill(row, Integer.MAX_VALUE); - for (int[] row : cameFrom) Arrays.fill(row, -1); - g[0][0] = 0; // start costs nothing to reach - - // Frontier entries are {row, col, f}, ordered smallest-f first. - PriorityQueue frontier = new PriorityQueue<>((a, b) -> a[2] - b[2]); - frontier.add(new int[] { 0, 0, heuristic(0, 0, goalR, goalC) }); - - while (!frontier.isEmpty()) { - int[] cur = frontier.poll(); // the most promising cell so far - int r = cur[0], c = cur[1]; - if (r == goalR && c == goalC) break; // reached the goal — stop - - Cell cell = maze.cellAt(r, c); - for (Direction dir : Direction.values()) { - if (cell.wall(dir)) continue; // no edge through a wall - ... step to the neighbour in dir ... - int tentative = g[r][c] + 1; // one more step than here - if (tentative < g[nr][nc]) { // found a cheaper way in? - g[nr][nc] = tentative; - cameFrom[nr][nc] = r * cols + c; // remember how we got here - frontier.add(new int[] { nr, nc, tentative + heuristic(...) }); - } - } - } - ... follow cameFrom back from the goal, then drive the robot along it ... -} +def solve(maze, robot): + rows, cols = maze.rows, maze.cols + goal_r, goal_c = rows - 1, cols - 1 # goal is the bottom-right cell + + g = {(0, 0): 0} # cheapest steps to reach each cell + came_from = {} # (r, c) -> (prev_r, prev_c, direction) + + # Frontier entries are (f, r, c), ordered smallest-f first. + frontier = [(heuristic(0, 0, goal_r, goal_c), 0, 0)] + + while frontier: + _, r, c = heapq.heappop(frontier) # the most promising cell so far + if (r, c) == (goal_r, goal_c): + break # reached the goal, stop + + cell = maze.cell_at(r, c) + for direction in Direction: + if cell.wall(direction): + continue # no edge through a wall + dr, dc = direction.delta() + nr, nc = r + dr, c + dc + tentative = g[(r, c)] + 1 # one more step than here + if tentative < g.get((nr, nc), math.inf): + g[(nr, nc)] = tentative + came_from[(nr, nc)] = (r, c, direction) + f = tentative + heuristic(nr, nc, goal_r, goal_c) + heapq.heappush(frontier, (f, nr, nc)) + + # Follow came_from back from the goal, reverse the steps, + # then drive the robot with robot.drive(direction). ``` -The shape is always the same: **poll** the best cell, look at its open neighbours, -and for each one ask "is the path *through me* cheaper than any route you'd found -before?" If so, record the cheaper cost, remember the step in `cameFrom`, and drop -the neighbour back into the frontier with its new `f`. When the goal finally comes -out of the queue, `cameFrom` holds a breadcrumb trail you can walk backwards to -reconstruct the shortest route — then drive it. +The shape is always the same: **pop** the best cell, look at its open +neighbours, and for each one ask "is the path *through me* cheaper than any +route you'd found before?" If so, record the cheaper cost, remember the step in +`came_from`, and push the neighbour onto the frontier with its new `f`. When +the goal finally comes out of the queue, `came_from` holds a breadcrumb trail +you can walk backwards to reconstruct the shortest route, then drive it with +`robot.drive(direction)`. Now the real thing. The editor below is pre-loaded with a **complete, working -A\*** — the code above, filled in. Run it first and watch the robot walk a clean, -direct line to the goal, no wandering. Then make it yours: - -- **Race it.** Note how many cells A\*'s path is. Open the wall follower lesson in - another tab, run it on a maze, and compare — A\* is never longer, usually much - shorter. -- **Sabotage the heuristic.** Change `heuristic` to `return 0;`. It still finds - the shortest path (now it's plain Dijkstra / breadth-first search) — but with no - hunch about *which way* the goal is, it explores far more cells to get there. -- **Over-estimate on purpose.** Multiply the heuristic by 5. Now A\* over-trusts - its guess, charges greedily at the goal, and can return a path that *isn't* the - shortest — a live demonstration of why admissibility matters. -- Add a `System.out.println(...)` inside the loop to print each cell as it's - expanded, and watch the search order in the output below. +A\***, the code above filled in. Run it first and watch the robot walk a clean, +direct line to the goal with no wandering. Then make it yours: + +- **Race it.** Note how many cells A\*'s path is. Open the wall follower lesson + in another tab, run it on a maze, and compare. A\* is never longer and is + usually much shorter. +- **Sabotage the heuristic.** Change `heuristic` to `return 0`. It still finds + the shortest path (now it's plain Dijkstra / breadth-first search), but with + no hunch about *which way* the goal is, it explores far more cells to get + there. +- **Over-estimate on purpose.** Multiply the heuristic by 5. Now A\* + over-trusts its guess, charges greedily at the goal, and can return a path + that *isn't* the shortest, a live demonstration of why admissibility matters. +- Add a `print(...)` inside the loop to print each cell as it's expanded, and + watch the search order in the output below. ```maze -solver: astar +solver: python-astar ``` diff --git a/lessons/README.md b/lessons/README.md index b0329a6..98e638b 100644 --- a/lessons/README.md +++ b/lessons/README.md @@ -14,19 +14,19 @@ it's the exact content the [training site](../site) renders, page by page. title: "Lesson 2: Variables" goal: "Explain what a variable is and why programs need them." order: 2 - section: "Java Fundamentals" + section: "Python Fundamentals" --- # A heading starts a new page Content for the first page a student sees. # Another heading, another page - More content. Code fences tagged \`java\` are rendered as a live, + More content. Code fences tagged `python` are rendered as a live, editable, runnable code block instead of plain text: - ​```java - String name = "Ada"; - System.out.println("Hello, " + name); + ​```python + name = "Ada" + print(f"Hello, {name}") ​``` # One more page @@ -36,47 +36,45 @@ it's the exact content the [training site](../site) renders, page by page. ### Rules the site relies on - **Frontmatter is required**: `title`, `goal`, and `order` (a number controlling - where the lesson sits in the lesson list). `section` is optional — lessons - sharing a `section` value are grouped together (under that heading) in the - index and sidebar, with sections ordered by their first lesson; lessons - without one fall under a default "Lessons" group. + where the lesson sits in the lesson list). `section` is optional. Lessons + sharing a `section` value are grouped together under that heading in the index + and sidebar, with sections ordered by their first lesson. Lessons without one + fall under a default "Lessons" group. - **Every top-level `#` heading starts a new page.** Don't use `#` for anything - except a page break — use `##` and smaller for in-page structure. -- **` ```java ` code fences are live**, not decoration. Students can edit and - run them right on the page (compiled with a real javac and executed via - [CheerpJ](https://cheerpj.com), a JVM compiled to WebAssembly — no server - involved). Only put code there that's meant to be run; use ` ```text ` or - plain prose for output samples or pseudocode. -- **The playground wraps bare statements in a program shell.** A snippet with - no `class`/`enum` declaration is compiled inside - `import java.util.*; public class Main { public static void main(...) { … } }`, - so early lessons can run `System.out.println("hi");` directly (and use - `ArrayList`/`HashMap` before imports are taught). A snippet that declares its - own class or enum runs **as written** — the class containing `main` is the - one executed. Lessons 6–10 rely on wrap mode; lesson 11 reveals the shell and - everything from there uses full files. -- **` ```blocks ` fences swap the Java playground for the visual block + except a page break. Use `##` and smaller for in-page structure. +- **` ```python ` code fences are live**, not decoration. Students can edit and + run them right on the page via the Python 3.12 server runner in + [`runner/`](../runner). Only put code there that's meant to be run; use + ` ```text ` or plain prose for output samples or pseudocode. +- **Every first ` ```python ` fence on a page must run cleanly on its own** under + `python3 -I` (isolated mode). Snippets execute as top-level Python scripts with + no hidden wrapper, so include any imports or definitions the snippet needs. +- **` ```blocks ` fences swap the Python playground for the visual block editor** (drag-and-drop flowcharts). The fence body is a directive, not - content — it names a starter graph, e.g. `preset: sequence`, and never renders + content. It names a starter graph, e.g. `preset: sequence`, and never renders in the prose. Every preset lives in - [`site/src/lib/blockPresets.ts`](../site/src/lib/blockPresets.ts); they come in - a `-demo` / `-edit` / `-build` trio per concept (watch-only → editable → + [`site/src/lib/blockPresets.ts`](../site/src/lib/blockPresets.ts). They come + in a `-demo` / `-edit` / `-build` trio per concept (watch-only, editable, free-build with a toolbar): `sequence`/`edit-values`/`build` (lesson 1, arithmetic), `cond-*` (lesson 2, compare + if), `loop-*` (lesson 3, repeat), `fn-*` (lesson 4, reusable call blocks with an "inside the block" view). A page - has one playground: a ` ```blocks ` fence takes precedence over any ` ```java ` - on the page. To add a new concept, add a preset (and any new block type) rather - than inventing markdown syntax. -- **`sm-*` presets render the state-machine playground instead** — same - ` ```blocks ` fence, but preset names defined in - [`site/src/lib/statePresets.ts`](../site/src/lib/statePresets.ts) are routed to - `StatePlayground` (a drivable state diagram with event buttons) rather than the - dataflow block editor. They follow the same demo → edit → build arc: + has one playground: a ` ```blocks ` fence takes precedence over any + ` ```python ` fence on the page. To add a new concept, add a preset (and any + new block type) rather than inventing markdown syntax. +- **`sm-*` presets render the state-machine playground instead.** They use the + same ` ```blocks ` fence, but preset names defined in + [`site/src/lib/statePresets.ts`](../site/src/lib/statePresets.ts) route to + `StatePlayground` (a drivable state diagram with event buttons) rather than + the dataflow block editor. They follow the same demo, edit, build arc: `sm-demo` (traffic light, lesson 20), `sm-edit` (game-piece handler), and `sm-build` (wire up a climber yourself). +- **` ```maze ` fences render the maze playground.** The fence body names a + starter solver (such as `solver: python-wallfollower` or + `solver: python-astar`) that runs on the server runner against + [`runner/maze_solver.py`](../runner/maze_solver.py). - Keep the `goal` to one sentence. It's shown on the lesson card and at the top - of the lesson — it should tell a student what they'll be able to do - afterwards, not just what topic it covers. + of the lesson, and should tell a student what they'll be able to do afterwards, + not just what topic it covers. - **`parked/` is invisible to the site.** The glob only matches `lessons/*/README.md`, so anything nested one level deeper doesn't render. Drafts we've pulled from the curriculum but want to keep live in diff --git a/lessons/algorithms-maze-data/README.md b/lessons/algorithms-maze-data/README.md index b25d447..3de6377 100644 --- a/lessons/algorithms-maze-data/README.md +++ b/lessons/algorithms-maze-data/README.md @@ -1,114 +1,85 @@ --- title: "The maze as data" -goal: "See a maze the way a program does — a grid of numbers — and learn to read a 2D array (an array of arrays) with maze[row][col], the shape almost every robot's-eye view of the field takes." +goal: "See a maze the way a program does, as a grid of numbers, and learn to read a 2D list with maze[row][col]." order: 196 section: "Algorithms" --- # A maze is just a grid of numbers -You've driven the maze by hand and watched three robots cross it. Now for the -move that lets a *computer* do it: seeing the maze as **data** — plain numbers a -program can hold in a variable. - -Back in the [Arrays](/lesson/12-arrays) lesson, an array was a row of boxes: a -single line of values, one after another. A maze isn't a single row, though — -it's a **grid**, with rows *and* columns. So we reach for the natural next step: -an array **whose elements are themselves arrays**. One array holds the rows; -each row is an array of cells. That's a **2D array**, and in Java its type is -`int[][]` — "an array of `int` arrays." - -Here's a small 5×5 maze written exactly that way: - -```java -int[][] maze = { - {4, 12, 12, 12, 10}, - {6, 12, 10, 6, 9}, - {5, 10, 3, 3, 2}, - {6, 9, 3, 5, 11}, - {5, 8, 5, 12, 9} -}; - -System.out.println("The maze has " + maze.length + " rows."); -System.out.println("Row 0 has " + maze[0].length + " columns."); +You have driven the maze by hand and watched three robots cross it. Now for the move that lets a *computer* do it: seeing the maze as **data**, plain numbers a program can hold in a variable. + +Back in the [Arrays](/lesson/12-arrays) lesson, a list was a row of boxes, a single line of values one after another. A maze is not a single row, though. It is a **grid**, with rows *and* columns. So we reach for the natural next step: a list **whose elements are themselves lists**. One outer list holds the rows, and each row is a list of cells. That is a **2D list**, and in Python its type hint is `list[list[int]]`, a list of `int` lists. + +Here is a small 5x5 maze written that way: + +```python +maze: list[list[int]] = [ + [4, 12, 12, 12, 10], + [6, 12, 10, 6, 9], + [5, 10, 3, 3, 2], + [6, 9, 3, 5, 11], + [5, 8, 5, 12, 9], +] + +print(f"The maze has {len(maze)} rows.") +print(f"Row 0 has {len(maze[0])} columns.") ``` -Read it top to bottom and it lays out as five rows of five cells — the same shape -as the mazes you've been crossing. The outer `{ }` holds the whole maze; each -inner `{ }` is one row. `maze.length` is the number of rows; `maze[0].length` is -how many columns are in the first row. Press **Run** and check those counts. +Read it top to bottom and it lays out as five rows of five cells, the same shape as the mazes you have been crossing. The outer `[ ]` holds the whole maze, and each inner `[ ]` is one row. `len(maze)` is the number of rows, and `len(maze[0])` is how many columns are in the first row. Press **Run** and check those counts. # Reaching one cell: maze[row][col] -A single index reached into a plain array — `scores[2]` was the third score. A -2D array takes **two** indices, in a fixed order that's worth burning into -memory: **row first, then column.** - -```java -int[][] maze = { - {4, 12, 12, 12, 10}, - {6, 12, 10, 6, 9}, - {5, 10, 3, 3, 2}, - {6, 9, 3, 5, 11}, - {5, 8, 5, 12, 9} -}; - -// maze[row][col] — row first, then column. Both start counting at 0. -System.out.println("Top-left cell: " + maze[0][0]); -System.out.println("Top-right cell: " + maze[0][4]); -System.out.println("Bottom-right cell: " + maze[4][4]); -System.out.println("Middle cell: " + maze[2][2]); +A single index reached into a flat list: `scores[2]` was the third score. A 2D list takes **two** indices, in a fixed order worth memorizing: **row first, then column.** + +```python +maze = [ + [4, 12, 12, 12, 10], + [6, 12, 10, 6, 9], + [5, 10, 3, 3, 2], + [6, 9, 3, 5, 11], + [5, 8, 5, 12, 9], +] + +# maze[row][col]: row first, then column. Both start counting at 0. +print("Top-left cell: ", maze[0][0]) +print("Top-right cell: ", maze[0][4]) +print("Bottom-right cell:", maze[4][4]) +print("Middle cell: ", maze[2][2]) ``` -`maze[0][0]` is the **start** (top-left — the green cell in the maze pictures). -`maze[4][4]` is the **goal** (bottom-right, the red cell) — the last row, the -last column. -Row `0` is the top and column `0` is the left, so as the row index grows you move -*down* and as the column index grows you move *right*. Getting `[row][col]` the -right way round is the single most common place people trip: `maze[4][0]` is the -bottom-left cell, but `maze[0][4]` is the top-right — swap them and you're in a -completely different corner. +`maze[0][0]` is the **start** (top-left, the green cell in the maze pictures). `maze[4][4]` is the **goal** (bottom-right, the red cell), the last row and the last column. Row `0` is the top and column `0` is the left, so as the row index grows you move *down*, and as the column index grows you move *right*. Getting `[row][col]` the right way round is the most common place people trip: `maze[4][0]` is the bottom-left cell, while `maze[0][4]` is the top-right. Swap them and you are in a completely different corner. # Walking the whole grid -To *look at every cell*, you nest one loop inside another: the outer loop walks -the rows, the inner loop walks the columns of that row. This double loop is the -bread-and-butter way to touch every square of a grid, and you'll write it -constantly. - -```java -int[][] maze = { - {4, 12, 12, 12, 10}, - {6, 12, 10, 6, 9}, - {5, 10, 3, 3, 2}, - {6, 9, 3, 5, 11}, - {5, 8, 5, 12, 9} -}; - -for (int row = 0; row < maze.length; row++) { - for (int col = 0; col < maze[row].length; col++) { - System.out.print(maze[row][col] + "\t"); - } - System.out.println(); // newline at the end of each row -} +To *look at every cell*, nest one loop inside another. The outer loop walks the rows, and the inner loop walks the columns of that row. This double loop is the standard way to touch every square of a grid, and you will write it often. + +```python +maze = [ + [4, 12, 12, 12, 10], + [6, 12, 10, 6, 9], + [5, 10, 3, 3, 2], + [6, 9, 3, 5, 11], + [5, 8, 5, 12, 9], +] + +for row in range(len(maze)): + for col in range(len(maze[row])): + print(maze[row][col], end="\t") + print() # newline at the end of each row ``` -Run it and the output is the maze laid back out as a grid — because the loops -visit the cells in exactly the order they're stored: all of row 0 left to right, -then all of row 1, and so on. +Run it and the output is the maze laid back out as a grid, because the loops visit the cells in the exact order they are stored: all of row 0 left to right, then all of row 1, and so on. ## What do the numbers *mean*? -Fair question — why is the start cell a `4` and the goal a `9`? Each number packs -in **which sides of that cell are open** (carved through) versus walled. The -start cell is `4`, which happens to mean "only the right side is open" — which -fits: the green start cell has just one way out, to the right. - -Here's the good news, and it's the whole point of the next lesson: **you will -never do that decoding by hand.** Squeezing four walls into one number is a -clever trick, but it's a distraction from actually *solving* the maze. So instead -of asking you to do bit-by-bit arithmetic on these values, we'll hand the grid to -a small **library** that reads it for you and gives you a friendly robot to -drive. The maze stays this same `int[][]` — that's how it travels between the -website and your Java code — but from here on you get to think in *"is there a -wall to my right?"*, not in numbers. +Why is the start cell a `4` and the goal a `9`? Each number is a **bitmask** that packs in **which sides of that cell are open** versus walled: + +- `1` means **up** is open +- `2` means **down** is open +- `4` means **right** is open +- `8` means **left** is open + +To store multiple open sides in one number, add their values together. The start cell is `4`, meaning only the right side is open. The goal cell is `9` (`1 + 8`), meaning up and left are open. You can test a single bit in Python with `&`, like `(cell & 4) != 0`. + +Here is the good news, and it is the whole point of the next lesson: **you will never do that decoding by hand.** Squeezing four walls into one number is a neat trick, but it is a distraction from actually *solving* the maze. Instead of doing bit arithmetic on these values, we hand the grid to a small **library** that reads it for you and gives you a friendly robot to drive. The maze stays this same `list[list[int]]`, since that is how it travels between the website and your Python code, and from here on you get to think in *"is there a wall to my right?"*, not in numbers. diff --git a/lessons/algorithms-maze-solver/README.md b/lessons/algorithms-maze-solver/README.md index d7c09fb..a111087 100644 --- a/lessons/algorithms-maze-solver/README.md +++ b/lessons/algorithms-maze-solver/README.md @@ -1,119 +1,149 @@ --- title: "Writing a maze solver" -goal: "Turn the wall follower from an idea into working Java: use the robot's facing() and the Direction turns to try right, straight, left, then back, and watch your own algorithm drive a robot out of a freshly generated maze." +goal: "Turn the wall follower from an idea into working Python using facing() and Direction turns, then watch your solver cross a freshly generated maze." order: 198 section: "Algorithms" --- # From a helper to an algorithm -You have a robot you understand and a `tryMove` helper that moves it one cell -*if it can*. Time to put them in a loop and cross the maze — the **wall -follower** from the visual lesson, now as real code. +You have a robot you understand and a `try_move` helper that moves it one cell *if it can*. Time to put them in a loop and cross the maze using the **wall follower** from the visual lesson, now as real Python code. -The rule, in words, was: *relative to the way I'm facing, take the first opening -in this order — right, straight, left, then (only as a last resort) back.* The -one fact it leans on is the robot's **heading**, and that's exactly the fact the -robot already remembers for you: `robot.facing()`. Because `drive` updates -`facing()` every time the robot actually moves, you never have to track the -heading yourself. +The rule, in words, was: *relative to the way I'm facing, take the first opening in this order: right, straight, left, then (only as a last resort) back.* The one fact it leans on is the robot's **heading**, and that is the fact the robot already remembers for you: `robot.facing()`. Because `drive` updates `facing()` every time the robot actually moves, you never have to track the heading yourself. -To turn "right, straight, left, back" into real `Direction`s, ask the heading to -rotate. `Direction` offers three turns: +To turn "right, straight, left, back" into real `Direction` values, ask the heading to rotate. `Direction` offers three turns: ```text -Direction.RIGHT.clockwise() → Direction.DOWN (a right turn) -Direction.RIGHT.counterClockwise() → Direction.UP (a left turn) -Direction.RIGHT.opposite() → Direction.LEFT (turn around) +Direction.RIGHT.clockwise() -> Direction.DOWN (a right turn) +Direction.RIGHT.counter_clockwise() -> Direction.UP (a left turn) +Direction.RIGHT.opposite() -> Direction.LEFT (turn around) ``` -So if the robot is `facing()` right, its own right-hand side is `clockwise()` of -that (down), straight ahead is the heading itself, its left is -`counterClockwise()`, and back is `opposite()`. Build that list of four and -`tryMove` the first one that's open: - -```java -import com.frc2713.mazesolver.*; - -public class WallFollower { - public static void main(String[] args) { - int[][] grid = { - {4, 12, 12, 12, 10}, - {6, 12, 10, 6, 9}, - {5, 10, 3, 3, 2}, - {6, 9, 3, 5, 11}, - {5, 8, 5, 12, 9} - }; - Maze maze = new GridMaze(grid); - Robot robot = maze.robot(); - - int maxSteps = 1000; // a safety stop, so a bad rule can't loop forever - for (int i = 0; i < maxSteps && !robot.atGoal(); i++) { - Direction ahead = robot.facing(); - // Right, straight, left, back — relative to the way we're facing. - Direction[] order = { - ahead.clockwise(), ahead, ahead.counterClockwise(), ahead.opposite() - }; - for (Direction dir : order) { - if (tryMove(robot, dir)) break; // took the first opening - } - } - - if (robot.atGoal()) { - System.out.println("Reached the goal in " + (robot.trail().length - 1) + " steps!"); - } else { - System.out.println("Gave up after " + maxSteps + " steps."); - } - } - - // Drive one step in dir if that side is open; report whether we moved. - static boolean tryMove(Robot robot, Direction dir) { - if (!robot.readWallSensor(dir)) { - robot.drive(dir); - return true; - } - return false; - } -} +If the robot is `facing()` right, its own right-hand side is `clockwise()` of that (down), straight ahead is the heading itself, its left is `counter_clockwise()`, and back is `opposite()`. Build that list of four and `try_move` the first one that is open: + +```python +from enum import Enum + +# --- maze_solver library (included here so this snippet runs standalone) --- +class Direction(Enum): + UP = 1 + DOWN = 2 + RIGHT = 4 + LEFT = 8 + + def clockwise(self): + return {Direction.UP: Direction.RIGHT, Direction.RIGHT: Direction.DOWN, + Direction.DOWN: Direction.LEFT, Direction.LEFT: Direction.UP}[self] + + def counter_clockwise(self): + return {Direction.UP: Direction.LEFT, Direction.LEFT: Direction.DOWN, + Direction.DOWN: Direction.RIGHT, Direction.RIGHT: Direction.UP}[self] + + def opposite(self): + return {Direction.UP: Direction.DOWN, Direction.DOWN: Direction.UP, + Direction.LEFT: Direction.RIGHT, Direction.RIGHT: Direction.LEFT}[self] + +class Robot: + def __init__(self, maze): + self._maze = maze + self.row = 0 + self.col = 0 + self._facing = Direction.RIGHT + self._trail = [[0, 0]] + + def read_wall_sensor(self, direction): + return (self._maze._grid[self.row][self.col] & direction.value) == 0 + + def drive(self, direction): + if self.read_wall_sensor(direction): + return + dr, dc = {Direction.UP: (-1, 0), Direction.DOWN: (1, 0), + Direction.LEFT: (0, -1), Direction.RIGHT: (0, 1)}[direction] + self.row += dr + self.col += dc + self._facing = direction + self._trail.append([self.row, self.col]) + + def facing(self): + return self._facing + + def at_goal(self): + return self.row == self._maze.rows - 1 and self.col == self._maze.cols - 1 + + def trail(self): + return list(self._trail) + +class GridMaze: + def __init__(self, grid): + self._grid = grid + self.rows = len(grid) + self.cols = len(grid[0]) + + def robot(self): + return Robot(self) + +# --- your solver --- +def try_move(robot, direction): + if not robot.read_wall_sensor(direction): + robot.drive(direction) + return True + return False + +def solve(robot): + max_steps = 1000 # a safety stop, so a bad rule cannot loop forever + for _ in range(max_steps): + if robot.at_goal(): + break + ahead = robot.facing() + # Right, straight, left, back, relative to the way we are facing. + order = [ + ahead.clockwise(), + ahead, + ahead.counter_clockwise(), + ahead.opposite(), + ] + for direction in order: + if try_move(robot, direction): + break # took the first opening + +grid = [ + [4, 12, 12, 12, 10], + [6, 12, 10, 6, 9], + [5, 10, 3, 3, 2], + [6, 9, 3, 5, 11], + [5, 8, 5, 12, 9], +] +maze = GridMaze(grid) +robot = maze.robot() +solve(robot) + +if robot.at_goal(): + print(f"Reached the goal in {len(robot.trail()) - 1} steps!") +else: + print("Gave up after 1000 steps.") ``` -Press **Run**: the robot hugs the right-hand wall all the way from the green cell -to the red one and prints how many steps it took. Everything the visual lesson -promised is here in a dozen lines — and the only state the algorithm keeps is the -heading, which the robot hands you for free. +Press **Run**: the robot hugs the right-hand wall all the way from the green cell to the red one and prints how many steps it took. Everything the visual lesson promised is here in a dozen lines, and the only state the algorithm keeps is the heading, which the robot hands you for free. # Now you try: your solver in a real maze -You just read a whole program you could run but not *change*. Now it's your turn, -and this time the maze is real — freshly generated, and different every time. +You just read a whole program you could run. Now it is your turn, and this time the maze is freshly generated and different every time. -Notice how much of that program was the same boilerplate every run: `main`, -building the `Maze`, the safety cap, printing the result. The only part that's -truly *the algorithm* is the decision inside the loop — so that's the only part -the playground asks you for. It hands you a `Robot` standing at the start and -asks for one method, `solve`: +Notice how much of that program was setup boilerplate: building the `GridMaze`, creating the `robot`, printing the result. The only part that is *the algorithm* is the decision inside the loop, so that is the only part the playground asks you for. It hands you a `robot` standing at the start and asks for one function: `def solve(robot):`. -The maze on the right is handed to your Java `solve` method, your algorithm drives -the `Robot`, and the exact path it took is animated right back here — the full -round-trip. You have the same API you've been using all along: +The maze on the right is handed to your Python `solve` function, your algorithm drives the `robot`, and the exact path it took is animated right back here. You have the same API you have been using all along: -- `robot.readWallSensor(Direction.UP/DOWN/LEFT/RIGHT)` — is that side a wall? -- `robot.drive(Direction.UP/DOWN/LEFT/RIGHT)` — drive one cell (a wall stops you). -- `robot.facing()` — the direction it last drove; `Direction` also has - `clockwise()`, `counterClockwise()`, and `opposite()`. -- `robot.atGoal()`, `robot.row()`, `robot.col()` — where am I, am I done? +- `robot.read_wall_sensor(Direction.UP/DOWN/LEFT/RIGHT)` checks whether that side is a wall. +- `robot.drive(Direction.UP/DOWN/LEFT/RIGHT)` drives one cell (a wall stops you). +- `robot.facing()` returns the direction it last drove. `Direction` also has `clockwise()`, `counter_clockwise()`, and `opposite()`. +- `robot.at_goal()`, `robot.row`, and `robot.col` tell you where the robot is and whether it is done. -The starter is the **wall follower** you just studied. Run it first and watch it -solve. Then make it yours: +The starter is the **wall follower** you just studied. Run it first and watch it solve. Then make it yours: -- Hit **Generate new maze** and run again — a good algorithm clears *any* maze, - not just one. -- Break it on purpose: swap `clockwise()` and `counterClockwise()` (a *left*-hand - follower — it still works!), or delete the wall check and drive blindly into - walls, and watch where your robot gets stuck. -- Throw out the wall follower entirely and write your own rule. Anything that - reaches red counts. +- Hit **Generate new maze** and run again. A good algorithm clears *any* maze, not just one. +- Break it on purpose: swap `clockwise()` and `counter_clockwise()` (a *left*-hand follower, which still works!), or delete the wall check and drive blindly into walls, and watch where your robot gets stuck. +- Throw out the wall follower entirely and write your own rule. Anything that reaches red counts. ```maze -solver: java +solver: python ``` diff --git a/lessons/algorithms-robot-api/README.md b/lessons/algorithms-robot-api/README.md index a140e33..832099b 100644 --- a/lessons/algorithms-robot-api/README.md +++ b/lessons/algorithms-robot-api/README.md @@ -1,147 +1,213 @@ --- title: "Reading the robot's API" -goal: "Meet the maze-solver library — the Maze, Robot, and Direction it hands you — and practice the real-world skill of reading an unfamiliar API by writing a small helper method, tryMove, out of the robot's sense and drive abilities." +goal: "Meet the Python maze_solver library and practice reading an unfamiliar API by writing a small try_move helper." order: 197 section: "Algorithms" --- # Meet the robot -Last lesson you saw the maze as an `int[][]` — and promised yourself you'd never -decode those numbers by hand. This is where that promise pays off. We hand the -grid to a small **library** (a bundle of ready-made code someone else wrote for -you), and it gives back two friendly objects: +Last lesson you saw the maze as a `list[list[int]]` and promised yourself you would never decode those bitmasks by hand. This is where that promise pays off. We hand the grid to a small **library** (`maze_solver`, a bundle of ready-made Python code), and it gives back two friendly objects: -```java -Maze maze = new GridMaze(grid); // turn the raw grid into a maze -Robot robot = maze.robot(); // a robot standing on the start cell +```text +maze = GridMaze(grid) # turn the raw grid into a maze +robot = maze.robot() # a robot standing on the start cell ``` -That's it — no bitmasks. From here you think about a **robot**, and a robot can -do exactly what the visual lessons described: **sense** what's around it and -**move**. Learning precisely what it can do means reading its **API** — the list -of methods it offers. Reading an API you didn't write is one of the most useful -skills in all of programming (it's most of what working with real robot code -*is*), so here's the robot's, in full: +No bitmasks. From here you think about a **robot**, and a robot can do what the visual lessons described: **sense** what is around it and **move**. Learning what it can do means reading its **API**, the list of methods and attributes it offers. Reading an API you did not write is one of the most useful skills in programming, since it is most of what working with real robot code *is*. Here is the robot's API in full: ```text -robot.readWallSensor(Direction.UP) is that side a wall? → true / false +robot.read_wall_sensor(Direction.UP) is that side a wall? -> True / False robot.drive(Direction.RIGHT) drive one cell that way (does nothing if walled) robot.facing() the Direction it last drove -robot.atGoal() standing on the goal (red) cell? -robot.row(), robot.col() where it is now +robot.at_goal() standing on the goal (red) cell? +robot.row, robot.col where it is now ``` -`Direction` is the four ways it can face or move: `Direction.UP`, -`Direction.DOWN`, `Direction.LEFT`, `Direction.RIGHT`. Two things are worth -underlining before you use them: - -- `readWallSensor(dir)` reports a **wall**: it's `true` when that side is - *blocked*. So an *opening* is when it comes back `false`. -- `drive(dir)` is honest about the walls: if you aim it at a wall, the robot just - stays put. And when it *does* move, it remembers that direction — so right - after `robot.drive(Direction.UP)`, `robot.facing()` is `Direction.UP`. A robot - that just drove up is now facing up. - -Here's the robot actually doing these things. Read the code, predict the output, -then press **Run**: - -```java -import com.frc2713.mazesolver.*; - -public class MeetTheRobot { - public static void main(String[] args) { - int[][] grid = { - {4, 12, 12, 12, 10}, - {6, 12, 10, 6, 9}, - {5, 10, 3, 3, 2}, - {6, 9, 3, 5, 11}, - {5, 8, 5, 12, 9} - }; - Maze maze = new GridMaze(grid); - Robot robot = maze.robot(); - - // What's around the robot at the start? - System.out.println("Wall above me? " + robot.readWallSensor(Direction.UP)); - System.out.println("Wall to right? " + robot.readWallSensor(Direction.RIGHT)); - - // Drive one cell to the right, then look again. - robot.drive(Direction.RIGHT); - System.out.println("Drove right. Now at row " + robot.row() + ", col " + robot.col()); - System.out.println("Facing: " + robot.facing()); - } -} +`Direction` is the four ways the robot can face or move: `Direction.UP`, `Direction.DOWN`, `Direction.LEFT`, `Direction.RIGHT`. Each direction also knows how to turn with `.clockwise()`, `.counter_clockwise()`, and `.opposite()`. Two things are worth noting before you use the robot: + +- `read_wall_sensor(direction)` reports a **wall**: it returns `True` when that side is *blocked*. An *opening* is when it returns `False`. +- `drive(direction)` respects the walls: if you aim it at a wall, the robot stays put. When it *does* move, it remembers that direction, so right after `robot.drive(Direction.UP)`, `robot.facing()` is `Direction.UP`. A robot that just drove up is now facing up. + +Here is the robot doing those things. The top part includes a compact copy of `maze_solver` so the snippet runs on its own. Read the code at the bottom, predict the output, then press **Run**: + +```python +from enum import Enum + +# --- maze_solver library (included here so this snippet runs standalone) --- +class Direction(Enum): + UP = 1 + DOWN = 2 + RIGHT = 4 + LEFT = 8 + + def clockwise(self): + return {Direction.UP: Direction.RIGHT, Direction.RIGHT: Direction.DOWN, + Direction.DOWN: Direction.LEFT, Direction.LEFT: Direction.UP}[self] + + def counter_clockwise(self): + return {Direction.UP: Direction.LEFT, Direction.LEFT: Direction.DOWN, + Direction.DOWN: Direction.RIGHT, Direction.RIGHT: Direction.UP}[self] + + def opposite(self): + return {Direction.UP: Direction.DOWN, Direction.DOWN: Direction.UP, + Direction.LEFT: Direction.RIGHT, Direction.RIGHT: Direction.LEFT}[self] + +class Robot: + def __init__(self, maze): + self._maze = maze + self.row = 0 + self.col = 0 + self._facing = Direction.RIGHT + + def read_wall_sensor(self, direction): + return (self._maze._grid[self.row][self.col] & direction.value) == 0 + + def drive(self, direction): + if self.read_wall_sensor(direction): + return + dr, dc = {Direction.UP: (-1, 0), Direction.DOWN: (1, 0), + Direction.LEFT: (0, -1), Direction.RIGHT: (0, 1)}[direction] + self.row += dr + self.col += dc + self._facing = direction + + def facing(self): + return self._facing + + def at_goal(self): + return self.row == self._maze.rows - 1 and self.col == self._maze.cols - 1 + +class GridMaze: + def __init__(self, grid): + self._grid = grid + self.rows = len(grid) + self.cols = len(grid[0]) + + def robot(self): + return Robot(self) + +# --- your code --- +grid = [ + [4, 12, 12, 12, 10], + [6, 12, 10, 6, 9], + [5, 10, 3, 3, 2], + [6, 9, 3, 5, 11], + [5, 8, 5, 12, 9], +] +maze = GridMaze(grid) +robot = maze.robot() + +# What is around the robot at the start? +print("Wall above me? ", robot.read_wall_sensor(Direction.UP)) +print("Wall to right? ", robot.read_wall_sensor(Direction.RIGHT)) + +# Drive one cell to the right, then look again. +robot.drive(Direction.RIGHT) +print(f"Drove right. Now at row {robot.row}, col {robot.col}") +print("Facing:", robot.facing()) ``` -At the start the robot is boxed in on every side but the right — that lone -opening is why the start cell's number was `4`. Try changing that first `drive` -to `Direction.UP` (into a wall) and re-run: the robot doesn't move, because the -drivetrain can't push through a wall. +At the start the robot is boxed in on every side except the right, which is why the start cell's number was `4`. Try changing that first `drive` to `Direction.UP` (into a wall) and re-run: the robot does not move, because the drivetrain cannot push through a wall. -# Build a helper: tryMove +# Build a helper: try_move -Look at the two abilities together and a small annoyance appears. To *safely* -move a direction you always do the same two-step dance: **check the sensor, and -only drive if it's open.** Drive without checking and you might just grind into a -wall. +Look at the two abilities together and a small annoyance appears. To *safely* move in a direction, you always do the same two-step dance: **check the sensor, and only drive if it is open.** Drive without checking and you might grind into a wall. -That pattern — "move that way *if you can*, and tell me whether you did" — is -worth bottling into one method of your own. Call it `tryMove`: +That pattern, "move that way *if you can*, and tell me whether you did", is worth bottling into one function of your own. Call it `try_move`: ```text -tryMove(robot, dir): +try_move(robot, direction): if that side is NOT a wall: drive that way - return true (yes, I moved) + return True (yes, I moved) otherwise: - return false (no, blocked) + return False (no, blocked) ``` -It's only a few lines, but writing it is the exercise: you're turning the raw API -into a tool shaped like the way you actually think about the problem. Here it is -in code. **Read the body of `tryMove` and make sure you can explain each line** — -then, to really learn it, delete the body and rewrite it from the pseudocode -above without looking. - -```java -import com.frc2713.mazesolver.*; - -public class TryMove { - public static void main(String[] args) { - int[][] grid = { - {4, 12, 12, 12, 10}, - {6, 12, 10, 6, 9}, - {5, 10, 3, 3, 2}, - {6, 9, 3, 5, 11}, - {5, 8, 5, 12, 9} - }; - Maze maze = new GridMaze(grid); - Robot robot = maze.robot(); - - // Try each direction once and report what happened. - Direction[] toTry = { Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT }; - for (Direction dir : toTry) { - boolean moved = tryMove(robot, dir); - System.out.println("tryMove " + dir + " -> " + moved - + " (now at row " + robot.row() + ", col " + robot.col() + ")"); - } - } - - // Drive one step in dir if that side is open; report whether we moved. - static boolean tryMove(Robot robot, Direction dir) { - if (!robot.readWallSensor(dir)) { // not a wall → there's an opening - robot.drive(dir); - return true; - } - return false; - } -} +It is only a few lines, and writing it is the exercise: you are turning the raw API into a tool shaped like the way you think about the problem. Here it is in code. **Read the body of `try_move` and make sure you can explain each line.** Then, to really learn it, delete the body and rewrite it from the pseudocode above without looking. + +```python +from enum import Enum + +# --- maze_solver library (included here so this snippet runs standalone) --- +class Direction(Enum): + UP = 1 + DOWN = 2 + RIGHT = 4 + LEFT = 8 + + def clockwise(self): + return {Direction.UP: Direction.RIGHT, Direction.RIGHT: Direction.DOWN, + Direction.DOWN: Direction.LEFT, Direction.LEFT: Direction.UP}[self] + + def counter_clockwise(self): + return {Direction.UP: Direction.LEFT, Direction.LEFT: Direction.DOWN, + Direction.DOWN: Direction.RIGHT, Direction.RIGHT: Direction.UP}[self] + + def opposite(self): + return {Direction.UP: Direction.DOWN, Direction.DOWN: Direction.UP, + Direction.LEFT: Direction.RIGHT, Direction.RIGHT: Direction.LEFT}[self] + +class Robot: + def __init__(self, maze): + self._maze = maze + self.row = 0 + self.col = 0 + self._facing = Direction.RIGHT + + def read_wall_sensor(self, direction): + return (self._maze._grid[self.row][self.col] & direction.value) == 0 + + def drive(self, direction): + if self.read_wall_sensor(direction): + return + dr, dc = {Direction.UP: (-1, 0), Direction.DOWN: (1, 0), + Direction.LEFT: (0, -1), Direction.RIGHT: (0, 1)}[direction] + self.row += dr + self.col += dc + self._facing = direction + + def facing(self): + return self._facing + + def at_goal(self): + return self.row == self._maze.rows - 1 and self.col == self._maze.cols - 1 + +class GridMaze: + def __init__(self, grid): + self._grid = grid + self.rows = len(grid) + self.cols = len(grid[0]) + + def robot(self): + return Robot(self) + +# --- your code --- +# Drive one step in direction if that side is open; report whether we moved. +def try_move(robot, direction): + if not robot.read_wall_sensor(direction): # not a wall -> there is an opening + robot.drive(direction) + return True + return False + +grid = [ + [4, 12, 12, 12, 10], + [6, 12, 10, 6, 9], + [5, 10, 3, 3, 2], + [6, 9, 3, 5, 11], + [5, 8, 5, 12, 9], +] +maze = GridMaze(grid) +robot = maze.robot() + +# Try each direction once and report what happened. +to_try = [Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT] +for direction in to_try: + moved = try_move(robot, direction) + print(f"try_move {direction.name} -> {moved} (now at row {robot.row}, col {robot.col})") ``` -Run it and read the trace: from the start only `RIGHT` comes back `true`, so -that's the only line where the robot's column changes. Every other direction is a -wall, so `tryMove` reports `false` and the robot holds its position — no crashing -into walls, exactly as designed. +Run it and read the trace: `UP` and `DOWN` are walls, so `try_move` returns `False` and the robot holds its position with no crashing into walls. `RIGHT` is open, so the robot steps to column 1, and then `LEFT` steps back to column 0. -You now have a robot you understand and one helper of your own. That's everything -you need to write a *real* maze-solving algorithm — which is the next lesson. +You now have a robot you understand and one helper of your own. That is everything you need to write a *real* maze-solving algorithm in the next lesson. diff --git a/lessons/algorithms/README.md b/lessons/algorithms/README.md index 94b056d..f23a400 100644 --- a/lessons/algorithms/README.md +++ b/lessons/algorithms/README.md @@ -1,61 +1,45 @@ --- title: "Navigating a maze" -goal: "See a maze as a robot's world — a grid it must cross — and learn what makes something an algorithm by watching three robots try to solve it: a random walk (no plan), a fixed rule that loops (an algorithm, but a bad one), and the wall follower (sense, decide, move, repeat)." +goal: "See a maze as a robot's world and learn what makes something an algorithm by watching three robots try to solve it: a random walk, a fixed rule that loops, and the wall follower." order: 195 section: "Algorithms" --- # A maze is a robot's world -On the right is a maze. It's fun to solve by hand — but for us it's really a -tiny, simplified version of the problem every FRC robot faces: **"I'm here, I -need to get there, and there are things in my way."** +On the right is a maze. It is fun to solve by hand, and for us it is also a tiny, simplified version of the problem every FRC robot faces: **"I'm here, I need to get there, and there are things in my way."** -Strip a competition field down to its essentials and you get exactly this: a -space divided into a **grid** of cells, some paths open, some blocked by -**walls**, a place you **start**, and a place you're trying to **reach**. +Strip a competition field down to its essentials and you get this: a space divided into a **grid** of cells, some paths open, some blocked by **walls**, a place you **start**, and a place you are trying to **reach**. - The **grid of cells** is the field, chopped into squares the robot can occupy. -- The **walls** are obstacles — you can't drive through them. -- The **green** cell is the **start**; the **red** cell is the **goal**. +- The **walls** are obstacles you cannot drive through. +- The **green** cell is the **start**, and the **red** cell is the **goal**. - The **blue dot** is the **robot**. -Before we talk about *how* a robot crosses this, get a feel for it: use the -arrow buttons (or your arrow keys) and drive the robot from green to red. Notice -you can't move through walls — only through the openings. +Before we talk about *how* a robot crosses this, get a feel for it: use the arrow buttons (or your arrow keys) and drive the robot from green to red. Notice you cannot move through walls, only through the openings. ```maze ``` # The robot only knows what's around it -Here's the crucial thing about robots — and it's easy to miss because *you* can -see the whole maze at once. **The robot can't.** +Here is the key thing about robots, and it is easy to miss because *you* can see the whole maze at once. **The robot can't.** -A real robot doesn't get a bird's-eye view. It knows two things: +A real robot does not get a bird's-eye view. It knows two things: -1. **Where it is right now** — which cell it's sitting in. That's its - **state**: a single fact, "I am at column 3, row 5." -2. **What's immediately around it** — which of its four sides (up, down, left, - right) are open, and which are walls. That's its **sensor reading** for this - moment. +1. **Where it is right now**, which cell it is sitting in. That is its **state**: a single fact, "I am at column 3, row 5." +2. **What is immediately around it**, which of its four sides (up, down, left, right) are open, and which are walls. That is its **sensor reading** for this moment. -That's it. From one cell, the robot can only see its own four walls. It has to -make its next decision using just that — then move, look again, and decide -again. +That is it. From one cell, the robot can only see its own four walls. It has to make its next decision using just that, then move, look again, and decide again. -When *you* press an arrow, you're being the robot's decision-maker for one step: -you pick a direction, and it either moves (opening) or stays put (wall). Each -press is one **"sense → decide → move"** cycle. +When *you* press an arrow, you are being the robot's decision-maker for one step: you pick a direction, and it either moves (opening) or stays put (wall). Each press is one **"sense -> decide -> move"** cycle. ```maze ``` # The dumbest possible robot: move at random -You just drove the maze by hand, making a real choice at every cell. So here's a -fair question — what if the robot *didn't* choose? What if, at each step, it just -picked one of the open directions **at random** and went? +You just drove the maze by hand, making a real choice at every cell. So here is a fair question: what if the robot *didn't* choose? What if, at each step, it just picked one of the open directions **at random** and went? Hit **Move at random** and watch. @@ -63,32 +47,22 @@ Hit **Move at random** and watch. solver: random ``` -Sometimes it stumbles onto the goal. Sometimes it wanders forever. And here's the -part that matters: **run it again and it does something completely different.** -There's no plan — just a coin flip at every cell. +Sometimes it stumbles onto the goal. Sometimes it wanders forever. And here is the part that matters: **run it again and it does something completely different.** There is no plan, just a coin flip at every cell. -That's exactly why this is *not an algorithm*. An algorithm is something you can -write down, hand to someone else, and have them get the **same result you did**. -You can't write down "flip a coin" and call that a plan. Notice, too, that -nothing guarantees it ever finishes — it could bounce around and simply never -happen to land on red. +That is why this is *not an algorithm*. An algorithm is something you can write down, hand to someone else, and have them get the **same result you did**. You cannot write down "flip a coin" and call that a plan. Nothing guarantees it ever finishes either. It could bounce around and never land on red. -(Random isn't worthless — real robots sometimes add a pinch of it on purpose. But -as *the whole strategy*, it's nothing you can count on, and that's the point.) +Random is not worthless. Real robots sometimes add a pinch of it on purpose. As *the whole strategy*, though, it is nothing you can count on. # A rule you can repeat -Let's give the robot an actual rule — the simplest one imaginable. At every cell, -always try the same directions in the same order, and take the first one that's -open: +Let's give the robot an actual rule, the simplest one imaginable. At every cell, always try the same directions in the same order, and take the first one that is open: ```text at each cell, try these in order and take the first open one: up, then left, then down, then right ``` -That's the entire rule. No randomness, no cleverness. Press **Run the naive -rule**: +That is the entire rule. No randomness, no cleverness. Press **Run the naive rule**: ```maze solver: naive @@ -96,51 +70,27 @@ solver: naive Two things to notice. -First, it's **completely repeatable**. Run it again on this same maze and the -robot retraces the *exact* same steps — every time. That's what random didn't -have, and it's what makes this an **algorithm**: a precise rule that produces the -same result on every run. +First, it is **completely repeatable**. Run it again on this same maze and the robot retraces the *exact* same steps every time. That is what random lacked, and it is what makes this an **algorithm**: a precise rule that produces the same result on every run. -Second… it barely gets anywhere. Watch it take a step and then immediately walk -**right back** the way it came, jittering between two cells forever. (A rule with -*no memory* that returns to a cell it's already seen will make the identical -choice it made last time — so it's provably doomed to loop there. We let it -bounce a few times so you can see it, then stop it.) +Second, it barely gets anywhere. Watch it take a step and then immediately walk **right back** the way it came, jittering between two cells forever. A rule with *no memory* that returns to a cell it has already seen will make the identical choice it made last time, so it is doomed to loop there. We let it bounce a few times so you can see it, then stop it. -Why does it trap itself so fast? Because "up" is first in its list, and once -it steps down into a cell, the very next thing it does is look up — back where it -came from — and take it. It has **no memory** of having just been there. It -doesn't know which way it was heading, and it doesn't know the goal exists. +Why does it trap itself so fast? Because "up" is first in its list. Once it steps down into a cell, the very next thing it does is look up, back where it came from, and take it. It has **no memory** of having just been there. It does not know which way it was heading, and it does not know the goal exists. -So being an algorithm doesn't make a rule *good*. This one is perfectly precise -and perfectly repeatable — and perfectly useless for crossing the maze. The bar -for "algorithm" is just *definiteness and repeatability*; **whether it actually -works is a separate question**, and it's the interesting one. Give this robot -just *one* fact to remember, and something surprising happens. +Being an algorithm does not make a rule *good*. This one is precise and repeatable, and completely useless for crossing the maze. The bar for "algorithm" is just *definiteness and repeatability*. **Whether it actually works is a separate question**, and it is the interesting one. Give this robot just *one* fact to remember, and something surprising happens. # An algorithm that actually crosses the maze -Here's the surprise: the **wall follower** is almost the same rule as the naive -one — a fixed order of directions, take the first open one. It adds exactly **one -remembered fact**: which way the robot is currently facing. And it tries its -directions *relative to that heading* instead of relative to the screen: +Here is the surprise: the **wall follower** is almost the same rule as the naive one, a fixed order of directions taking the first open one. It adds exactly **one remembered fact**: which way the robot is currently facing. It tries its directions *relative to that heading* instead of relative to the screen: ```text at each cell, relative to the way I'm facing, take the first open one: -1. turn right — is there an opening to my right? take it. -2. go straight — else, is the way ahead open? take it. -3. turn left — else, is there an opening left? take it. -4. turn around — else, it's a dead end. go back. +1. turn right : is there an opening to my right? take it. +2. go straight : else, is the way ahead open? take it. +3. turn left : else, is there an opening left? take it. +4. turn around : else, it's a dead end. go back. ``` -That's the whole idea behind **"keep your right hand on the wall."** And look at -what it does to the jitter: "turn around" is now **dead last**, so the robot only -reverses at a true dead end — never on the very next step. Because "right" and -"straight" are measured from a heading the robot *remembers* between steps, it -hugs the wall and keeps moving instead of bouncing in place. That single -remembered fact — its facing — is the *only* thing it adds to the naive rule. No -map, no list of visited cells, no idea where the goal is. Press **Run wall -follower**: +That is the whole idea behind **"keep your right hand on the wall."** Look at what it does to the jitter: "turn around" is now **dead last**, so the robot only reverses at a true dead end, never on the very next step. Because "right" and "straight" are measured from a heading the robot *remembers* between steps, it hugs the wall and keeps moving instead of bouncing in place. That single remembered fact, its facing, is the *only* thing it adds to the naive rule. No map, no list of visited cells, no idea where the goal is. Press **Run wall follower**: ```maze solver: wall @@ -148,35 +98,17 @@ solver: wall ## Why it works -Here's the surprising part. The walls of this maze aren't a scattering of -separate obstacles — they're all **one single connected piece**. The generator -carved the maze by knocking out walls without ever sealing off a loop, so what's -left is one continuous wall with no islands (mazes like this are called *simply -connected*, or "perfect" mazes). - -Now picture tracing your finger along the edge of one connected shape — say, the -outline of a single puzzle piece. Keep going and you always come back around; you -can't get stranded, because there's only one border to follow. The wall follower -does exactly that: it traces the boundary of that one giant wall. Since the start -and the goal both sit on that same connected boundary, faithfully following it -**must** eventually walk the robot from one to the other. It might wander down -dead ends and back out — but it can never get permanently lost. - -That's why the naive rule fails and this one doesn't: it isn't luck, it's the -memory. Facing is just enough state to keep the robot *committed to a wall* -rather than making the same local choice from scratch each time. - -But "works" still isn't "good." The wall follower cheerfully explores every dead -end, and the path it finds is usually far from the **shortest** one. And the -whole guarantee rests on that one assumption — one connected wall. Add a loop to -the maze, a wall island floating in the middle, and the robot can circle that -island forever, hugging a border that never touches the goal. For our perfect -mazes, though, it always gets there. +Here is the surprising part. The walls of this maze are not a scattering of separate obstacles. They are all **one single connected piece**. The generator carved the maze by knocking out walls without ever sealing off a loop, so what is left is one continuous wall with no islands (mazes like this are called *simply connected*, or "perfect" mazes). + +Now picture tracing your finger along the edge of one connected shape, like the outline of a single puzzle piece. Keep going and you always come back around. You cannot get stranded, because there is only one border to follow. The wall follower does that: it traces the boundary of that one giant wall. Since the start and the goal both sit on that same connected boundary, following it **must** eventually walk the robot from one to the other. It might wander down dead ends and back out, but it can never get permanently lost. + +That is why the naive rule fails and this one does not. It is not luck, it is memory. Facing is just enough state to keep the robot *committed to a wall* rather than making the same local choice from scratch each time. + +Still, "works" is not the same as "good." The wall follower explores every dead end, and the path it finds is usually far from the **shortest** one. And the whole guarantee rests on one assumption: one connected wall. Add a loop to the maze, a wall island floating in the middle, and the robot can circle that island forever, hugging a border that never touches the goal. For our perfect mazes, though, it always gets there. ## The same skeleton, over and over -Look back at all three robots and you'll see they're built from the *same loop* — -they only disagree about one step: +Look back at all three robots and you will see they are built from the *same loop*. They only disagree about one step: ```text start at the green cell @@ -186,25 +118,12 @@ repeat until you reach the red cell: step that way (move) ``` -Everything interesting lives in that middle line — **"choose one."** Random rolls -a die there; the naive rule reads a fixed list; the wall follower consults its -remembered heading. Swap in a smarter "decide" and you get smarter algorithms: - -- **Wall follower** — "keep your right hand on the wall." One remembered fact, - and it clears any perfect maze. -- **Depth-first search** — "keep pushing into new cells; when you hit a dead end, - back up to the last spot with an untried opening and try that." (Fun fact: this - maze was *built* by that exact idea, running in reverse.) -- **Breadth-first search** — "explore all the cells one step away, then all the - cells two steps away…" — more to write, but it finds the *shortest* path. - -Same skeleton — **sense, decide, move, repeat** — every time, differing only in -"decide." That skeleton is the shape of an enormous amount of robot code: read -your sensors, decide what to do, act, and loop. - -So far this has all been visual — you drove the robot, you watched the three -robots run. But the whole promise of an algorithm is that it's a plan precise -enough to *hand to a computer*. Over the next few lessons you'll do exactly that: -first see the maze as plain **data** a program can hold, then meet the **robot** -your Java code gets to drive, and finally write the wall follower yourself and -watch *your* code solve a maze. +Everything interesting lives in that middle line: **"choose one."** Random rolls a die there, the naive rule reads a fixed list, and the wall follower checks its remembered heading. Swap in a smarter "decide" and you get smarter algorithms: + +- **Wall follower.** "Keep your right hand on the wall." One remembered fact clears any perfect maze. +- **Depth-first search.** "Keep pushing into new cells; when you hit a dead end, back up to the last spot with an untried opening and try that." Fun fact: this maze was *built* by that exact idea, running in reverse. +- **Breadth-first search.** "Explore all the cells one step away, then all the cells two steps away." More to write, and it finds the *shortest* path. + +Same skeleton every time: **sense, decide, move, repeat**, differing only in "decide." That skeleton is the shape of a huge amount of robot code: read your sensors, decide what to do, act, and loop. + +So far this has all been visual. You drove the robot and watched three robots run. The whole promise of an algorithm is that it is a plan precise enough to *hand to a computer*. Over the next few lessons you will do that: first see the maze as plain **data** a program can hold, then meet the **robot** your Python code gets to drive, and finally write the wall follower yourself and watch *your* code solve a maze.