• No results found

Learning objectives

N/A
N/A
Protected

Academic year: 2021

Share "Learning objectives"

Copied!
15
0
0

Bezig met laden.... (Bekijk nu de volledige tekst)

Hele tekst

(1)

Algorithmic Thinking and Structured Programming (in Greenfoot)

2017 Renske Smetsers-Weeda & Sjaak Smetsersc 1

Contents

Introduction 1

Learning objectives 2

Instructions 2

Theory 2

8.1 Greenfoot feature:while loop in the Run . . . . 2

8.2 Calling a method inact . . . 4

8.3 Run while you can! . . . 4

8.4 Run or Act? . . . 5

8.5 TheMovableActor class . . . 5

8.6 Nestedif .. then .. else .. statements . . . 6

Challenges 9 8.1 Find the egg usingif .. then .. else .. (instead ofwhile) . . . 9

8.2 Getting started with Sokoban . . . 10

8.3 Responding to arrow keys . . . 10

8.4 Mimi pushes eggs forward . . . 10

8.5 Scoreboard . . . 11

8.6 Level achieved . . . 11

8.7 Oops .. undo? . . . 12

8.8 New levels . . . 12

Reflection 13

Saving and Handing in 14

1Licensed under the Creative Commons Attribution 4.0 license:https://creativecommons.org/licenses/by/4.0/

(2)

Introduction

In this assignment you will write a game in Greenfoot known asSokoban. See http://sokoban.info/

for an example. Our variation is called ’Mimi the egg-hoarder’. The original game takes place in a warehouse. The player is a warehouse employee whose task is to push crates to the correct location.

This game is played in theMadagaskarworld; the world in which Mimi lives. The goal is for Mimi to push all the eggs into the nests. The following rules apply:

• Mimi can only push eggs forward, she can’t pull an egg;

• Mimi cannot sit on an egg or step over it;

• Mimi can only push one egg at a time. As a consequence, Mimi cannot push two (consecutive or adjacent) eggs simultaneously;

• No two eggs can occupy one cell (not even in a nest);

• A nest can hold only one egg;

• An egg can be pushed out of a nest;

• Neither Mimi nor an egg can be pushed through a fence;

• Mimi can step over a nest (of course, very carefully so that she doesn’t destroy it). If the nest holds an egg, she will push the egg out;

• There are as many nests in the world as eggs;

• The level is completed when each nest is filled with an egg.

Contrary to the previous assignments, you will not implement an algorithm to make Mimi do some- thing. This time the user directs Mimi by pressing a key, and in the code we must explain what Mimi must do depending on which key is pressed.

We start by explaining a particular use ofif .. then .. elsestatements. This is needed to incor- porate user-interaction for the different keys in the Sokoban game.

In addition, you will learn to use theRun which is built into Greenfoot. This is needed for user- interaction. With this, methods called in theactmethod will continuously be repeated. As a conse- quence, we don’t need awhileloop to repeat the steps of our algorithm.

(3)

Learning objectives

After completing this assignment, you will be able to:

• explain in your own words how the Greenfoot Run works (as repeating the code in act( ));

• stop a Greenfoot program;

• handle user interaction in the code;

• apply nestedif..then..elsestatements;

• apply the knowledge from previous assignments to implement a game on your own.

Instructions

For this assignment you will need:

• scenario ’DodoScenario8’: to be downloaded from the course website2.

Throughout the assignment you will also need to answer some questions. The following must be handed in:

• All flowcharts: use pencil and paper, or go to https://www.draw.io/;

• Your code: the fileMyDodo.javandEgg.javacontain all your code and must be handed in;

• The reflection sheet: complete and hand it in.

You must discuss all other answers with a programming partner. Jot down a short answer on (the assignment) paper.

There are three types of challenges:

Recommended. Students who need more practice or with limited programming experi- ence should complete all of these.

Mandatory. Everyone must complete these.

Excelling. More inquisitive tasks, designed for students who completed 2 star tasks and are ready for a bigger challenge.

Students who skip 1-star challenges should complete all 3-star challenges.

A note in advance:

• In this assignment you may only make changes to theMyDodoclass and theEgg;

• You may use methods from theDodo,EggandMovableActorclass, not from theActorclass;

Theory

Theory 8.1: Greenfoot feature: while loop in the Run

Greenfoot has a built-inRun command feature. If you press the Run button, then theactmethod will called repeatedly. This is great for programming games and things with user interaction because we want the game to continue even after the user has given a first input.

2http://course.cs.ru.nl/greenfoot/

(4)

Using the Run is only useful if the algorithm consists of repeating the same steps over and over again, like checking for user-input. The step that must be repeated must then be placed in theact( ) method. The code in theact( )method is called repeatedly in thewhileloop of theRun.

Consequences for your code

However, if you want to use theRun you have to change the way you specify your algorithm. In the previous assignments you described algorithms which make use of awhileto repeat certain steps. An example is the ’find-the-egg’ algorithm (Challenge 2.6)which used: ”While not egg found, take a step.”

Figure 1 shows the corresponding flowchart.

Figure 1: Flowchart for ’find-the-egg’ algorithm using awhile(Challenge 2.6)

Using theRun, thewhile-construct in the algorithm will be replaced with a if..then..elsecon- struct as follows:

(5)

Figure 2: Flowchart for ’find-the-egg’ algorithm in theact( ) method

From now on we will set-up the program so that each step of the algorithm is placed in theact method. Then, when theRun button is pressed, the entire program is executed.

TheRun, with it’swhile-loop always remains the same. From now on we will therefore not draw thewhileloop anymore. You won’t find the loop anywhere in the code either: it is built-in Greenfoot.

Stopping the program

UseGreenfoot.stop( ) to interrupt theRun and stop the program. Alternatively, you can press the

’Pause’ or ’Reset’ button.

Theory 8.2: Calling a method in act

By calling a method inact( )it will be run once when theAct button is pressed, or repeatedly when theRun button is pressed. Call a method in theactas follows:

public void act( ) { methodName( );

}

Theory 8.3: Run while you can!

If you press theRun button in Greenfoot, then the whole scenario is executed. That means that for each actor theactmethod is continuously executed. This repeats, for each actor, over and over again until you press thePause button, or untilGreenfoot.stop( )is called somewhere in the code.

Flowchart

The flowchart in figure 3 describes theRun behaviour.

(6)

Figure 3: Flowchart forRun

The flowchart explained:

When the user pressesRun, then:

• First the condition expression in the diamond ’NOT stop’ is checked;

• If the condition expression is ’False’ (that is,Greenfoot.stop( )has been called in the code), then theRun method ends.

• If the conditional expression is ’True’, then for each actor theactmethod is called.

After the act method is executed for each actor, the method jumps back to the diamond and checks the conditional expression again. Is ’NOT stop’ still true? Then the ’True’ path is followed again and the actmethod is called again (loop). This continues to happen until the condition becomes ’False’.

Note: In Greenfoot you can execute a method in several ways:

• By calling the method directly. Right-click on the object (for example, Mimi) and select the method.

• Press the Act button. For this to work, the method must be called in thevoid act( )code.

• Press the Run button. Here too, for this to work, the method must be called in thevoid act( ) code. In this case, the method is called repeatedly.

Theory 8.4: Run or Act?

You maybe wondering ”Why on Earth did they add aRun button?”. There are several reasons for this:

• Too respond to user-input (mouse or keyboard). Using the Run functionality you’re not forced to do everything at once in theact. If you would place all the code in the everything in theact, it may take a long time before the program responds to any user-input, if it responds at all. Obviously that’s not the intention, and very frustrating for the user. By using theRun, your program can quickly responds to user-input.

• To involve multiple actors, each with their ownactmethod. For example: if you place twoMyDodo instances in the world, then each will have their ownact. Try it out. What you usually want is that all these objects do something (more or less) simultaneously. You won’t be able to do that if you have the entire task in theactmethod, but you will if you break the task down into smaller steps.

Theory 8.5: The MovableActor class

(7)

New to the Sokoban scenario is theMovableActorclass. EachDodocan be moved (and is thus movable), and now belongs to theMovableActorclass. Contrary to the previous assignments,Eggs can now be moved too. BothEggs andDodos belong to theMovableActorclass. The class diagram shows bothDodoandEggas sub-classes ofMovableActor.

TheMovableActorhas several ’move’-related methods such as

void step (int direction) and boolean borderAhead (int direction) (both have been moved from theDodo class to the MovableActorclass). Mimi now in- herits these methods fromMovableActor. See figure 4:

Figure 4: Methods which Dodo inherits fromMovableActor

Egg class

Eggs now belong to the MovableActor class. They too can use the step and borderAheadmethods. In addition, several new methods have been added to the Eggclass. The most important are:

• void push ( int direction): which allows an egg to be pushed in a partic- ular direction. This direction is passed as a parameter.

• boolean canBePushed ( int direction ): which can be used to test if an egg can be moved in the specified direction.

Theory 8.6: Nested if .. then .. else .. statements

To test multiple cases simultaneously, nested if .. then .. else statements can be used. We use nesting to handle keyboard input. When the user presses one of the arrow keys on the keyboard, Mimi must face in that direction.

Code using nestedif .. then .. else ..statements

The Greenfoot methodboolean isKeyDown (String key)tests whether the user has pressed a partic- ular key. The following method checks the ”up-arrow” button has pressed:

Greenfoot.isKeyDown ("up");

In the handleKeyPress method this test is used to determine which key has been pressed and changes the direction in which Mimi is facing accordingly:

public void handleKeyPress() {

// check if the left-arrow key has been pressed if ( Greenfoot.isKeyDown( "left" ) ) {

setDirection ( WEST );

} else {

// check if the right-arrow key has been pressed

(8)

if ( Greenfoot.isKeyDown( "right" ) ) { setDirection ( EAST );

} else {

// check if the up-arrow key has been pressed if ( Greenfoot.isKeyDown( "up" ) ) {

setDirection ( NORTH );

} else {

// check if the down-arrow key has been pressed if ( Greenfoot.isKeyDown( "down" ) ) {

setDirection ( SOUTH );

} } } } }

Flowchart using nested conditional statements:

The corresponding flowchart looks like this:

Figure 5: Flowchart forhandleKeyPress

Note: As a result of the numerous accolades and the fact that the code stretches further and further to the right, the code becomes hard to oversee and furthermore error-prone. We will now explain another construct which leads to clearer code.

Simpler code usingelse .. if..statements

In Java, there is an simpler way for writing these types of nested conditional statements. Most pro- grammers combine theelse and the if into one code-line using an else .. if.. statement. The methodhandleKeyPressthen becomes:

public void handleKeyPress() {

if ( Greenfoot.isKeyDown( "left" ) ) { setDirection ( WEST );

} else if ( Greenfoot.isKeyDown( "right" ) ) {

(9)

setDirection ( EAST );

} else if ( Greenfoot.isKeyDown( "up" ) ) { setDirection ( NORTH );

} else if ( Greenfoot.isKeyDown( "down" ) ) { setDirection ( DOWN );

} }

Note: This results in less lines of code, and furthermore, the code-structure becomes much clearer.

(10)

Challenges

Please read Theory 8.1: Greenfoot feature: while loop in the Run.

Please read Theory 8.2: Calling a method in act.

Please read Theory 8.3: Run while you can!.

Challenge 8.1: Find the egg using if .. then .. else .. (instead of

while

)

Now that theRun has been introduced, we will practice using it. Because the code in the act( ) method is called repeatedly, you don’t need to use awhilein your code anymore. Instead, use anif..then..

else.

a) Write code for the method shown in the following flowchart.

Figure 6: Flowchart for searching the egg usingifinstead ofwhile Tip: UseGreenfoot.stop( )to stop the program.

b) Test your method using the right-mouse-button (very often!!!). After calling the method many times, Mimi eventually finds an egg and the program stops.

c) Theact( )method can continuously call a method (instead of you having to right-click on the method):

i) Find theact( )method inMyDodo. ii) Call your method inact( ).

(11)

iii) Test your program using theAct button. Does the program do the same as a right-click on the method call?

iv) Test your program using theRun button.

TheRun command ensures the repetition by continuously executing theact( )method. Methods called in theact( )use anif..then..elsestatement instead of awhile.

Please read Theory 8.4: Run or Act?.

Please read Theory 8.5: The MovableActor class.

Challenge 8.2: Getting started with Sokoban

a) Download and open theDodoScenario8 scenario.

b) Open the code and see which method is called in theact( )method.

c) Run the scenario, by pressing theRun button.

i) Describe what happens.

ii) Press the arrow keys on your keyboard. As you can see thehandleKeyPressmethod is not complete yet.

iii) Which key(s) does Mimi respond to? Which doesn’t Mimi respond to?

d) By right-clicking on an egg, test the newEggmethodspushandcanBePushed. Do this several times, each time with the egg in a different position in the world. Do these methods work as expected?

As you have seen, lots of things don’t work properly yet. Mimi walks through fences and over eggs, and does not adequately respond to the arrow keys pressed. In the next challenge you will create order in Mimi’s world.

Please read Theory 8.6: Nested if .. then .. else .. statements.

Challenge 8.3: Responding to arrow keys

We must create order in Mimi’s world, by fixing all the things that don’t work properly. We start by fixing Mimi’s behavior to the user’s input:

a) Open theMyDodoclass in the editor and findhandleKeyPress.

b) Have a look at the body of thehandleKeyPressmethod. Here, a sub-method calledgetNewDirection is used. Describe whatgetNewDirectiondoes.

c) Adjust the code so that Mimi adequately responds to all the arrow keys. Tip: Have a look at Theory 8.6 about ’Nestedif .. then .. else ..statements’ in which the Greenfoot methodisKeyDown is discussed. In each case, return the desired direction.

d) Run the scenario and ensure that Mimi indeed responds to each arrow key adequately. Tip: don’t forget to callhandleKeyPressfromact.

Mimi now takes a step in the direction of the arrow-key pressed.

(12)

Challenge 8.4: Mimi pushes eggs forward

Mimi has to learn how to push eggs forward. If Mimi is in front of an egg, we must ensure that she doesn’t just step over an egg, but that she actually pushes it forward. We will now adjusthandleKeyPress

to work as expected. To do so, follow the next tips:

• First decide which specific cases should be distinguished and adjusted;

• TheDodoclass contains all the methods which you need to distinguish these cases;

• Obviously, the newEggmethods will be useful;

• Mimi can check whether there is an egg laying directly in front of by callingeggAhead;

• Mimi can get a hold of the egg usinggetEggAhead;

• Using the existing methods, she can ask the egg whether or not it can be pushed, and if so, push it forwards and then (in the same direction), take a step herself.

Run and test your changes. Try a few cases systematically. Make sure that the rules described in the introduction are complied to.

Challenge 8.5: Scoreboard

We need a scoreboard show how many steps Mimi has taken and how many eggs have been placed in a nest. We will let Mimi keep track of these scores herself and have a scoreboard display the values.

Do this as follows:

a) First, add two instance variables toMyDodofor storing this information (one for number of steps taken, the other for the number of eggs in a nest), see Theory ??. Consider meaningful names, appropriate types and a suitable initial value.

b) As soon as Mimi takes a step, change the value of the instance variable for the number of steps taken.

c) After each step, callupdateScoresto ensure that the changed situation is actually displayed on the scoreboard.

d) To ensure you haven’t made any mistakes thus far, compile and test your changes before pro- ceeding.

e) Now adjust the second variable to keep track of how many eggs have been placed in a nest. Tip:

TheDodomethodboolean nestAhead()may be useful.

f ) Again, callupdateScoreafter an egg is placed in a nest.

g) Run and test your program.

You know have a working scoreboard!

Challenge 8.6: Level achieved

The program must now decide whether the level has been completed or not.

a) Add abooleanmethod that checks whether the level has been completed. Tips:

• The level is completed as soon as the egg-score is equal to the number of eggs in the world.

• The best place to do this is where the egg-score changes.

(13)

• Use theWorldmethodgetObjectsto determine how many eggs the world contains.

b) If the level is completed, call the methodlevelFinished. Have a look at the Java documentation about what the method does and consider how you can use the result of this method after you determined if the level has been completed or not.

Challenge 8.7: Oops .. undo?

Finally, it is still a bit unsatisfying that when the user accidentally presses the wrong key he may not be able to complete the level anymore (he gets into a situation in which the level cannot longer be solved).

Anundo function would be helpful.

This can be achieved with some code adjustments to the myDodo class. We will only give some general indications on how to do this; its up to you to come up with and implement the details.

a) Determine a suitableundo-key. Add a method to handle the user-interaction.

b) Determine which information must be remembered/stored in order to undo a move.

c) Besides having Mimi take a step back, sometimes an egg’s position must be restored (or undone) too.

d) Consider what should happen if the user wants to undo multiple steps.

e) Does the correct value appear on the scoreboard after anundo?

Challenge 8.8: New levels

Add your own new challenging levels to the scenario. Let a fellow student test whether they can be solved or not. Also have them decide what the level’s difficulty is.

(14)

Reflection

In this assignment you practiced using list to store values. You also learned about the for-each-loop to traverse lists and how to use a list to store (Egg) objects. One of the most important steps in becoming good at anything is to evaluate and reflect on what you did and how it went:

Result

I know my solution works because . . . I am proud of my solution because . . . I could improve my solution by . . .

Method

My approach was good because . . . What I could do better next time is . . .

Fill the following table with smileys

indicating how things went. I can do it

I did it a bit but didn’t fully get it

I didn’t get it at all

I can express formulas in code;

I can simulate complex Physics laws in a program which I wrote on my own.

(15)

Saving and Handing in

You have just finished the assignment. Save your work! You will need this for future assignments. In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. You now have all the scenario components in one folder. The folder has the name you chose when you selected ’Save As ...’.

Handing in

Hand in your code: The java fileMyDodo.jav.

Referenties

GERELATEERDE DOCUMENTEN

It renders the premise of emotion analysis software – a tool analyzing a person’s emotions solely based on facial expressions – questionable.. Moreover, the context in which

Since the MB dealership network encompasses 315 dealerships that in some cases have different characteristics, it was determined, in cooperation with the management of

The pubs on the university campus were okay, but there too I had difficulties actually making contact, no doubt this is mostly due to me but sometimes the people

The next step is to examine the role social conventions play in his work and focus on Albee's favourite setting: the American family.. I will present a general chapter about

The main objective of this research was to examine the interpretation and evaluation of interpersonal visual images in print advertisements, as well as to examine a personal

The focus of this research will be on Dutch entrepreneurial ICT firms residing in the Netherlands that have received venture capital financing from at least one foreign

H4b: When online- and offline advertisements are shown together, it will have a greater positive effect on the decision of how many low-involvement products to

The conceptual model sketches the main research question which is aimed at finding out the influences of resistors and enablers on collaborative behaviours, and how