Itching for More. An Intermediate Course in Computing Science by Jeremy Scott LEARNER NOTES



Similar documents
Starting from. An Introduction to Computing Science by Jeremy Scott LEARNER NOTES

Scratch Primary Lesson 4

Fruit Machine. Level. Activity Checklist Follow these INSTRUCTIONS one by one. Test Your Project Click on the green flag to TEST your code

Fish Chomp. Level. Activity Checklist Follow these INSTRUCTIONS one by one. Test Your Project Click on the green flag to TEST your code

How to Build a Simple Pac-Man Game

REFERENCE GUIDE 1. INTRODUCTION

The Richard Pate School. Draft Year 4 Scheme of Work for Scratch

Use fireworks and Bonfire night as a stimulus for programming

Make your own Temple Run game

SCRATCH PROGRAMMING AND NUMERACY IN SENIOR PRIMARY CLASSES

CODESPARK TEACHER S GUIDE Hour of Code

CREATIVE S SKETCHBOOK

Algorithms Abstraction

Getting Started with Scratch

Would You Like To Earn $1000 s With The Click Of A Button?

Programming in Access VBA

Computer Science Education Week Teacher/Volunteer Guide

SCRATCH Lesson Plan What is SCRATCH? Why SCRATCH?

SCOTTISH RESOURCES. First Level/Second Level Autumn Tuesdays and 23 September BBC Radio 4 digital (terrestrial, cable, satellite)

I My Smartphone. A Computing Science Course in Mobile App Development by Jeremy Scott LEARNER NOTES

Central England People First s friendly guide to downloading

understanding sensors

BBC LEARNING ENGLISH 6 Minute English Do you fear Artificial Intelligence?

Introduction to Python

1.0-Scratch Interface 1.1. Valuable Information

Year 8 KS3 Computer Science Homework Booklet

Getting Started in Tinkercad

MAKE YOUR FIRST A-MAZE-ING GAME IN GAME MAKER 7

This Method will show you exactly how you can profit from this specific online casino and beat them at their own game.

what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored?

Python. KS3 Programming Workbook. Name. ICT Teacher Form. Do you speak Parseltongue?

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Databases in Microsoft Access David M. Marcovitz, Ph.D.

Whack-a-Witch. Level. Activity Checklist Follow these INSTRUCTIONS one by one. Test Your Project Click on the green flag to TEST your code

My Family FREE SAMPLE. This unit focuses on sequencing. These extension

Welcome to Introduction to programming in Python

Stocks and Mutual Funds

Agent s Handbook. Your guide to satisfied customers

Computer Science Concepts in Scratch

Sage One. Our 5 top tips to stress-free payroll. tress-free. ayroll

Hector s World Lesson plan Episode: Computer security: Oops Lower primary

Samsung Xchange for Mac User Guide. Winter 2013 v2.3

GOALS: The goal for this session is: OBJECTIVES: By the end of the lesson participants should be able to: MATERIALS: Instructor ACTVITIES: EVALUATION:

STEP 0: OPEN UP THE PYTHON EDITOR. If python is on your computer already, it's time to get started. On Windows, find IDLE in the start menu.

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

How-To-Make-Money-Easily. Congratulations!!

1. Get to know the SCRATCH Work Space:

Introduction to Microsoft Publisher : Tools You May Need

Turtle Power. Introduction: Python. In this project, you ll learn how to use a turtle to draw awesome shapes and patterns. Activity Checklist

Easy Casino Profits. Congratulations!!

Quick Start Guide. Microsoft OneNote 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve.

Week 2 Practical Objects and Turtles

CREATING YOUR OWN PROFESSIONAL WEBSITE

Computer Programming In QBasic

Pinterest has to be one of my favourite Social Media platforms and I m not alone!

The Dance Lesson. A good dance lesson should contain some or all of the following:-

Stu S Double Jeopardy Create Your Own Quizzes

DAY ONE ICE-BREAKERS AND INTRODUCTION. Hello. Name of the activity Objectives

What makes a good coder and technology user at Mountfields Lodge School?

Ten easy steps to creating great MicroWorlds EX projects. Steve Robson

Game Programming & Game Design

People know the more common apps such as Angry Birds and Around Me, but can you work out what the following apps do?

Computing Unit Planner: Year 5 Unit 1 Quiz and Game

Fun Learning Activities for Mentors and Tutors

The easy way to accept EFTPOS, Visa and MasterCard payments on the spot. Mobile Users Charging your PayClip. 2. Downloading the PayClip app.

Finding and Opening Documents

Using SMART Boards. Display Power (Projector) & PC Buttons on the Console

mouse (or the option key on Macintosh) and move the mouse. You should see that you are able to zoom into and out of the scene.

Sponsored by: Speaker: Brian Madden, Independent Industry Analyst and Blogger

Getting Started with Excel Table of Contents

Quick Start Guide. Microsoft OneNote 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve.

Dates count as one word. For example, December 2, 1935 would all count as one word.

Conditionals: (Coding with Cards)

The Step by Step Users Guide & 6 Top Trader Skills. Live 24/7 Support Number to Lodge Urgent Query: +44 (0)

Unified Communications Using Microsoft Office Live Meeting 2007

Introduction to Computers

Club Accounts Question 6.

Cal Answers Analysis Training Part I. Creating Analyses in OBIEE

Apple Mac Fundamentals: A Tutorial. Updated 24/4/2013 By Mac Thing enquiries@macthing.co.uk Table of Contents:

Chapter 2. Making Shapes

NETWORKING. What is a packet-switching network?

School. Lesson plan. Topic. Aims. Age group. Level. Time. Materials. School, school objects, rules, subjects, rooms and uniforms

Visual Logic Instructions and Assignments

Child s Communication Book

Your EdVenture into Robotics You re a Programmer

Fun ways to group students

Business Mastery: Smart Strategies Every Business Owner Needs to Promote, Protect and Prosper

File Management Where did it go? Teachers College Summer Workshop

Metatrader 4 Tutorial

Vanderbilt University School of Nursing. Running Scopia Videoconferencing from Windows

Excel macros made easy

13 Managing Devices. Your computer is an assembly of many components from different manufacturers. LESSON OBJECTIVES

Counselor Lesson Plan

Hector s World Lesson plan Episode: Computer security: Oops Upper primary

The Basics of Robot Mazes Teacher Notes

Transcription:

Itching for More An Intermediate Course in Computing Science by Jeremy Scott LEARNER NOTES

1

An Intermediate Course in Computing Science 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 Computer Science 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

An Intermediate Course in Computing Science ii

An Intermediate Course in Computing Science Contents Itching for More... 0 by Jeremy Scott... 0 Acknowledgements... i Contents... iii A Brief History of the Computer... 1 What is a computer?... 1 Representing Information... 7 Switched on... 7 Binary: The language of computers... 10 Layer cake... 12 Programming in BYOB... 13 1: Haunted House Game... 15 Putting Things In Order... 16 Event-driven programming... 18 2: Fancy a Chat?... 23 The Importance of Design... 23 3: Guessing Game... 29 Procedures: Building Your Own Blocks (BYOB)... 31 Validating Input... 33 4: Hungry Frog Game... 39 Divide and Conquer... 42 5: Shaping Up... 45 Parameters: More Flexible Procedures... 46 Project... 51 Congratulations!... 61 An Ancient Programmer s Proverb... 61 iii

An Intermediate Course in Computing Science iv

A Brief History of the Computer A Brief History of the Computer What is a computer? Have you ever wondered what the word computer means? If you look it up in a dictionary, you will find something like: an electronic device which runs a program to process data at great speed We will come to the words program and data soon; however, the word computer means something that computes. So what does compute mean? Well, it means to calculate or work out. The very first computers were actually people. They did sums all day, every day! From around the 1700s until the 1950s, teams of these computers used to carry out complex calculations (and check each other s work). The Computer Room at NASA (opposite) This photograph shows human computers working at NASA as late as 1949. What would be the problem in doing calculations this way? What was happening during the 1700s and 1800s that created the need to do lots of accurate calculations? Page 1

A Brief History of the Computer Investigate one of the following people or developments in Computing and write a short paragraph about it. abacus, Ada Lovelace, Alan Turing, Altair, Antikythera Mechanism, Apple II, Apple Macintosh, Charles Babbage, Colossus, IBM, IBM PC, Internet, iphone, ipad, Jacquard Loom, LEO, Napier s Bones, Microsoft, silicon chip, World Wide Web Made in Britain Around 1940, the first electronic computers began to appear. There is debate about what was the very first, but Britain led developments with Colossus. This early computer was built and used by British Intelligence to break secret German codes during World War II. Colossus was huge (it took up an entire room) and had a tiny fraction of the power of a modern computer or even a smartphone. Nevertheless, the work done using Colossus and other machines like it is said to have shortened World War II by at least two years 1 saving millions of lives. Alan Turing One of the people who worked on this and other early computers was Alan Turing. Turing was a genius whose ideas laid the foundations for what would become the subject of Computing Science. One of Turing s main ideas was that a computer could perform the task of any machine, provided it was given the correct instructions (program). Because of this and many other feats, Turing has been described as The Father of Computing Science. In 2012, events took place around the world to celebrate what would have been his 100 th birthday. 1 Hinsley, Francis Harry (1993), British intelligence in the Second World War: Cambridge University Press, ISBN 978-0-521-44304-3 Page 2

A Brief History of the Computer The Turing Test In 1950, Alan Turing posed a question that has occupied the minds of leading experts in many fields since. He asked: Can machines think? To help answer the question, he proposed a test which would, he said, determine if a computer could think. This has become known as The Turing Test. In the Turing Test, a person asks questions via a keyboard to: a computer (A) and a human (B). If the person asking the questions cannot tell the human and the computer apart from the answers given, Turing claimed that the computer has passed the test and could be said to be intelligent. The wider field of machine intelligence has become known as Artificial Intelligence (AI). Try the following chat programs online then answer the questions that follow overleaf: http://nlp-addiction.com/eliza/ http://cleverbot.com/ Page 3

A Brief History of the Computer What was it like talking to Eliza? What was it like talking to Cleverbot? How were Eliza and Cleverbot similar? How were Eliza and Cleverbot different? When did it seem like you were talking to a human? When did it seem like you were not talking to a human? Which chatbot did you like talking to more? Why? If you could not tell whether you were talking to a human or a machine, does it mean that the machine is intelligent? Yes/No Explain your answer Page 4

A Brief History of the Computer 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: What makes it intelligent: Machine: What makes it intelligent: 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?! 2 How would you know? Discuss this with your (human) partner and write down your ideas. 2 No one is seriously suggesting this is the case, but it maybe says something about how humans react to each other. This is a common theme in science fiction. Page 5

A Brief History of the Computer Page 6

A Brief History of the Computer Representing Information A computer is a machine that processes information (data) using instructions given to it by a human. Computers are electronic machines, so the instructions and information they work with is represented electronically by switches. Switched on No matter what kind of computer you are using a desktop PC, smartphone, games console or embedded computer it is doing one thing: processing information (data). Since a computer is made up of switches, then the information it processes is represented by the positions of switches. How is this possible? Well, think about an ordinary switch. It has two positions OFF and ON but we could also call these positions (or make them stand for): YES or NO BLACK or WHITE 0 or 1 If we had two switches, there would be four possible combinations of these. Look at the table below that shows the four combinations of two switches and examples of the way that you could represent different kinds of information by these. Switch positions OFF / OFF OFF / ON ON / OFF ON / ON Numbers 0 1 2 3 Colours Black Blue Red White Letters A B C D Now consider if there were millions of switches you can see how there could be almost endless combinations of OFF and ON for all of these switches. A modern computer does contain millions (even billions) of tiny switches and they are used to represent all such information. Page 7

A Brief History of the Computer The silicon chip As you have seen, a computer is basically a collection of electronic switches. Over the years, the technology used for this has changed from old electronic valves used in Colossus to the silicon chip. Incredibly, a modern silicon chip can contain over a billion switches (called transistors) on a wafer of silicon smaller than your fingernail! Moore s Law In 1965, Gordon Moore (a founder of silicon chip company Intel, shown opposite 3 ), made an important observation. He noticed that the number of transistors that could be fitted on a silicon chip was doubling approximately every two years. This meant that computer power was also doubling every two years. Roughly speaking, this has stayed true since Moore made the observation and has become known as Moore s Law. At a doubling of power every two years, how long would it take for computers to become: a) 100 times more powerful? b) 1,000 times more powerful? c) 1,000,000 times more powerful? 3 Intel. Image of Gordon Moore remains the exclusive property of Intel and cannot be used or reproduced without Intel s prior written consent. Page 8

A Brief History of the Computer Find out what is meant by the word law in science. Is Moore s Law a law? Explain your answer Find out how many transistors are on a typical modern computer s processor. Processor name: Transistor count: How many times more is that than Colossus 1,500 valves (an older kind of transistor) that is, how many Collossuses (Collossi) could fit onto a single example of your chosen processor? Page 9

Programming in BYOB Binary: The language of computers No matter what you are using your computer for watching a movie, listening to music or surfing the web the data (information) that the computer is processing is represented by the positions of millions of switches. Computing scientists like to call the positions 0 and 1 instead of OFF and ON. This is known as binary. It may seem strange, but it is easier than you might think. For example, when a computer is working with text, each letter is given a binary code. A table of text characters and their binary codes is shown below. Letter Binary code Letter Binary code A 100 0001 N 100 1110 B 100 0010 O 100 1111 C 100 0011 P 101 0000 D 100 0100 Q 101 0001 E 100 0101 R 101 0010 F 100 0110 S 101 0011 G 100 0111 T 101 0100 H 100 1000 U 101 0101 I 100 1001 V 101 0110 J 100 1010 W 101 0111 K 100 1011 X 101 1000 L 100 1100 Y 101 1001 M 100 1101 Z 101 1010 <space> 010 0000 Page 10

Programming in BYOB Activity Decode the message below to reveal the name of a famous person. Binary Code 101 0010 100 1111 100 0010 100 0101 101 0010 101 0100 Letter Binary code 100 0010 101 0101 101 0010 100 1110 101 0011 Letter 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! Page 11

Programming in BYOB Layer cake So if all the information that computers work with is represented by patterns of 1 and 0 (binary), how do computer programs work? If you have done some programming before, you will know that programs are made up of lists of instructions. In the earliest days of Computing Science, these instructions had to be written in the computer s own language of binary. This was very difficult and time consuming. For this reason, programming languages were created that let programmers give the computer instructions using commands that are more like English. However, these commands must be translated into binary before they can work, and that s what packages like Scratch (and BYOB) do they allow us to give the computer instructions in Scratch s language. When we run a program (usually by clicking the green flag), the instructions get converted into binary then carried out by the computer. Gets translated into 1011 0110 1010 0000 1011 0011 1111 0001 0101 1010 0101 0010 1111 1011 1011 0110 1011 0110 1001 1011 Scratch/BYOB programming language Binary Building things up in layers like this is a common idea in Computing Science. What the user sees Program instructions Binary Computer hardware Page 12

Programming in BYOB Programming in BYOB The rest of this course will focus on how to write computer programs. You will be using BYOB (Build Your Own Blocks), an extension of Scratch which was created by University of California, Berkeley, one of the USA s leading universities. If you have used Scratch before, then you already know how to use most of BYOB if not, then don t worry it is easy to learn! In addition to providing a friendly programming language, BYOB is a powerful software development package that lets you create programs (called projects). Importantly, it also lets you build programs up in layers. Scratch projects can also be opened in BYOB; however, it doesn t work the other way Scratch cannot open BYOB projects. You will learn how to use BYOB through a series of lessons. At the end of each task, there will be some questions that will help to check if you have understood the lesson. http://byob.berkeley.edu Page 13

Programming in BYOB Page 14

1: Haunted House Game 1: Haunted House Game This lesson will introduce The BYOB environment o Sprites & stage o Properties Scripts Costumes/backgrounds Sounds Creating a program Introduction Like Scratch, a BYOB program contains sprites (characters) that perform on a stage. Sprites and the stage have three kinds of properties (or settings): 1. Scripts These are the instructions that make our program work. In BYOB, scripts are made from code blocks. There are eight different kinds of blocks to do with motion, control, looks, etc. and over 100 blocks in total. 2. Sprite Costumes or Stage Backgrounds Costumes are outfits for a sprite. The same sprite can have several costumes and so be made to look completely different. A program can have many sprites. The stage can have different backgrounds which can be changed. Backgrounds are just like costumes for the stage. 3. Sounds These are sounds that sprite or the stage can use and make. Again, each sprite (or the stage) can have many different sounds. Sprites need scripts to perform a task. Task 1: Haunted House Watch screencast HauntedHouse. This covers the main features of BYOB and takes you through creating your first BYOB program. If you get stuck, go back in the screencast or ask your partner. Pause the screencast when it tells you to. Page 15

1: Haunted House Game Putting Things In Order Blocks in the same script get executed (carried out) in sequence, one after the other. Blocks in separate scripts can sometimes be executed at the same time. This is called parallel processing having the computer do more than one thing at a time. For example, if you have several when the green flag is clicked. scripts, they will all get executed together Task 2: I ain t afraid of no ghost! Continue screencast HauntedHouse to see how to add a ghost that chases the main character. Remember, ghosts can travel through walls! Pause the screencast when it tells you to. Task 3: Collect bonuses Finish watching screencast HauntedHouse. This shows you how to create a bonus sprite that adds to a score when your character collects it. Congratulations you have just created your first program in BYOB! Bugs A bug is an error which stops your code working as expected. There are two main types of bug which can occur in a program: Syntax error This happens when the rules of the language have been broken e.g. by misspelling a command. Syntax errors usually stop the code from running. Languages like Scratch and BYOB provide code in ready-written blocks, so you won t make many syntax errors. Logic error This means your code runs, but doesn t do what you expect. Unfortunately, it s still possible to make logic errors in BYOB! Finding and fixing these errors in a program is known as debugging. Page 16

1: Haunted House Game Extension 1: More bonuses Add more bonus sprites so that there is one in each room. Hint: Once your first bonus sprite is working properly, simply duplicate it and change its costume before moving it to another room. You could also vary the bonus score and the time for which each object disappears. Extension 2: The key to success Make one of your bonuses a key which unlocks a room when it is collected. The room should only remain unlocked for a certain amount of time. Hint: One way of doing this might be to broadcast a message (call it UnlockDoor). A sprite that looks like a section of wall will hide when it receives the message. Extension 3: It s a living thing Give your character 3 lives. Every time it touches the ghost, it should lose a life. When lives reaches 0, the game should stop. Hint: create a variable lives and set it to 3 when the flag is clicked. Extension 4: Sound effects Add some more sound effects to the stage script which play until done at random times. Here s one to get you started: Remember: you will have to import the sounds to your program before you can use them in a script. Page 17

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. Page 18

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 Explain why 1.2 A programmer has created a bonus sprite which a character (Cat) can 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. Page 19

1: Haunted House Game 1.3 A programmer wants to make a random sound (DoorClosing) 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 flag is clicked. What would she need to do to make her program work as she intended? 1.4 It is possible to perform several different tasks in a single script. Why do you think experienced programmers would prefer to use separate scripts for different tasks? Page 20

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? Explain your answer Page 21

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 Page 22

2: Fancy a Chat? 2: Fancy a Chat? This lesson will introduce Handling text Handling user input Conditional loops Conditional statements Introduction In this lesson, you will create your own Turing Test-style chatbot. 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! Designing the solution Let s list the main stages our chatbot needs to do that is, write an algorithm: 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 Page 23

2: Fancy a Chat? Refining the design Whilst our algorithm certainly gives a clear idea of what our program needs to do, it s not yet detailed enough. We certainly couldn t write the code from this alone. We need to break down these big jobs into smaller stages so that these can be coded. Main task 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 Breakdown start at left hand side move to middle of screen say Hello. I m Scratch cat! for 2 seconds ask What s your name? say It s nice to meet you, <name> ask How old are you, <name>? if answer is >18 else say Wow you re old! for 2 seconds say You re still quite young! for 2 seconds ask I like chasing mice. What do you like to do? say <answer> sounds really cool! ask Tell me more about it keep repeating until answer is not no Please say Okay then, we ve chatted for long enough. for 3 seconds say Must go - those mice don t chase themselves! for 3 seconds move off screen Algorithms let programmers concentrate on what the program has to do instead of how to do it on the computer. Once the algorithm is worked out, writing the code is easy! Notice how an algorithm is indented to show which parts belong inside other parts e.g. if answer > 18 else say Wow you re old! for 2 seconds... carried out if answer > 18 say Bad luck! Try again.... carried out if answer is not > 18 Page 24

2: Fancy a Chat? Task 1 Now watch screencast Chatbot which will take you through the stage of creating the code for the algorithm above. Alternatively, you could try coding this without the help of the screencast. To help, here are some of the blocks you might find useful : Block Use Example Sprite displays text in a speech bubble for the number of seconds Asks the user a question and waits until a value is entered Stores the value the user enters in ask box Used to make decisions in a program Used to make decisions in a program Repeats code until a condition is true Combines two values together Task 2 Add an extra question to the chatbot. Page 25

2: Fancy a Chat? Task 3 Now design a chatbot of your own. Your 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 Plan out the main stages and refinements below. Main task Breakdown Walk onto screen Walk off screen Page 26

2: Fancy a Chat? Task 4 Now create the code for your chatbot in BYOB. Extension 1 What did Eliza and Cleverbot do to make themselves sound more human? Now show your answer to your teacher then try to adapt your chatbot in similar ways. 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 b) the user s date of birth c) guessing a random number between 1 and 10 d) a test score as a percentage Page 27

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: 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): Page 28

3: Guessing Game 3: Guessing Game This lesson will introduce Breaking down a problem into subproblems Building your own blocks (procedures) Nesting (decision statements) Random numbers Input validation Introduction You are going to create a simple game where the user guesses a number chosen at random by the computer. The user keeps guessing until they get the correct answer. Task 1: Designing the solution Let s look at the main things we need to code in our game: 1. choose the random number 2. get the user s guess 3. check if correct 4. steps 2 and 3 should repeat until the user guesses correctly An algorithm for doing this is shown below. 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 gives a clear idea of what our code will have to do. However, 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. Page 29

3: Guessing Game Our program also needs to hold information while it is running: the random number (number) the user s guess (guess) so we will need to use variables for these. Algorithm Code Choose random number set number variable to a random number between 1 and 10 set guess variable to 0 Code this one yourself! give user message about the program Take in user s guess ask user to guess the number (1-10) and wait for answer set guess variable to user s answer Code this one yourself! Check user s guess Write this one yourself! Code this one yourself! Task 2 Watch screencast GuessingGame to learn how to create the game. After you have watched the screencast, create the game using your own code. Remember to use procedures (your own blocks)! Page 30

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! 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? Page 31

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? What should your program do? Now read on to see how to solve this problem... Page 32

3: Guessing Game 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 Extension 1: Validate The program should not progress until the user enters a valid value for their guess. Which procedure will you need to change? Check your answer with your teacher then make the change. Hint: when taking in the user s guess: repeat until guess>0 and guess <11 Extension 2: A fair attempt Your program should add to the user s attempts only if they enter a valid guess. Which procedure will you need to change? Check your answer with your teacher then make the change. Page 33

3: Guessing Game 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? Now make this change to your own program. Extension 3: (Not) much harder Now adapt your program so that the user has to guess a number between 1 and 1000! Hint: Your program should also validate the user s input to ensure it is in the correct range before continuing. Remember to check for this when testing, too! How does using variables for the lower and upper limits of the range make this easier? Page 34

3: Guessing Game Did you understand (part 2)? 3.2 Write down the range of valid values for the following: a) someone s age b) the current day of the month c) gender d) someone s title (or salutation) e) The answer to the question: Do you want to continue? (Yes/No) 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 b) 1 and 100 c) 1 and 1000 d) Explain how you got the answers above. Page 35

3: Guessing Game 3.4 Discuss the following examples from real life. What procedures could they be broken down into? a) Cooking a meal b) Building a house 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. Page 36

3: Guessing Game 3.6 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): Will the correct code work if the user enters a valid percentage the first time? Explain your answer. Page 37

3: Guessing Game Page 38

4: Hungry Frog Game 4: Hungry Frog Game This lesson will introduce Breaking down a problem (problem decomposition) Introduction You are going to create a game where a hungry frog jumps up to catch some tasty flies. However, the frog must conserve its energy by jumping no higher than necessary! The frog s energy decreases by 1 every second and the game will when the frog runs out of energy. Task 1: Designing the solution Let s look at the main things we need to code in our game: FROG while energy is more than 0 reduce energy by 1 every second 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 In video games, the word spawn (or respawn ) means to make a character appear. That we re talking about spawn in a game about a frog is mere coincidence! Page 39

4: Hungry Frog Game 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. Our program also needs to hold information while it is running: the frog s energy (energy) the user s score (score) so we will use variables for these. 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 40

4: Hungry Frog Game PROCEDURE/BLOCK JumpLow when flag is clicked call SpawnFly procedure loop forever FLY Algorithms SCRIPT - Move fly glide for random 0.1 to 0.5 seconds to position x = random from -240 to 240, y = random from -120 to 180 when flag is clicked call SpawnFly procedure loop forever if touching frog sprite call EatFly procedure call SpawnFly procedure SCRIPT - Fly gets eaten 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 41

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! Task 1 No screencast this time try coding HungryFrog yourself! The backgrounds, sprites and sounds are provided for you in the Itching For More folders in BYOB. Remember to use procedures in your code. Page 42

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? 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? 4.3 Write an algorithm for getting ready for school. a) Start with the main stages: Page 43

4: Hungry Frog Game 4.3 (contd.) b) Now choose one of the stages and refine it further as a procedure. Page 44

5: Shaping Up 5: Shaping Up This lesson will cover Creating simple graphics in BYOB Creating more flexible procedures Introduction In this lesson, you will write programs to create simple computer graphics using BYOB s Pen blocks. You will also learn more about using procedures, as well as making them more flexible. Task 1: Shaping up Watch screencast ShapeUp to learn how to create shapes using BYOB s Pen commands. Pause the screencast when it tells you to and create the procedures (blocks) as shown. Write down below procedures to create a heptagon (7 sides) and triangle: Square Pentagon Hexagon Heptagon Triangle Now create procedures for each of the shapes above. Did your procedures work? If not, why not? Page 45

5: Shaping Up Task 2: Circular pattern Make a procedure called DrawPattern that draws 36 squares arranged in a circle. An algorithm is shown below: DrawPattern repeat 36 times draw a square... use a procedure here turn 10 degrees Try changing the shape to triangles, pentagons, hexagons, etc. using your procedures from Task 1. Task 3: Big ones, small ones Continue screencast ShapeUp to learn how to create procedures that can be used to create shapes of different sizes. Pause the screencast when it tells you to and create the procedures (blocks) as shown. 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!) Page 46

5: Shaping Up The Rule of Turn Did you spot the pattern here? In every shape, we turned a full circle (360 ). To work out how many degrees we need to make at each turn, simply Divide the total number of degrees turned in the shape by the number of turns taken So in a square, we go round 360 in 4 turns, so 360/4 = 90 per turn; in a pentagon, we go round 360 in 5 turns, so 360/5 = 72 per turn Task 4: All shapes and sizes Now finish screencast ShapeUp to see how to create a procedure that can be used to create any polygon of any size. Now create the procedure (block) as shown. Task 5: Pattern revisited Change your DrawPattern procedure so that it can draw 36 of any shape arranged in a circle. Use the procedure shown in Task 4 above to draw the shape of your choice. An algorithm is shown below: DrawPattern repeat 36 times DrawShape (sides) (turns)... use a procedure with parameters here turn 10 degrees Try changing the shape to triangles, pentagons, hexagons, etc. by changing the parameters (sides and turns) given to the DrawShape procedure. Page 47

5: Shaping Up Extension 1: General collection Go back to your Haunted House game and create a procedure for collecting bonus items. Importantly, this 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)... [bonus value] is a parameter point in direction (direction) move 5 steps This may not reduce the amount of code by very much, but it does have one important benefit. What is it? 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 48

5: Shaping Up Extension 4: Final pattern Change your DrawPattern procedure so that it can draw a variable number of shapes arranged in a circle. An algorithm is shown below: DrawPattern (numberofshapes) repeat (number of shapes) times DrawShape (sides) (turns)... use a procedure with parameters here turn??? degrees... this can be calculated. Can you work out how? Experiment with using different parameters to change the number of shapes and type of shape Page 49

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 script Carrot script How could the programmer made the code more efficient using procedures and parameters? Write new procedure and new Slice broccoli scripts below. Broccoli script a) New procedure script (inc. name) b) New broccoli script Page 50

Project Project Working in a pair or group, you are now going to create a BYOB project of your own! You may have some ideas already, but programs are normally created in a series of stages: 1. Analyse 2. Design 3. Implement 4. Test 5. Document 6. Evaluate 7. Maintain Or A Dance In The Dark Every Midnight! Now read on to see how these stages apply to you project Page 51

Project Analyse Working in pairs or small groups, brainstorm three ideas for your project. Think of how it might link in with other subject areas you re studying. Think of the areas you ve covered so far... Is it going to be music or graphics-based? A story? A game? The Scratch gallery at http://scratch.mit.edu might give you some ideas. Remember, BYOB can open Scratch projects that you have downloaded. 1. 2. 3. Now discuss your ideas with your teacher. Once you have agreed on your project, describe what it will do below. Page 52

Project Design (Screen) Make a storyboard of your project. Your sketch should be labelled to show what is happening and what each sprite does. Page 53

Project Design (Code) Design the steps for your code (algorithm): Think about blocks/procedures you will want to create. This is easiest done by thinking about your program in big chunks, then breaking each one down. Remember to write the design in English. Think about variables your project will use. Stage Algorithm(s) Head up any procedure/block names you create with CAPITALS Page 54

Project Sprite Algorithm(s) Head up any procedure/block names you create with CAPITALS Page 55

Project Sprite Algorithm(s) Head up any procedure/block names you create with CAPITALS Page 56

Project Think about variables your project will use. Variable name What it will store Implement Now create your project! Gather the sprites, costumes, sounds and backgrounds Remember to give them sensible names. Then create the scripts Make sure you have your algorithms in front of you! Page 57

Project Test Test your project to make sure it works. Let your classmates test it too and note their comments below: Good points: Bad points: Describe bugs that were found (by you or by testers) and how you fixed them: Bug: Solution: Bug: Solution: Page 58

Project Document Let s imagine that you re going to post your project on a website to share with others. Write down below a brief description (50 words max.) of: your project s main features and how to use them. Remember you want to get people to try out your project! Once you have written the description, enter it into your project s notes (File Project notes ). Page 59

Project Evaluate How did the project turn out compared to how you originally planned it? What mistakes did you make on the way? If you were to start again from the beginning, what would you do differently? Look at your code again. Is there anywhere you could have taken a shortcut to make it slicker (for example, by using procedures and parameters)? Page 60

Project Maintain What additional features would make your project better? Congratulations! You have now completed this intermediate course in Computing Science! Remember that you can download and use BYOB at home, so there s no need for this to be the end of your time as a programmer. http://byob.berkeley.edu 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 61