Waimate High School/OER projects/Programming with Greenfoot

From WikiEducator
Jump to: navigation, search

 Introduction



Icon objectives.jpg
Objectives
* Understand what Greenfoot is
* Understand why Greenfoot is great for beginning programmers


Greenfoot is an environment for computer programming.  In particular, Greenfoot has been specially designed for young programmers aged 13 years and up.  Greenfoot uses the Java programming language as a base to enable simple games to be created. 


Computer programming is often thought of as difficult to learn.  It can be tricky, and you will have to concentrate and learn from your mistakes, but Greenfoot will help you understand the concepts of computer programming.


Java is a very common programming language that is used worldwide to make computer programs and also in internet-based technologies.  To learn Java can be quite challenging.  Greenfoot will allow you to learn simple Java in a way that will interest and motivate you.


The Greenfoot website is a rich source of more information on all things Greenfoot!


Greenfoot is freely available for you to download and install on your own computer.

What is Computer Programming?

Most of us probably think we already know what computer programming is.  We are going to look at this in a little more detail now.  We will not need to remember everything we learn at this point as we will be visiting these concepts several times.


Icon activity.jpg
Activity
Text for your activity goes here. You can add bullet lists
  • Go to this simple website on programming
  • Find and use the What is programming link
  • Read through the page - some of this will not make perfects sense but we will come back to it later.
  • On educo, find the what is programming forum and contribute to the discussion topics




What is a Game?

We are going to use Greenfoot to make a simple game.  We therefore need to know - among other things:

  • What is a game and what makes a good game
  • How to use greenfoot


Icon discussion.gif
Discussion
Go on to the educo forum called What is a game and what is your favourite game? Complete the forum activity which involves discussing which game is your favourite game - and why and also what makes a good game?



Using Greenfoot

Before we use Greenfoot for the first time, we'll take a look at what Greenfoot can do. The Greenfoot gallery has lots of games on there to try out. The games can be exported as web pages - try the Mars patrol game which can be found at http://greenfootgallery.org/scenarios/695.

Getting Started - a simple introduction to programming using Greenfoot.

Activity: First Steps with Greenfoot

Icon activity.jpg

Activity: First Steps with Greenfoot

Complete the beginners tutorial on the Greenfoot website. Note: this tutorial requires you to read carefully and follow detailed instructions. Take your time and ask for help if it is required. Complete sections 8 through to 21 and read sections 22 & 23. You may wish to make your own check list to keep track of your progress.



Pseudocode

Pseudocode is a simple way of making statements about how to solve a problem in computer programming.  Pseudocode helps us understand the algorithms needed to solve problems.  The easiset way of understanding pseudocode is to look at some simple problems. 


For example, pseudocode for baking a cake might be:



Could you bake a cake using pseudocode?

  1. Heat oven to 180C
  2. Gather the ingredients together
  3. Mix ingredients in a bowl
  4. Pour the ingredients into a cake tin
  5. Bake in the oven for 20 minutes
  6. While       

                cake uncooked

                bake for 5 minutes more

     7. Take cake out of oven and place on cake rack.


Pseudocode to calculate weekly pay

Pseudocode to calculate the weekly pay for a worker who gets paid 1.5 times the normal rate after working 40 hours in a week would be:

Weekly pay

get hours worked

get hourly pay rate

if hours worked this week =< 40 then

       gross pay = pay rate x hours worked

else

       gross pay = pay rate x 40 + 1.5(pay rate X (hours worked – 40))

display gross pay

halt


More problems

The pseudocode that you use may depend on the problem for example. Sometimes you will need to use while/endwhile, and some use while/wend. Some use = and <> to mean equal and not equal, whereas some use = = and != - or you could write it in English. Some use input and output, some use read/print , some useaccept/display. It doesn't really matter - pseudocode is more concerned with the logic - the control flow issues.



Produce pseudocode to solve the following problems:



Icon qmark.gif

Essential Questions

Produce pseudocode to solve the following problems:


The Car Park


A car park has an entry barrier and displays a “Car Park Full” message when all the spaces have been taken. Write an algorithm that will display this message. The car park has 110 places.

The Online Retailer


An online computer parts retailer has a discount scheme if customers buy multiple items of a part in the same order. For example, the price of hard drives (excluing GST) is discounted as follows


Number purchased Discount taken off full retail price
1 - 3 0.00%
4 - 8 2.00%
9 - 15 6.50%
16 + 10.00%

Your pseudocode needs to be able to calculate the final price that a customer will pay, including GST.

Simple Problems #1

Write pseudocode to ...


  1. Input the dimensions of a rectangle and print its area.
  2. Input the dimensions of a rectangle and print area and perimeter.
  3. Input the length of the side of a square, and print its area. Produce an error message if the length is negative. (i.e.validation)
  4. Input 3 numbers and print either an "all 3 equal" or a "not all equal" message.
  5. Input 3 numbers, and print the biggest.

Another Car Park


Another car park has 200 places for cars and 30 for motorcyles. The automatic barrier will prevent display appropriate full messages if the spaces are taken. Write an algorithm to solve this problem.

Simple (Perhaps slightly more difficult!) Problems #2

  1. Print the numbers 1 to 100 inclusive- with a while loop.
  2. Print the numbers 1 to 100 inclusive with a for loop.
  3. Input 2 values into the variables: start and finish, then print the integers from start to finish inclusive. (use for)
  4. Input 2 values into the variables: start and finish, then print the integers from start to finish inclusive. (use for)
  5. BUT, if start is bigger than finish, don't print the numbers: an error message instead!
  6. Input 2 values into the variables: start and finish, then print the integers from start to finish inclusive. (use for) BUT if start is bigger than finish, swap over their values so they are now in the proper order, then print the integers as specified.
  7. Input 10 numbers, and print their total.
  8. Input 10 numbers, and print their total - but any numbers>100 should be ignored, i.e should not be summed.

Sum and Product


Write pseudocode to take two integers from a user and display the sum and the product (ie the number are multiplied together) of the numbers.

Odd or Even


Write pseudocode to determine if an integer (number) number is odd or even. Hint in computing, the MODULO function will return the remainder after dividing one number by another. Eg. 8 MOD 5 = 3.(ie 8 divided by 5 has 3 'leftover').

Average Class Size


Write pseudocode to calculate the average age of people in a class. Use a while loop.in your solution.

Snap


Look at the pseudocode example for playing monopoly http://www.wiley.com/college/busin/icmis/oakman/outline/chap05/slides/pseudo.htm look also at the link for one person's move http://www.wiley.com/college/busin/icmis/oakman/outline/chap05/misc/monopoly.htm, now using these rules: http://www.ehow.com/list_6448167_snap-card-game-rules.html


produce pseudocode for the game of snap.

Some more slighty difficult problems

  1. Input a count, which specifies how many numbers will follow it. Print the total of the following numbers. (eg the input might be: 4 33 52 67 83 - where the count is 4)
  2. Input a series of positive (>=0) numbers, ended by a negative one. Add up the numbers, and print the total. The negative one is not to form part of the sum.
  3. Input 100 positive (>=0) numbers. Add up the numbers, and print the total. If a negative number is encountered mid-way, the program should terminate, and print the sum so far.
  4. Using nested fors, print an hours and minutes table, of the form:


00:00    00:01    00:02 ....   through to 11:57   11:58   11:59

as far as 11 hours 59 mins.


Files

Assume the following file pseudocode:

open "fred" for input(reading)


open "june" for output(writing)


read data items from "fred"(you may read the whole line as a string, or read it into separate variables - it depends on the problem)


write data items to "june"


close "fred"


test for end of file, eg:

while not end of file

etc


3.1Display each line of file "fred" on the screen.


3.2Read every line in "fred", and write them to file "june"


3.3Count the number of lines in "fred"


In the following, assume that each line (record) contains a persons name and age


3.4Display the ages of everyone called "smith"


3.5Display the names of everyone who is over 40.


3.6write the names of everyone who is over 40 onto a new file.


3.7Write the names of everyone who is over 40 to one file, and the names of everyone <= 40 to another file.


Arrays

The following assume 2 integer arrays, a and b, with elements a[1] to a[100],and b[1] to b[100]

Note that in e.g C++, arrays are numbered from 0, - but that is a minor problem. Imagine that we choose to avoid using element number 0. In VB, you will use ( ) for arrays - in pseudocode, it doesn't really matter.


4.1Set every element of b to 0


4.2Set a[1] to 1, a[2] to 4, a[3] to 9 etc


4.3Read in 100 numbers, and store them in a. Display them on the screen, then in reverse order.


4.4Read in a count, then read in the data values, storing them in a.

eg- the data could be: 4, 55,1232,786,456

If the count is above 100, the program should terminate without reading any numbers.


4.5Read a series of positive numbers into a. The numbers are ended by a negative one, which is not to be stored. (Assume there is not more than 100 numbers)


4.6Assume that 100 numbers have already been stored in a.

Copy each one from the array a into the array b.


4.7Assume that 100 numbers have already been stored in a.

Find the biggest value in a.


4.8Assume that 100 numbers have already been stored in a.

Find the position of the biggest value.


4.9Assume that 100 numbers have already been stored in a.

Search the array a for the value 9876. Either print its position, or print a 'not found' message.


4.10Read 100 numbers into a, then print the sequence in reverse order.

(eg- 123 43 -23 47 ... 667is printed as:

667 ... 47 -23 43 123 )

4.11Assume that 100 numbers have already been stored in a.

Input 2 numbers ( position numbers in the range 1 to 100) then print the values stored in the elements between the two positions. (eg an input of 3 7 should cause the printing of the contents of a[3], a[4], a[5], a[6], a[7] )


4.12Input 2 values - then look at the value stored in each element of the array (100 of them) and print each value that falls between the 2 input values


4.13100 students sit a 'before' exam, and their marks can be assumed to be in the array b. Later, they do an 'after' exam, and those marks are in a. Print the subscript number (i.e in range 1 to 100) of the student who:

a)got the lowest mark overall (before + after)

b)improved the most between b and a.


-----------------------------------------------------------------------------------------------

Example Assessment Problem

The Solar Hot water Heater

Diagram of a typical solar hot water system. The temperature sensors are shown in green, one in the collector and one in the tank.
Scenario and Background Information

The solar water heater works as follows:  The water is heated when the sun shines on the collector. Cold water is pumped from the bottom of the tank to the collector and back. Temperature sensors detect the temperature of the water in the collector and the bottom of the tank. The controller controls the pump. When the temperature of the water in the collector is greater than the temperature of the water in the bottom of the tank, the pump runs (see the details below).

Detailed information required to answer the questions below.


  • The controller has a ON/OFF button.
  • The pump has two speed settings FAST, SLOW and can also be OFF
  • While the temperature of the water in the collector is greater than or equal to 7C more than the temperature detected by the sensor in the tank, the pump is run FAST.
  • While the temperature of the water in the collector is between 1C and 6C more than the temperature detected by the sensor in the tank, the pump is run SLOW.
  • If the temperature of the water in the collector is the same as or lower than the temperature detected by the sensor in the tank, the pump is turned off.
  • The controller requires electricity to run. A more expensive version of the controller has a detector light that flashes continuously while the mains electricty supply is working, even if the controller has been switched off using the on/off button.

Questions - how to write the pseudocode - if you get stuck on any point, move on to the next.

  1. Write down the inputs and variables. For example int collectorTemp = temperature detected by the collector sensor. You will need both int and boolean variables (remember these are true/false). Give them sensible names
  2. Write a WHILE loop to solve the third bullet above. You can use something like "get temperature of collector sensor" and "get temperature of tank sensor" to find out the temperatures required. The pump speed can be set using "pump speed = FAST" (SLOW/OFF etc)
  3. Write a WHILE loop to solve the fourth bullet point above.
  4. Add an IF statement to cover the fifth bullet point.
  5. Add code to control the ON/OFF - is this an IF or a WHILE?
  6. For a Merit: Add the code to control the flashing light - this is a WHILE that goes around all your code. You could use" Get mains power status" to check if the mains electricity is on.


Solution to the solar water heater problem


//1. First we decide our variables and the type - e.g. int or boolean. Give them sensible names.

int collectorTemp //is the temperature detected by the collector sensor
int tankTemp//temperature detected by the tank sensor
boolean onSwitch//is the state of on/off switch (on = true, off = false)
int difference = 0
collectorTemp = 0
tankTemp = 0
onSwitch == true

//2. now we do a while loop for the pump speed when the temperature difference 7C or more.
//This sets the speed pump speed to fast, rechecks the sensor temperatures and recalculates
//the temperature difference.

While difference =>7 (greater than 7)
    pump speed = FAST
    collector Temp = get temperature of collector sensor
    tankTemp = get temperature of tank sensor
    difference = collectorTemp - tankTemp
EndWhile

//3.Now we do it for between 1C and 6C.

While difference =>1 and =<6 (between 1 and 6)
    pump speed = SLOW
    collector Temp = get temperature of collector sensor
    tankTemp = get temperature of tank sensor
    difference = collectorTemp - tankTemp
EndWhile

//4. Now we add the if to turn the pump off when the tank is warmer
//or the same temp as the collector.

If
    difference =<0 (less than or equal to zero)
    pump speed = OFF


//Now we add the ON/OFF switch. The difference between a
//while and an if is that whil continually checks but an if is
//run through once.



int collectorTemp //is the temperature detected by the collector sensor
int tankTemp //temperature detected by the tank sensor
boolean onSwitch //is the state of on/off switch (on = true, off = false)
int difference = 0
collectorTemp = 0
tankTemp = 0
onSwitch == true

//we add the if before the while loops - so they will only
//run if the switch is ON.

if onSwitch == true

    While difference =>7 (greater than 7)
        pump speed = FAST
        collector Temp = get temperature of collector sensor
        tankTemp = get temperature of tank sensor
        difference = collectorTemp - tankTemp
    EndWhile


    While difference =>1 and =<6 (between 1 and 6)
        pump speed = SLOW
        collector Temp = get temperature of collector sensor
        tankTemp = get temperature of tank sensor
        difference = collectorTemp - tankTemp
    EndWhile

    If
        difference =<0 (less than or equal to zero)
        pump speed = OFF
    endif


//Now for the MERIT part.
//We need to add a while that checks the staus of mainspower
//and makes a greeen light flash even if the on switch is 'off'.

int collectorTemp = temperature detected by the collector sensor
int tankTemp = temperature detected by the tank sensor
int difference = 0
boolean onSwitch = state of on/off switch (on = true, off = false)
//add another boolean to see if the power is on
boolean powerOn = state of mains power (true = pwer connected, false = power disconnected)

while powerOn == true greenlight == flashing

    if onSwitch == true

        While difference =>7 (greater than 7)

            pump speed = FAST             

            collector Temp = get temperature of collector sensor             

            tankTemp = get temperature of tank sensor             

            difference = collectorTemp - tankTemp         

        EndWhile



        While difference =>1 and =<6 (between 1 and 6)

            pump speed = SLOW

            collector Temp = get temperature of collector sensor

            tankTemp = get temperature of tank sensor

            difference = collectorTemp - tankTemp

        EndWhile

        If             difference =<0 (less than or equal to zero)

            pump speed = OFF

        endif

     endif

powerOn = get mains power status

EndWhile