Problem Solving with Scratch 🐱
การแก้ปัญหาด้วย Scratch
Make your own blocks (functions), combine conditions with and / or / not, and pass values into your blocks. Every example, activity and exercise below comes from the IPST textbook (book pp. 50–73).
🎯 Learning objectives จุดประสงค์ของบทเรียน
By the end of this chapter you can:
- ✅ Write Scratch programs that create functions (your own blocks).
- ✅ Write Scratch programs that use Boolean operators.
In this chapter: 3.1 Functions ฟังก์ชัน · 3.2 Boolean operators ตัวดำเนินการบูลีน · 3.3 Passing values to functions การรับค่าและส่งค่าให้ฟังก์ชัน
🎮 Starting problem
Learning media and games are application programs too. They help users learn and solve problems in an interesting way, and they are fun. You can use Scratch to build media and games and to solve problems easily, quickly and in an interesting way, and at the same time practise thinking systematically, step by step.
…with a main character, a cat that chases the mouse to score points, and maybe a special character that takes points away, how would you design how the game works?
- Cat: follows the arrow keys (or the mouse); when it touches the mouse → score +1.
- Mouse: appears at a random place, moves around, hides again when caught.
- Special character (e.g. a ball): when the cat touches it → score −1.
- Stage: START screen, score variable, a timer that ends the game.
Each bullet is a small job. In this chapter you will learn to make each job its own block (function), and to test conditions like “touching the mouse and time left”. You will build this game for real in the end-of-chapter activity.
📖 Review before you start ทบทวนความรู้ก่อนเรียน
Tick (✓) every statement that is correct.
Think about the steps of cleaning clothes you have worn, all the way to putting the clean clothes back in the wardrobe. What jobs are there?
- Sort: separate whites from colours.
- Wash: soak in detergent, scrub, rinse until clean.
- Dry: wring out, hang on the line, wait until dry.
- Fold or iron.
- Store: put each piece back in the wardrobe.
“Wash” happens again for every load, so if you wrote it once as a named job you could just say “Wash” each time. That is exactly what a function is.
You have already written Scratch programs that run in sequence, make choices and repeat, take input, show output and use operators and variables for simple maths. In this chapter you will write programs that use functions and Boolean operators, so you can solve problems more efficiently.
🃏 Key-term flashcards Tap to flip
3.1 Functions ฟังก์ชัน
A large program has many commands that do many jobs. If you write them all one after another, the program becomes hard to check and fix. If you group the commands into sub-programs that each do one specific job, it is easier to check and fix them, and you can reuse a sub-program in other programs that are similar.
Scratch has commands for making a subroutine โปรแกรมย่อย, also called a function ฟังก์ชัน. You give the function a name, which you use to call it, and you put the commands it should run inside it. Choose a name that matches the job, so it is easy to understand.
🧱 Creating a function การสร้างฟังก์ชัน
- Click the My Blocks category.
- Click Make a Block.
- The Make a Block window appears. Type the function name in the block (here:
myFunction) and click OK. - A block with the function's name appears, plus a define block, the function's header ส่วนหัวของฟังก์ชัน, in the script area.
- Drag the commands you want and snap them under the header.
📞 Calling a function การเรียกใช้งานฟังก์ชัน
Once the function exists, call it like this:
- Click the function block you want (in My Blocks).
- Drag it into the script area, e.g. under when green flag clicked.
When the flag is clicked, the sprite runs all the commands under define myFunction: it moves 100 steps and says “Hello myFunction” for 2 seconds.
Rebuilt: the definition
Rebuilt: the call
✏️ Renaming a function การแก้ไขชื่อฟังก์ชัน
- Right-click the function block you made and choose Edit.
- In the Make a Block window, change the name and click OK.
🗑️ Deleting a function การลบฟังก์ชัน
Right-click the function's define block and choose Delete Block, or drag the define block out of the script area back onto the block palette.
🍉 Example 3.1 · A watermelon-slicing game ตัวอย่างที่ 3.1 สร้างเกมตัดแตงโม
Make a simple watermelon-slicing game. When it starts, watermelons appear one at a time, each with a different size and position. When the player clicks a watermelon with the mouse, it shows as cut and the score goes up. If the player does not click it in time, the watermelon disappears.
Design the program by thinking about these sub-problems:
- How do you make watermelons appear on screen with different sizes and positions?
- How do you make a watermelon disappear after some time has passed?
- How do you know a watermelon was cut?
- How do you show a cut watermelon?
- How do you score when you cut one watermelon?
Make watermelons appear at random positions
Watermelons are made one at a time, each at a different random position, and each a different size.
Idea: split the work into sub-tasks: show a watermelon, and set the watermelon's size and position. The main program and each sub-task as flowcharts:
The program
Main program (Start)
- Line 1 sets the starting point: when the user clicks the green flag.
- Line 2 sets the starting position for showing the watermelon: x = 0, y = −100.
- Line 3 sets the watermelon sprite's size to its real size (100%).
- Line 4 calls the function
showMelonto show watermelons.
Function showMelon
- Line 1 declares the header of the function
showMelon. - Lines 2–5 repeat forever.
- Line 3 calls the function
setSizeAndPosto set the size and position of the watermelon sprite. - Line 4 makes a watermelon by cloning โคลน, copying the sprite with
create clone of myself, which means “clone the sprite running this command”: here, the watermelon. - Line 5 waits 1 second between watermelons (
wait 1 seconds).
Function setSizeAndPos
- Line 1 declares the header of the function
setSizeAndPos. - Line 2 sets the size to a random value from 20 to 100, as a percentage of the real size. For example, 30 shows the sprite at 30% of its real size (100%).
- Line 3 sets the x position to a random value from −180 to 180.
- Line 4 sets the y position to a random value from −150 to 150.
Result: many watermelons appear at different positions.
Lines 2 and 3 of the main program (go to x: 0 y: −100 and set size to 100 %). Before the very first clone is made, setSizeAndPos already gives the sprite a new random size and a new random x and y, so whatever lines 2–3 set is overwritten straight away. The main program could be just when flag clicked → showMelon.
🍉 Play it: Example 3.1 → Activity 3.1, step by step
This is the watermelon program running in the page. Choose how much of Activity 3.1 has been added, then press the green flag.
1. Write the program in Example 3.1, then:
- After clones are made, Scratch also has a block for deleting a clone. Search for the block that does this.
- Improve the program from 1) by adding commands to the part that makes clones, using the
when I start as a cloneblock, so that a watermelon the mouse touches is deleted. - Improve the program so it counts and shows a score whenever a watermelon is touched.
1) delete this clone, in the Control category (at the bottom, with when I start as a clone and create clone of).
2) and 3) The empty hexagon in the book's script needs a Boolean block. Create a variable score first:
The original sprite runs showMelon, and every copy runs the clone script by itself. Each clone waits in its own forever loop until the mouse touches it, then it adds 1 to the score and deletes itself. The game above runs exactly this logic when you choose “step 3”.
2. Design a drawing of something you want, e.g. a house, tree, flower, person or robot:
- Think about and split the drawing into parts. How many parts are there, what are they, and what does each part do?
- Design pseudocode or a flowchart for each part.
- Write the program you designed.
- trunk: a brown rectangle (repeat 2: move width, turn 90°, move height, turn 90°).
- leaves: a green triangle on top (repeat 3: move size, turn 120°), or three triangles stacked for a pine tree.
- tree (main function): go to the start, pen down, call
trunk, move to the top of the trunk, callleaves, pen up.
Same pattern as the house in Example 3.3: small functions for the parts, plus one function that puts the parts together.
3.2 Boolean operators ตัวดำเนินการบูลีน
You have already written programs that calculate with the maths operators + - * / and programs that check a condition with the comparison operators > < =. Now you will learn the Boolean operators, used when a program has more than one condition. They are shown in Table 3.1.
| Operator | Meaning | Example | Situation 1 | Situation 2 | Result |
|---|---|---|---|---|---|
| and และ true only if both are true | touching mouse-pointer | touching orange | true | ||
| touching mouse-pointer | touching blue | false | |||
| not touching mouse-pointer | touching orange | false | |||
| not touching mouse-pointer | touching pink | false | |||
| or หรือ true if at least one is true | count = 2 | mouse clicked | true | ||
| count = 1 | mouse not clicked | true | |||
| count = 5 | mouse clicked | true | |||
| count = 4 | mouse not clicked | false | |||
| not นิเสธ (ไม่ใช่) flips true ↔ false | green is touching orange | true | |||
| green is touching pink | false | ||||
🔀 Boolean lab: flip the inputs, watch the result
Each row is one block from Table 3.1. Toggle what is happening to the sprite and the result updates.
- Age is greater than or equal to 13.
- The score is less than 50 but more than 30.
- The day is not equal to 3.
- The mouse is clicked and touching the mouse-pointer.
- Love is not less than 80 but not more than 100.
Scratch has no ≥ or ≤ block, so “greater than or equal to” is built from > or = (exactly the hint on the monitor).
Other correct forms: (1) not (age < 13) or age > 12; (5) not (love < 80) and not (love > 100).
- Enter age 9.
- Enter age 16.
- Enter age 25.
- Change the operator
andtoorin line 5, then try ages 9, 16 and 25 in turn. Is the result different from usingand? Why?
| Age | age > 12 | age < 18 | with and | with or |
|---|---|---|---|---|
| 9 | false | true | false → BabyOrAdult | true → teenager |
| 16 | true | true | true → teenager | true → teenager |
| 25 | true | false | false → BabyOrAdult | true → teenager |
Yes, it is different. With or, every age gives “teenager”: any number is either greater than 12 or less than 18 (or both), so the condition can never be false. A range “between 12 and 18” needs and.
🎓 Example 3.2 · A grading program ตัวอย่างที่ 3.2 โปรแกรมตัดเกรด
A school runs a language-level test scored 0–100. A score of 80 or more is level “Very good” ดีมาก, 50–79 is “Fair” พอใช้, and below 50 is “Needs improvement” ปรับปรุง.
Pseudocode
- Input the test score
- If score ≥ 80 then
- show the message “Very good”
otherwise - if score ≥ 50 then 2.2.1 show “Fair”, otherwise 2.2.2 show “Needs improvement”
- show the message “Very good”
How it works
- Line 2 takes the score from the user and stores it in the variable
answer. - Line 3 stores the value of
answerin the variablescore. - Line 4 checks whether score ≥ 80 (
score > 80 or score = 80). If so, line 5 shows “Very good”. - Line 7 checks whether score ≥ 50. If so, line 8 shows “Fair”; if not, line 10 shows “Needs improvement”.
Example 3.2 expects scores of 0–100. What happens if the score is below 0 or above 100? Improve the program to cover those scores.
The original program still gives a level: −5 → “Needs improvement”, 120 → “Very good”. Neither is a real score. Check for invalid input first with or:
Tick “use the improved program” above and try −5 or 120.
1. Write the result of checking each condition. Choose, then press Check.
| No. | Block | Situation | Result |
|---|
2. Look at the program and the situations below, in order, and say what happens.
Sprite green's script
Sprite yellow's script
- 2.1 Move sprite green to touch sprites pink, yellow and Dinosaur1, in that order.
- 2.2 Move sprite yellow to touch sprites pink and green, in that order.
- 2.3 Move sprite yellow to touch sprites pink and green at the same time.
2.1 Touching pink: green's condition (green colour touching pink) is true → count goes up by 1 (count = 1) and green jumps back to (−12, 28). Touching yellow: nothing happens. Neither condition in either script is true. Touching Dinosaur1: green's colour touches the dinosaur's dark-teal colour → count = 2, and green jumps back again. Final count: 2.
2.2 Nothing changes (count stays 0). Yellow needs to touch pink and green at the same moment, and green's script only reacts to pink or teal, not yellow.
2.3 Now both of yellow's conditions are true together: it waits 0.2 s, count goes down by 1 (count = −1) and yellow jumps back to (134, 81). (If pink and green also touch each other in the squeeze, green's script adds 1 as well.)
3. Continue the program from Activity 3.1:
- 3.1 Add a costume for the watermelon: a watermelon cut in half.
- 3.2 When the mouse is clicked and touches the sprite, change to the cut-in-half costume.
- 3.3 Add features to make the game more interesting.
Ideas for 3.3: a timer that ends the game, a bomb sprite that takes points away, melons that fall instead of sitting still, a sound effect on each cut. The last option in the game on the 3.1 tab plays this version.
3.3 Passing values to functions การรับค่าและส่งค่าให้ฟังก์ชัน
When you make a function in Scratch, you can let it receive values called parameters พารามิเตอร์ to use inside the function. It can receive several. When you call the function you must send it the values it needs, called arguments อาร์กิวเมนต์. The number of arguments must equal the number of parameters, and they must be the same data type, for the function to work correctly.
define house (size)); the argument is the actual value you put in when calling it (house (100)).🧩 Creating a function with a parameter การสร้างฟังก์ชันที่มีพารามิเตอร์
- Click the My Blocks category.
- Click Make a Block. The Make a Block window appears.
- Type a name that matches the job. Here, try
house. - Click the kind of parameter you want:
- Add an input (number or text): the parameter takes a number or text.
- Add an input (boolean): the parameter takes a Boolean value, true or false.
- Add a label: text that appears in the function's header, to explain it more or act as a comment.
- Run without screen refresh: whether the screen is redrawn while the block runs.
- Click OK. The function's header appears and you can snap commands under it. A block with the same name also appears, ready to use.
If you make a function house whose parameters are the size of a house and the number of houses to build, what type should each parameter be?
Both are number or text inputs (round slots). Size and number of houses are numbers. A boolean input (hexagon) only holds true/false, so it cannot hold 100 or 3. The text “build many houses” is a label, not a parameter.
📤 Sending values to a function การส่งค่าให้ฟังก์ชัน
When you call a function that has parameters, you must send arguments to it as well. For example, send 100 to the function house: inside the function, size now means 100.
🏠 Example 3.3 · Draw our house ตัวอย่างที่ 3.3 โปรแกรมวาดบ้านของเรา
Idea: write a program that draws a house made of a wall and a roof, using 3 functions: one draws the wall, one draws the roof, and one puts the wall and roof together.
Function wall
Repeat 4 times: 1) move size units, 2) turn clockwise 90°.
Function roof
Repeat 3 times: 1) move size units, 2) turn clockwise 120°.
Function house
1) Call the wall function. 2) Call the roof function.
Where does the wall start: the bottom-left, bottom-right, top-left or top-right corner? After the roof is drawn, which way is the sprite facing?
The wall starts at the top-left corner. The sprite faces right (90) and turns clockwise, so it draws the top edge, then goes down the right side, along the bottom, and back up. The turn ↺ 180 makes it face left. After the roof's three 120° turns it ends back at the top-left corner, facing left (direction −90).
wall draws a square with side size. Line 1 declares the header of wall with the parameter size. Line 2 repeats lines 3–4 four times: line 3 moves size steps, line 4 turns clockwise 90°.
Note: to use a parameter inside the function, drag it out of the function's header.
roof draws an equilateral triangle with side size. Line 2 repeats lines 3–4 three times: line 3 turns clockwise 120°, line 4 moves size steps.
house: line 2 points the sprite right (90); line 3 calls wall, sending the argument size, to draw the body; line 4 turns anticlockwise 180° ready for the roof; line 5 calls roof with size.
Main program: line 2 clears the screen; line 3 sets the starting point x = −100, y = 0; line 4 puts the pen down; line 5 calls house, sending the size 100; line 6 lifts the pen.
🖊️ Scratch stage: run Example 3.3 (and the activities)
The stage uses Scratch's coordinates (x −240…240, y −180…180, direction 90 = right). Pick a program, change the arguments and press the green flag. The log shows every block call.
1. Plan how to improve the house program in Example 3.3 so it can draw as many houses as you specify, by answering:
- Which parts do you need to change?
- Do you need any new functions? If so, which?
- Write the program you designed.
2. Write a program that draws 5 overlapping hearts as in the picture, with a function myHeart that draws one heart.
Keep wall, roof and house as they are. Add one new function with two parameters: how many houses and how big. After each house the sprite is back at the top-left corner, so lift the pen, face right and move along to the next start.
Choose “street” on the stage above to run it.
A heart is two straight sides plus two half-circles. A half-circle is “repeat 18: move a little, turn 10°” (18 × 10° = 180°). Starting at the bottom tip:
Then the main program sets the pen colour, goes to each tip and calls myHeart (60) five times. Choose “five hearts” on the stage above to run it. Each half-circle has radius size ÷ 2, so its length is π × size ÷ 2, split into 18 small moves.
If you want to draw different shapes where you can set the side length, the angle and the number of repeats, how should you design the program?
Make one function with three parameters:
For a regular polygon with n sides, use times = n and angle = 360 ÷ n (square: 4 and 90; hexagon: 6 and 60). Try angle 144 with 5 repeats for a star. Choose “shape” on the stage above.
📋 Chapter summary สรุปท้ายบท
Scratch has blocks for many kinds of work, including decisions with choices. You can use the Boolean operators and, or and not in comparison expressions to build more complex conditions.
Scratch also has blocks for making sub-programs, or functions, which can take one or more parameters to use inside the function. When you call a function you must send it arguments that match the parameters in number and type, so the function works correctly. With functions you can call the same block many times instead of rewriting the same commands. That makes large programs quicker to build and easier to check.
💻 End-of-chapter activity กิจกรรมท้ายบท
Design and write your own cat-catches-mouse game. Think about the sub-tasks the game can have: how many characters are there, what sub-tasks does each one have, and how is the score given?
| Sprite | Functions (My Blocks) | Conditions used |
|---|---|---|
| Cat | moveWithKeys, catchMouse | touching Mouse? and not game over |
| Mouse | appearRandom (like setSizeAndPos), runAway | clones like the watermelons |
| Stars / bonus | showStar | touching Cat? → score + 5 |
| Stage | startScreen, countdown (seconds) | timer > 60 or score = 20 → stop all |
📝 End-of-chapter exercises แบบฝึกหัดท้ายบท
Solve each situation by following the problem-solving steps, then write a Scratch program for it.
1 · Plates after the New Year party
Your village is holding a New Year party. You are in charge of washing and storing a large number of plates, all the same size. After washing, they go into boxes that hold 3 stacks of 10 plates. Work out the smallest number of boxes needed so every plate is stored and no box is left over.
One box holds 3 × 10 = 30 plates. Boxes = plates ÷ 30, rounded up (a part-full box is still a box). Scratch's ceiling of (in the abs of menu) rounds up.
2 · Selling food for commission
You sell food and get a commission from the shop owner as in the table. If your total sales are more than 500 baht, you also get an extra 10% of total sales. Write a program that sums your total sales and your commission.
| Food | Price per unit (฿) | Commission per unit (฿) | Extra commission |
|---|---|---|---|
| Cake ขนมเค้ก | 10 | 2 | more than 20 pieces → 3 ฿ per piece |
| Sticky rice + chicken ข้าวเหนียวไก่ | 20 | 5 | more than 30 packs → 7 ฿ per pack |
| Water น้ำดื่ม | 15 | 3 | more than 30 bottles → 5 ฿ per bottle |
We read “more than 20 pieces → 3 ฿ per piece” as: the whole order earns the higher rate once you pass the limit. A function per food keeps it tidy:
3 · Which ride is cheapest?
- Air-con bus: 5 baht per kilometre per person; under 1 km still costs 5 baht.
- Taxi: starts at 35 baht for the first 3 km, then 2 baht per extra km; one taxi takes at most 4 passengers.
You and a group of friends want to travel to a station. Which ride should you choose to pay the least?
Bus = people × 5 × km (at least 5 each). Taxis = ceiling(people ÷ 4), each costing 35 + 2 × (km − 3) when km > 3. We assume whole kilometres.
4 · A class data report
Your class teacher asks you to record your classmates' height, weight and sex, and make a summary report containing:
- Name–surname, sex, height, weight
- the average height and weight of the whole class, and separately by sex
Use four Scratch lists (Variables → Make a List): names, sex, height, weight. Item i of each list belongs to the same student.
inputStudents (n): repeat n times: ask name, sex (M/F), height, weight → add each answer to its list.average (sexWanted): go through every item; ifsexWanted = "all" or item i of sex = sexWantedthen add the height and weight to totals and add 1 to count; then say totals ÷ count.- Main:
inputStudents (40), thenaverage (all),average (M),average (F). Show the lists on stage for the name–sex–height–weight table.
The or in step 2 lets one function handle all three averages. That is the point of a parameter.
5 · Aunt Cherry's basil chicken boxes
A teacher hires Aunt Cherry to make x boxes of rice with basil chicken and fried egg at school, and she brings her own ingredients. How much will the ingredients cost in total, and how much should she charge per box to make a 30% profit?
15 boxes use these ingredients:
| Ingredient | Price | Cost for 15 boxes |
|---|---|---|
| Jasmine rice 2 kg | 38 ฿/kg | 76.00 |
| Chicken 1 kg | 70 ฿/kg | 70.00 |
| Basil leaves 200 g | 20 ฿/kg | 4.00 |
| Chilli 200 g | 45 ฿/kg | 9.00 |
| Garlic 20 g | 80 ฿/kg | 1.60 |
| Eggs 15 | 3.50 ฿ each | 52.50 |
| Total | 213.10 | |
Note: seasonings (sauce, soy sauce, sugar), the stove, water, electricity and containers are provided by the school kitchen and are not counted. The last column is worked out for you; the book gives only the first two.
Cost per box = 213.10 ÷ 15 ≈ 14.21 ฿. Total cost = x × 213.10 ÷ 15. Price per box for 30% profit on cost = cost per box × 1.3 ≈ 18.47 ฿, whatever x is. (Answers are accepted to within 0.05 ฿ for rounding.)
🧠 Mini-quiz
Source: IPST (สสวท.) Basic Science and Technology textbook, Technology (Computing Science), Grade 8 (M.2), Chapter 3. Figures are from the textbook; text translated and adapted by Guru Jazzy. The model answers are Guru Jazzy's (the textbook does not print answers).