Itching for

More

An Intermediate Course in Science by Jeremy Scott

TUTOR NOTES

Acknowledgements

This resource was partially funded by a grant from Education Scotland. We are also grateful for the help and support provided by the following contributors:

George Heriot’s School Crieff High School CompEdNet, Scottish Forum for Computing Science Teachers Computing At School Brian Clark, Portobello High School Susan Evans, Cleveland High School Colleen Lewis, UC Berkeley Mitchel Resnick, MIT Scottish Informatics and Alliance (SICSA) Edinburgh Napier University School of Computing Glasgow University School of Computing Science Heriot-Watt University School of Mathematical and Computer Sciences University of Edinburgh School of Informatics Robert Gordon University School of Computing University of Dundee School of Computing University of Stirling Department of Computing Science and Mathematics University of West of Scotland School of Computing International Olympic Committee ScotlandIS Brightsolid Online Innovation JP Morgan Microsoft Research Oracle O2 Sword Ciboodle

The contribution of the following individuals who served on the RSE/BCS Project Advisory Group is also gratefully acknowledged:

Professor Sally Brown (chair), Mr David Bethune, Mr Ian Birrell, Professor Alan Bundy, Mr Paddy Burns, Dr Quintin Cutts, Ms Kate Farrell, Mr William Hardie, Mr Simon Humphreys, Professor Greg Michaelson, Dr Bill Mitchell, Ms Polly Purvis, Ms Jane Richardson and Ms Caroline Stuart.

Some of the material within this resource is based on existing work from the ScratchEd site, reproduced and adapted under Creative Commons licence. The author thanks the individuals concerned for permission to use and adapt their materials.

BCS is a registered charity: No 292786 The Royal Society of Edinburgh. Scotland's National Academy. Scottish Charity No. SC000470

i

ii

Contents

Overview ...... 1 Introduction ...... 1 Computational Thinking ...... 2 Why BYOB? ...... 3 Using this resource ...... 4 BYOB ...... 7 Known Issues ...... 8 Installation ...... 8 Useful Resources ...... 9 Lessons and approach ...... 11 Screencasts ...... 11 Deep Understanding ...... 11 Pair Programming ...... 11 Suggested Activities ...... 12 Inter-Disciplinary Learning ...... 12 A Brief History of the Computer ...... 13 What is a computer? ...... 13 Representing information...... 17 Binary: The language of computers ...... 19 Layer cake ...... 19 Programming in BYOB ...... 21 1: Haunted House Game ...... 23 Event-driven programming ...... 26 2: Fancy a Chat? ...... 31 The Importance of Design ...... 32 3: Guessing Game ...... 37 Procedures: Building Your Own Blocks (BYOB) ...... 40 Validating Input ...... 41 4: Hungry Frog Game ...... 47 Divide and Conquer...... 51 5: Shaping up ...... 53 Parameters: More Flexible Procedures ...... 55 Project ...... 59 Congratulations! ...... 60 An ancient programmer’s proverb ...... 60 Appendices ...... 61 Appendix A: Learner Tracking Sheet ...... 62 Appendix B: Sample Code ...... 63

iii

iv Itching for More Overview

Overview

Introduction

Implementation of Curriculum for Excellence and the development of new National Qualifications presented a timely opportunity to revise the way computing science is taught in schools and to provide a more interesting, up-to-date and engaging experience for both tutors and learners.

This is the second in a series of three resources developed by the Royal Society of Edinburgh and the BCS Academy of Computing that exemplify a subset of the computing science-related outcomes of CfE at Levels 3 & 4 and beyond.

This resource is intended for use with learners who already have some programming experience – possibly via the first resource in this series Starting from Scratch: An Introduction to Computing Science. It will seek to consolidate learners’ understanding of Computing Science concepts, with a focus on abstraction and modularity, via the BYOB programming environment developed by the University of California, Berkeley.

All three resources build on state-of-the-art understanding of the pedagogy of Computing, drawn from around the world. This should enable learners to develop both programming skills and deep understanding of core Computing concepts, including computational thinking (see overleaf).

Whilst this resource is intended to support tutors’ thinking about how they might translate the intentions of the curriculum into classroom activity, it should not be seen as prescriptive. Rather, it is intended to stimulate innovation and offer tutors the flexibility and opportunity to deploy their creativity and skills in meeting the needs of learners.

Page 1 Itching for More Overview

Computational Thinking

Computational thinking is recognised as a key skill set for all 21st century learners – whether they intend to continue with Computing Science or not. It involves viewing the world through thinking practices that developers use to write programs.

These can be grouped into five main areas:

 seeing a problem and its solution at many levels of detail (abstraction)  thinking about tasks as a series of steps (algorithms)  understanding that solving a large problem will involve breaking it down into a set of smaller problems (decomposition)  appreciating that a new problem is likely to be related to other problems the learner has already solved (pattern recognition), and  realising that a solution to a problem may be made to solve a whole range of related problems (generalisation).

Furthermore, there are some key understandings about computers:

 Computers are deterministic: they do what you tell them to do. This is news to many, who think of them as pure magic.  Computers are precise: they do exactly what you tell them to do.  Computers can therefore be understood; they are just machines with logical working.

Whilst computational thinking can be a component of many subjects, Computing Science is particularly well-placed to deliver it.

Page 2 Itching for More Overview

Why BYOB?

Since its launch, MIT’s Scratch has received widespread acclaim as an ideal environment through which to introduce learners to computer programming and computational thinking. BYOB takes Scratch further by introducing the ability for users to create their own blocks (procedures/subroutines) with parameter passing, amongst many other features. BYOB is, in this sense, a fully-fledged programming language.

Like Scratch, its building blocks approach all but eliminates a major problem for learners presented by traditional text-based languages i.e. the requirement to recall and type instructions according to a strict syntax.

In addition, its cartoon-style approach with emphasis on rich media types – sound, graphics and animation – have made it popular in the classroom as an engaging and entertaining way to introduce learners to Computing Science.

Abstraction and modularity are major themes in this resource. BYOB’s ability to let users create their own blocks/procedures/modules was a major factor in its choice (this resource was created prior to the release of Scratch 2.0). Abstraction and modularity are implicit from early activities and become more explicit as learners progress through the resource:

OVERVIEW SECTION (may be done as a unit or embedded throughout program tasks)

A Brief History of the Computer placing computation in a historical context

Representing information representing information in binary and associated abstraction

PROGRAMMING SECTION

1: Haunted House Game a broad reintroduction to programming for learners

2: Fancy a Chat? identifying a problem and its associated sub- problems

3: Guessing Game creating procedures in code

4: Hungry Frog Game further work on procedures, problem decomposition and stepwise refinement

5: Shaping Up introducing simple parameters to create more generalised and flexible procedures

Project allowing learners to bring this modular approach to their own programming

Page 3 Itching for More Overview

Using this resource

As well as lessons, exercises and sample answers, this book contains suggested supplementary activities and inter-disciplinary learning opportunities.

It is not the author’s intention that all of these are attempted; rather, they are simply suggestions as to the kind of activities that tutors may find useful in order to enrich learners’ experiences.

Feel free to use this resource as you wish:

 as part of the Computing Science content within Curriculum for Excellence;  to support aspects of the National 4/5 Software Design & Development unit.

Above all, these materials should not be seen as prescriptive. They merely contain guidance and suggestions as to the kinds of approach which can make learning more engaging whilst fostering computational thinking and greater understanding of Computing Science concepts in learners.

Page 4 Itching for More Overview

Curriculum for Excellence outcomes This resource seeks to address the following outcomes within Curriculum for Excellence:

 Using appropriate software, I can work individually or collaboratively to design and implement a game, animation or other application. TCH 3-09a  I can build a digital solution which includes some aspects of multimedia to communicate information to others. TCH 3-08b  By learning the basic principles of a programming language or control technology, I can design a solution to a scenario, implement it and evaluate its success. TCH 4-09a  I can integrate different media to create a digital solution which allows interaction and collaboration with others. TCH 4-08c  I can create graphics and animations using appropriate software which utilise my skills and knowledge of the application. TCH 4-09b

Page 5 Itching for More Overview

Page 6 Itching for More BYOB

BYOB

BYOB (Build Your On Blocks) (http://byob.berkeley.edu/) is a software development environment developed by Jens Mönig with design ideas and documentation provided by Brian Harvey, both from the University of California, Berkeley. It is an open-source variant of MIT’s Scratch and has been used to teach The Beauty and Joy of Computing introductory course in computer science for non-CS-major students at UC Berkeley.

Like Scratch, it allows users with little or no experience of programming to create rich, multimedia projects, but with a number of added features. Chief among these is the ability for users to create their own blocks (hence the name).

BYOB uses almost the same graphical interface as Scratch and thus draws upon significant prior research in educational computing which was informed by constructionist learning theories. These theories emphasise programming as a vehicle for engaging powerful ideas through active learning.

BYOB can open Scratch projects; however Scratch cannot open BYOB projects so BYOB projects cannot be published to the Scratch website.

As a blocks-based programming language, BYOB all but eliminates a major problem for learners presented by traditional text-based languages i.e. the requirement to recall and type instructions according to a strict syntax.

At the time of writing, the latest version of BYOB was 3.1, although a browser-based version called Snap! was also under development.

http://byob.berkeley.edu/

Page 7 Itching for More BYOB

Known Issues

 BYOB is a cross-platform development environment (Windows, Macintosh). It also works on Linux, but requires a little more work to install.  Like Scratch, BYOB creates its own slightly non-standard dialogue boxes when opening and saving files:

Installation

BYOB requires a little preparation before using it in the classroom, but is a mature product that should present few problems.

BYOB can be deployed on a Windows network, requiring only a single installation on a server. This can ease the maintenance of the package, including the ability to centrally manage the contents of the predefined media folders (sprites, backgrounds, costumes, etc).

o Some institutions have found that under these circumstances, double- clicking a BYOB project file may not automatically load in BYOB. The solution to this is to open the project from within the BYOB environment (File→Open…)

Above all, tutors are strongly recommended to test the installation on a learner account before trying to use BYOB with a class.

Page 8 Itching for More BYOB

Useful Resources

There are numerous excellent sites for use with BYOB; however, some notable ones include: http://veritas.eecs.berkeley.edu/courses/course/view.php?id=17 A version of U C Berkeley’s The Beauty and Joy of Computing tailored for high schools

Plus, of course, the following Scratch sites: http://scratch.mit.edu The Scratch home page at MIT. http://info.scratch.mit.edu/Support/Reference_Guide_1.4 Scratch documentation at MIT. http://www.scratch.ie LERO Scratch site.

Page 9 Itching for More BYOB

Page 10 Itching for More Lessons and approach

Lessons and approach

Tutors using this resource may wish to consider the following approaches.

Screencasts

In addition to a traditional booklet, this resource uses screencasts to deliver some of the exemplar tutorials. Each set of screencasts is available as part of the resource download and is also on the RSE/BCS Youtube channel. Tutors may wish to use them on a whole- class basis and/or for learners individually, stopping and starting as they need.

The rationale behind using screencasts is that learners can make quicker progress, as it's more visual and immediate. Screencasts are also a medium that learners are familiar with in their own digital lives via services such as YouTube.

As the lessons progress, it is assumed that learners have gained an understanding of how to use the environment, so the use of screencasts as “scaffolding” is reduced.

Deep Understanding

To accompany the lessons, there are sample written and discussion tasks to enable learners and tutors to assess “deep understanding” of the Computing Science concepts. This draws upon recent work in the CS Principles course at the Universities of San Diego and Glasgow. Aspects of this approach are also seen in UC Berkeley’s The Beauty and Joy of Computing course.

Traditionally, tutors have inferred the degree of learners’ understanding of what they have learned from the programs they have produced; however, research has shown that this is not always a strong indicator. Consequently, consolidation via quizzes, group discussion, questioning and class work/homework should be used to enable the tutor to formatively assess the learners’ understanding throughout the course, rather than simply infer this from their completed programs.

Pair Programming

Collaborative learning is a cornerstone of Curriculum for Excellence and these materials encourage this, through pair programming. Pair programming can be defined as:

“… an agile software development technique in which two programmers work together at one workstation. One, the driver, types in code while the other, the observer (or navigator), reviews each line of code as it is typed in. The two programmers switch roles frequently.

Page 11 Itching for More Lessons and approach

While reviewing, the observer also considers the strategic direction of the work, coming up with ideas for improvements and likely future problems to address. This frees the driver to focus all of his or her attention on the "tactical" aspects of completing the current task, using the observer as a safety net and guide.” Source: Wikipedia

Pair programming can encourage collaboration between learners, as well as making good use of available resources within the classroom.

It is recommended that tutors explicitly advise learners to seek help from a neighbour before asking the tutor for help. Tutors will, however, understand the need to ensure that both learners are equally engaged in the work!

Suggested Activities

Additional activities are suggested throughout the notes. These should not be seen as prescriptive, but as possible ways to enrich a task or topic. Tutors are free to cherry-pick these as going through all of them is likely to significantly extend the unit.

Suggested Activity These opportunities are indicated by Suggested Activity in the left margin.

Inter-Disciplinary Learning

BYOB is a “rich” multimedia environment that offers ample opportunity for inter- disciplinary learning. Within the materials, there are suggestions for possible inter- disciplinary activities, as well as many of the activities being inter-disciplinary in themselves.

IDL Inter-Disciplinary Learning opportunities are indicated by IDL in the left margin.

Page 12 Itching for More A Brief History of the Computer

A Brief History of the Computer

This section outlines the development of computers. It is up to tutors to decide whether to use it as a self-contained unit or to embed the content within the practical lesson sequence. What is a computer?

Stress the long-awaited need for a machine that would take the drudgery and error out of doing calculations.

What would be the problem in doing calculations this way?

Human error/inaccuracy – especially when the human computers get bored or tired.

What was going on during the 1700s and 1800s that created a need to do lots of accurate calculations?

The industrial revolution gave rise to the need for accurate results of calculations to ensure that engineering and tasks could be completed properly. Examples include calculations required for construction of bridges, buildings, building roads, railways and canals, etc.

Even the resulting increased commerce highlighted the need for machines that could perform financial calculations quickly and accurately.

Investigate one of the following people or developments in Computing and write a short paragraph about it.

abacus, , , Altair, Antikythera Mechanism, Apple II, Apple Macintosh, , Colossus, IBM, IBM PC, Internet, iPhone, iPad, Jacquard Loom, LEO, Napier’s “Bones”, Microsoft, silicon chip, World Wide Web

Suggested Activity Create a timeline of Computing for a classroom wall display e.g.

 Divide learners into groups and give each group one or more cards with a development /person.  Groups should research each development/person, obtaining a date and a brief description of the development /person.  Place cards on the time line. The scale will have to be variable; however, this can be a useful illustration of the escalating pace of development in the field.  After all dates were placed students might be invited to tell the class about their device/person.

Page 13

Itching for More A Brief History of the Computer

The following videos may prove useful:

Computers Over Time http://www.bbc.co.uk/learningzone/clips/12724.flv

History of Computer Technology http://www.bbc.co.uk/learningzone/clips/3736.flv

The Turing Test This lesson is intended to prepare the ground for lesson 2: Fancy a Chat? and therefore may work best if used just before it.

Try the following chat programs online then answer the questions that follow:

• http://nlp-addiction.com/eliza/ • http://cleverbot.com/

In discussing the results of the chatbots test with learners, the following might be useful:

ELIZA

ELIZA was written by Joseph Weizenbaum at the Massachusetts Institute of Technology between 1964 and 1966 and was one of the world’s first chatbots. It mimics a Rogerian therapist, often responding by asking the user further questions.

CLEVERBOT

Unlike other chatbots, Cleverbot’s responses are not programmed, but selected from responses created by humans that sit at their computers every day.

When a user types into Cleverbot, the system searches through its saved conversations to find keywords (or an exact phrase) matching the input. It then responds by finding how a human responded to that input.

In 2011, Cleverbot took part in a formal Turing Test at the Techniche Festival at the Indian Institute of Technology Guwahati. Out of the 334 votes cast, Cleverbot was judged to be “59.3% human”, compared to the “63.3% human” achieved by human participants. A score of over 50% is considered by some to be a pass.1

1 http://en.wikipedia.org/wiki/Cleverbot

Page 14

Itching for More A Brief History of the Computer

If you could not tell whether you were talking to a human or a machine, does it mean that the machine is intelligent? No

Explain your answer: The Turing Test tests for anthropomorphic (human-like) responses and behaviour. To pass the Turing test (and thus appear convincingly human), a computer would also have to exhibit human weaknesses, some of which could even be considered to be unintelligent, such as typing errors – effectively “dumbing down”.

Ask learners: “What if the machine looked human? Would you be more likely to think it was intelligent?” Activity Show examples of humanoid robots from YouTube such as Asimo, Gemonoid, etc. NB It is best to vet these videos first before classroom use because of unfiltered comments that accompany YouTube videos.

Give examples of some machines that you think show some kind of “intelligence”. Below each one, describe a way in which you think it is intelligent.

Machine: Satellite navigation unit (e.g. in-car satnav)

What makes it intelligent: Can work out the fastest route for a journey (which is not always the shortest). Can even allow for how busy routes will be at certain times of the day.

Machine: Siri voice recognition technology on Apple iPhone

What makes it intelligent: It can interpret natural spoken language*. It can give intelligent answers such as whether you will need an umbrella today by looking up a weather forecast for the current location (pinpointed by GPS). * Ask learners: does this mean Siri understands natural spoken language?

Look around at your classmates. Can you be sure that they are thinking just like you? What if they’re actually very sophisticated robots with built-in chatbot programs…?!

How would you know? Discuss this with your (human) partner and write down your ideas.

This is a ripe area for discussion. Get learners to come up with a test for consciousness and ask their peers to contradict it.

When learners have covered this work, they will be ready to tackle Lesson 2: Fancy a chat? where they create their own chatbot program.

Page 15

Itching for More A Brief History of the Computer

IDL Philosophy & Religion

Debate: This house would ban the development of super-intelligent computers.

Questions to pose to learners might include:

 How will we know if the Technological Singularity2 has been reached?  How could we test if a machine was truly intelligent?  What would be the implications for the human race? (perhaps even look at the Centre for the Study of Existential Risk and articles in the popular press: http://www.pcpro.co.uk/news/378349/will-artificial-intelligence-wipe-us-all-out http://www.bbc.co.uk/news/technology-20501091 )

The following videos may prove useful:

Ray Kurzweil TED talk on the future of technology: http://www.ted.com/talks/ray_kurzweil_on_how_technology_will_transform_us.html

Ray Kurzweil BigThink talk on the Technological Singularity: http://www.youtube.com/watch?v=1uIzS1uCOcE

2 The “technological singularity” is the theoretical emergence of greater-than-human intelligence, after Vernor Vinge, and Ray Kurzweil. Many theorists suggest it will happen at some point in the mid 21st century.

Page 16

Itching for More Representing information

Representing information

Activity Show learners a microprocessor from a redundant computer. Stress that the actual microprocessor is the small part in the middle and the chip is the size it is in order to allow for the connections to the motherboard.

If tutors could acquire an old valve/vacuum tube, this could very clearly communicate to students the advances that have been made in miniaturisation in the second half of the 20th century.

Moore’s Law

Whilst the relationship between transistor count and processing power is not direct as suggested in the learner notes, it works well as a comparator at this stage.

At a doubling of power every two years, how long would it take for computers to become:

a) 100 times more powerful? Less than 14 years (27 = 128, so fewer than 7 doublings required to reach 100).

b) 1,000 times more powerful? Less than 20 years (210 = 1024, so fewer than 10 doublings required to reach 1,000).

c) 1,000,000 times more powerful? 40 years (220 = 1,048,576, so fewer than 20 doublings required to reach 1,000,000). This means that, at the time of writing in 2012, Moore’s Law would see computers having at least 8 million times more transistors than when Gordon Moore first made his observation.

Page 17

Itching for More Representing information

Find out what is meant by the word “law” in science.

Is Moore’s Law a law? No

Explain your answer A scientific law requires that certain behaviours will always be exhibited under the same conditions. Moore’s Law is not a law because we know that one day it will no longer hold true e.g. it cannot continue indefinitely because we will approach fundamental barriers as transistors approach the limits of miniaturisation at atomic levels. Moore himself stated this in 2005 on the 40th anniversary of his observation.

Find out how many transistors are on a typical modern computer’s processor.

Processor name: Intel Core i7

Transistor count: 1.4 billion

How many times more is that than Colossus’ 1,500 valves (an older kind of transistor) – that is, how many Colossuses (Colossi) could fit onto a single example of your chosen processor? 933,000 – almost 1 million. Colossus filled an entire room whilst a Core i7 processor measures approximately 1.6 cm2

Page 18

Itching for More Representing information

Binary: The language of computers

Conversion between binary and decimal is not explicitly covered here; however tutors may wish to go over this with learners.

Activity The following video may help to explain binary column values to learners: http://www.youtube.com/watch?v=b6vHZ95XDwU

Activity Decode the message below to reveal the name of a famous person.

Binary 101 0010 100 1111 100 0010 100 0101 101 0010 101 0100 Code Letter R O B E R T Binary 100 0010 101 0101 101 0010 100 1110 101 0011 code Letter B U R N S

Activity Using the table shown previously, write your first name in binary!

Write each letter of your first name going down rather than across. Then look up the binary code for each letter in the table overleaf and write it on the lines across from the letter.

You will have written your name in the computer’s own language!

http://www.convertbinary.com provides an online binary conversion tool.

Layer cake Translation from high level language into machine code/binary is a perfect example of abstraction – one of the main themes of this resource.

Activity The following video covers translation between high level language and binary, as well as providing learners with an idea of the size and nature of early computers. http://www.bbc.co.uk/learningzone/clips/software-development/4398.html

Explain to learners the abstraction layers shown in the second diagram on page 16 of their notes.

Page 19

Itching for More Representing information

Page 20

Itching for More Programming in BYOB

Programming in BYOB

As previously mentioned, it is assumed that learners using this resource will have already had an introduction to programming, perhaps via the first resource in this series Starting from Scratch.

Abstraction and modularity are major themes in this resource. Abstraction and modularity are implicit from early activities and become more explicit as learners progress through the resource:

1: Haunted House Game a broad reintroduction to programming for learners

2: Fancy a Chat? identifying a problem and its associated sub- problems

3: Guessing Game creating procedures in code

4: Hungry Frog Game further work on procedures, problem decomposition and stepwise refinement

5: Shaping Up introducing simple parameters to create more generalised and flexible procedures

Project allowing learners to bring this modular approach to their own programming

Page 21

Itching for More Programming in BYOB

Page 22

Itching for More 1: Haunted House Game

1: Haunted House Game

Concepts introduced  The BYOB environment, including o Sprites & stage o Properties . Scripts . Costumes/backgrounds . Sounds  Creating a program with animation & sound  Sequencing instructions  Decision statements  Iteration  Event-driven programming

BYOB commands introduced

 Motion o move steps o turn degrees  Control o when flag clicked o wait secs o [repeat] forever  Sounds o play sound [until done]  Looks o next costume

Computational Thinking themes  Abstraction o what happens e.g. sound plays, sprite moves o position represented by x & y coordinates o broadcast to trigger event  Generalisation o use of variable to represent any value  Decomposition o use of separate scripts to solve separate sub-problems  Algorithm o sequence o event triggers action

Page 23

Itching for More 1: Haunted House Game

Objectives The main purpose of this task is to introduce learners to the BYOB environment and provide a reintroduction to programming. By the end of the lesson, learners should be able to:

 identify the major parts of the BYOB environment  understand how sprites and blocks work and interact  understand the concept of a computer program as a set of instructions  work with simple animation and sound  understand parallel vs sequential execution of instructions  understand that events can trigger actions in a program

Materials  BYOB project: HauntedHouse  Screencast: HauntedHouse

Introduction

 Demonstrate the BYOB environment, linking back to Scratch if appropriate.  Show/let learners watch first part of screencast HauntedHouse.

Task 1: Haunted House

 Teachers could then let learners watch the HauntedHouse screencast or demonstrate the BYOB environment themselves, stressing Sprites & Stage and Scripts, Costumes/Backgrounds & Sounds.  Once learners have done this, they should try to recreate the first part of the HauntedHouse program

Task 2: I ain’t afraid of no ghost!

 Learners should continue with part 2 of screencast HauntedHouse, which will take them through adding a second character to the game.  Stress the use of broadcast and wait to restart the game. This can be a useful route into discussing the idea of “sub-tasks” (as broadcast is the only way of handling sub-tasks in Scratch 1.4, as featured in the previous resource to this one, Starting from Scratch).

Task 3: Collect bonuses Learners should then complete the screencast HauntedHouse and create a bonus sprite. Stress the use of the pick random block, with upper and lower limits.

Page 24

Itching for More 1: Haunted House Game

Extension 1: More bonuses There are lots of appropriate sprites here. Learners should ensure that they get one sprite working as they want it, then duplicate it, change the name and alter the script to change the time it disappears, score, etc.

Extension 2: The key to success For the door, learners will have to create a new sprite whose costume is a white rectangle on a transparent background. They can then resize/rotate it to fit.

When the key sprite is chosen, it should broadcast a suitably-named event which is picked up by the door sprite. The door could either:

 disappear or  rotate, whilst making a creaking sound

If doing the latter, ensure the costume centre is set to the edge of the sprite in the costume editor so that it rotates about the edge.

Extension 3: It’s a living thing Learners will need to create a suitably named variable for lives and reduce this by 1 every time the ghost touches the cat/explorer.

Extension 4: Sound effects The best place to place the sound effects scripts and why each effect works best in a separate script is covered in the questions which follow.

Page 25

Itching for More 1: Haunted House Game

Event-driven programming

Some computer programs just run and continue on their own with no input from the user e.g. your program to play a tune. However, many programs react to events, such as: ● the click of a mouse; ● the tilt of of game controller; ● a swipe of a smartphone screen; ● a body movement detected by a motion-sensing controller such as a Kinect.

In BYOB (and Scratch), event blocks have a curved top (sometimes called a “hat”):

Reacts when the green flag is clicked. Often used to start a program.

Reacts when a key is pressed. Click the small black triangle to select the key you want to detect

Reacts when a sprite is clicked. Useful for controlling characters in a program

As we have seen, it is also possible to create your own events in BYOB using the broadcast and when I receive blocks.

Discuss event driven programming with learners. Go over some other events or conditions that BYOB programs can react to. e.g.

 hitting the edge of the screen (if on edge, bounce)  broadcast a user-definable event  of e.g. o X/Y position of sprite o direction of sprite o background of stage  touching sprite/edge  touching color

Page 26

Itching for More 1: Haunted House Game

Did you understand? 1.1 The following code is used to play a background music in a haunted house game.

Where is the best place for this code to appear – in a sprite on in the stage?

Place The stage.

Explain why It is a game-wide script, rather than belonging in just one sprite. This is an opportunity to introduce the idea of scope within a program.

1.2 A programmer has created a bonus sprite for a character (Cat) to collect during a game. When the programmer tests the game, nothing happens when the Cat “collects” the hat – the bonus sprite doesn’t disappear and the score remains the same.

The code for the bonus sprite is shown below. Explain what mistake the programmer has made.

The code only gets executed at the moment when the green flag is clicked. The remainder should be inside a forever loop.

Page 27

Itching for More 1: Haunted House Game

1.3 A programmer wants to make a random sound (DoorClose) play whilst some background music (Music) is playing.

She has written the code below, but it does not work as expected. Describe what happens when the green flag is clicked.

The Music loop will play. When it has completed one full play-though, there will be a variable pause of between 5 and 15 seconds, then the DoorClose sound will play.

This process will repeat forever.

What would she need to do to make her program work as she intended?

Have the code in two separate blocks that get executed in parallel:

1.4 It is possible to do several tasks within a program in a single script.

Why do you think experienced programmers would prefer to use separate scripts?

It keeps different activities separate, allowing programmers to focus on one thing at a time.

Stress this important idea in Computing Science (decomposition) – breaking down a big problem into smaller ones and solving each of these separately. We will return to this Computational Thinking theme in the lessons which follow...

Page 28

Itching for More 1: Haunted House Game

1.5 A programmer has created code that move a sprite around the screen.

In order to make it more efficient, he decides to remove the move 5 steps block from every if block and have it appear just once at the end of the forever block.

Original code Updated code

Would this work? No.

Explain your answer In the updated code, the move 5 steps block would be constantly executed, causing the character to move in whatever direction was pressed last, even if a key has not been pressed.

Page 29

Itching for More 1: Haunted House Game

1.6 In this lesson, you used the broadcast and wait block; however, there is also a broadcast block.

Describe below what you think is the difference between how the blocks work.

How I think it works How I think it works

Sends an event called ‘restart’ to the Sends an event called ‘restart’ to the rest of the program and immediately rest of the program and waits until any goes on to the next block in the event triggered by that has been current script. completed.

Any When I receive restart script that is triggered will execute concurrently with the remainder of the current script.

Page 30

Itching for More 2: Fancy a chat?

2: Fancy a Chat?

Concepts introduced  Handling text  Handling user input  Conditional loops  Two-way conditional statements

BYOB commands introduced  Motion o glide secs to  Looks o say for secs  Control o repeat until o if…else  Sensing o ask and wait o answer  Operators o join o not, not =

Computational Thinking themes  Abstraction o position represented by x & y coordinates o broadcast to trigger event  Generalisation o use of variable to represent any value of user answer  Decomposition o breaking down problem into component sub-problems  Algorithm o sequence o event triggers action

Objectives Learners should be able to:

 identify an overall problem and its associated sub-problems  work with user text input  Create decision statements (possibly complex/nested)

Page 31

Itching for More 2: Fancy a chat?

Materials

 BYOB project: ChatBot  Screencast: ChatBot

Introduction This lesson is intended to accompany the section in the Introduction on Turing and Chatbots. This should have been covered prior to beginning this lesson.

This lesson may appear to be superficially simpler than Haunted House which precedes it. However, Haunted House is intended as a recap of programming and introduction to BYOB, whereas this lesson is intended to cover program design and decomposition.

(Thanks to Susan Evans for the original chatbot idea on the Scratch Ed website).

The Importance of Design

Before we make anything – a house, a dress or a computer program – we should start with a design. Because there are two important parts to most programs – the interface (how it looks) and the code – we design these separately. ● The easiest way to design the interface is by sketching it out on paper. ● To design the code, write out a list of steps it will have to perform in English. This is known as an algorithm and is just like the steps in a food recipe. Solving problems like this is what programming is really about, rather than entering commands on the computer. All good programmers design algorithms before starting to code!

 Go over the panel above and recap on the concept of an algorithm – a list of steps to solve a problem (usually written in English).  Point out to learners that they are learning to “think like a computer”.

Page 32

Itching for More 2: Fancy a chat?

Designing the solution Go over the top level algorithm for this task, stressing how the overall problem can be broken down in a sequence of steps.

Tutors may wish to demonstrate the Chatbot program and elicit the main steps below from learners prior to them looking at their notes. If so, it is best to demonstrate the program in full screen mode in order to hide the code.

walk onto screen greet user ask for user’s age ask for user’s hobby ask user to tell you more wind up conversation walk off screen

Refining the design Stress that, whilst our top-level algorithm (above) gives a clear idea of what our program needs to do, it’s not yet detailed enough. We must break down these big jobs into smaller stages so that these can be coded.

Main task Breakdown start at left hand side Walk onto screen move to middle of screen say “Hello. I’m Scratch cat!” for 2 seconds Greet user ask “What’s your name?” say “It’s nice to meet you, “ ask “How old are you, ?” if answer is >18 Ask for user’s age say “Wow – you’re old!” for 2 seconds else say “You’re still quite young!” for 2 seconds ask “I like chasing mice. What do you like to do?” Ask for user’s hobby say “Wow!” “sounds really cool!” ask “Tell me more about it” Ask user to tell you keep repeating until answer is not no more “Please…” say “Okay then, we’ve chatted for long enough.” for 3 seconds Wind up conversation say” Must go - those mice don’t chase themselves!” for 3 seconds Walk off screen move off screen

Page 33

Itching for More 2: Fancy a chat?

Go over the section on indentation, stressing its importance in making algorithms and programs more readable. Point out that BYOB takes this a stage further by changing the shade of blocks that are nested inside other blocks (which Scratch does not do).

Task 1 Show/let learners watch screencast Chatbot which will take them through the process of creating the code for the algorithms above.

Alternatively, learners could be encouraged to code this without the help of the screencast, and useful blocks are outlined below:

Task 2 Learners could be encouraged to include a nested if in order to provide the user with more sophisticated feedback (and hence appear more human).

Task 3 Learners design a chatbot of their own. The chat bot must:

 Start when the green flag is clicked  Ask five questions  Responses must use the answers from the user  Use at least one if or if…else block  Use at least one repeat command

Stress to learners the importance of planning their programs before starting to code.

Main task Breakdown Walk onto screen

Walk off screen

Page 34

Itching for More 2: Fancy a chat?

Task 4 Learners create the code for their chatbots in BYOB. Ensure that learners work from their algorithms.

Extension 1

What did Eliza and Cleverbot do to make themselves sound more human? There is a range of possible answers here e.g. Eliza turns around questions to the user and asks for more information.

It is important to approve learners’ suggestions here to ensure they are achievable within the skill/time available.

Did you understand?

2.1 In this program, we accepted input typed in by the user. When doing so, we should always provide a short, helpful message (called a prompt) to tell the user what they’re expected to enter.

Write a prompt asking for the following inputs:

a) the user’s name Please enter your name in the space below.

b) the user’s date of birth Please enter your date of birth (dd/mm/yyyy).

c) guessing a random number between 1 and 10 Guess the number (1-10).

d) a test score as a percentage Please enter your score (0-100).

IDL LANGUAGE Stress the importance of meaningful prompts that are concise but informative (including a hint about the range of acceptable values). Remind learners that sentences should also start with a capital letter and end with a full stop!

Page 35

Itching for More 2: Fancy a chat?

2.2 In this program, we saw the use of the not block to reverse the meaning of another block.

a) Explain in your own words, what will happen in the code shown below:

The program display a message to the user saying “Tell me more about your hobby”. It will then continue to ask “Please…” until the user enters a value other than “no”.

b) Which of the following pieces of code would perform the same task as the code shown above in part a) above?

Write the letters of the correct statements below the table.

A

B

C

Code (letters): B

Page 36

Itching for More 3: Guessing game

3: Guessing Game

Concepts introduced  Problem decomposition  Procedures3  Nesting (decision statements)  Random numbers  Input validation  Complex conditions using AND, OR and NOT

BYOB commands introduced No new BYOB commands are introduced in this lesson

Computational Thinking themes  Abstraction o top level algorithm and refinements o use of procedures to solve sub-problems  Generalisation o use of variable to represent any value  Decomposition o breaking down a task into component sub-tasks  Algorithm o sequence

Materials

 BYOB project: GuessingGame  Screencast: GuessingGame

3 Whilst BYOB uses the term ‘blocks’, ‘procedures’ is a widely used term in education; however, tutors should use the term that they feel most comfortable with, whether it be sub-program, sub-routine, method, etc. The reason for the use of the word “procedure” in these notes stems partly from its use in App Inventor, the development environment used in Pack 3 in this series I ♥ My Smartphone: A Computing Science Course in Mobile App Development, thereby ensuring continuity of terminology.

Page 37

Itching for More 3: Guessing game

Objectives By the end of the lesson, learners should be able to:

 decompose a problem into its component parts  create procedures  understand conditional statements – simple and complex, including the use of NOT to negate a condition  work with nested decision statements  understand the importance of input validation

Task 1: Designing the solution Go over the top level algorithm for this task, stressing how the overall problem can be broken down in a sequence of steps.

As in the previous lesson, tutors may wish to demonstrate the Guessing Game program and elicit the main steps below from learners prior to them looking at their notes. Once again, if doing so, it is best to demonstrate the program in full screen mode in order to hide the code.

when the flag is clicked

choose random number (1-10)

repeat until user’s guess = number

take in user’s guess

check if guess is correct

Just like the previous lesson, the algorithm above provides a clear idea of what any code will have to do. However, stress to learners that we don’t have simple commands in BYOB to “choose random number”, “take in user’s guess” or “check if guess is correct” (shown in bold).

We will therefore need to break down these stages further before we can code them.

Elicit from learners the information (and therefore variables) that the program will need to hold while it is running:

 the random number (number)  the user’s guess (guess)

Page 38

Itching for More 3: Guessing game

Algorithm Code Choose random number set number variable to a random number between 1 and 10 Code this one yourself! set guess variable to 0 give user message about the program

Take in user’s guess ask user to guess the number (1-10) and wait for answer Code this one yourself! set guess variable to user’s answer

Check user’s guess

Write this one yourself! Code this one yourself!

By this stage, all learners are expected to try to create both an algorithm and code themselves.

Task 2 Show/let learners watch screencast GuessingGame which will take them through the process of creating the code for the game.

After watching the screencast, learners should create the game using their own procedures and code.

Point out that they may not have the same code as in the screencast; however, that does not mean theirs is wrong. This provides a good opportunity to discuss the idea that there may be more than one solution to the same problem.

Page 39

Itching for More 3: Guessing game

Procedures: Building Your Own Blocks (BYOB)

In this program, we saw how lines of code can be grouped together into a single block (also called a procedure). Creating a procedure is like creating a new command in your programming language. Procedures let us: ● break down a problem into smaller problems and solve each of those separately. We can then concentrate on just one small “sub-program” at a time. ● create a single piece of code that we can use (or call) as often as we need to within a program. This saves us “reinventing the wheel” by entering the same code lots of times. As a general rule, whenever you have a clear “sub-task” in your program, you should create a procedure to do this. It will make your life easier!

Some learners may view procedures as an additional, unnecessary complication, so go over the panel above stressing the benefits of using procedures.

Task 3: Count guesses Adapt your program so that every time you take in the user’s guess, it counts the user’s guesses.

Hint: Store this in a variable called attempts and display it on the screen (by ticking the name of the variable in the Variables section).

What procedure will you need to change? Take In Number

Page 40

Itching for More 3: Guessing game

Task 4: Hint, hint When checking the user’s guess, tell them if their guess was too low or too high.

Hint: adapt your CheckGuess procedure so that it works in the following way: if guess = number Say “Well done! You guessed it” else ...... so guess is not equal to number if guess < number ...... notice the nested If (one If inside another) say “Too low!” else ...... so guess must be greater than number say “Too high”

Now try to enter a guess that is below 1 or above 10. What does your program do?

The program accepts the input.

What should your program do? Display an error and continue asking the user for the correct input before proceeding any further in the program.

Validating Input

Whenever we get input in a program we should always check that it is valid – allowable or reasonable – before we process it. If an input is invalid, we should: ● tell the user they have entered an invalid value ● tell them what the valid values are ● ask them to re-enter their input

Cover the importance of validation with learners. Elicit what may happen when a program accepts:

 a value out of range  text when it expects a number (or other data type error)  a null string  a zero for a value it will go on to divide by e.g.

Page 41

Itching for More 3: Guessing game

Extension 1: Validate The program should not progress until the user enters a valid value for their guess. repeat until guess>0 and guess <11 blocks.

Extension 2: A fair attempt The program should add to the user’s attempts only if they enter a valid guess. Learners should adapt the TakeInGuess procedure, incrementing the attempts variable only when a valid guess is taken.

Did you understand (part 1)? 3.1 A programmer creates a guessing game like the one in this lesson, but uses variables for the lower and upper limits of the range of numbers.

So, instead of the Choose Number procedure starting with:

it starts with: and the values of lower and upper are set at the beginning of the program:

Although this seems like extra work, why is it a good idea?

It generalises the problem. Once variables are used to store the upper and lower limits, they can be changed in one place and the values are changed anywhere else they are used. Note: The variables in this example are acting like constants used in some other languages. It therefore saves us having to go through our code and change the limits – even in prompts, etc.

Students should then make this change to their program. Tutors should ensure that students replace the lower and upper limits with the new variables wherever they are used.

Page 42

Itching for More 3: Guessing game

Extension 3: (Not) much harder Learners should now adapt their programs so that the user has to guess a number between 1 and 1000! Check that learners’ programs also validate that the user’s input is in the correct range before continuing.

How does the change you made above make this easier?

You only have to enter the range in one place and it changes throughout the program.

Did you understand (part 2)?

3.2 Write down the range of valid values for the following:

a) someone’s age 0–1224

b) the current day of the month 1–31

c) gender “Male”, “Female” (accept “M”, “F”)

d) someone’s title (or salutation) “Mr”, “Ms”, “Miss”, “Mrs”, “Doctor”, etc.

e) The answer to the question: “Do you want to continue? (Yes/No)” “Yes”, “No” Discuss with learners whether the program should also accept “yes”, “no”, “Y”, “N”, “y”, “n”?

3.3 What is the maximum number of guesses a skilled user should take to guess the correct answer when guessing a number between:

a) 1 and 10 ...... 4 b) 1 and 100 ...... 7 c) 1 and 1000 ...... 10 d) Explain how you got the answers above. By going for the midpoint between the possible range each time. Learners may require a visual explanation of this. This could be an opportunity to introduce the concept of a binary search and how an algorithm such as this can lead to much more efficient solutions to a problem compared to simple brute force.

4 Jeanne Calment, the oldest verified human, died in Arles, France (the place of her birth) aged 122 years and 164 days on 4th August, 1997.

Page 43

Itching for More 3: Guessing game

3.4 Discuss the following examples from real life. What “procedures” could they be broken down into?

a) Cooking a three-course meal Look for major stages here, rather than individual steps e.g.

 Prepare starter

 Prepare main meal

 Prepare dessert, etc.

b) Building a house

 Build foundations

 Build wall

 Build roof, etc.

3.5 Research a classic video game (e.g. Pong, Breakout or even a newer one like Angry Birds).

Discuss with your partner some examples of “sub-tasks” within your chosen game that could be coded as procedures.

Write down the “sub tasks” in the space below.

Obvious possible answers here include: Start up game, new level, move character, etc.

Page 44

Itching for More 3: Guessing game

3.6 This question is likely to pose a significant challenge to learners. It will work best if they work in pairs or small groups as signposted in the notes.

In this lesson, we validated input from the user – that is, made sure that it was an allowable value for the input.

Look at the code below that takes in a percentage as a whole number from the user. If the value entered is not valid, it displays an error and asks for the percentage again. This is repeated until the input is valid.

Which of the following repeat until blocks would ensure the user entered a valid percentage? Write the letters of the correct statements below the table.

A

B

C

D

Correct pieces of code (letters): A, C, D ______

Will the correct code work if the user enters a valid percentage the first time? Explain your answer. Yes. In Scratch and BYOB, the loop condition is tested at the start of the loop.

Page 45

Itching for More 3: Guessing game

Page 46

Itching for More 4: Hungry Frog Game

4: Hungry Frog Game

Concepts introduced  Successive decomposition of a problem.

BYOB commands introduced No new BYOB commands are introduced.

Computational Thinking themes  Abstraction o position represented by x & y coordinates o broadcast to trigger event  Generalisation o use of variable to represent any value of user answer  Decomposition o breaking down problem into component sub-problems  Algorithm o sequence o event triggers action

Objectives Learners should be able to:

 identify an overall problem and its associated sub-problems  successively decompose this problem  code final sub-problems using procedures

Materials  BYOB project: Hungry Frog

Introduction Demonstrate Hungry Frog game to learners (press L for a low jump and H for a high jump). Emphasise the need to conserve energy by using a low jump whenever possible.

Go over the top level algorithm for this task, stressing how the overall problem can be broken down in a sequence of steps.

Note that there is no screencast for this lesson. Tutors may wish to elicit the main steps below from learners prior to them looking at their notes.

Page 47

Itching for More 4: Hungry Frog Game

Task 1: Designing the solution Go over the three main objects that need to be coded in the game and the top level algorithms for each.

FROG while energy is more than 0 reduce energy every 5 seconds let user make frog jump game over

FLY move around the screen if eaten by frog increase score and energy respawn fly character

STAGE show pond background play background sound end game when appropriate

Again, point out that just like in previous lessons, these algorithms give a clear idea of what our code will have to do. However, they are not yet detailed enough, so we will need to break them down further before we can code them.

Try to elicit from learners the information (and therefore variables) that the program will need to hold while it is running:

 energy  score

Page 48

Itching for More 4: Hungry Frog Game

FROG – Algorithms SCRIPT - Make frog jump when flag is clicked set energy variable to 50 set score variable to 0 repeat until energy is no longer > 0 if key ‘h’ is pressed call JumpHigh procedure if key ‘l’ is pressed call JumpLow procedure else broadcast GameOver event SCRIPT - Reduce frog’s energy script when flag is clicked repeat forever wait 1 seconds reduce energy by 1

PROCEDURE/BLOCK - JumpHigh play “boing” sound glide for 0.25 seconds to current X position, current y position + 300 glide for 0.25 seconds to current X position, current y position - 300 reduce energy by 3

PROCEDURE/BLOCK – JumpLow Create this algorithm yourself - make the frog jump vertically 150 units and reduce the energy by 1 (space overleaf) /…

Page 49

Itching for More 4: Hungry Frog Game

PROCEDURE/BLOCK – JumpLow Tutors with a knowledge of Physics will realise that if the frog jumps vertically for 150 units, it should use a half, not a third of the 300 unit jump (using energy = mass x gravity x height); however, despite protestations from the author’s namesake, licence has been taken with the laws of Physics in the interests of making the low jump worthwhile!

FLY – Algorithms SCRIPT - Move fly when flag is clicked call SpawnFly procedure loop forever glide for random 0.1 to 0.5 seconds to position x = random from -240 to 240, y = random from -120 to 180

SCRIPT - Fly gets eaten when flag is clicked call SpawnFly procedure loop forever if touching frog sprite call EatFly procedure call SpawnFly procedure

PROCEDURE/BLOCK - SpawnFly hide sprite wait random time between 0.5 and 3 seconds go to position x = random -240 to 240, y = random -100 to 180 show sprite

PROCEDURE/BLOCK - EatFly play “slurp” sound hide sprite increase score by 10 increase energy by 3

Page 50

Itching for More 4: Hungry Frog Game

STAGE – Algorithms SCRIPT - Start of game when flag is clicked set background to “pond” loop forever play swamp sound

SCRIPT - End of game when GameOver event is received set background to ”game over” stop program

Divide and Conquer

Solving a problem like this might seem daunting at first (just like the list of algorithms above)! However, by breaking the problem down into successively smaller and smaller sub-problems, we just have to focus on one small sub-problem at a time. The correct term for this is decomposition – but programmers often just call it “Divide and Conquer”!

Go over the panel above stressing the idea that by subdividing a problem, we give ourselves a series of small (easier) problems to solve instead of one large (difficult) one.

Task 1 Learners are expected to code this program without the help of screencast, so are likely to require some assistance.

Ensure that learners use procedures in their code.

Page 51

Itching for More 4: Hungry Frog Game

Did you understand?

4.1 In this example, why was it particularly useful to code the Spawn Fly part of our program as a separate procedure?

Because it gets used more than once, saving us having to copy out the code multiple times (and edit it in multiple places should we need to change it).

4.2 A programmer has written a program that takes in several numbers, performs a calculation then prints out the result. His program uses the following procedures:

Take In Numbers Perform Calculations Display Results

The program seems to work, but prints out the wrong answer. Which procedure is most likely to have a mistake in it?

Perform Calculations.

4.3 Write a algorithm for getting ready for school.

a) Start with the main stages:

get up have breakfast get washed get dressed leave house

b) Now choose one of the stages and refine it further as a “procedure”.

Learners may choose any stage and refine it. Even then, individual stages of this refinement could be further decomposed e.g. if choosing make breakfast, make toast could be decomposed.

Page 52

Itching for More 5: Shaping Up

5: Shaping up

Concepts introduced  Problem decomposition  Procedures  Nesting (decision statements)  Random numbers  Input validation  Complex conditions using AND, OR and NOT

BYOB commands introduced No new BYOB commands are introduced in this lesson

Computational Thinking themes  Abstraction o top level algorithm and refinements o use of procedures to solve sub-problems  Generalisation o use of parameters to generalise sub-procedures  Decomposition o breaking down a task into component sub-tasks  Algorithm o sequence

Materials

 BYOB project: ShapingUp  Screencast: ShapingUp

Objectives By the end of the lesson, learners should be able to create more flexible procedures by using simple parameters.

Page 53

Itching for More 5: Shaping Up

Introduction Reinforce the benefits of modular programming using procedures e.g.

 once written/defined, a procedure can be called multiple times. The corollary of this is that if a change is required to this code, it only has to be updated once.  procedures let programmers concentrate on one sub-program at a time  procedures make the location (and therefore correction) of errors in code easier.

What happens, however, when we want to reuse code (as in the first bullet point above), but we have to make the code slightly different?

Illustrate this with an example, such as the JumpLow and JumpHigh procedures from the previous lesson (Hungry Frog Game). The procedures are identical, except for the height jumped and the energy used. Ask learners if they can think of an approach to keeping the same code, but letting us change these values.

The answer is, of course, to use variables – but variables we can change whenever we use/call the procedure. In short, we want to generalise our procedures.

Task 1: Shaping up Show/learners watch screencast ShapingUp to learn how to create shapes using BYOB’s Pen commands.

Learners should pause the screencast when it tells them to and create the procedures (blocks) as indicated. Note that if they keep the side length at 100, they will have to alter the sprite’s starting position to avoid hitting the screen edge on larger shapes.

Task 2: Circular pattern Before continuing with the screencast, learners should create a procedure called DrawPattern that calls a DrawSquare procedure to draw 36 squares arranged in a circle.

Learners should be encouraged to change the shape to triangles, pentagons, hexagons, etc. using your procedures from Task 1.

Task 3: Big ones, small ones Continue to show/ let learners watch screencast ShapeUp to learn how to create procedures that can be used to create shapes of different sizes.

Learners should pause the screencast when it tells them to and create the procedures (blocks) as indicated.

Page 54

Itching for More 5: Shaping Up

Parameters: More Flexible Procedures

We can make procedures more flexible by using parameters – variables that the procedure can use to perform a wider range of tasks. In the example above, instead of having different procedures to draw squares of different sizes, we made one “general purpose” square procedure that could be used to draw a square of any size. To do this, it needed a parameter (variable) to tell it the length of a side. When we used (called) the procedure, we could set this to any value. This is another example of computing scientists using shortcuts to make life easier. Q: Does this make them lazy or smart? (Hint: the answer is smart!)

The Rule of Turn Go over the Rule of Turn with learners. Point out that the rule generalises the problem of how to draw a polygon.

If learners have previously studied Pack 1 in this series Starting from Scratch: An Introduction to Computing Science, they may be familiar with the Rule of Turn; however, it is probably still worth going over with them.

Task 4: All shapes and sizes Continue to show/ let learners watch screencast ShapeUp to see how to create procedures that can be used to create any regular polygon of any size.

Task 5: Pattern revisited Following on from the screencast in Task 4, learners should adapt their DrawPattern procedure so that it can draw 36 of any shape arranged in a circle (using a DrawShape procedure with parameters).

Encourage learners to change the repeating shape to triangles, pentagons, hexagons, etc. simply by changing the parameters given to it.

Stress how parameters have generalised the DrawShape procedure, thereby making it much more flexible (versus writing a lot of specific but similar code).

IDL There is clearly a great deal of mathematical content in this lesson. Teachers may wish to relate this to the maths that learners have already covered, or to liaise with their maths teacher in advance.

Page 55

Itching for More 5: Shaping Up

Extension 1: General collection Learners should go back to their Haunted House game and create a procedure for collecting bonus items. Importantly, the same procedure should use a parameter that permits different bonus values for different objects.

The algorithm for the procedure might look like this:

CollectBonus (bonusValue) ...... (bonus value) is a parameter if touching explorer sprite hide change score by (bonusValue) wait random 1-10 secs show

Extension 2: Any which way you can Create procedure in your Haunted House game that can be used to move the explorer, with the direction a parameter. The algorithm for the procedure might look like this:

MoveExplorer (direction) ...... (direction) is a parameter point in direction (direction) move 5 steps This may not reduce our code by very much, but it does have one important benefit. What is it?

It generalises the problem, so that if we need to change the speed of our character (by changing the number of steps it takes in each movement), we need only change it in one place.

Extension 3: One jump to catch them all Go back to your Hungry Frog game and look at the JumpLow and JumpHigh procedures. the code is almost identical, except for the height of the jump and the energy used.

Alter your program so that it uses a single procedure that can jump any height and lose any energy.

Page 56

Itching for More 5: Shaping Up

Extension 4: Final pattern Learners should change their DrawPattern procedure so that it can draw a variable number of shapes arranged in a circle. arranged in a circle of their own. An algorithm is shown below:

DrawPattern (numberOfShapes) repeat (number of shapes) times DrawShape (sides) (turns) turn 360/numberOfShapes degrees

Once again, encourage learners experiment with different parameters, changing the number of shapes and type of shape.

Page 57

Itching for More 5: Shaping Up

Did you understand? 5.1 A programmer has created a game called Vegetable Samurai to encourage healthy eating in children. In the game, the Samurai character has to slice flying vegetables with his trusty sword before cooking them. The programmer has created three scripts for when various vegetables are sliced (left).

Potato How could the programmer script made the code more efficient using procedures and parameters? Write new procedure and new “Slice broccoli” scripts below.

Carrot script

Broccoli script

a) New procedure script (inc. name) b) New broccoli script

SliceFruit (scoreValue) when flag is clicked

play sound forever if touching sword

change score by (scoreValue) say “Broccoli bonus” for 2 secs

hide SliceFruit (100)

Note that say “Broccoli bonus!” for 2 secs is specific to the Broccoli script and so cannot be generalised in this case. However, if every sprite has a say block associated with it, this could be incorporated into the SliceFruit procedure and the specific string passed in as a parameter.

Page 58

Itching for More Project

Project

Analyse  Encourage learners to think about how their project could link with work they’re doing elsewhere. In order to remain focussed, allow a maximum of 15 minutes to look at examples from the Scratch gallery.  Tutors may also wish to demonstrate work done by Brian Clark in BYOB during his time at Learning & Teaching Scotland’s Consolarium: http://consolarium.glo.li/byob/ These materials cover game creation in BYOB, including networked and two-player examples.

Now discuss your ideas with your teacher. Once you have agreed on your project, describe what it will do below.

 At this point, ensure that the scope of the proposed project is achievable for the learners concerned.

Design (Screen)  One or two simple labelled sketches should suffice here. The purpose of this is to force learners to think through their project and how it will function.

Design (Code)  Stress to learners that they must decompose their problem before trying to write any code.  Stress the importance of using procedure to solve separate sub-problems. In order to help with this, encourage learners to name procedures and show any parameters in brackets after the procedure heading.  Stress to learners the importance of taking time to get their algorithms right before coding.

Implement  Remind learners about use of meaningful identifiers for sprites/costumes/sounds and variables.  Stress to learners again that they should be working from their algorithms. These should be in front of them as they code.

Page 59

Itching for More Project

Test  Learners should perform self-testing and get their classmates to test. They should describe the bugs that were found and how they were fixed (or not).

Document  Learners should show they have considered how to write a short, snappy description of their project, including its main features.

Evaluate  Encourage learners to discuss and reflect honestly on their work.  Encourage learners to look at their code to see if they could make it more elegant (refer back to “Lazy or Smart?”)

Maintain  Suggest to learners the maxim: “A computer program is never finished – we just stop developing it any further.”

Congratulations!

Get learners to present their completed projects to the class. This could be done to the front of the class, as a “Dragons’ Den”-style pitch, or have each project set up a different workstation, with groups going around and trying each one.

Encourage learners to continue their BYOB development at home.

An ancient programmer’s proverb

One last thing: never forget the ancient programmer’s proverb… “Hours of coding can save minutes of design” Think about it! ;-)

Page 60

Itching for More Appendices

Appendices

Page 61

Itching for More Appendices

Appendix A: Learner Tracking Sheet

Name: ______Class: ______

Progress * Date Stage Comment (D, C or S) completed A Brief History of the

Computer Representing

Information Programming in BYOB 1: Haunted House Game

2: Fancy a Chat?

3: Guessing Game

4: Hungry Frog Game

5: Shaping Up Project Analysis

Design

Implementation

Testing

Documentation

Evaluation

Maintenance

PROGRESS * Developing Where the learner is working to acquire skills or knowledge. Consolidating Where the learner is building competence and confidence in using the skills or knowledge. Secure Where the learner is able to apply the skills or knowledge confidently in more complex or new situations.

Page 62

Itching for More Appendices

Appendix B: Sample Code

Lesson 1: Haunted House Game Stage Cat/Explorer sprite

Ghost sprite

Bonus sprite

Page 63

Itching for More Appendices

Lesson 2: Fancy a Chat?

Page 64

Itching for More Appendices

Lesson 3: Guessing Game Alonzo sprite (top level)

Choose Number procedure

Take In Guess procedure Check Guess procedure

Page 65

Itching for More Appendices

Lesson 4: Hungry Frog Game Frog sprite (top level)

Jump High procedure

Jump Low procedure

Page 66

Itching for More Appendices

Lesson 4: Hungry Frog Game (continued) Fly sprite (top level)

Eat Fly procedure Spawn Fly procedure

Stage

Page 67

Itching for More Appendices

Lesson 5: Shaping Up

Page 68