s LearnSqueak.com

EASY · PRACTICAL · CHALLENGE

The practice lab

Thirty hands-on exercises: one easy, one practical and one challenge after each tutorial. Try the task first, reveal hints gradually, then compare the runnable solution and its checks.

30 exercises90 progressive hints113 assertions

Practice deliberately, then compare

  1. Use a fresh Squeak 6.1 image or a copy of your learning image.
  2. Load the prerequisite files listed for that exercise first. Most .st prerequisites use File List > fileIn. forms-setup.st is a Workspace expression: open it, select all, and do it.
  3. Open a Workspace. Paste the entire solution, including its temporary declaration or class setup, and choose do it (Ctrl+D on Windows/Linux, Command+D on macOS). Use print it for returned values or inspect it for returned models.
  4. Class-building solution snippets compile Exercise-prefixed subclasses and are meant to be evaluated in a Workspace, not installed as chunk file-ins. Run each complete snippet as one selection.
  5. To run a check, assign the solution’s final returned value to answer in a Workspace, then evaluate the test block with value: answer. The packaged verification harness executes these same snippets and tests automatically.
  6. Expected test outcome is true. A failed check raises an Error with the specific assertion message. Tests sometimes change sample state; media captions state when this happens.
  7. All supplied exercises are self-contained after their listed prerequisites and do not write application data files. Close generated sample windows and discard sample edits when appropriate.

Try the task before opening a solution. Hints reveal one at a time. Each solution is self-contained after its listed prerequisites; it can install Exercise-prefixed classes or create sample windows. Use a learning image.

Download all exercises, prerequisites and verifier

Choose your next challenge

30 exercises

language · easy

Price a tiny shopping basket

Convert prices in cents #(125 250 375) to a subtotal, add a 10% tax, and return a Dictionary with subtotal, tax and total in cents. Use exact arithmetic; do not convert to Float.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

Use inject:into: to accumulate the prices.

Hint 2

Store the three answers in a Dictionary using at:put:.

Hint 3

Tax is subtotal / 10; an Integer or Fraction keeps the calculation exact.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| prices subtotal tax |
prices := #(125 250 375).
subtotal := prices inject: 0 into: [:sum :price | sum + price].
tax := subtotal / 10.
Dictionary new
    at: #subtotal put: subtotal;
    at: #tax put: tax;
    at: #total put: subtotal + tax;
    yourself

Expected: Subtotal 750 cents, tax 75 cents, total 825 cents.

The currency unit is part of the model. Computing in cents avoids an unnecessary binary floating-point conversion.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    (answer at: #subtotal) = 750 ifFalse: [self error: 'Subtotal'].
    (answer at: #tax) = 75 ifFalse: [self error: 'Tax'].
    (answer at: #total) = 825 ifFalse: [self error: 'Total'].
    (answer at: #total) isInteger ifFalse: [self error: 'Keep cents exact'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

language · practical

Clean and deduplicate names

Given #(' ada ' 'GRACE' 'Ada' '' ' linus '), trim whitespace, remove empty entries, lowercase the remaining names, and return an alphabetically sorted unique Array.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

Transform every string with collect:.

Hint 2

Use reject: for empty strings and asSet to remove duplicates.

Hint 3

A Set has no useful display order: sort it before converting to an Array.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| names cleaned |
names := #(' ada ' 'GRACE' 'Ada' '' '  linus ').
cleaned := names collect: [:name | name withBlanksTrimmed asLowercase].
(cleaned reject: [:name | name isEmpty]) asSet asSortedCollection asArray

Expected: #('ada' 'grace' 'linus')

The pipeline makes each change explicit. Converting to a Set solves identity after normalization; sorting makes the result repeatable.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer = #('ada' 'grace' 'linus') ifFalse: [self error: 'Normalize, deduplicate and sort'].
    answer isArray ifFalse: [self error: 'Return an Array'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

language · challenge

Group words into a frequency table

Write a reusable block that counts case-insensitive whitespace-delimited words. Return a Dictionary for each input, ignore repeated spaces and line breaks, and handle the empty string. Punctuation stays attached to words in this version.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

Return a block taking one string, rather than hard-coding a single paragraph.

Hint 2

findTokens: accepts a String of delimiters. Include space, tab, CR and LF.

Hint 3

Use at:ifAbsent: to get zero for a new key, then store count + 1.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
[:text | | counts delimiters |
    counts := Dictionary new.
    delimiters := String with: Character space with: Character tab
        with: Character cr with: Character lf.
    (text asLowercase findTokens: delimiters) do: [:word |
        counts at: word put: (counts at: word ifAbsent: [0]) + 1].
    counts]

Expected: For 'Smalltalk smalltalk' plus a newline and 'Morphic': smalltalk -> 2, morphic -> 1; empty text gives an empty Dictionary.

A dictionary stores the aggregate rather than searching the whole collection repeatedly. This is whitespace tokenization, not linguistic word segmentation.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | counts |
    counts := answer value: 'Smalltalk smalltalk', String cr, 'Morphic'.
    (counts at: 'smalltalk') = 2 ifFalse: [self error: 'Case folding'].
    (counts at: 'morphic') = 1 ifFalse: [self error: 'Line break'].
    (answer value: '') isEmpty ifFalse: [self error: 'Empty input'].
    (answer value: '  a', String tab, 'a  ') size = 1 ifFalse: [self error: 'Whitespace'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

classes · easy

Give two counters separate jobs

Create a Laps counter starting at 3 and a Breaks counter starting at 0. Increment Laps twice and label Breaks “Rest breaks”. Return both in an Array and prove that changing one does not change the other.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearningCounter.st with File List > fileIn.
Hint 1

Send startingAt:label: to the class to create each object.

Hint 2

Use a cascade for the two increments.

Hint 3

Keep both instances in separate variables and return {laps. breaks}.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| laps breaks |
laps := LearningCounter startingAt: 3 label: 'Laps'.
breaks := LearningCounter startingAt: 0 label: 'Breaks'.
laps increment; increment.
breaks label: 'Rest breaks'.
{laps. breaks}

Expected: An Array containing Laps: 5 and Rest breaks: 0. Only Laps changes when you increment it again.

Instance variables belong to an individual object. Both counters have the same class and behavior, but their values are independent.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer first value = 5 ifFalse: [self error: 'Laps value'].
    answer second value = 0 ifFalse: [self error: 'Separate state'].
    answer second label = 'Rest breaks' ifFalse: [self error: 'Label'].
    answer first increment.
    answer second value = 0 ifFalse: [self error: 'No shared value'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

classes · practical

Reset to a configured starting value

Derive ExerciseResetCounter from LearningCounter. Add a startValue instance variable and startAt:. Its reset should restore the configured start instead of zero. Leave LearningCounter unchanged.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearningCounter.st with File List > fileIn.
Hint 1

Define the subclass before compiling methods into it.

Hint 2

Call super initialize, then initialize your additional state.

Hint 3

Store the starting value separately from the current value; reset reads only that stored value.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearningCounter subclass: #ExerciseResetCounter
    instanceVariableNames: 'startValue'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseResetCounter) compile: 'initialize
    super initialize.
    startValue := 0'.
(Smalltalk at: #ExerciseResetCounter) compile: 'startAt: aNumber
    aNumber isInteger ifFalse: [self error: ''Use a whole number''].
    startValue := aNumber.
    value := aNumber'.
(Smalltalk at: #ExerciseResetCounter) compile: 'reset
    value := startValue'.

[| counter |
counter := ExerciseResetCounter new.
counter startAt: 10; incrementBy: 5; reset.
counter] value

Expected: Resetting the subclass returns it to 10. A normal LearningCounter still starts at 0.

Inheritance supplies incrementBy: and printing. The override changes just reset, while the extra variable preserves the configured starting point.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer value = 10 ifFalse: [self error: 'Reset to configured start'].
    answer incrementBy: -3.
    answer value = 7 ifFalse: [self error: 'Inherited behavior'].
    answer reset.
    answer value = 10 ifFalse: [self error: 'Repeatable reset'].
    LearningCounter new value = 0 ifFalse: [self error: 'Base class unchanged'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

classes · challenge

Keep an object valid after rejected edits

Build a LearningCounter subclass whose value must stay from 0 through 10. Reject fractional increments and operations outside that range before changing state. Check both limits and prove a failed edit leaves the old value intact.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearningCounter.st with File List > fileIn.
Hint 1

Compute a candidate value before assigning to the instance variable.

Hint 2

Validate both the input type and candidate range.

Hint 3

Use an Error handler in tests to record a rejection, then assert the previous value is unchanged.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearningCounter subclass: #ExerciseBoundedCounter
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseBoundedCounter) compile: 'incrementBy: anInteger
    | candidate |
    anInteger isInteger ifFalse: [self error: ''Use a whole number''].
    candidate := value + anInteger.
    (candidate between: 0 and: 10)
        ifFalse: [self error: ''Counter must stay between 0 and 10''].
    value := candidate'.

ExerciseBoundedCounter startingAt: 8 label: 'Capacity'

Expected: 8 + 2 is 10; +1 fails and leaves 10. Subtracting 10 reaches 0; -1 and 1/2 fail and leave 0.

This is an object invariant. Validate before committing a new state so callers can safely recover from an error.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | rejected |
    answer incrementBy: 2.
    answer value = 10 ifFalse: [self error: 'Upper edge allowed'].
    rejected := false.
    [answer increment] on: Error do: [:error | rejected := true].
    (rejected and: [answer value = 10]) ifFalse: [self error: 'Upper rejection is atomic'].
    answer incrementBy: -10.
    answer value = 0 ifFalse: [self error: 'Lower edge allowed'].
    rejected := false.
    [answer incrementBy: -1] on: Error do: [:error | rejected := true].
    (rejected and: [answer value = 0]) ifFalse: [self error: 'Lower rejection is atomic'].
    rejected := false.
    [answer incrementBy: 1/2] on: Error do: [:error | rejected := true].
    (rejected and: [answer value = 0]) ifFalse: [self error: 'Reject fractions'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

morphic · easy

Compose a reusable status badge

Build a 360-by-110 card containing a green dot, a title and a subtitle. Position the children relative to the card, open it, then move the entire card. Return the card so you can inspect its submorphs.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

A parent Morph owns and moves its children.

Hint 2

Add each child before positioning it relative to the parent.

Hint 3

Use StringMorph contents: for labels and EllipseMorph for the status dot.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| card dot title subtitle |
card := Morph new color: (Color gray: 0.94); extent: 360@110.
dot := EllipseMorph new color: Color green darker; extent: 24@24.
title := StringMorph contents: 'All systems ready'.
subtitle := StringMorph contents: 'Three native Morphic children'.
card addMorph: dot; addMorph: title; addMorph: subtitle.
dot position: card position + (18@24).
title position: card position + (58@24).
subtitle position: card position + (58@56).
card openInWorld; position: 80@80.
card

Expected: A card with a green dot and two labels. Moving the parent preserves the three child offsets.

Composition gives the object a lifetime and coordinate system. You do not need to move each child separately.

NATIVE SQUEAK CAPTURE
Compose a reusable status badge solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | before child |
    answer extent = (360@110) ifFalse: [self error: 'Card size'].
    answer submorphs size = 3 ifFalse: [self error: 'Child count'].
    child := answer submorphs first.
    before := child position - answer position.
    answer position: answer position + (35@20).
    child position - answer position = before ifFalse: [self error: 'Relative placement'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

morphic · practical

Wire a button to an object

Create a model that owns a count and a label. Build a Count one button whose target/action sends increment to that model, and update the label after each click. Keep the count in the model, not in the label text.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

SimpleButtonMorph needs target: and actionSelector:.

Hint 2

Store count as an Integer; construct the display string from it.

Hint 3

The increment method must change both the value and the visible label.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
Model subclass: #ExerciseCounterPanel
    instanceVariableNames: 'count label'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseCounterPanel) compile: 'initialize
    super initialize.
    count := 0'.
(Smalltalk at: #ExerciseCounterPanel) compile: 'count
    ^ count'.
(Smalltalk at: #ExerciseCounterPanel) compile: 'increment
    count := count + 1.
    label ifNotNil: [label contents: ''Clicks: '', count printString]'.
(Smalltalk at: #ExerciseCounterPanel) compile: 'open
    | panel button |
    panel := Morph new color: (Color gray: 0.93); extent: 340@150.
    label := StringMorph contents: ''Clicks: '', count printString.
    button := SimpleButtonMorph new label: ''Count one'';
        target: self; actionSelector: #increment; extent: 140@40.
    panel addMorph: label; addMorph: button.
    label position: panel position + (24@24).
    button position: panel position + (24@70).
    panel openInWorld.
    ^ panel'.

[| model panel |
model := ExerciseCounterPanel new.
panel := model open.
{model. panel}] value

Expected: Each click adds one. After the test sends three native button actions the label reads Clicks: 3.

Target/action is the connection between a UI event and model behavior. The test invokes the native button action without pretending to be a recorded click.

NATIVE SQUEAK CAPTURE
Wire a button to an object solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | model panel button |
    model := answer first. panel := answer second.
    button := panel submorphs detect: [:each | each isKindOf: SimpleButtonMorph].
    button doButtonAction. button doButtonAction. button doButtonAction.
    model count = 3 ifFalse: [self error: 'Button target/action'].
    (panel submorphs anySatisfy: [:each | (each isKindOf: StringMorph)
        and: [each contents = 'Clicks: 3']]) ifFalse: [self error: 'View update'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

morphic · challenge

Bounce inside a moving parent

Create a ball with velocity and step. Keep its entire extent inside a parent rectangle, reverse the relevant velocity component at each boundary, and work correctly after the parent is moved. Leave animation paused until the learner explicitly starts stepping.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

Compare against owner position and owner bottomRight, not the desktop origin.

Hint 2

Subtract the ball extent from the owner’s far corner.

Hint 3

Clamp the proposed position to the legal rectangle, then reverse only the components that hit a boundary.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
EllipseMorph subclass: #ExerciseBouncingDot
    instanceVariableNames: 'velocity'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseBouncingDot) compile: 'initialize
    super initialize.
    self color: Color orange; extent: 26@26.
    velocity := 5@3'.
(Smalltalk at: #ExerciseBouncingDot) compile: 'velocity
    ^ velocity'.
(Smalltalk at: #ExerciseBouncingDot) compile: 'velocity: aPoint
    velocity := aPoint'.
(Smalltalk at: #ExerciseBouncingDot) compile: 'stepTime
    ^ 30'.
(Smalltalk at: #ExerciseBouncingDot) compile: 'step
    | next dx dy low high |
    self owner ifNil: [^ self].
    low := self owner position.
    high := self owner bottomRight - self extent.
    next := self position + velocity.
    dx := velocity x. dy := velocity y.
    (next x < low x or: [next x > high x]) ifTrue: [dx := dx negated].
    (next y < low y or: [next y > high y]) ifTrue: [dy := dy negated].
    self position: ((next x max: low x) min: high x)
        @ ((next y max: low y) min: high y).
    velocity := dx@dy'.

[| arena ball |
arena := Morph new color: (Color r: 0.08 g: 0.13 b: 0.22); extent: 400@220.
ball := ExerciseBouncingDot new.
arena addMorph: ball.
ball position: arena position + (30@40).
arena openInWorld.
ball stopStepping.
{arena. ball}] value

Expected: The ball remains entirely inside the arena for 201 deterministic steps, including a corner bounce after moving the parent. To animate, send startStepping to the ball; send stopStepping before closing.

This intentionally clamps at a wall rather than preserving overshoot distance. Keep the arena larger than the ball. Motion uses Morphic stepping, not a separately forked loop.

Scope: A small clamped animation exercise, not continuous collision physics.

NATIVE SQUEAK CAPTURE
Bounce inside a moving parent solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
NATIVE SQUEAK CAPTURE
Native ball bounces inside its Morphic parent
Programmatic native-render demonstration: the verifier calls step twice per frame. These are real Morphic imageForm frames, not recorded mouse input or a real-time performance benchmark.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | arena ball |
    arena := answer first. ball := answer second.
    arena position: 130@80.
    ball position: arena bottomRight - ball extent - (1@1).
    ball velocity: 5@3. ball step.
    (ball velocity x < 0 and: [ball velocity y < 0]) ifFalse: [self error: 'Corner bounce'].
    1 to: 200 do: [:ignored | ball step.
        (arena bounds containsRect: ball bounds) ifFalse: [self error: 'Remain inside owner']].
    ball stopStepping.
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

forms · easy

Add a greeting option

Derive a form with a fourth greeting, Good evening. Select it, accept a name with leading/trailing spaces, and display the greeting. Preserve the base form’s checkbox, slider and reset behavior.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load forms-setup.st as one Workspace expression.
Hint 1

Override the choices method in a subclass.

Hint 2

List selections are one-based indices.

Hint 3

The existing acceptName: trims spaces and greet reads the selection.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearnSqueakFormDemo subclass: #ExerciseGreetingForm
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseGreetingForm) compile: 'choices
    ^ #(''Hello'' ''Welcome'' ''Good morning'' ''Good evening'')'.

[| model |
model := ExerciseGreetingForm new.
model acceptName: '  Ada  '; choice: 4; greet.
{model. model open}] value

Expected: The fourth list item produces Good evening, Ada.; turning on uppercase produces GOOD EVENING, ADA.

One override extends a data-driven control. The inherited list reads choices dynamically.

NATIVE SQUEAK CAPTURE
Add a greeting option solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | model |
    model := answer first.
    model choices size = 4 ifFalse: [self error: 'Fourth choice'].
    model result = 'Good evening, Ada.' ifFalse: [self error: 'Greeting and trim'].
    model toggleLoud; greet.
    model result = 'GOOD EVENING, ADA.' ifFalse: [self error: 'Checkbox still applies'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

forms · practical

Reject invalid input without losing the last good value

Validate names before accepting them. Empty/whitespace-only names and names longer than 40 characters must return false, show an explanation, and keep the previously accepted name.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load forms-setup.st as one Workspace expression.
Hint 1

Work with a proposed value first.

Hint 2

PluggableTextMorph’s accept callback returns a Boolean.

Hint 3

On rejection update result and announce changed: #result, but do not assign the name.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearnSqueakFormDemo subclass: #ExerciseValidatedForm
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseValidatedForm) compile: 'acceptName: aText
    | proposed |
    proposed := aText asString withBlanksTrimmed.
    (proposed isEmpty or: [proposed size > 40]) ifTrue: [
        result := ''Use a name from 1 to 40 characters.''.
        self changed: #result.
        ^ false].
    ^ super acceptName: proposed'.

[| model | model := ExerciseValidatedForm new. {model. model open}] value

Expected: Grace is accepted. Blank and 41-character names are rejected, leave Grace in the model, and show the 1-to-40-character message.

Validation is a transaction: decide first, assign second. The old valid state survives rejected edits.

NATIVE SQUEAK CAPTURE
Reject invalid input without losing the last good value solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | model |
    model := answer first.
    (model acceptName: 'Grace') ifFalse: [self error: 'Accept valid name'].
    (model acceptName: '   ') ifTrue: [self error: 'Reject blank'].
    model nameText = 'Grace' ifFalse: [self error: 'Preserve accepted name'].
    (model acceptName: (String new: 41 withAll: $x)) ifTrue: [self error: 'Length limit'].
    model nameText = 'Grace' ifFalse: [self error: 'Preserve after long input'].
    (model result includesSubstring: '1 to 40') ifFalse: [self error: 'Visible explanation'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

forms · challenge

Build a temperature converter

Create a native window with an accepted Celsius field, a Convert button and read-only Fahrenheit output. Accept whole numbers, including negatives, and display a helpful error for invalid input. Parse data without compiling input as code.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

Separate inputText/acceptInput: from outputText.

Hint 2

Check the optional minus sign and remaining digits before asNumber.

Hint 3

Use a read-only PluggableTextMorph and changed: #outputText to refresh output.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
Model subclass: #ExerciseTemperatureForm
    instanceVariableNames: 'input output window'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseTemperatureForm) compile: 'initialize
    super initialize.
    input := ''20''. output := ''Press Convert.'''.
(Smalltalk at: #ExerciseTemperatureForm) compile: 'inputText
    ^ input'.
(Smalltalk at: #ExerciseTemperatureForm) compile: 'outputText
    ^ output'.
(Smalltalk at: #ExerciseTemperatureForm) compile: 'acceptInput: aText
    input := aText asString withBlanksTrimmed.
    ^ true'.
(Smalltalk at: #ExerciseTemperatureForm) compile: 'convert
    | digits fahrenheit |
    digits := input.
    (digits notEmpty and: [digits first = $-]) ifTrue: [digits := digits allButFirst].
    (digits isEmpty or: [(digits allSatisfy: [:c | c between: $0 and: $9]) not])
        ifTrue: [output := ''Enter a whole number, for example -10.'' ]
        ifFalse: [fahrenheit := (input asNumber * 9 / 5) + 32.
            output := fahrenheit printString, '' degrees F''].
    self changed: #outputText'.
(Smalltalk at: #ExerciseTemperatureForm) compile: 'open
    | entry display button |
    window := SystemWindow new model: self; setLabel: ''Whole-degree temperature converter''.
    entry := PluggableTextMorph on: self text: #inputText accept: #acceptInput:.
    entry acceptOnCR: true; wrapFlag: false.
    display := PluggableTextMorph on: self text: #outputText accept: nil.
    display readOnly: true.
    button := SimpleButtonMorph new label: ''Convert''; target: self; actionSelector: #convert.
    window addMorph: (StringMorph contents: ''Celsius: type a whole number, then press Enter'')
        frame: (0.04@0.03 corner: 0.96@0.16).
    window addMorph: entry frame: (0.04@0.20 corner: 0.63@0.40).
    window addMorph: button frame: (0.68@0.20 corner: 0.96@0.40).
    window addMorph: display frame: (0.04@0.48 corner: 0.96@0.91).
    window openInWorld; extent: 580@240.
    ^ window'.

[| model | model := ExerciseTemperatureForm new. model convert. {model. model open}] value

Expected: 20 °C becomes 68 degrees F and -40 °C becomes -40 degrees F. Invalid text shows an explanation; entering 20 recovers.

This deliberately supports whole-degree inputs only, and the field must be accepted with Enter before Convert. Some inputs produce exact Fraction output, which is valid for this model; decimal formatting is a further exercise.

NATIVE SQUEAK CAPTURE
Build a temperature converter solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | model |
    model := answer first.
    model outputText = '68 degrees F' ifFalse: [self error: '20 C'].
    model acceptInput: '-40'; convert.
    model outputText = '-40 degrees F' ifFalse: [self error: 'Negative input'].
    model acceptInput: 'abc'; convert.
    (model outputText beginsWith: 'Enter a whole number') ifFalse: [self error: 'Invalid input'].
    model acceptInput: '-'; convert.
    (model outputText beginsWith: 'Enter a whole number') ifFalse: [self error: 'Bare minus'].
    model acceptInput: '20'; convert.
    model outputText = '68 degrees F' ifFalse: [self error: 'Recovery'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

calculator · easy

Replay a receipt calculation

Use the calculator model’s press: protocol to compute (12 + 7) * 3. Return each intermediate display string so you can see immediate-execution behavior.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakCalculatorModel.st with File List > fileIn.
Hint 1

Each token is a String, including operators and equals.

Hint 2

collect: can capture the display after every press.

Hint 3

This calculator executes pending operations as you select the next operator.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| model tokens |
model := LearnSqueakCalculatorModel new.
tokens := #('1' '2' '+' '7' '*' '3' '=').
tokens collect: [:token | model press: token]

Expected: #('1' '12' '12' '7' '19' '3' '57')

The * press first finishes 12 + 7. This is a pocket calculator’s immediate-execution model; it does not parse an expression with multiplication precedence.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer = #('1' '12' '12' '7' '19' '3' '57') ifFalse: [self error: 'Immediate execution trace'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

calculator · practical

Exercise recovery paths

Build a reusable token-replay block. Use it to check three behaviors: CE replaces only the current operand, a digit recovers from division by zero, and repeated equals repeats the last operation.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakCalculatorModel.st with File List > fileIn.
Hint 1

Return a block that creates a fresh model for each token array.

Hint 2

CE and C have different meanings.

Hint 3

Test full sequences, because the same token can act differently after an error or completed result.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
[:tokens | | model |
    model := LearnSqueakCalculatorModel new.
    tokens do: [:token | model press: token].
    model display]

Expected: 8 + 9 CE 2 = gives 10; 8 / 0 = shows Error; then 4 starts fresh; 2 + 3 = = = gives 11.

Testing transitions is more revealing than checking isolated additions. Each replay starts from a fresh instance to avoid order-dependent tests.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    (answer value: #('8' '+' '9' 'CE' '2' '=')) = '10' ifFalse: [self error: 'CE keeps pending addition'].
    (answer value: #('8' '/' '0' '=')) = 'Error' ifFalse: [self error: 'Zero divisor'].
    (answer value: #('8' '/' '0' '=' '4')) = '4' ifFalse: [self error: 'Digit recovery'].
    (answer value: #('2' '+' '3' '=' '=' '=')) = '11' ifFalse: [self error: 'Repeated equals'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

calculator · challenge

Undo by replaying commands

Wrap the calculator model with a token history and undo. Undo removes exactly the last button press and rebuilds the model by replaying the remaining tokens. Preserve the model’s decimal and error behavior without copying its private variables.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakCalculatorModel.st with File List > fileIn.
Hint 1

Use composition: your wrapper owns one calculator model.

Hint 2

Rebuilding from the command log avoids partial snapshots of private state.

Hint 3

Return a copy of history so callers cannot remove your internal tokens.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
Object subclass: #ExerciseUndoCalculator
    instanceVariableNames: 'model tokens'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseUndoCalculator) compile: 'initialize
    super initialize.
    model := LearnSqueakCalculatorModel new.
    tokens := OrderedCollection new'.
(Smalltalk at: #ExerciseUndoCalculator) compile: 'press: aToken
    tokens add: aToken copy.
    ^ model press: aToken'.
(Smalltalk at: #ExerciseUndoCalculator) compile: 'display
    ^ model display'.
(Smalltalk at: #ExerciseUndoCalculator) compile: 'history
    ^ tokens copy'.
(Smalltalk at: #ExerciseUndoCalculator) compile: 'undo
    tokens ifNotEmpty: [tokens removeLast].
    model := LearnSqueakCalculatorModel new.
    tokens do: [:token | model press: token].
    ^ model display'.

[| calculator | calculator := ExerciseUndoCalculator new. #('1' '2' '+' '3' '=') do: [:token | calculator press: token]. calculator] value

Expected: 12 + 3 = is 15. Undo once shows 3; undo again shows 12. Entering 4 = then gives 16. Repeated undo safely reaches 0.

This is a tested model extension, with no Undo button added to the tutorial’s calculator window. Command replay is easy to reason about for a small history; very long histories would need checkpoints or bounded storage.

Scope: Headless undo model. Adding a UI button and mapping keyboard shortcuts are optional extensions.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | copy |
    answer display = '15' ifFalse: [self error: 'Initial result'].
    answer undo = '3' ifFalse: [self error: 'Undo equals'].
    answer undo = '12' ifFalse: [self error: 'Undo operand'].
    answer press: '4'; press: '='.
    answer display = '16' ifFalse: [self error: 'Branch after undo'].
    copy := answer history. copy removeAll.
    answer history isEmpty ifTrue: [self error: 'Defensive history copy'].
    1 to: 10 do: [:ignored | answer undo].
    answer display = '0' ifFalse: [self error: 'Undo past start'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

notepad · easy

Count words in the live buffer

Extend the status bar with a whitespace-delimited word count. It must count unaccepted editor text, treat tabs/newlines as separators, and return zero for blank text. Do not save any files.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load MorphicNotepad.st with File List > fileIn.
Hint 1

Use currentText instead of text so unaccepted edits count.

Hint 2

Split on spaces, tabs, CR and LF.

Hint 3

Override statusText by appending to super statusText.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
MorphicNotepad subclass: #ExerciseWordCountNotepad
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseWordCountNotepad) compile: 'wordCount
    | delimiters |
    delimiters := String with: Character space with: Character tab
        with: Character cr with: Character lf.
    ^ (self currentText findTokens: delimiters) size'.
(Smalltalk at: #ExerciseWordCountNotepad) compile: 'statusText
    ^ super statusText, ''  |  '', self wordCount printString, '' words'''.

[| app | app := ExerciseWordCountNotepad open. app editor setText: 'Smalltalk makes live objects'. app noteTextEdited: app currentText. app] value

Expected: The live text Smalltalk makes live objects displays 4 words. Accepting or saving the editor is not required.

This is a whitespace count, not a language-specific word counter. Punctuation attached to a token counts as part of the same word.

NATIVE SQUEAK CAPTURE
Count words in the live buffer solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
NATIVE SQUEAK CAPTURE
Native Notepad live-buffer word count changes from zero to four
Programmatic native-render demonstration: five editor buffers are set by code, then the real status bar is rendered. This does not depict a person typing.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer wordCount = 4 ifFalse: [self error: 'Live text count'].
    answer editor setText: 'one', String tab, 'two', String cr, 'three'.
    answer wordCount = 3 ifFalse: [self error: 'Mixed whitespace'].
    answer editor setText: '   '.
    answer wordCount = 0 ifFalse: [self error: 'Blank text'].
    answer editor setText: 'Smalltalk makes live objects'.
    answer noteTextEdited: answer currentText.
    (answer statusText includesSubstring: '4 words') ifFalse: [self error: 'Status bar'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close the sample Notepad window and choose Discard if you do not want to keep this generated sample text.

notepad · practical

Find and replace without marking edits saved

Add a case-sensitive find:startingAt: returning a one-based index or zero, and replaceAll:with: over the live buffer. Reject an empty search string. Preserve savedText so replacement leaves the document dirty.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load MorphicNotepad.st with File List > fileIn.
Hint 1

Search currentText rather than the last accepted model text.

Hint 2

A replacement is an edit: do not call replaceDocumentWith:named:, which marks text saved.

Hint 3

Update the model and visible editor, then refresh chrome.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
MorphicNotepad subclass: #ExerciseReplaceNotepad
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseReplaceNotepad) compile: 'find: aString startingAt: anIndex
    aString isEmpty ifTrue: [^ 0].
    ^ self currentText findString: aString startingAt: (anIndex max: 1)'.
(Smalltalk at: #ExerciseReplaceNotepad) compile: 'replaceAll: oldText with: newText
    | original updated |
    oldText isEmpty ifTrue: [self error: ''Search text must not be empty''].
    original := self currentText.
    updated := original copyReplaceAll: oldText with: newText.
    documentText := updated.
    editor ifNotNil: [editor setText: updated].
    self changed: #text.
    statusMessage := ''Replaced matching text''.
    self refreshChrome.
    ^ updated'.

[| app | app := ExerciseReplaceNotepad open. app editor setText: 'red bird, red boat'. app replaceAll: 'red' with: 'blue'. app] value

Expected: “red bird, red boat” becomes “blue bird, blue boat”; the next blue after index 1 is at 12. The window remains marked modified.

The solution provides tested commands callable from a Workspace or Inspector. It does not claim to include a Find dialog, selection highlighting, regex search, or one-step undo.

Scope: Case-sensitive, non-overlapping plain-text search and replacement commands. UI search controls are a separate extension.

NATIVE SQUEAK CAPTURE
Find and replace without marking edits saved solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | rejected before |
    answer currentText = 'blue bird, blue boat' ifFalse: [self error: 'Replace all occurrences'].
    answer isDirty ifFalse: [self error: 'Replacement remains unsaved'].
    (answer find: 'blue' startingAt: 2) = 12 ifFalse: [self error: 'Find next match'].
    (answer find: 'BLUE' startingAt: 1) = 0 ifFalse: [self error: 'Case-sensitive search'].
    before := answer currentText. rejected := false.
    [answer replaceAll: '' with: 'x'] on: Error do: [:error | rejected := true].
    (rejected and: [answer currentText = before]) ifFalse: [self error: 'Reject empty search safely'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close the sample window and choose Discard to remove the generated replacement text.

notepad · challenge

Launch independent document windows

Build a minimal launcher with a New document button. Each click opens a distinct MorphicNotepad instance with independent live text, dirty state and file name. Verify editing one does not edit the other. Explain what a complete multi-document application would still need.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load MorphicNotepad.st with File List > fileIn.
Hint 1

Keep an OrderedCollection of document models, not one shared documentText.

Hint 2

Let each existing Notepad own its window, buffer, path and close guard.

Hint 3

Do not treat closing the launcher as permission to discard the open documents.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
Model subclass: #ExerciseNotepadLauncher
    instanceVariableNames: 'documents window'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseNotepadLauncher) compile: 'initialize
    super initialize.
    documents := OrderedCollection new'.
(Smalltalk at: #ExerciseNotepadLauncher) compile: 'documents
    ^ documents copy'.
(Smalltalk at: #ExerciseNotepadLauncher) compile: 'newDocument
    | document |
    document := MorphicNotepad open.
    documents add: document.
    document window position: (60 + (documents size * 35)) @ (80 + (documents size * 25)).
    ^ document'.
(Smalltalk at: #ExerciseNotepadLauncher) compile: 'open
    | button |
    window := SystemWindow new model: self; setLabel: ''Multiple-window Notepad launcher''.
    button := SimpleButtonMorph new label: ''New document''; target: self; actionSelector: #newDocument.
    window addMorph: button frame: (0.05@0.20 corner: 0.95@0.70).
    window openInWorld; extent: 370@130.
    ^ window'.

[| launcher window first second |
launcher := ExerciseNotepadLauncher new. window := launcher open.
first := launcher newDocument. second := launcher newDocument.
first editor setText: 'Document one: independent text'.
second editor setText: 'Document two: independent text'.
first noteTextEdited: first currentText. second noteTextEdited: second currentText.
{launcher. window. first. second}] value

Expected: Two separate document windows initially contain different text. Editing the first leaves the second unchanged. The button opens a third, empty document.

This is a verified multiple-window launcher, not a full tabbed editor. A complete design needs document activation/listing, removal of closed models, unique untitled labels, tab or window navigation, Save All failure policy, and a coordinated Close All with per-document Save/Discard/Cancel. Existing Notepad save and close guards remain responsible for each window.

Scope: Tested minimal multiple-window launcher. Full multi-document navigation and coordinated closing remain a design challenge and are not represented as completed.

NATIVE SQUEAK CAPTURE
Launch independent document windows solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | launcher first second button |
    launcher := answer first. first := answer third. second := answer fourth.
    first == second ifTrue: [self error: 'Distinct instances'].
    first editor setText: 'Only the first changed'.
    first noteTextEdited: first currentText.
    second currentText = 'Document two: independent text' ifFalse: [self error: 'Independent buffers'].
    (first isDirty and: [second isDirty]) ifFalse: [self error: 'Separate dirty tracking'].
    (first fileName isNil and: [second fileName isNil]) ifFalse: [self error: 'Untitled files'].
    button := answer second submorphs detect: [:each | each isKindOf: SimpleButtonMorph].
    button doButtonAction.
    launcher documents size = 3 ifFalse: [self error: 'New document target/action'].
    launcher documents third currentText isEmpty ifFalse: [self error: 'New empty buffer'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close each generated Notepad separately, choosing Discard for sample text; then close the launcher. Closing the launcher does not close its documents.

wireframe · easy

Compare two projection modes

Create two same-sized cube morphs with the same angle. Render one orthographically and one in perspective, side by side. Check that the perspective version makes a point nearer the camera appear farther from screen center.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakWireframeCube.st with File List > fileIn.
Hint 1

Both cubes need the same extent and angle.

Hint 2

Projection acts on already rotated vertices.

Hint 3

Compare the distance from each cube center for the point #(1 0 1).

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| panel left right label |
panel := Morph new color: (Color gray: 0.92); extent: 850@390.
left := LearnSqueakWireframeCube new extent: 400@330; angleDegrees: 30; orthographic.
right := LearnSqueakWireframeCube new extent: 400@330; angleDegrees: 30; perspective.
panel addMorph: left; addMorph: right.
left position: panel position + (15@45).
right position: panel position + (435@45).
label := StringMorph contents: 'Orthographic'.
panel addMorph: label. label position: panel position + (30@15).
label := StringMorph contents: 'Perspective'.
panel addMorph: label. label position: panel position + (450@15).
panel openInWorld.
{panel. left. right}

Expected: Two native wireframes show the same rotation. A point at z = 1 has a larger screen offset with perspective.

Projection and object rotation are separate operations. This is a software wireframe using ordinary Morphic Canvas, not a GPU or full 3D engine.

NATIVE SQUEAK CAPTURE
Compare two projection modes solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | left right a b |
    left := answer second. right := answer third.
    left angle = right angle ifFalse: [self error: 'Equal angle'].
    a := ((left projectVertex: #(1 0 1)) - left center) r.
    b := ((right projectVertex: #(1 0 1)) - right center) r.
    b > a ifFalse: [self error: 'Near point enlarged in perspective'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

wireframe · practical

Draw an octahedron by changing data

Subclass the cube to draw an octahedron with six vertices and twelve edges. Keep the inherited rotation, projection and Canvas drawing. Make sure every edge references a valid vertex and no edge connects a point to itself.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakWireframeCube.st with File List > fileIn.
Hint 1

Place one point on each positive/negative coordinate axis.

Hint 2

Four equatorial edges form a diamond; connect both poles to its four corners.

Hint 3

Override only vertices and edges.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearnSqueakWireframeCube subclass: #ExerciseWireframeOctahedron
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseWireframeOctahedron) compile: 'vertices
    ^ #((1 0 0) (-1 0 0) (0 1 0) (0 -1 0) (0 0 1) (0 0 -1))'.
(Smalltalk at: #ExerciseWireframeOctahedron) compile: 'edges
    ^ #((1 3) (3 2) (2 4) (4 1)
        (5 1) (5 2) (5 3) (5 4)
        (6 1) (6 2) (6 3) (6 4))'.

ExerciseWireframeOctahedron new angleDegrees: 32; openInWorld; yourself

Expected: A rotating-ready six-vertex octahedron appears. Its rendering uses the same projection and drawing code as the cube.

Geometry is data. A shared rendering protocol makes a new shape a small change instead of a duplicated program.

NATIVE SQUEAK CAPTURE
Draw an octahedron by changing data solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer vertices size = 6 ifFalse: [self error: 'Six vertices'].
    answer edges size = 12 ifFalse: [self error: 'Twelve edges'].
    answer edges do: [:edge |
        ((edge first between: 1 and: 6) and: [edge second between: 1 and: 6])
            ifFalse: [self error: 'Valid indices'].
        edge first = edge second ifTrue: [self error: 'No self edge']].
    answer projectedVertices size = 6 ifFalse: [self error: 'Projection reused'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

wireframe · challenge

Make camera distance safe to edit

Add a cameraDistance: setter in a subclass. Accept distances greater than 2 and at most 20, reject invalid values before changing state, and compare perspective distortion at 2.5 and 12. Explain why greater than 2 keeps the cube in front of the camera at every rotation.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakWireframeCube.st with File List > fileIn.
Hint 1

The cube’s farthest vertex lies sqrt(3) from its center.

Hint 2

Override cameraDistance to return your new instance variable.

Hint 3

A positive denominator is a geometry invariant; validate before assigning.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearnSqueakWireframeCube subclass: #ExerciseCameraCube
    instanceVariableNames: 'distance'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseCameraCube) compile: 'initialize
    super initialize.
    distance := 5.0'.
(Smalltalk at: #ExerciseCameraCube) compile: 'cameraDistance
    ^ distance'.
(Smalltalk at: #ExerciseCameraCube) compile: 'projectionScale
    ^ (self width min: self height) / 6.0'.
(Smalltalk at: #ExerciseCameraCube) compile: 'cameraDistance: aNumber
    (aNumber isNumber and: [aNumber > 2 and: [aNumber <= 20]])
        ifFalse: [self error: ''Use a camera distance greater than 2 and at most 20''].
    distance := aNumber asFloat.
    self changed'.

[| panel near far |
panel := Morph new color: (Color gray: 0.92); extent: 850@390.
near := ExerciseCameraCube new extent: 400@330; angleDegrees: 35; cameraDistance: 2.5.
far := ExerciseCameraCube new extent: 400@330; angleDegrees: 35; cameraDistance: 12.
panel addMorph: near; addMorph: far.
near position: panel position + (15@45). far position: panel position + (435@45).
panel addMorph: (StringMorph contents: 'Camera 2.5').
panel submorphs first position: panel position + (30@15).
panel addMorph: (StringMorph contents: 'Camera 12').
panel submorphs first position: panel position + (450@15).
panel openInWorld. {panel. near. far}] value

Expected: Distance 2.5 produces stronger perspective than 12. Unsafe distance 1 is rejected without changing the current distance. All sampled rotations have positive projection denominators.

Rotation preserves distance from the origin. Since sqrt(3) < 2, a camera farther than 2 cannot intersect the unit cube. The proof covers all angles; the sampled test is an implementation check, not the proof.

NATIVE SQUEAK CAPTURE
Make camera distance safe to edit solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | near far rejected previous a b |
    near := answer second. far := answer third.
    a := ((near projectVertex: #(1 0 1)) - near center) r.
    b := ((far projectVertex: #(1 0 1)) - far center) r.
    a > b ifFalse: [self error: 'Near camera has stronger perspective'].
    previous := near cameraDistance. rejected := false.
    [near cameraDistance: 1] on: Error do: [:error | rejected := true].
    (rejected and: [near cameraDistance = previous]) ifFalse: [self error: 'Reject unsafe distance atomically'].
    0 to: 360 by: 15 do: [:degrees |
        near angleDegrees: degrees.
        near vertices do: [:vertex |
            near cameraDistance - (near rotateVertex: vertex) third > 0
                ifFalse: [self error: 'All vertices remain in front of camera']]].
    near angleDegrees: 35.
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

todo · easy

Summarize a task list

Create three sample tasks, complete the second, and compute total, complete and remaining counts from the model’s public tasks snapshot. Return the app and counts. Do not save the sample.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load MorphicTodo.st with File List > fileIn.
Hint 1

Add each task by accepting a draft and sending addTask.

Hint 2

The completion Boolean is the third field of each task record.

Hint 3

Select the second visible row before toggleComplete.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| app snapshot complete |
app := MorphicTodo new.
#('Read the lesson' 'Try the exercise' 'Explain the result') do: [:title |
    app acceptDraft: title; addTask].
app selection: 2; toggleComplete.
snapshot := app tasks.
complete := snapshot count: [:task | task third].
app open; refresh.
{app. snapshot size. complete. snapshot size - complete}

Expected: Three tasks, one complete, two remaining. The native list marks Try the exercise complete.

The tasks accessor returns a snapshot. Read-only summary code should not mutate internal records.

NATIVE SQUEAK CAPTURE
Summarize a task list solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer allButFirst = #(3 1 2) ifFalse: [self error: 'Total, complete, remaining'].
    answer first tasks second third ifFalse: [self error: 'Second completed'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close the sample and choose to discard its unsaved generated tasks.

todo · practical

Search without confusing rows and IDs

Create a reusable case-insensitive title-search block taking a Todo model and query. Return matching task records without changing the model’s current filter or selection. Test an empty query and prove the returned records are safe copies.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load MorphicTodo.st with File List > fileIn.
Hint 1

Search model tasks, not the strings displayed by the list widget.

Hint 2

Normalize both query and title to lowercase.

Hint 3

Keep row indices local to the view; the first field is a stable task ID.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
[:model :query | | needle |
    needle := query withBlanksTrimmed asLowercase.
    model tasks select: [:task |
        needle isEmpty or: [task second asLowercase includesSubstring: needle]]]

Expected: Searching READ returns stable IDs 1 and 3 while selected ID 2 stays selected. Empty search returns all tasks.

This is a tested search command, not a new search widget. If you add a search field later, keep selection by ID and derive the visible row index after filtering.

Scope: Model-level search; optional UI wiring is not supplied.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | app matches selected |
    app := MorphicTodo new.
    #('Read Smalltalk' 'Build Morphic UI' 'Read tests') do: [:title | app acceptDraft: title; addTask].
    app selection: 2. selected := app selectedTask first.
    matches := answer value: app value: ' READ '.
    (matches collect: [:task | task first]) asArray = #(1 3) ifFalse: [self error: 'Case-insensitive matches'].
    app selectedTask first = selected ifFalse: [self error: 'Selection preserved'].
    (answer value: app value: '') size = 3 ifFalse: [self error: 'Empty query means all'].
    matches first at: 2 put: 'changed externally'.
    app tasks first second = 'Read Smalltalk' ifFalse: [self error: 'No mutation through results'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

todo · challenge

Merge validated JSON without partial changes

Add a merge command that validates the whole JSON document first, skips duplicate titles case-insensitively, assigns new local IDs, and commits all additions together. Preserve local data if any imported record is invalid. Import from the supplied string; no file access is required.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load MorphicTodo.st with File List > fileIn.
Hint 1

Reuse parseTasks: for the format and record validation.

Hint 2

Build additions in a temporary collection; do not add while validating.

Hint 3

Use local nextId values rather than trusting imported IDs, and check capacity before committing.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
MorphicTodo subclass: #ExerciseImportTodo
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseImportTodo) compile: 'mergeJSON: aString
    | incoming known additions nextCandidate |
    incoming := self parseTasks: aString.
    known := (tasks collect: [:task | task second asLowercase]) asSet.
    additions := OrderedCollection new.
    nextCandidate := nextId.
    incoming do: [:record |
        (known includes: record second asLowercase) ifFalse: [
            additions add: {nextCandidate. record second copy. record third}.
            known add: record second asLowercase.
            nextCandidate := nextCandidate + 1]].
    tasks size + additions size > 1000 ifTrue: [self error: ''Too many tasks''].
    nextCandidate > 1000000001 ifTrue: [self error: ''No task IDs remain''].
    tasks addAll: additions.
    nextId := nextCandidate.
    status := ''Imported '', additions size printString, '' new tasks''.
    self refresh.
    ^ additions size'.

[| app | app := ExerciseImportTodo new. app acceptDraft: 'Read lesson'; addTask. app mergeJSON: '{"version":1,"tasks":[[1,"READ LESSON",false],[2,"Build a UI",true]]}'. app open. app] value

Expected: The existing Read lesson is retained, READ LESSON is skipped, Build a UI is added with local ID 2, and a malformed import leaves all tasks unchanged.

This policy treats titles as the deduplication key, so equal titles intentionally merge. It does not synchronize edits or resolve conflicts by imported ID. Those need a different explicit data model.

NATIVE SQUEAK CAPTURE
Merge validated JSON without partial changes solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | before rejected added |
    answer taskCount = 2 ifFalse: [self error: 'Skip title duplicate'].
    answer tasks second = #(2 'Build a UI' true) ifFalse: [self error: 'New local ID and completion'].
    before := answer tasks asArray. rejected := false.
    [answer mergeJSON: '{"version":1,"tasks":[[5,"Good title",false],[6,"",false]]}']
        on: Error do: [:error | rejected := true].
    (rejected and: [answer tasks asArray = before]) ifFalse: [self error: 'Reject entire invalid import'].
    added := answer mergeJSON: '{"version":1,"tasks":[[99,"Next task",false],[100,"NEXT TASK",true]]}'.
    added = 1 ifFalse: [self error: 'Deduplicate incoming titles'].
    answer tasks last first = 3 ifFalse: [self error: 'Invalid import did not consume IDs'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close the sample and discard its generated unsaved task list.

debugging · easy

Fix a collection transformation

A student wrote “#(2 4 6) do: [:number | number squared]” and expected #(4 16 36). Explain the actual return value, replace the appropriate message, and return the transformed collection without changing the input.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

do: is for visiting elements for side effects.

Hint 2

The result of do: is the receiver, not a collection of block results.

Hint 3

Use collect: when each input must produce one output.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
| original transformed |
original := #(2 4 6).
transformed := original collect: [:number | number squared].
{original. transformed}

Expected: do: returns the original #(2 4 6). collect: returns #(4 16 36), leaving the input unchanged.

Inspect the receiver, selected message and returned value before changing code. A syntactically valid program can still ask the wrong question.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer first = #(2 4 6) ifFalse: [self error: 'Original preserved'].
    answer second = #(4 16 36) ifFalse: [self error: 'Collect transformation'].
    (#(2 4 6) do: [:number | number squared]) = #(2 4 6)
        ifFalse: [self error: 'Understand do: return value'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

debugging · practical

Handle the empty case deliberately

Write an average block that returns nil for an empty collection and an exact Number otherwise. Test integer and fractional results. Explain why rescuing every Error and returning zero would hide unrelated mistakes.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

The empty collection has no average; choose an explicit result.

Hint 2

Guard before dividing by size.

Hint 3

Use inject:into: and / to preserve Fraction results.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
[:numbers |
    numbers isEmpty
        ifTrue: [nil]
        ifFalse: [(numbers inject: 0 into: [:sum :number | sum + number]) / numbers size]]

Expected: Empty input returns nil, #(2 4 6) returns 4, #(1 2) returns 3/2, and #(-3 3) returns 0.

Nil means unavailable, while zero is a valid result. A broad Error handler would erase evidence of non-number input or an unrelated defect.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    (answer value: #()) isNil ifFalse: [self error: 'Explicit empty result'].
    (answer value: #(2 4 6)) = 4 ifFalse: [self error: 'Integer average'].
    (answer value: #(1 2)) = (3/2) ifFalse: [self error: 'Exact fractional average'].
    (answer value: #(-3 3)) = 0 ifFalse: [self error: 'Real zero differs from missing'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

debugging · challenge

Find and repair accidental aliasing

Create an inventory class with independent item collections. Copy incoming mutable strings and return copies of both the collection and its elements. Demonstrate that modifying an input string or a returned snapshot cannot corrupt stored data.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Only a standard Squeak 6.1 image is needed.
Hint 1

A fresh collection in initialize prevents sharing between instances.

Hint 2

Copying only the outer collection still shares mutable elements.

Hint 3

Test mutation through every reference that crosses the object boundary.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
Object subclass: #ExerciseSafeInventory
    instanceVariableNames: 'items'
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseSafeInventory) compile: 'initialize
    super initialize.
    items := OrderedCollection new'.
(Smalltalk at: #ExerciseSafeInventory) compile: 'add: aString
    items add: aString copy'.
(Smalltalk at: #ExerciseSafeInventory) compile: 'items
    ^ items collect: [:each | each copy]'.

[| first second name |
first := ExerciseSafeInventory new. second := ExerciseSafeInventory new.
name := 'Pencil' copy. first add: name.
{first. second. name}] value

Expected: Stored Pencil stays unchanged after the caller edits the input string and returned snapshot. A second inventory remains empty.

This is a concrete aliasing bug you can observe in two Inspectors. The copy policy is sufficient for strings; nested arbitrary objects would require an explicit deeper ownership policy.

Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | first second supplied snapshot |
    first := answer first. second := answer second. supplied := answer third.
    supplied at: 1 put: $X.
    first items first = 'Pencil' ifFalse: [self error: 'Copy on input'].
    snapshot := first items. snapshot first at: 1 put: $Y. snapshot add: 'Eraser'.
    first items asArray = #('Pencil') ifFalse: [self error: 'Copy collection and strings on output'].
    second items isEmpty ifFalse: [self error: 'Independent instances'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

breakout · easy

Create a slower practice serve

Subclass Breakout so every serve starts with velocity 100 @ -160. Keep scoring, lives, collision rules and restart behavior inherited. Verify restart reapplies the slower velocity.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakBreakout.st with File List > fileIn.
Hint 1

Override serve, not initialize alone, because losing a life serves again.

Hint 2

Call super serve to preserve the ball’s starting position.

Hint 3

Set only velocity after the inherited setup.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearnSqueakBreakout subclass: #ExercisePracticeBreakout
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExercisePracticeBreakout) compile: 'serve
    super serve.
    velocity := 100.0 @ -160.0'.

ExercisePracticeBreakout new openInWorld; yourself

Expected: The practice game starts with a slower upward serve. Restart restores three lives, zero score, and the practice velocity.

Choose the method matching the lifecycle event. Overriding only initialization would miss subsequent serves.

NATIVE SQUEAK CAPTURE
Create a slower practice serve solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer |
    answer ballVelocity = (100.0 @ -160.0) ifFalse: [self error: 'Practice serve'].
    answer ballPosition: 300@300 velocity: 250@250.
    answer restart.
    answer ballVelocity = (100.0 @ -160.0) ifFalse: [self error: 'Restart reuses serve'].
    (answer lives = 3 and: [answer score = 0]) ifFalse: [self error: 'Other reset behavior preserved'].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

breakout · practical

Design a shorter brick wall

Build an 18-brick layout with three rows and six columns, centered in the existing logical field. Reuse the original brick size and row spacing so drawing and collision code still work. Check every brick fits and no two bricks overlap.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakBreakout.st with File List > fileIn.
Hint 1

Use row and column loops with coordinates in the logical 640-by-460 space.

Hint 2

Six 65-wide bricks with five 8-unit gaps span 430 units.

Hint 3

Center that span at x = 320, so the first left edge is 105; use a symmetric layout and verify its center.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearnSqueakBreakout subclass: #ExerciseSmallWallBreakout
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseSmallWallBreakout) compile: 'buildBricks
    bricks := OrderedCollection new.
    0 to: 2 do: [:row |
        0 to: 5 do: [:column |
            bricks add: ((105 + (column * 73)) @ (100 + (row * 28)) extent: 65@19)]]'.

ExerciseSmallWallBreakout new openInWorld; yourself

Expected: An 18-brick wall spans x = 105 through 535, centered at 320, with no overlapping rectangles.

This test uses instVarNamed: as an Inspector-style diagnostic to inspect the fixture; production application code should prefer a deliberate query method. The three original row colors remain valid.

NATIVE SQUEAK CAPTURE
Design a shorter brick wall solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | bricks box |
    answer brickCount = 18 ifFalse: [self error: '18 bricks'].
    bricks := answer instVarNamed: 'bricks'.
    box := bricks first.
    bricks do: [:brick | box := box merge: brick.
        (answer field containsRect: brick) ifFalse: [self error: 'Brick inside field']].
    box center x = 320 ifFalse: [self error: 'Centered wall'].
    1 to: bricks size do: [:i | i + 1 to: bricks size do: [:j |
        ((bricks at: i) intersects: (bricks at: j)) ifTrue: [self error: 'No overlapping bricks']]].
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

breakout · challenge

Increase difficulty only after real hits

Increase ball velocity by 8% after a brick is actually removed, but cap the largest absolute component at 420 logical units/second. Empty collision checks must not accelerate it. Preserve collision direction changes and stop after the final brick.

Review the related tutorial · Download this topic’s exercises

Set up:

  • Load LearnSqueakBreakout.st with File List > fileIn.
Hint 1

Record score before invoking the inherited collision method.

Hint 2

A higher score proves a brick was removed; checking overlaps alone can count a hit twice.

Hint 3

Scale both components by the same factor, using min: to apply the speed cap.

Show tested solution and explanation
Complete Workspace solution · Do it / Print it as described
LearnSqueakBreakout subclass: #ExerciseSpeedBreakout
    instanceVariableNames: ''
    classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Exercises'.
(Smalltalk at: #ExerciseSpeedBreakout) compile: 'collideBrickOn: axis from: previous
    | oldScore peak factor |
    oldScore := score.
    super collideBrickOn: axis from: previous.
    score > oldScore ifTrue: [
        peak := velocity x abs max: velocity y abs.
        peak > 0 ifTrue: [
            factor := 1.08 min: (420.0 / peak).
            velocity := velocity * factor]]'.

ExerciseSpeedBreakout new openInWorld; yourself

Expected: No-hit checks preserve velocity. A hit changes upward -200 to downward +216. A later hit near the cap reaches 420, and removing the final brick still ends the game.

The cap is explicitly on the largest component, not total Euclidean speed. The inherited substep calculation uses that same maximum component to limit movement distance. This is a deterministic scripted collision test, not a play-through recording. The override forwards the previous axis coordinate so the base collision method can verify a directional face crossing rather than treating tangency as a hit.

NATIVE SQUEAK CAPTURE
Increase difficulty only after real hits solution rendered by native Squeak Morphic
Native Squeak 6.1 rendering of the supplied solution. State was set by the test script, not a recording of mouse or keyboard input.
Read the matching verification block
Test block · evaluate with value: answer after storing the solution result
[:answer | | before |
    answer bricks: {200@200 extent: 65@19. 400@200 extent: 65@19}.
    answer ballPosition: 300@300 velocity: 100@ -200.
    before := answer ballVelocity.
    answer collideBrickOn: #y from: 240.
    answer ballVelocity = before ifFalse: [self error: 'No hit means no acceleration'].
    answer ballPosition: 220@200 velocity: 100@ -200.
    answer collideBrickOn: #y from: 240.
    answer brickCount = 1 ifFalse: [self error: 'Remove one brick'].
    (answer ballVelocity y - 216.0) abs < 0.0001 ifFalse: [self error: 'Bounce and increase 8 percent'].
    answer ballPosition: 420@200 velocity: 300@ -410.
    answer collideBrickOn: #y from: 240.
    ((answer ballVelocity x abs max: answer ballVelocity y abs) - 420) abs < 0.0001
        ifFalse: [self error: 'Component cap'].
    (answer gameState = #won and: [answer running not]) ifFalse: [self error: 'Final brick still wins and stops'].
    answer restart.
    true]

The supplied VerifyAll.st runs each exact solution and matching block automatically. Follow the package README; do not run a one-argument test block without supplying its solution result.

Download solution · Download test block

Cleanup: No files are written. Close any sample windows when you finish; use a fresh image or remove only the Exercise-prefixed classes you installed if you want to undo class definitions.

What was tested

All 30 exact solutions passed in a combined native run and in 30 separate fresh-image runs using only each exercise’s listed prerequisites. The supplied checks contain 113 assertions. The extracted portable verifier also passed all 30 solutions.

The 17 screenshots and two GIFs are native Morphic renders arranged by the verification script. They demonstrate the tested objects and state; they are not mouse/keyboard recordings.

  • Media depicts programmatically arranged native UI states, not human interaction recordings.
  • Calculator undo and Todo search are model commands without new UI controls.
  • Notepad multi-document challenge is a tested minimal multiple-window launcher; tab management, Save All and coordinated Close All are explicitly left as design extensions.

Later architectural extensions are named explicitly. A tested command does not imply a completed toolbar or dialog. The multi-document Notepad challenge opens independent document windows; tabs and coordinated Save All remain separate design work.