Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Help your kids with computer coding _ a unique step-by-step visual guide, from binary code to building games_clone

Help your kids with computer coding _ a unique step-by-step visual guide, from binary code to building games_clone

Published by THE MANTHAN SCHOOL, 2021-02-25 04:09:36

Description: Help your kids with computer coding _ a unique step-by-step visual guide, from binary code to building games

Search

Read the Text Version

ComDinegrC0 pUtHELP YOUR KIDS WITH



ComDinegrC0 pUtHELP YOUR KIDS WITH A UNIQUE STEP-BY-STEP VISUAL GUIDE, FROM BINARY CODE TO BUILDING GAMES

LONDON, NEW YORK, MELBOURNE, MUNICH, AND DELHI DK LONDON Editor Sam Priddy Designer Fiona Macdonald Additional editors Sam Atkinson, Lizzie Davey, Daniel Mills, Ben Morgan US editor Jill Hamilton Additional designer Simon Murrell Managing editor Paula Regan Managing art editor Owen Peyton Jones Senior producer, pre-production Ben Marcus Senior producer Mary Slater Jacket editor Maud Whatley Jacket designer Laura Brim Jacket design development manager Sophia MTT Publisher Sarah Larter Art director Phil Ormerod Associate publishing director Liz Wheeler Publishing director Jonathan Metcalf DK INDIA Senior art editor Devika Dwarkadas Editors Suefa Lee, Neha Pande Art editors Sanjay Chauhan, Shreya Anand Virmani Assistant art editor Vanya Mittal DTP designer Sachin Gupta Managing editor Rohan Sinha Deputy managing art editor Sudakshina Basu Pre-production manager Balwant Singh Jacket designer Suhita Dharamjit Senior DTP designer Harish Aggarwal First American Edition, 2014 Published in the United States by DK Publishing 345 Hudson Street, 4th Floor, New York, New York 10014 14 15 16 17 18 10 9 8 7 6 5 4 3 2 1 001 – 192672 – Jun/2014 Copyright © 2014 Dorling Kindersley Limited All rights reserved. Without limiting the rights under copyright reserved above, no part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), without the prior written permission of the copyright owner. Published in Great Britain by Dorling Kindersley Limited. A catalog record for this book is available from the Library of Congress. ISBN: 978-1-4654-1956-9 DK books are available at special discounts when purchased in bulk for sales promotions, premiums, fund-raising, or educational use. For details, contact: DK Publishing Special Markets, 345 Hudson Street, New York, New York 10014 or [email protected]. Printed and bound in China by South China Printing Company. Discover more at www.dk.com

CAROL VORDERMAN M.A. CANTAB, MBE is one of Britain’s best-loved TV presenters and is renowned for her skills in mathematics. She has a degree in Engineering from the Univerisity of Cambridge. Carol has a keen interest in coding, and feels strongly that every child should have the chance to learn such a valuable skill. She has hosted numerous TV shows on science and technology, such as Tomorrow’s World and How 2, as well as The Pride of Britain Awards, on the BBC, ITV, and Channel 4. Whether co-hosting Channel 4’s Countdown for 26 years, becoming the second best selling female nonfiction author of the noughties decade in the UK, or advising British Prime Minister David Cameron on the future of potential mathematics education in the UK, Carol has a passion and devotion to explaining mathematics, science, and technology in an exciting and easily understandable way. DR. JON WOODCOCK M.A. (OXON) has a degree in Physics from the University of Oxford and a Ph.D. in Computational Astrophysics from the University of London. He started coding at the age of eight and has programmed all kinds of computers from single-chip microcontrollers to world-class supercomputers. His many projects include giant space simulations, research in high-tech companies, and intelligent robots made from junk. Jon has a passion for science and technology education, giving talks on space and running computer programming clubs in schools. He has worked on numerous science and technology books as a contributor and consultant. SEAN MCMANUS learned to program when he was nine. His first programming language was Logo. Today he is an expert technology author and journalist. His other books include Scratch Programming in Easy Steps, Web Design in Easy Steps, and Raspberry Pi For Dummies. Visit his website at www.sean.co.uk for Scratch games and tutorials. CRAIG STEELE is a specialist in Computing Science education. He is Project Manager for CoderDojo Scotland, which runs free coding clubs for young people. Craig has previously worked for the Scottish Qualification Authority, Glasgow Science Centre, and the University of Glasgow. Craig’s first computer was a ZX Spectrum. CLAIRE QUIGLEY studied Computing Science at Glasgow University where she obtained a B.S. and a Ph.D. She has worked in the Computer Laboratory at Cambridge University and on a project that aimed to develop computational thinking skills in primary school pupils. She is a mentor at CoderDojo Scotland, a coding club for young people. DANIEL MCCAFFERTY holds a degree in Computer Science from the University of Strathclyde. Since graduating, he has been developing software for some of the world’s largest investment banks. In his spare time, Daniel is a mentor at CoderDojo Scotland, a coding club for young people.

Contents 8 FOREWORD by Carol Vorderman 10 H O W T H I S B O O K W O R K S WHAT IS CODING? 64 Decisions and branches 66 Sensing and detecting 14 What is a computer program? 68 Complex loops 16 Thinking like a computer 70 Sending messages 18 Becoming a coder 72 Creating blocks 74 Project 3: Monkey mayhem STARTING FROM SCRATCH 82 Time to experiment 22 What is Scratch? PLAYING WITH PYTHON 24 Installing Scratch 26 Scratch interface 86 What is Python? 28 Sprites 88 Installing Python 30 Colored blocks and scripts 92 Introducing IDLE 32 Project 1: Escape the dragon! 94 Errors 38 Making things move 96 Project 4: Ghost game 40 Costumes 98 Ghost game decoded 42 Hide and seek 100 Program flow 44 Events 102 Simple commands 46 Simple loops 104 Harder commands 48 Pens and turtles 106 Which window? 50 Variables 108 Variables in Python 52 Math 110 Types of data 54 Strings and lists 112 Math in Python 56 Coordinates 114 Strings in Python 58 Make some noise 116 Input and output 60 Project 2: Roll the dice 118 Making decisions 62 True or false? 120 Branching

122 Loops in Python 188 Processors and memory 124 While loops 190 Essential programs 126 Escaping loops 192 Storing data in files 128 Lists 194 The Internet 130 Functions 132 Project 5: Silly sentences PROGRAMMING IN THE 134 Tuples and dictionaries REAL WORLD 136 Lists in variables 138 Variables and functions 198 Computer languages 140 Project 6: Drawing machine 200 Coding stars 148 Bugs and debugging 202 Busy programs 150 Algorithms 204 Computer games 152 Libraries 206 Making apps 154 Making windows 208 Programming for the Internet 156 Color and coordinates 210 Using JavaScript 158 Making shapes 212 Bad programs 160 Changing things 214 Mini computers 162 Reacting to events 216 Becoming a master programmer 164 Project 7: Bubble blaster 176 What next? 218 Glossary 220 Index INSIDE COMPUTERS 224 Acknowledgments 180 Inside a computer Find out more at: 182 Binary and bases www.dk.com/computercoding 184 Symbols and codes 186 Logic gates

Foreword Just a few years ago, computer coding seemed like a mysterious skill that could only be practiced by specialists. To many people, the idea that coding could be fun was a strange one. But then the world changed. In the space of a few years, the Internet, email, social networks, smartphones, and apps hit us like a tornado, transforming the way we live. Computers are a huge part of life that we all now take for granted. Instead of calling someone on the phone, we send a text message or use social media. From shopping and entertainment to news and games, we guzzle everything computers have to offer. But we can do more than just use this technology, we can create it. If we can learn to code, we can make our own digital masterpieces. Everything computers do is controlled by lines of code that someone has typed out on a keyboard. It might look like a foreign language, but it’s a language anybody can pick up quite quickly. Many would argue that coding has become one of the most important skills you can learn in the 21st century.

Learning to code is tremendous fun because you can get instant results, no matter how much more you have to learn. In fact, it’s such fun creating games and programs that it feels effortless once you’re hooked. It’s also creative— perhaps the first science that combines art, logic, storytelling, and business. Not only that, coding is a fantastic skill for life. It strengthens logical thinking and problem-solving skills—vital in many different areas of life, from science and engineering to medicine and law. The number of jobs that require coding is set to increase dramatically in the future, and there’s already a shortage of good coders. Learn to code, and the digital world is yours for the taking! CAROL VORDERMAN

10 How this book works Pixel people give 170 P L A Y I N G W I T H P Y T hints and tips along This book introduces all the essential BUBBLE BLASTER concepts needed to understand computer the way coding. Fun projects throughout put these Figuring out the distance ideas into practice. Everything is broken down into small chunks so that it’s easy to follow In this game, and lots of others, it is and understand. between two objects. Here’s how to formula to have the computer work Each topic is “See also” boxes list described in detail, other subjects that are This function calculates the distance be with examples linked to the topic 11 two objects. Add this bit of code direct and exercises the code you wrote in step 9. from math import sqrt def distance(id1, id2): x1, y1 = get_coords(id x2, y2 = get_coords(id return sqrt((x2 - x1)* 42 S T A R T I N G F R O M S C R A T C H Hide and seek SEE ALSO Sizes and effects Choose the type from the dr Welcome to the special effects studio! Using the purple  38–39 Making Scripts can be used to change the size of a menu. The “Looks” blocks, find out how to make sprites vanish and sprite and add special effects to it. reappear, grow and shrink, and fade in and out. things move effect makes becom Sending 70–71 Type in positive numbers messages to make sprites bigger and negative numbers change size by 10 to make them smaller change Hiding sprites Use the “hide” block Higher numbers make set co to make sprites sprites bigger and To make a sprite disappear, use the “hide” block. The lower numbers make clear gr sprite is still on the stage, and it can still move around, disappear in games them smaller. 100 is but it can’t be seen unless the “show” block is used to normal size △ Addin make it visible again. set size to 100 % The grap Resets all used to c △ Changing a sprite’s size the effects or distort These two blocks can be used to experime Colorful ▷ Hide and show hide make a sprite bigger or smaller, illustrations show either by a set amount or by a To make a sprite vanish, use the “hide” percentage of its size. highlight block. When you’re ready for it to be different seen again, use the “show” block. Using effects to teleport Y programming These blocks are found in the “Looks” concepts section of the blocks palette. Add a ghost sprite from the “Fantasy” category of the sprite library, and create the script shown Programming ▽ Disappearing cat below. It makes the ghost appear to teleport scripts and Try this script using the cat sprite. It when clicked. code are disappears and reappears but it keeps moving, even when you can’t see it. EXPERT TIPS explained line by line when clicked Showing sprites when this sprite clicked The “ghost” effect makes the clear graphic effects fade slightly; by repeating th forever Select a sprite in the sprite list. repeat 20 block 20 times the sprite fad Click the “i” button on it to open away completely wait 1 secs This block hides the information panel. There you change ghost ▾ effect by 5 the cat can also use the “show” tick box This “Opera to show or hide a sprite. selects a ra This block rotates horizontal the cat clockwise hide The cat still moves turn 90 degrees even when hidden Sprite1 This block shows x: 84 y: -69 direction: -90° glide 0.1 secs to x: pick random -150 to 150 y: pic the cat again rotation style: repeat 20 move 100 steps can drag in player: show: change ghost ▾ effect by -5 wait 1 secs show Show a Using this block makes the hidden sprite sprite fade back in Instructions show what Labels help explain to click, drag, or select each step

HOW THIS BOOK WORKS 11 Seven projects build up Simple step-by-step coding skills. Project pages are instructions guide you highlighted with a blue band through each project THON 171B U B B L E B L A S T E R e between points Now update the main game loop to use the Each line of code is clearly s useful to know the distance 13 functions you have just created. Remember that labeled so o use a well-known mathematical the order is important, so make sure you put you can’t k it out. go wrong everything in the right place. Then run the code. This icon Bubbles should burst when they hit the sub. indicates that the project Check the shell window to see the score. continues on the next page etween score = 0 ly after Don’t forget to Loads the “sqrt” function save your work from the Math library #MAIN GAME LOOP Sets the score to zero while True: when the game starts Gets the position of Creates new bubbles the first object if randint(1, BUB_CHANCE) == 1: Gets the position of create_bubble() the second object d1) Gives back the distance move_bubbles() Adds the bubble d2) between them clean_up_bubs() score to the total **2 + (y2 - y1)**2) score += collision() print(score) g buHbIbDleEs. BAigN bDubSbElEesK 43 window.update() Shows the score in the shell sleep(0.01) window—it will be displayed properly later oints. The next section of This pauses the action for a very short time—try eisofpefofepctped by using its Change the removing this and see rr“opptix-odeoltawhtene” edge). what happens numbers in the the sprite b▷locCkos ltloissieotn sensing me blurred hIfotwhestdroisntgance between sh into each other, the tthheeecffeenctteisr of the sub and the center update the score. This of a bubble is less than their radiuses EXPERT TIPS the code in step 11. added together, they have collided. Python shortcut Don’t forget to pixelate ▾ effect by 25 save your work The code “score += collision()” e keeps This loop goes through the entire list is a shortcut for writing “score = score + collision()”. It adds nts scored of bubbles (it goes backwards to Checks for collisions the collision score to the total between the sub score, then updates the total score. lor ▾ effect to 0avoid errors when deleting bubbles) Code like this is common, so a shortcut is useful. You can also do bub_id)-1, -1, -1)E:ach color is and any bubbles the same thing using the “–” symbol. For example, “score –= 10” riadph2i,c efbfeucbts_id[bub]) r<epre(sSenHteIdPb_y Ra + bub_r[bub]): is the same as “score = score – 10”. number. Change b_r[bub] + bub_spetehedn[ubmubber]to) ng graphic effects bhi)c effects inDSelcertaetscthhecabnubbbele set the color Calculates the number of points this bubble is worth hange a sprite’s appearance and adds it to “points” t its shape. They’re fun to ecnk tthweith. of points You’ll never know where I’ll appear next! e sprite This block Boxes give extra EXPERT TIPS his selects a random information: tips, des vertical position definitions, and things When to save ators” block to remember This save icon appears ndom on the project spreads. It position Read on and reminds you when to save get coding! the work you’ve done, ck random -150 to 150 so that nothing is lost if the computer crashes. This block makes the Always remember to save ghost move slowly, your work frequently. hidden from view



What is coding?

14 W H A T I S C O M P U T E R C O D I N G ? SEE ALSO What is a computer Thinking like 16–17 program? a computer Becoming 18–19 A computer program is a set of instructions that a a coder computer follows to complete a task. “Coding”, or “programming”, means writing the step-by-step instructions that tell the computer what to do. Computer programs are everywhere We are surrounded by computer programs. Many of the devices and gadgets we use every day are controlled by them. These machines all follow step-by-step instructions written by a computer programmer. ◁ Mobile phones △ Computer software Everything a computer does, from Programs allow you to make a browsing the Internet to writing phone call or send text messages. documents or playing music, works When you search for a contact, because of code written by a a program finds the correct computer programmer. phone number. ◁ Games Consoles are just another type of computer, and all the games that run on them are programs. All the graphics, sounds, and controls are written in computer code. △ Washing machines ▷ Cars Washing machines are programmed In some cars, computer to follow different cycles. Computer programs monitor the code controls how hot the water is speed, temperature, and how long the wash takes. and amount of fuel in the tank. Computer programs can even help control the brakes to keep people safe.

WHAT IS A COMPUTER PROGRAM? 15 How computer programs work Computers might seem very smart, but they are actually just boxes that follow instructions very quickly and accurately. As intelligent humans, we can get them to carry out different tasks by writing programs, or lists of instructions. 1 Computers can’t think 2 Write a program A computer won’t do You can tell a computer what to anything by itself. It’s up to do by writing a set of very detailed the computer programmer instructions called a program. Each to give it instructions. instruction has to be small enough that the computer can understand it. If the Without instructions a instructions are incorrect, the computer computer is clueless won’t behave the way you want it to. This is a computer for count in range(10, 0, -1): program counting print(“Counting down”, count) down to launch 3 Programming languages Computers can only follow instructions in a language they understand. It’s up to the programmer to choose which language is best for the task. for count in range(10, 0, -1): All programs are finally print(“Counting down”, count) converted into “binary code”, a basic computer language that uses only ones and zeroes BLAST OFF! LINGO Hardware and software “Hardware” means the physical parts of the computer that you can see or touch (all the wires, the circuits, the keyboard, the display screen, and so on). “Software” means the programs that run on the computer and control how it works. Software and hardware work together to make computers do useful things.

16 W H A T I S C O D I N G ? SEE ALSO Think like a computer  14–15 What is a A programmer must learn to think like a computer. All computer program? tasks must be broken down into small chunks so that they are easy to follow and impossible to get wrong. Becoming 18–19 a coder Thinking like a robot LINGO Imagine a café where the waiter is a robot. The robot has Algorithm a simple computer brain, and needs to be told how to get from the café kitchen to serve food to diners seated An algorithm is a set of simple at tables. First the process has to be broken down into instructions for performing a task. simple tasks the computer can understand. A program is an algorithm that has been translated into a language 1 Waiter robot program 1 that computers can understand. Using this program the robot grabs the food from the plate, crashes straight through the kitchen wall ◁ Disaster! into the dining area, and puts the food on the floor. The instructions This algorithm wasn’t detailed enough. weren’t clear: we forgot to tell the 1. Pick up food robot to use the door. It might seem obvious 2. Move from kitchen to diner’s table to humans but computers can’t think 3. Put food down for themselves. 2 Waiter robot program 2 △ Still not perfect This time we’ve told the robot waiter to use the kitchen door. It makes it through the door, but then hits The robot doesn’t know how to deal with the café cat, trips, and smashes the plate on the floor. obstacles like the cat. The program needs to give the robot even more detailed 1. Pick up a plate with food on it instructions so it can move around safely. 2. Move from kitchen to diner’s table by: Move to door between kitchen and dining area Move from door to the table 3. Put plate down on the table in front of the diner

THINK LIKE A COMPUTER 17 3 Waiter robot program 3 In this version of the program, the robot successfully delivers the food to the diner avoiding any obstacles. But after putting the plate down, the robot remains standing at the table while food piles up in the kitchen. 1. Pick up a plate with food on it holding it level at all times △ Success at last? 2. Move from kitchen to diner’s table by: Finally the robot can deliver the Move to door between kitchen and dining area food safely. But we forgot to give checking for obstacles and steering around them it instructions to go back to the kitchen and get the next plate. Move from door to the table checking for obstacles and steering around them 3. Put plate down on the table in front of the diner Real-world example The waiter robot might be imaginary, but algorithms like this are in action all around us. For example, a computer- controlled elevator faces the same sort of problems. Should it go up or down? Which floor should it go to next? 1. Wait until doors are closed ◁ Elevator program 2. Wait for button to be pressed For the elevator to work If button pressed is higher than current floor: correctly and safely, every Move lift upwards step has to be precise, clear, and cover every possibility. If button pressed is lower than current floor: The programmers have to Move lift downwards make sure that they create a suitable algorithm. 3. Wait until current floor equals button pressed 4. Open doors

18 W H A T I S C O D I N G ? Becoming a coder SEE ALSO Coders are the people who write the programs behind What is 22–23 everything we see and do on a computer. You can create your own programs by learning a programming language. Scratch? What is 86–87 Python? Programming languages There are a huge range of programming languages to choose from. Each one can be used for different tasks. Here are some of the most popular languages and what they are often used for: C A powerful language for building MATLAB Ideal for programs that need to Ada computer operating systems. carry out lots of calculations. Java Used to control spacecraft, Ruby Automatically turns lots of satellites, and airplanes. information into web pages. Works on computers, cell phones, Javascript A language used to build and tablets. interactive websites. Scratch A visual language that’s ideal Python A text-based language that can for learning programming. be used to build all kinds of This is the first language things. It’s the second language covered in this book. covered in this book. What is Scratch? SCRATCH File ▾ Edit ▾ Tips ? Scratch is a great way to start Untitled Scripts Costumes Sounds coding. Programs are created by connecting together blocks by abcd (unshared) of code, instead of typing it out. Scratch is quick and easy to use, Motion Events x: -126 and also teaches you the key Looks Control y: 96 ideas you need to use other Sound Sensing programming languages. Pen Operators Data More Blocks The program appears on this side of the screen when clicked move 10 steps forever turn 15 degrees turn 15 degrees go to mouse pointer ▾ point in direction 90 ▾ point towards ▾ move 10 steps go to x: 0 y: 0 go to mouse pointer ▾ forever glide 1 secs to x: 0 y: 0 next costume play sound bubbles ▾ until done x: 153 y: -61 Sprites New sprite: Stage Sprite 1 Sprite 2 1 backdrop New backdrop: Backpack Code is made by connecting colored blocks together

BECOMING A CODER 19 What is Python? IDLE File Edit Shell Debug Window Help ghostgame People around the world use Python to build games, tools, and # Ghost Game websites. It’s a great language from random import randint to master because it can help print(‘Ghost Game’) you build all kinds of different feeling_brave = True programs. Python looks like a score = 0 mixture of recognizable words while feeling_brave: and characters, so it can be easily read and understood by humans. ghost_door = randint(1, 3) print(‘Three doors ahead...’) A program written in Python Getting started It’s time to start programming. All you need is a computer with an Internet connection. This book starts with Scratch—the perfect language to help you on your way to becoming a coding expert. Get ready to jump into the exciting world of computer coding. EXPERT TIPS Enjoy experimenting As a programmer you should experiment with the code and programs you make. One of the best ways to learn programming is to play around and see what happens when you change different parts of the code. By tinkering and fiddling, you’ll discover new ways of doing things. You’ll learn much more about computer programming and have even more fun.



Starting from Scratch

22 S T A R T I N G F R O M S C R A T C H What is Scratch? SEE ALSO Scratch is a visual programming language that Installing and 24–25 makes coding simple. It can be used to make all sorts of fun and interesting programs. launching Scratch Scratch 26–27 interface Colored blocks 30–31 and scripts Understanding Scratch Blocks lock together like Scratch is perfect for making games and animations. jigsaw pieces It has large collections (or “libraries”) of cool graphics and sounds that you can play around with. 1 Start programming 2 Put together Scratch is a programming language. programming blocks There’s not much typing, and it’s easy to get started. Scratch uses colored blocks of code. Blocks are selected and Write your joined together to make a script, first program which is a set of instructions. in Scratch! 3 Make sprites move and speak Sprites like me can be LINGO Objects such as people, vehicles, programmed to talk and animals can be added to a program. in speech bubbles. Why is it called Scratch? These objects are called sprites. Scripts make them move and speak. “Scratching” is a way of mixing different sounds to make new music. The Scratch programming language enables you to mix pictures, sounds, and scripts to make new computer programs. Sprites can be programmed to walk, run, and dance

WHAT IS SCRATCH? 23 A typical Scratch program The red button stops a program Here is an example of a Scratch program. All of the action takes place in an area on the screen called the “stage.” The green flag Background images and sprites can be added to the stage, runs a program and you can write scripts to make things happen. ▷ Running a program Untitled Starting a program is by abcd (unshared) called “running” it. To run a program in Scratch, click the green flag above the stage. Background image Adding a script makes the shark sprite move Several sprites can be on the stage at once ▷ Scripts make when clicked REMEMBER sprites move Scratch contains blocks forever Scratch programs that can be used to make scripts. This script makes next costume In Scratch, when you save your the shark bounce around work it is called a “project.” A the screen. The “next wait 0.25 secs project includes all the sprites, costume” block makes it backgrounds, sounds, and scripts open and close its mouth move 10 steps you’re working with. When you with each movement. load a project again later, if on edge, bounce everything will be where it was The “forever” block when you saved it. A Scratch keeps the sprite project is a computer program. moving endlessly

24 S T A R T I N G F R O M S C R A T C H REMEMBER Installing and Scratch website launching Scratch Find the Scratch website at: To start programming in Scratch, you need to http://scratch.mit.edu/ have the Scratch software. It can be installed on a computer, or it can be used online. Create a Scratch account A Scratch account can be used to share the programs you make on the Scratch website. It’s also used to save work online. Visit the Scratch website at: http://scratch.mit.edu/ and click “Join Scratch” to create your account. ▷ Getting started 2 Launching Scratch The way Scratch is set up depends on Once you’ve joined the Scratch website, whether it’s used over click “Sign in,” and enter your username the Internet (online) and password. Click “Create” at the top of or from downloaded the screen to begin a new program. software (offline). Double-click the icon on the desktop 1 Set-up and Scratch will start, ready to begin programming. Online Visit http://scratch.mit.edu and click “Join Scratch.” Fill in the form to create a username and password. Make sure you get permission from your parent or caregiver to join the website. Offline Download the software version of Scratch at: http://scratch.mit.edu/ scratch2download/. Run the installation program and a Scratch icon will appear on your desktop.

INSTALLING AND LAUNCHING SCRATCH 25 EXPERT TIPS Different versions of Scratch Mouse control This book uses Scratch 2.0, the latest version of Scratch. Use this version if possible. An older The “click” instruction means press version will differ slightly. the left mouse button if there is more than one. “Right-click” means use the right mouse button. If a mouse only has one button, hold the “CTRL” key on the keyboard and press the mouse button to perform a right-click. △ Scratch 1.4 △ Scratch 2.0 The older version of Scratch The latest version of Scratch has has the stage on the right of some new commands and the the screen. stage is on the left of the screen. 3 Saving work 4 Operating systems Ready? Let’s go! When you’re logged in, Scratch The web version of Scratch works well on automatically saves work for you. To find Windows, Ubuntu, and Mac operating your work, click your username at the top systems. It needs Adobe Flash software, right of the screen and click “My Stuff.” though, so it won’t work on some tablets. Click the “File” menu at the top of the The offline version of Scratch works well on screen and choose “Save As.” Ask the computers with Windows and Mac operating person who owns the computer where systems. It doesn’t work well on computers you should save your work. that use Ubuntu. If a computer uses Ubuntu, try the online version instead.

26 S T A R T I N G F R O M S C R A T C H Scratch interface ▽ Experiment This is Scratch’s screen layout, or “interface.” Click the buttons and tabs to The stage is on the left and programs are explore and experiment with created on the right. the Scratch interface. The projects that follow explain how to use them. Click for full Change Menu Cursor screen view language options tools EXPERT TIPS SCRATCH File ▾ Edit ▾ Tips ? Menu and tools MENU OPTIONS Untitled This is what the menu options by abcd (unshared) at the top of the screen do. Program name box File ▾ Save work or start a new project. Edit ▾ Undo any mistakes or change the stage size. Click a sprite on the Tips If you get stuck, find stage or in the sprite help here. list to select it CURSOR TOOLS x: 153 y: -61 Click on the tool you want to use, Sprites New sprite: and then click on the sprite or script that you want to use it on. Copy a sprite or script. Delete a sprite or script. Enlarge a sprite. Stage Sprite 1 Sprite 2 Sprite 3 Shrink a sprite. 1 backdrop ? Get help on a block. New backdrop: Buttons to change Blue box around Buttons to add new sprites the background the selected sprite

SCRATCH INTERFACE 27 Sounds tab ▷ Scratch map STAGE AREA BLOCKS SCRIPTS Costumes tab The stage is where PALETTE AREA programs run. Sprites are Scripts tab managed in the sprite list SPRITE LIST and script blocks can be found in the blocks BACKPACK palette. Build scripts in the scripts area. STAGE LIST Scripts Costumes Sounds Motion Events Select different Current Looks Control types of blocks sprite Sound Sensing selected Pen Operators x: -126 Data More Blocks y: 96 Position of the when clicked current sprite on move 10 steps forever the stage go to mouse-pointer ▾ turn 15 degrees move 10 steps turn 15 degrees Blocks snap together—use the point in direction 90 ▾ mouse to move them around forever point towards ▾ next costume play sound hoot ▾ until done go to x: 0 y: 0 go to mouse-pointer ▾ glide 1 secs to x: 0 y: 0 These scripts control the owl sprite Backpack Drag blocks from here Build Store scripts, sprites, sounds Zoom in into the scripts area to scripts here and costumes in the backpack on scripts make scripts

28 S T A R T I N G F R O M S C R A T C H Sprites SEE ALSO Sprites are the basic components of Scratch. Every Scratch  26–27 Scratch program is made up of sprites and the scripts that control them. The “Escape the dragon!” program on pages 32–37 interface uses the cat, dragon, and donut sprites. Costumes 40–41 Hide and seek 42–43 What can sprites do? We can make lots of different sounds. Sprites are the images on the stage. Scripts are programmed to make them do things. Sprites can be instructed to react to other sprites and the user of the program. Here are a few things sprites can do: Move around the stage React when they touch things Change their appearance Be controlled by the user Play sounds and music Talk in speech bubbles Sprites in the Scratch interface The scripts being shown belong to the Each project can have several sprites, and each one can have its own scripts. It’s important to add scripts to the correct sprite, sprite shown here and to know how to switch between them. SCRATCH File ▾ Edit ▾ Tips ? Untitled Scripts Costumes Sounds by abcd (unshared) Motion Events x: -126 Looks Control y: 96 Sound Sensing Pen Operators Data More Blocks when clicked move 10 steps forever go to mouse-pointer ▾ turn 15 degrees move 10 steps turn 15 degrees Select different point in direction 90 ▾ sprites by clicking point towards ▾ forever on them next costume play sound pop ▾ until done ▷ Sprites and scripts A project can have lots go to x: 0 y: 0 of sprites, and each sprite can have lots of scripts. x: 153 y: -61 go to mouse-pointer ▾ Sprites New sprite: glide 1 secs to x: 0 y: 0 Stage Sprite 1 Sprite 2 Sprite 3 1 backdrop New backdrop: Backpack

SPRITES 29 Creating and editing sprites Games are more exciting when there are more sprites to hit, dodge, or chase each other around the stage. It’s simple to create, copy, and delete sprites. ▽ Create a sprite ▽ Copy or delete a sprite Use the buttons above the sprite list to To copy a sprite and its scripts, right-click add or create a sprite for your program. on it in the sprite list and choose “duplicate.” New sprite: Sprites This option copies a sprite Choose from the library Use your duplicate webcam Create a delete new sprite Select a picture save to local file from your computer hide Sprite 1 Sprite 2 This option deletes a sprite Naming a sprite 1 Select the sprite Select a sprite in the sprite list, and then When you start a new program in click on the blue “i” button in the corner. Scratch the cat sprite is called “Sprite1.” It’s easier to write programs if you give Sprites The blue “i” your sprites more meaningful names. button It also makes it easier to understand and manage scripts. Sprite 1 Sprite 2 Sprite 3 2 Change the name Type the 3 Renamed sprite When the information panel opens, sprite’s new Click the blue arrow to the left of click on the text box and use the keyboard name here the sprite to close the information panel. to change the name of the sprite. The sprite’s Spike direction: -90° new name appears in x: 84 y: -69 the sprite list rotation style: can drag in player: Spike show:

30 S T A R T I N G F R O M S C R A T C H Colored blocks SEE ALSO and scripts  26–27 Scratch Blocks are color-coded depending on what they do. Putting them together builds scripts that run in the interface order in which they are placed. Escape the 32–37 dragon! Colored blocks Scripts Costumes Sounds There are ten different types of blocks in Motion Events Scratch. Switch between them using the Looks Control buttons in the blocks palette. Click on a Sound Sensing color to see all the blocks in that section. Pen Operators Data More Blocks Button to show the orange “Data” blocks Functions of blocks ▽ Motion, looks, sound, and pen These blocks control what a sprite does on Different types of blocks do different things screen—this is called the output of a program. in programs. Some of them make sprites Pick a sprite and try each block to see what it does. move, some manage sounds, and some decide when things happen. turn 15 degrees This block rotates the ▽ Events and sensing sprite Brown “Events” blocks make things happen. Light blue “Sensing” blocks think Hmm... for 2 secs This block detect information about the keyboard, play sound meow ▾ shows a mouse, and what a sprite is touching. thought bubble when clicked key space ▾ pressed? Detects when pen down This block the green flag plays a sound is clicked recording Checks whether This block draws a line the spacebar as a sprite moves is pressed

COLORED BLOCKS AND SCRIPTS 31 ▽ Data and operators ▽ Control Orange “Data” blocks and green The “Control” blocks make decisions about “Operators” blocks store numbers when blocks run. They can be programmed and words and do things with them. to repeat instructions. set age ▾ to 10 Stores a number forever in a variable pick random 1 to 10 This makes the Chooses a blocks inside it run random number on loop (forever) Flow of scripts When a program runs, Scratch carries out the instructions on the blocks. It starts at the top of the scripts and works its way down. when clicked ◁ The thoughtful cat When this script is used with the cat sprite, wait 2 secs the cat will wait 2 seconds, think for a moment, pause 1 second, and then move. think Hmm... for 2 secs wait 1 secs Programs run REMEMBER move 100 steps from top to bottom Stopping scripts This instruction To stop all scripts in a program is run last that are running, click the red stop button above the stage. It’s shaped Running scripts like a hexagon. You’ll find it beside the green flag button used to start When a script is running, it glows. Use the green your program. flag button on the stage to run a script or click Untitled a script or a block to make it run. by abcd (unshared) The glowing outline Press this button to stop a means this script program when clicked is running wait 2 secs think Hmm... for 2 secs ◁ Testing scripts wait 2 secs Test whether a script is move 100 steps working properly by clicking on it.

32 S T A R T I N G F R O M S C R A T C H PROJECT 1 Escape the dragon! SEE ALSO This project introduces some basic Scratch  24–25 Installing and coding. It shows how to make a game to help the cat sprite dodge a fire-breathing dragon. launching Scratch  26–27 Scratch interface Blocks palette “Control” button Make the cat move Scripts Costumes Sounds This stage explains how to make the cat sprite Motion Events move around and chase the mouse-pointer. Looks Control Follow the instructions carefully because otherwise Sound Sensing the game might not work. Pen Operators Data More Blocks Open Scratch. Click “File” on Click the yellow wait 10 secs Drag the block into 1 the menu and select “New” to 2 “Control” button in repeat 10 the scripts area start a new project. The cat the blocks palette. forever forever sprite appears. Then click the “forever” block, keep Every new project in the mouse button Scratch includes me, pressed down, and drag the block into the cat sprite. the scripts area on the right. Release the button to drop the block. Click this block Click the blue “Motion” button in the blocks palette. Click the “Events” button in the blocks palette. Drag 3 The blue “Motion” commands will appear. Drag the 4 the “when green flag clicked” block into the scripts “point toward” block into the scripts area and drop it area. Join it to the top of your script. inside the “forever” block. Click the black arrow in This block snaps to the top of the script the block and choose “mouse-pointer.” The menu shows Click the drop-down when clicked “mouse-pointer” menu and select forever has been chosen forever “mouse-pointer” point towards ▾ point towards mouse-pointer ▾ mouse-pointer

ESCAPE THE DRAGON! 33 Try running the program by clicking the Move the mouse and watch the cat 5 green flag at the top of the stage. As you move spin around the mouse around the stage, the cat turns to following it face the mouse-pointer. Untitled by abcd (unshared) Use the Run the Stop the full screen program program Click the “Motion” button again, and drag the “move The picture behind the sprites is called a backdrop. 6 10 steps” block into the scripts area. Drop it inside 7 To the left of the sprite list is a button to add a the “forever” block. Click the green flag button so backdrop from the library. Click it, then select the the cat chases the mouse-pointer! “Space” theme from the list. Click the “stars” image and then click the “OK” button at the bottom right. when clicked Stage forever 1 backdrop point towards mouse-pointer ▾ Choose backdrop New backdrop: from the library move 10 steps The “forever” block Drop this block inside automatically stretches the “forever” block to make room SCRATCH File ▾ Edit ▾ Tips ? ◁ Cat in space The Scratch interface Untitled Scripts Costumes Sounds now looks like this. Run the program and the cat by abcd (unshared) chases the mouse-pointer through space. Motion Events x: -126 Looks Control y: 96 Scratch automatically saves Sound Sensing work if you’re online. To save work Pen Operators Data More Blocks while offline—click “File” and select “Save As.” when clicked move 10 steps forever point towards mouse pointer ▾ turn 15 degrees move 10 steps turn 15 degrees point in direction 90 ▾ point towards ▾ go to x: 0 y: 0 x: 153 y: -61 go to mouse pointer ▾ Sprites New sprite: glide 1 secs to x: 0 y: 0 Stage Sprite 1 1 backdrop New backdrop: Backpack

34 S T A R T I N G F R O M S C R A T C H ESCAPE THE DRAGON! Add a fire-breathing dragon Now that the cat can chase the mouse, make a dragon to chase the cat. Don’t let the dragon catch the cat, or it will get scorched. Above the sprite list is a button to add a sprite from Add this script to the dragon sprite. Click the 8 the library. Click it, choose the “Fantasy” category 9 color-coded buttons in the blocks palette to select from the menu on the left, and select “Dragon.” Click the blocks below, then drag the blocks into the the “OK” button in the bottom-right of the screen. scripts area. The dragon will now chase the cat. New sprite: when clicked Use the menu to make the dragon Add a forever point toward the sprite from cat (“Sprite1”) the library point towards Sprite1 ▾ The dragon is highlighted in blue move 10 steps to show it’s your Sprite 1 current sprite Click the blue “Motion” button and drag the “go to With the dragon sprite highlighted, add this 10 x:0 y:0” block into the script. Click the number 11 second script to the scripts area. The “wait until” boxes in the block and change them to -200 and block is found in the “Control” section, and the -150. Click the purple “Looks” button and add the “touching” block is in the “Sensing” section. The “switch costume to” block to your script. dragon now breathes fire when it touches the cat. when clicked Place this block when clicked Use the menu to here to make the choose “Sprite1” dragon start in (the cat) the corner go to x: -200 y: -150 wait until touching Sprite1 ▾ ? switch costume to dragon1-a ▾ switch costume to dragon1-b ▾ forever Use the menu stop all ▾ Drag this point towards Sprite1 ▾ to choose block inside move 4 steps “dragon1-a.” This “Control” block the “wait The dragon stops the program until” block will start in this costume Change 10 to 4 to make Costume the dragon move slower “dragon1-b” than the cat makes the dragon breathe fire

ESCAPE THE DRAGON! 35 In coding, a “variable” is used to store information. This EXPERT TIPS 12 step uses a variable to create a timer to measure how long Make the game harder a player survives before getting toasted. Click the “Data” Try changing the speed or size button and then click “Make a Variable.” of your sprites. Make the dragon faster: Scripts Costumes Sounds move 5 steps Data Motion Events button Looks Control Make the dragon larger or smaller: Sound Sensing Click this icon and then click Pen Operators a sprite to make it larger. Data More Blocks Click this icon and then click Click to create Make a Variable a sprite to make it smaller. a variable Type in the variable name “Time” and make sure The variable name and the number in it appear 13 the “For all sprites” button is selected underneath, 14 on the stage in a small box. Right-click it and then click “OK.” This means that the cat, dragon, choose “large readout.” This shows just the and any other sprites can use the variable. number in the box. Select New Variable Time 0 this option Variable name: Time normal readout The number in your large readout then click For all sprites For this sprite only “Time” variable slider “OK” hide Cloud variable (stored on server) OK Cancel Making a variable adds when clicked This resets the timer to 0 when 15 new blocks to the “Data” set Time ▾ to 0 the game starts section of the blocks forever palette. Drag the “set Choose from the Time to 0” and “change wait 1 secs “Control” section. Adds Time by 1” blocks from a 1 second delay the “Data” section to the scripts area to make this change Time ▾ by 1 new script. You can give this script to any sprite. Increases the Don’t forget to timer by 1 save your work

36 S T A R T I N G F R O M S C R A T C H ESCAPE THE DRAGON! Add a delicious donut Scratch comes with lots of sprites in its library. Make the game trickier by adding a donut sprite to the program for the cat to chase. Click the button above the sprite list to add a Add this script to the donut. The “mouse down?” 16 new sprite from the library. Select “Donut” from 17 block can be found in the “Sensing” section, and the “Things” category on the left and click “OK.” the “go to mouse-pointer” block in the “Motion” New sprite: section. This script makes the donut follow the mouse-pointer when the mouse button is clicked. Add a sprite when clicked This is a from the library forever “Sensing” block wait until mouse down? go to mouse-pointer ▾ Sprite 1 The donut is now your selected sprite Select the cat in the sprite list so its script Click the green flag button to run the program. 18 appears. Click the menu in the “point toward 19 Press the mouse button and the donut moves to the mouse-pointer. The cat follows the mouse-pointer” block. Change it so that the cat donut, and the dragon chases the cat. follows the donut instead of the mouse-pointer. when clicked Click to open Save the cat the menu from the dragon! forever Move the point towards Donut ▾ donut using the mouse-pointer move 5 steps mouse-pointer Donut Dragon Choose the donut from the drop-down menu

ESCAPE THE DRAGON! 37 Now add some music. Click the “Sounds” tab Select the “drip drop” sound and click the 20 above the blocks palette. Each sprite has its 21 “OK” button at the bottom-right. The sound own sounds, and they are managed here. is added to the cat sprite, and appears in the “Sounds” area. Click the button on the left to add a sound “Sounds” tab from the library. 2 Scripts Costumes Sounds New sound: Use a sound from Delete your computer. sounds here Record a sound drip drop 00:02.8 Add a sound from the library This is how long the sound lasts Click the “Scripts” tab to go back to the Congratulations! You’ve 22 scripts area. Add this script to the cat sprite, written your first computer game. so it plays the music all the time. Run the program and have fun! when clicked forever play sound drip drop ▾ until done Don’t forget to save your work Use the “Sound” button to find this block REMEMBER Achievements This project has shown some of Made sprites move: You’ve made sprites the things Scratch can do. Here’s chase each other. what you’ve achieved. Used a variable: You’ve created a timer for Created a program: By combining blocks of your game. code into scripts, you’ve put together a game. Added pictures: You’ve used both backdrops Used costumes: You’ve changed the dragon’s and sprites. appearance using different costumes. Added music: You’ve added a sound, and made it play when your program runs.

38 S T A R T I N G F R O M S C R A T C H Making things move SEE ALSO Computer games are all about firing, dodging, catching,  28–29 Sprites and escaping. Characters might run, fly spaceships, or Co-ordinates 56–57 drive fast cars. To create great games in Scratch, you first need to learn how to make sprites move. Motion blocks Scratch won’t let sprites walk off the stage, so The dark blue “Motion” blocks make sprites move. Start a new project you’ll never lose us. by clicking the “File” menu and choosing “New.” The new project begins with the cat in the middle of the stage, ready for action. 1 First steps move 10 steps Drag the “move 10 steps” block from the Click the white window on “Motion” section of the the block and type in a blocks palette and drop it different number to change into the scripts area to its how far the cat moves right. Each time you click the block, the cat moves. Add this block to tell The “forever” block Scratch when to start repeats anything 2 Keep on moving running the script inside it endlessly Drag a yellow “forever” block from the when clicked blocks palette and drop it around the “move 10 forever EXPERT TIPS steps” block. Click the move 10 steps green flag on the stage Rotation styles to run the program. The cat moves until it hits Try changing Find the cat in the “Sprites” list in the edge of the stage. 10 to 30 to make the bottom left of the screen. Click the cat sprint! the “i” button in the top left of the 3 Bouncing frame. Here you’ll find a button to Drag an “if on edge, when clicked change the cat’s rotation style—so bounce” block inside your it doesn’t walk around on its head! “forever” block. Now the cat bounces when it hits forever The cat faces the direction the edge of the stage. The move 10 steps it’s walking in, sometimes cat is upside down when if on edge, bounce upside down. it walks to the left. The cat faces left or right, and This block makes the cat is always the right way up. turn around when it hits The cat doesn’t rotate at all. the edge of the stage

MAKING THINGS MOVE 39 Which direction? The direction -90° 0° means “left” 90° The cat is now marching left and right across the screen. It’s possible to change the cat’s direction, so it walks up and down, or even diagonally. The “Motion” blocks can -90° be used to make a game of cat and mouse. Click the block to make Select or type in a new the cat change direction number to change the direction of the cat 4 Heading the point in direction 180° right way 45 ▾ The drop-down (90) right △ Compass Drag the “point in direction” menu gives you Directions are measured in block into the scripts area (-90) left degrees, from 0° at the top. and open its drop-down four options You can use any number menu. There are four (0) up between -179° and +180°. directions to choose from. Or, click on the number in (180) down The cat will follow the window and type in a the mouse-pointer new direction. 5 Cat and mouse Click the green flag Remove the “move to start the program 10 steps” and “if on edge, bounce” blocks from the when clicked script. Now drag a “point toward” block into the forever “forever” block. Open the menu and choose point towards mouse-pointer ▾ “mouse-pointer.” REMEMBER As the mouse-pointer moves, the cat turns to face it Sprites 6 Chase the mouse Can the cat catch the mouse? Drag a “move 10 steps” block into the “forever” loop. Now the cat walks toward the mouse-pointer. when clicked Sprites are objects in a Scratch program that you can move forever around (see pp.28–29). Every new project stars the cat sprite, but you point towards mouse-pointer ▾ can add cars, dinosaurs, dancers, and all sorts of other sprites from move 10 steps the library. You can even have a go at designing your own. Adjust the number of steps to change the cat’s speed

40 S T A R T I N G F R O M S C R A T C H Costumes SEE ALSO To change what a sprite looks like, its expression,  38–39 Making or its position, you need to change its “costume.” Costumes are pictures of a sprite in different poses. things move Sending 70–71 messages Costumes tab Changing costumes Scripts Costumes Sounds Different costumes can make your sprite New costume: costume2 look like it’s moving its arms and legs. When you switch between the cat’s two costumes, 1 it looks like it’s walking. Start a new project and try this example. One of the costume1 cat’s costumes 93x101 2 1 Different costumes costume2 Click the “Costumes” tab to see the cat’s 89x101 costumes. They show the cat with its legs and arms in two different positions. 3 Change the cat’s costume Add the “next costume” block from the 2 Make the cat walk “Looks” section of the blocks palette, so the cat Add this script to make the cat walk. changes its costume with each step. This makes When it moves, it slides across the screen without its legs and arms move. moving its legs, because its picture always stays the same. when clicked when clicked forever forever This picks the next costume move 10 steps next costume Pauses so the if on edge, bounce wait 0.5 secs costumes don’t change too quickly move 10 steps if on edge, bounce The colors remind you where to find the blocks

COSTUMES 41 Dancing ballerina The green flag starts the ballerina’s dance Now try making a ballerina dance. Add the ballerina sprite from the library. Select when clicked your cat in the sprite list and drag its script on to the ballerina in the sprite list. forever This copies the script to the ballerina. Sprite 1 next costume Drop the script on to the ballerina in the sprite list wait 0.5 secs move 10 steps if on edge, bounce △ Ballerina’s script The same script works for the ballerina and the cat. The ballerina has four costumes, and she uses them all as she dances on the stage. EXPERT TIPS switch costume to ballerina-a ▾ Switch costumes: Use the menu in the block to choose a costume. Switching switch backdrop to backdrop1 ▾ You can choose to show a specific Switch backdrops: Change the picture on the stage with this block. costume for your sprite using the “switch costume to” block. You can use this block to choose a particular position for your sprite. Adding speech bubbles when clicked The ballerina forever stands up You can add speech bubbles to make your sprites talk when they change costumes. switch costume to ballerina-a ▾ Use the “say Hello! for 2 secs” block and change the text in it to make your sprite say Up! for 1 secs say something else. switch costume to ballerina-b ▾ The ballerina says “Up!” say Down! for 1 secs She crouches and says “Down!”

42 S T A R T I N G F R O M S C R A T C H Hide and seek SEE ALSO Welcome to the special effects studio! Using the purple  38–39 Making “Looks” blocks, find out how to make sprites vanish and reappear, grow and shrink, and fade in and out. things move Sending 70–71 messages Hiding sprites Use the “hide” block to make sprites To make a sprite disappear, use the “hide” block. The sprite is still on the stage, and it can still move around, disappear in games but it can’t be seen unless the “show” block is used to make it visible again. ▷ Hide and show hide show To make a sprite vanish, use the “hide” block. When you’re ready for it to be seen again, use the “show” block. These blocks are found in the “Looks” section of the blocks palette. ▽ Disappearing cat EXPERT TIPS Try this script using the cat sprite. It disappears and reappears but it keeps Showing sprites moving, even when you can’t see it. Select a sprite in the sprite list. when clicked Click the “i” button on it to open the information panel. There you forever can also use the “show” tick box to show or hide a sprite. wait 1 secs This block hides the cat hide This block rotates turn 90 degrees the cat clockwise Sprite1 The cat still moves x: 84 y: -69 direction: -90° even when hidden rotation style: move 100 steps can drag in player: This block shows show: wait 1 secs the cat again show Show a hidden sprite

HIDE AND SEEK 43 Sizes and effects Choose the type of effect Change the from the drop-down numbers in the Scripts can be used to change the size of a menu. The “pixelate” blocks to set sprite and add special effects to it. how strong effect makes the sprite become blurred Type in positive numbers the effect is to make sprites bigger change size by 10 and negative numbers change pixelate ▾ effect by 25 to make them smaller Higher numbers make set color ▾ effect to 0 sprites bigger and set size to 100 % lower numbers make clear graphic effects Each color is them smaller. 100 is △ Adding graphic effects represented by a △ Changing a sprite’s size normal size number. Change These two blocks can be used to the number to make a sprite bigger or smaller, Resets all set the color either by a set amount or by a the effects percentage of its size. The graphic effects in Scratch can be used to change a sprite’s appearance or distort its shape. They’re fun to experiment with. Using effects to teleport You’ll never know where I’ll appear next! Add a ghost sprite from the “Fantasy” category of the sprite library, and create the script shown below. It makes the ghost appear to teleport when clicked. when this sprite clicked The “ghost” effect makes the sprite This block clear graphic effects fade slightly; by repeating this selects a random repeat 20 block 20 times the sprite fades vertical position away completely change ghost ▾ effect by 5 This “Operators” block selects a random horizontal position glide 0.1 secs to x: pick random -150 to 150 y: pick random -150 to 150 repeat 20 This block makes the change ghost ▾ effect by -5 ghost move slowly, hidden from view Using this block makes the sprite fade back in

44 S T A R T I N G F R O M S C R A T C H SEE ALSO Events Sensing 66–67 The brown “Events” blocks in Scratch start scripts and detecting when certain things happen. For example, when the user presses a key, clicks a sprite, or uses Sending 70–71 a webcam or microphone. messages Clicking LINGO A script can be added to a sprite that makes it do What is an event? something if the sprite is clicked while the program is running. Experiment with different blocks to see An event is something that what a sprite can do when clicked. happens, such as a key being pressed or the green flag being Drag this block clicked. The blocks that look for from the “Events” events go at the top of a script. menu to start The script waits until the event the script happens, and then it runs. when this sprite clicked play sound meow ▾ until done △ Click a sprite The cat sprite This script makes the cat sprite already has this meow when you click it. sound effect attached to it Key presses Programs can be built to react when different keys on the keyboard are pressed. For another way of using the keyboard that’s better for creating games, see pages 66–67. Choose the Change the Choose the key here text here key here when h ▾ key pressed when g ▾ key pressed say Goodbye! for 1 secs say Hello! for 1 secs △ Say goodbye △ Say hello This script uses the G key to make a sprite Add this script to a sprite and when the say “Goodbye!” H key is pressed, the sprite says “Hello!”

EVENTS 45 Sound events EXPERT TIPS If your computer has a microphone, sprites can Asking permission detect how loud the sounds in a room are on a scale of 0 (very quiet) to 100 (very loud). Use the Scratch asks for permission “when loudness > 10” block to make a script start to use your webcam and when the sounds are loud enough. microphone. When the box pops up, click “Allow.” 1 Make the cat sensitive to noise 2 Shout at the cat Start a new project, and add the “room3” Shout into the microphone—the cat will backdrop image from the backdrop library. jump out of its seat with fright and meow. It Drag the cat sprite on to the chair and add will also respond to music and other sounds the script shown here. if they are loud enough. Change the number to 40 when loudness ▾ > 40 This makes the go to x: 145 y: 130 cat jump up play sound meow ▾ until done go to x: 145 y: 0 This makes the cat fall back down Webcam motion detector when video motion ▾ > 40 Change the play sound meow ▾ until done number to 40 If you have a webcam, it can be used with Scratch too. Add this script to the △ Detect motion cat, and when you wave at it through Use the “when loudness > 10” block. Click the menu the webcam, it will meow back. to change “loudness” to “video motion.” The script will start when you’re moving around enough. EXPERT TIPS Choose the Backdrop changes backdrop here A sprite can react to the backdrop when backdrop switches to desert ▾ changing. For example, you can have a backdrop that makes the sprite disappear. hide Hides the sprite when Upload a new backdrop from the stage the backdrop changes list in the bottom left of the screen, and then add the “when backdrop switches to backdrop1” block to do this.

46 S T A R T I N G F R O M S C R A T C H Simple loops SEE ALSO A loop is a part of a program that repeats itself. The Complex 68–69 loop blocks (from the “Control” section) tell Scratch loops Loops 122–123 in Python which blocks to repeat, and how many times. They save us from adding the same blocks over and over again. Drop blocks inside this loop to repeat the actions forever Forever loop forever Whatever you put inside the “forever” block move 10 steps repeats itself forever. There’s no option to join anything at the bottom, because a if on edge, bounce “forever” loop never ends. No option to add △ Looping forever When the actions more Scratch blocks When the last block inside the finish the program loop ends, the loop goes back goes back to the start to the start again. of the loop again Repeat loop REMEMBER To repeat an action a certain number of times, use a Loop block shape “repeat 10” block. Change the number in it to set how many times the loop will repeat itself. Add the “Dinosaur1” The loop blocks are shaped like sprite to a new project and build it this script. jaws. Drop the blocks that you want to repeat into the jaws, so when clicked the loop wraps around them. As you add more blocks, the jaws repeat 3 Change the number to 3 stretch to make room for them. switch costume to dinosaur 1-d ▾ wait 0.5 secs The sprite stands up straight switch costume to dinosaur 1-c ▾ wait 0.5 secs The sprite stands on one leg △ Dancing dino You can add more blocks When the green flag is clicked, after a “repeat” loop the dinosaur dances. He repeats his dance moves three times.

SIMPLE LOOPS 47 Nested loops Try giving me some Loops can also be “nested,” which means they can be put looping music! inside each other. In this script, the dinosaur finishes his dance by walking right and left and then thinking for a moment. When he’s got his breath back, he dances again and stops only when you click the red stop button. Click on the green flag above the stage to start the script ▷ Loops in loops when clicked This “forever” loop has several repeat forever loops inside it. Make sure the blocks are repeat 3 inside the right loops, otherwise the program switch costume to dinosaur 1-d ▾ won’t work properly. wait 0.5 secs The “forever” block surrounds switch costume to dinosaur 1-c ▾ everything wait 0.5 secs The previous repeat 3 dance move move 20 steps (see opposite) wait 0.5 secs The dinosaur wait 1 secs This block creates moves three repeat 3 a short pause steps to the right move -20 steps The dinosaur wait 0.5 secs moves three steps to the left think I love to dance! for 2 secs Type in what you want the dinosaur to think—it will appear in a thought bubble

48 S T A R T I N G F R O M S C R A T C H SEE ALSO Pens and turtles  44–45 Events  46–47 Simple loops Each sprite has a pen tool that can draw a line behind it wherever it goes. To create a picture, turn on the pen and then move the sprite across the stage, like moving a pen across paper. Pen blocks pen down pen up The dark green blocks are used to Turns the Turns the control the pen. Each sprite has its own pen on pen off pen that can be turned on by using the “pen down” block and turned off using clear stamp the “pen up” block. The size and color of the pen can also be changed. Clears all drawings Leaves a picture of the sprite △ Playing with pens Experiment with how you can use the pen blocks to make drawings. Draw a square The sprite will leave a line To draw a square, you simply put the pen behind it down on the stage and then move the sprite in a square shape. Use a loop to draw the four sides and turn the corners. when clicked Draws a line pen down Turns the of the square repeat 4 pen on ▷ Change the shape move 100 steps Turns the This code will draw a corners square. To draw a triangle, change the “repeat” loop turn 90 degrees to repeat three times for the three sides, and wait 1 secs change the turn from 90 to 120 degrees. Makes it easier to see what’s happening


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook