• No results found

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

N/A
N/A
Protected

Academic year: 2021

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

Copied!
67
0
0

Loading.... (view fulltext now)

Full text

(1)

Itching for

More

An Intermediate Course in Computing

Science

by Jeremy Scott

(2)
(3)

Itching for More An Intermediate Course in Computing Science

i

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

(4)
(5)

Itching for More An Intermediate Course in Computing Science

iii

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

(6)
(7)

Itching for More A Brief History of the Computer

Page 1

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?

_______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________

(8)

Page 2

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 years1 – 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 100th birthday.

1

Hinsley, Francis Harry (1993), British intelligence in the Second World War: Cambridge University Press, ISBN 978-0-521-44304-3

(9)

Itching for More A Brief History of the Computer

Page 3

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 TheTuring 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/

(10)

Page 4

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 ____________________________________ _______________________________________________________________________ _______________________________________________________________________

(11)

Itching for More A Brief History of the Computer

Page 5

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.

(12)

Page 6

(13)

Itching for More A Brief History of the Computer

Page 7

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.

(14)

Page 8

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 opposite3), 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.

(15)

Itching for More A Brief History of the Computer

Page 9

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?

_______________________________________________________________________ _______________________________________________________________________

(16)

Page 10

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

(17)

Itching for More Programming in BYOB

Page 11

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!

(18)

Page 12

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.

Program instructions

Binary

Computer hardware

What the user sees

(19)

Itching for More Programming in BYOB

Page 13

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.

(20)

Page 14

(21)

Itching for More 1: Haunted House Game

Page 15

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 arethe 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.

(22)

Page 16

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 scripts, they will all get executed together

when the green flag is clicked.

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 mis-spelling 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.

(23)

Itching for More 1: Haunted House Game

Page 17

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.

(24)

Page 18

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

(25)

Itching for More 1: Haunted House Game

Page 19

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.

___________________________________ ___________________________________ ___________________________________ ___________________________________ ___________________________________

(26)

Page 20

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?

__________________________________________________________________ __________________________________________________________________ __________________________________________________________________

(27)

Itching for More 1: Haunted House Game

Page 21

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 __________________________________________________ __________________________________________________________________ __________________________________________________________________ __________________________________________________________________

(28)

Page 22

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

_______________________________ _______________________________ _______________________________ _______________________________ _______________________________ _______________________________ _______________________________

(29)

Itching for More 2: Fancy a Chat?

Page 23

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

(30)

Page 24

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 Breakdown

Walk onto screen start at left hand side

move to middle of screen

Greet user

say “Hello. I’m Scratch cat!” for 2 seconds ask “What’s your name?”

say “It’s nice to meet you, “ <name>

Ask for user’s age

ask “How old are you, <name>?” if answer is >18

say “Wow – you’re old!” for 2 seconds else

say “You’re still quite young!” for 2 seconds

Ask for user’s hobby ask “I like chasing mice. What do you like to do?”

say <answer> “ sounds really cool!”

Ask user to tell you more

ask “Tell me more about it”

keep repeating until answer is not no “Please…”

Wind up conversation

say “Okay then, we’ve chatted for long enough.” for 3 seconds

say “Must go - those mice don’t chase themselves!” for 3 seconds

Walk off screen 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

→ say “Wow – you’re old!” for 2 seconds ... carried out if answer > 18 else

(31)

Itching for More 2: Fancy a Chat?

Page 25

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

(32)

Page 26

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

(33)

Itching for More 2: Fancy a Chat?

Page 27

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

(34)

Page 28

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

(35)

Itching for More 3: Guessing Game

Page 29

3: Guessing Game

This lesson will introduce

 Breaking down a problem into sub-problems

 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).

(36)

Page 30

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

give user message about the program

Code this one yourself!

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.

(37)

Itching for More 3: Guessing Game

Page 31

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).

(38)

Page 32

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? ______________________________________________ _______________________________________________________________________

(39)

Itching for More 3: Guessing Game

Page 33

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.

(40)

Page 34

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? _______________________________________________________________________ _______________________________________________________________________

(41)

Itching for More 3: Guessing Game

Page 35

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.

_____________________________________________________________ _____________________________________________________________ _____________________________________________________________

(42)

Page 36

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.

__________________________________________________________________ __________________________________________________________________ __________________________________________________________________ __________________________________________________________________

(43)

Itching for More 3: Guessing Game

Page 37

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.

__________________________________________________________________ __________________________________________________________________

(44)

Page 38

(45)

Itching for More 4: Hungry Frog Game

Page 39

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!

(46)

Page 40

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) /…

(47)

Itching for More 4: Hungry Frog Game

Page 41

PROCEDURE/BLOCK – JumpLow

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

(48)

Page 42

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.

(49)

Itching for More 4: Hungry Frog Game

Page 43

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:

_____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________

(50)

Page 44

4.3 (contd.)

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

(51)

Itching for More 5: Shaping Up

Page 45

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? __________________________________________________________ _______________________________________________________________________ _______________________________________________________________________

(52)

Page 46

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!)

(53)

Itching for More 5: Shaping Up

Page 47

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.

(54)

Page 48

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.

(55)

Itching for More 5: Shaping Up

Page 49

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

(56)

Page 50

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). How could the programmer made the code more efficient using procedures and

parameters?

Write new procedure and new “Slice broccoli” scripts below.

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

____________________________ ___________________________ ____________________________ ___________________________ ____________________________ ___________________________ ____________________________ ___________________________ ____________________________ ___________________________ ____________________________ ___________________________ ____________________________ ___________________________

Potato script

Carrot script

Broccoli script

(57)

Itching for More Project

Page 51

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… ADance In The Dark Every Midnight!

(58)

Page 52

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.

_______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________

(59)

Itching for More Project

Page 53

Design (Screen)

Make a storyboard of your project.

(60)

Page 54

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)

(61)

Itching for More Project

Page 55

Sprite Algorithm(s)

(62)

Page 56

Sprite Algorithm(s)

(63)

Itching for More Project

Page 57

 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

(64)

Page 58

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: ________________________________________________________________ _______________________________________________________________________

(65)

Itching for More Project

Page 59

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…).

(66)

Page 60

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)?

_______________________________________________________________________ _______________________________________________________________________ _______________________________________________________________________

References

Related documents

VanDerbilt uniVerSity law School; naShVille, tn.. This market shift will likely become even more pronounced with the release of a new worldwide standard published by

Structured settlements generally involve many parties, including the plaintiff, the defendant, their attorneys, the defendant’s li- ability insurer, a life insurer (often an

discrimination laws “relate to” but do not necessarily “aris[e] out of” the container contract. Each allegation hinges on conduct that is far removed from the agreement, such as

We carry out series of optimizations for wings based on three significantly different aircraft configurations (long-range transport, regional transport, and short-range commuter)

Here, public support for innovation is revealed as a key factor for facilitating investments in innovation by LAC manufacturing firms, different from Crespi and Zuñiga (2012)

Edson, Filho, Selenia, Di Fronso, Fabio, Forzini, Mauro, Murgia, Tiziano, Agostini, Laura, Bortoli, Claudio, Robazza and Maurizio, Bertollo (2015) Athletic Performance and

Writing before the publication of Weitzman’s [30] proof of the necessity of the transver- sality condition for bounded utility functions, Brock [6] (p. 140) proposed a

In 2005 and 2006 winter and spring subplots, total percent plant cover, cover crop or cotton cover, and Palmer amaranth (Amaranthus palmeri Wats.) and common purslane