Transcription

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

2 1

3 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 The Royal Society of Edinburgh. Scotland's National Academy. Scottish Charity No. SC i

4 An Intermediate Course in Computing Science ii

5 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 Layer cake Programming in BYOB : Haunted House Game Putting Things In Order Event-driven programming : Fancy a Chat? The Importance of Design : Guessing Game Procedures: Building Your Own Blocks (BYOB) Validating Input : Hungry Frog Game Divide and Conquer : Shaping Up Parameters: More Flexible Procedures Project Congratulations! An Ancient Programmer s Proverb iii

6 An Intermediate Course in Computing Science iv

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

8 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 Page 2

9 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: Page 3

10 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

11 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

12 A Brief History of the Computer Page 6

13 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 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

14 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

15 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

16 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 N B O C P D Q E R F S G T H U I V J W K X L Y M Z <space> Page 10

17 Programming in BYOB Activity Decode the message below to reveal the name of a famous person. Binary Code Letter Binary code 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

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

19 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. Page 13

20 Programming in BYOB Page 14

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

36 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

37 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

38 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

39 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

40 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

41 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

42 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

43 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

44 3: Guessing Game Page 38

45 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

46 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 glide for 0.25 seconds to current X position, current y position 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

48 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

49 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

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

51 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

52 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

53 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

54 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

55 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

56 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

57 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

58 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 might give you some ideas. Remember, BYOB can open Scratch projects that you have downloaded Now discuss your ideas with your teacher. Once you have agreed on your project, describe what it will do below. Page 52

59 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

60 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

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

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

63 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

64 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

65 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

66 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

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

Starting from An Introduction to Computing Science by Jeremy Scott LEARNER NOTES An Introduction to Computing Science Acknowledgements This resource was partially funded by a grant from Education Scotland.

Introduction: This is a game that has three sprites that change costume. You have to stop them when they re showing the same picture (like a fruit machine!). Activity Checklist Follow these INSTRUCTIONS

Scratch Primary Lesson 4 Motion and Direction creativecomputerlab.com Motion and Direction In this session we re going to learn how to move a sprite. Go to http://scratch.mit.edu/ and start a new project:

Introduction: We re going to make a game! Guide the large Hungry Fish and try to eat all the prey that are swimming around. Activity Checklist Follow these INSTRUCTIONS one by one Click on the green flag

1. INTRODUCTION Scratch is a new programming language that makes it easy to create interactive stories, games, and animations and share your creations with others on the web. This Reference Guide provides

CLASSROOM CHALLENGE SIMPLE ANIMATION USING THE RASPBERRY PI In this lesson you will learn how to create simple animations using Scratch and Python. You are going to create repeating patterns using iteration

The Richard Pate School Draft Year 4 Scheme of Work for Scratch Marcus Gilvear July 2014 (Acknowledgements: Phil Bagge and Duncan Hooper) Re Scratch: This work is licensed under the Creative Commons Attribution-NonCommercial

Make your own Temple Run game These instructions will talk you through how to make your own Temple Run game with your pupils. The game is made in Scratch, which can be downloaded here: http://scratch.mit.edu

SCRATCH Lesson Plan What is SCRATCH? SCRATCH is a programming language that makes it easy to create interactive stories, animations, games, music, and art that can then easily be shared on the web. Scratch

I My Smartphone A Computing Science Course in Mobile App Development by Jeremy Scott LEARNER NOTES A Computing Science Course in Mobile App Development Acknowledgements This resource was partially funded

Getting Started with Scratch a guide to designing introductory Scratch workshops draft version, september 2009 Overview There s no one way to host a Scratch workshop. Workshops can take on a variety of

Year 8 KS3 Computer Science Homework Booklet Information for students and parents: Throughout the year your ICT/Computer Science Teacher will set a number of pieces of homework from this booklet. If you

VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

BBC LEARNING ENGLISH 6 Minute English Do you fear Artificial Intelligence? NB: This is not a word-for-word transcript Hello, I'm. Welcome to 6 Minute English and with me in the studio is. Hello,. Hello.

WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

Python KS3 Programming Workbook Do you speak Parseltongue? Name ICT Teacher Form Welcome to Python The python software has two windows that we will use. The main window is called the Python Shell and allows

Databases in Microsoft Access David M. Marcovitz, Ph.D. Introduction Schools have been using integrated programs, such as Microsoft Works and Claris/AppleWorks, for many years to fulfill word processing,

MAKE YOUR FIRST A-MAZE-ING GAME IN GAME MAKER 7 In this tutorial, you will learn how to create your first game in Game Maker. The game you will create will be a simple maze game. The object of the game

Inside the CPU how does the CPU work? what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored? some short, boring programs to illustrate the

The LEGO MINDSTORMS NXT 2.0 robotics kit includes three types of sensors: Ultrasonic, Touch, and Color. You can use these sensors to build a robot that makes sounds when it sees you or to build a vehicle

Introduction: This project is like the game Whack-a-Mole. You get points for hitting the witches that appear on the screen. The aim is to get as many points as possible in 30 seconds! Activity Checklist

Easy Casino Profits The Easy Way To Beat The Online Casinos Everytime! www.easycasinoprofits.com Disclaimer The authors of this ebook do not promote illegal, underage gambling or gambling to those living

Quick Start Guide Microsoft OneNote 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve. Switch between touch and mouse If you re using OneNote

Sage One tress-free ayroll Our 5 top tips to stress-free payroll What do I need to think about? Setting up and running a small business takes a lot of time and effort, so you need enthusiasm, confidence

Getting Started in Tinkercad By Bonnie Roskes, 3DVinci Tinkercad is a fun, easy to use, web-based 3D design application. You don t need any design experience - Tinkercad can be used by anyone. In fact,

Hello ipad 1.0 The Basics 1 The Home Screen & Basic ipad Controls To turn on the ipad Press the Lock Button, the Lock Screen will appear. The date and time will be displayed on the Lock Screen. Slide the

Agent s Handbook Your guide to satisfied customers Introduction LiveChat is a tool that facilitates communication between a company and its customers. Agents who wield that tool use it to make customers

In this chapter Learn how to get around in the Open File dialog box. See how to navigate through drives and folders and display the files in other folders. Learn how to search for a file when you can t

Quick Start Guide Microsoft OneNote 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve. Switch between touch and mouse If you re using OneNote

Hector s World Lesson plan Episode: Computer security: Oops Lower primary BACKGROUND Very young students are unlikely to fully understand how computers work. They may have limited understanding about the

DEAR HOPSCOTCH TEACHER, We are so happy that you have taken an interest in teaching your students computer science! As you may already know, computer science is a discipline that is increasingly necessary

GOALS: The goal for this session is: Learn how to connect and use the SMART Board for effective instruction Ability to annotate and save work using Microsoft Office and SMART Notebook Software OBJECTIVES:

NETWORKING What is a packet-switching network? The internet is an example of a packet-switching network! All internet traffic is broken down into packets, which are small chunks of data that are sent individually

DAY ONE ICE-BREAKERS AND INTRODUCTION Hello This will set the tone for the workshop: it is easy and fun, it helps participants to relax and start to get to know each other. 5 minutes None Group work The

Introduction to Google SketchUp (Mac Version) This guide is handy to read if you need some basic knowledge to get started using SketchUp. You will see how to download and install Sketchup, and learn how

How-To-Make-Money-Easily The Hidden Secrets Of Making Money Online Every Day! www.how-to-make-money-easily.com 2008 Congratulations!! You re about to discover a slightly strange, rather unkown method to

LESSON 14 Stocks and Mutual Funds I ntroduction One characteristic of a market economy is private ownership of property. Property is not just land and real estate; it is anything of economic value that

Table of Contents Elements of An Excel Document... 2 Resizing and Hiding Columns and Rows... 3 Using Panes to Create Spreadsheet Headers... 3 Using the AutoFill Command... 4 Using AutoFill for Sequences...

LESSON 13 Managing Devices OBJECTIVES After completing this lesson, you will be able to: 1. Open System Properties. 2. Use Device Manager. 3. Understand hardware profiles. 4. Set performance options. Estimated

Week 2 Practical Objects and Turtles Aims and Objectives Your aim in this practical is: to practise the creation and use of objects in Java By the end of this practical you should be able to: create objects

Unit 5 This unit focuses on sequencing. These extension Unit Objectives activities give the children practice with sequencing beginning, middle, and end. As the learn to name family members and rooms children

Introduction to Computers Parts of a computer Monitor CPU 3 Keyboard 3 4 4 Mouse 3 4 Monitor The monitor displays the content and operations of the computer. It is the visual display of what the computer

First go to Google s main page (www.google.com). If you don t already have a Gmail account you will need one to continue. Click on the Gmail link and continue. 1 Go ahead and sign in if you already have

Computer Programming In QBasic Name: Class ID. Computer# Introduction You've probably used computers to play games, and to write reports for school. It's a lot more fun to create your own games to play

Plain English Campaign: Tips for clear websites Copyright Plain English Campaign Tips for clear websites This is only a basic guide. If you have any suggestions, corrections or improvements, please contact

Apple introduced the App Store via an itunes update in July 2008. Since then over 15 billion apps have been downloaded and is now worth around $ 7.08 billion. People know the more common apps such as Angry

First Time Off-Campus Remote Desktop Connection ipad Edition General: This guide is a step-by-step guide for configuring and using an ipad to remotely connect to a work computer from off campus. This guide

01 Turtle Power Introduction: This term we're going to be learning a computer programming language called Python. The person who created Python named it after his favourite TV show: Monty Python s Flying

\ (1) Focus of your portfolio: The goal of SED 514 is to equip teachers with technical and pedagogical skills to enhance teaching and learning. You will prepare a 514-portfolio (electronic or paper) of

CHAPTER 1 HelloPurr This chapter gets you started building apps. It presents the key elements of App Inventor, the Component Designer and the Blocks Editor, and leads you through the basic steps of creating

Advanced Interactive Multimedia Presentation Name: Class: Teacher: Developed by Tim Gamble From your last presentation, you learnt how to add interactivity to your presentation. You used action buttons,

Python 1 ASCII Art All Code Clubs must be registered. By registering your club we can measure our impact, and we can continue to provide free resources that help children learn to code. You can register

King s Student Perspectives Computer Science with Maths Profir, 1st year Profir is from Chișinău, the capital city of the Republic of Moldova (which is between Romania and Ukraine). He took A levels the

Hector s World Lesson plan Episode: Computer security: Oops Upper primary BACKGROUND Students of this age are emerging users of internet-enabled computers. They may be involved in a range of online activities

What is an exhibit? An exhibit is a visual representation of your research and interpretation of your topic's significance in history. Your exhibit will look a lot like a small version of an exhibit you

Introduction to Programming If you re new to programming, you might be intimidated by code and flowcharts. You might even wonder how you ll ever understand them. This lesson offers some basic ideas and

Portfolio & Interview Guide Joanna Birkett, BA (Hons) Illustration Contents 04 Live Make at Plymouth College of Art 06 What is a portfolio? 08 Starting from scratch 10 What we would like to see 12 Content

1 I m Miss Smith, and I teach English and German. Today I ll show you how I use NetSupport School to plan, prepare and conduct my classes. Before I take my first class, I ll guide you through the basics