Presentation is loading. Please wait.

Presentation is loading. Please wait.

Iteration Looping in Java.

Similar presentations


Presentation on theme: "Iteration Looping in Java."— Presentation transcript:

1 Iteration Looping in Java

2 Tedious…

3 A better way public void lines(int howMany) {
for(int countSoFar = 0; countSoFar < howMany; countSoFar++) System.out.println(“I will not mock Mrs. Dumbface”); } int countSoFar = 0; while(countSoFar < howMany) countSoFar++;

4 for for-loops are a good starting point for new programmers
They have a place holder for all 3 necessary pieces of any loop for(initial condition; continue condition; update condition) { //code to repeat }

5 while while-loops are another common syntax we will use but they only require a condition to continue looping You must initialize and update the values elsewhere while(condition) { //code to repeat }

6 for vs. while They are equivalent with a little bit of rearranging
I will not force you to use one kind of loop but you must try using both in this first unit for(initial condition; continue condition; update condition) { //code to repeat } initial condition; while(continue condition) update condition;

7 Task #1 – Initializing the world
Enemy one = new Enemy(); int randomX = (int)(Math.random()*getWidth()); int randomY = (int)(Math.random()*getHeight()); addObject(one, randomX, randomY); Enemy two = new Enemy(); randomX = (int)(Math.random()*getWidth()); randomY = (int)(Math.random()*getHeight()); addObject(two, randomX, randomY); Enemy three = new Enemy(); addObject(three, randomX, randomY);

8 Copy/Paste Remember, this is your first clue that there is a better way to write your code. In this case the repetition should be looped public void addEnemies() { for(int added = 0; added < 3; added++) Enemy e = new Enemy(); int randomX = (int)(Math.random()*getWidth()); int randomY = (int)(Math.random()*getHeight()); addObject(e, randomX, randomY); } int added = 0; while(added < 3) added++;

9 addEnemies We can do better…
In particular we should at least make this method: public void addEnemies(int n) I’ve done that in my project. I’ll show you what the finished product looks like

10 Task #2 – super weapon I would like Mario to fire many rounds with one key stroke A loop I’ll call this the “panic” weapon When I push the “w” key Mario will shoot fireballs in a wall protect him.

11 Task #2 – super weapon

12 Fireball no - loop public void panicWall() { //shoot 5 Fireballs int x = getX(); int y = getY(); int fbX= x + 30; World level = getWorld(); int spacing = 10; int fbY = y – 4*spacing;//top Fireball level.addObject(new Fireball(fbStrength_, speed_ + 1, shootingDist_), fbX, fbY); fbY += 2*spacing; }

13 We can do better with a loop
The same method could be made (with a fixed number of Fireballs) Or we could make a better one: public void panicWall(int n) There is no “right” answer about where the Fireballs should be placed when the number is arbitrary. If you write good code it will be easy to change if you want to later on I’ll show you my finished example… but not my code

14 Task #2 – super weapon Instead of a wall, I could also enclose Mario in a ring of (protective) fire

15 Fireball no - loop public void panicCircle() { //shoot 8 Fireballs int x = getX(); int y = getY(); int change = 360/8;//angle between adjacent Fireballs int currentAngle = 0; World level = getWorld(); Fireball fb1 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb1.setRotation(currentAngle); level.addObject(fb1, x, y); currentAngle += change; Fireball fb2 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb2.setRotation(currentAngle); level.addObject(fb2, x, y); Fireball fb3 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb3.setRotation(currentAngle); level.addObject(fb3, x, y); Fireball fb4 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb4.setRotation(currentAngle); level.addObject(fb4, x, y); currentAngle += change; Fireball fb5 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb5.setRotation(currentAngle); level.addObject(fb5, x, y); Fireball fb6 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb6.setRotation(currentAngle); level.addObject(fb6, x, y); Fireball fb7 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb7.setRotation(currentAngle); level.addObject(fb7, x, y); Fireball fb8 = new Fireball(fbStrength_, speed_ + 1, shootingDist_); fb8.setRotation(currentAngle); level.addObject(fb8, x, y); }

16 We can do better with a loop
The same method could be made (with a fixed number of Fireballs) Or we could make a better one: public void panicCircle(int n) In this case the rotation can be adjusted from 45 degrees in my example by using n in the parameters I’ll show you my finished example… but not my code

17 Precision Something strange will happen when you try things like: public void panicCircle(30) To help exaggerate the problem, I’m going to demo a new method slowPanicCircle The only difference is the speed of the Fireballs is 1

18 Precision Pixels are integers (int) but movement into locations is with decimal numbers With a speed of 1, that means the movement of an Actor is limited to the adjacent cells: That means no matter what the angle, only 8 moves are possible If speed = 2 there would be 16 locations to choose A

19 RealActor I’ve made a helper class that behaves just like its parent, the Actor class but keeps track of its movement and rotation using decimal (double) values. The values are stored as decimal numbers but every time the Actor is displayed on screen, it is an approximation to its actual location (2.1, 3.4)  (2,3) I accomplish this by casting (as was done with Random numbers) The source code is posted for you to review or use where you like

20 Other ideas public void rainBomb(int n) public void rapidFire(int n)
rainBomb(10) would place 10 bombs across the top of the screen (evenly spaced) public void rapidFire(int n) rapidFire(3) fires 3 rounds in a single instant. You can decide if they are on top of one another or have some spacing between them

21 The List Class When we want to keep track of more than one item we use a container A container has a single location in memory but keeps track of many things for us So far an array is the only container we’ve worked with. Another common container is a List Like arrays, they are used in many languages Lists don’t need to be a fixed size, they will manage their size at run time If more space is needed it will “grow”

22 Java Lists There are many types of lists in Java
All have advantages and disadvantages that experienced programmers use to improve their programs There is one interface though that ALL of them implement  List

23 Interfaces An interface is not an Object you can create but instead gives you a way to interact with many Objects in a common way

24 List Phones List myList = new List();//Error
Keypad dial = new Keypad();//? Keypad dial = new iPhone(); Keypad dial = new Galaxy(); List myList = new List();//Error List myList = new ArrayList();//OK List myList = new LinkedList();//OK These lists hold Objects You will have to cast the objects you get from them Enemy badGuy = (Enemy)myList.get(0); List<Enemy> myList = new ArrayList(); List<Enemy> myList = new LinkedList(); These lists store Enemies No need to cast them Enemy badGuy = myList.get(0);

25 Helpful List<TYPE> methods
In Greenfoot we will mostly use: size() isEmpty() get(int n) Zero based like an array First element is zero listIterator() The most efficient way to traverse (look through) the List In general, these are also used frequently with Lists: add(TYPE data) add(TYPE data, int index) remove(int index) remove(TYPE data) set(int index, TYPE data) toArray()

26 ListIterator The List interface provides access to its items with a simple method called get for(int index = 0; index < myList.size(); index++) { Enemy e = myList.get(index); //do something with each Enemy } Though on the surface its convenient, it can be horribly inefficient depending on the list implementation LinkedList vs ArrayList

27 ListIterator A ListIterator is another interface that “knows” how to traverse a List. The reason it gets a whole other interface is because the best way to traverse depends on the type of List The good news: You don’t need to worry about the implementation details of Lists or ListIterators Knowing how to use the interface is good enough (for now)

28 ListIterator The most common methods we’ll use are: hasNext() next()
boolean to see if the traversal can find another item or is finished next() gets the next item in the list and updates the iterator

29 Typical List Iteration
import java.util.List; import java.util.ListIterator; List<Enemy> badGuys = getWorld().getObjects(Enemy.class); ListIterator<Enemy> iter = badGuys.listIterator(); while( iter.hasNext() ) { Enemy next = iter.next(); //do something with this Enemy }

30 Why Lists? Greenfoot’s World class has a mechanism to access all objects in a class World myLevel = getWorld(); List<Enemy> allEnemies = myLevel.getObjects( Enemy.class ); Greenfoot Actors can also look for Lists of other Actors getIntersectingObjects getNeighbours getObjectsAtOffset getObjectsInRange

31 Ideas - demo bumpAll(double strength) forcefield(int radius)
freezeAll(int time) I added a method to the Paratroopa called freeze It uses a counter that won`t allow the Paratroopa to act until the counter has expired (<= 0) magnet(int time) Pull up the Paratroopas close by getObjectsInRange turnTowards magnet move

32 The ever popular Platform…
Platform World can be made but they require loops Until now we didn’t have this option. Like our world, your World needs to enforce the law of gravity public static final int GRAVITY The act() method of your World must call up all Actors and apply gravity to them There are a few issues with this

33 Issue – Gravity vs None We don’t want to move everything
Ground or Objects like platforms are immune

34 Exploiting OOP in Java’s
OOP = Object Oriented Programming I could program every Platform class separately and but that seems awfully tedious… Bad design Instead I’ll make one class (parent) to describe what ALL platforms can do Similarly I’ll make another class, RealMover, that describes all the Actors that gravity will effect

35 Setup in Greenfoot

36 Level  act()  applyGravity()
public void applyGravity() { List<RealMover> movers = getObjects(RealMover.class); ListIterator<RealMover> iter = movers.listIterator(); while(iter.hasNext()) RealMover next = iter.next(); next.applyForce(0,GRAVITY); }

37 RealMover I’ve uploaded the source code for a RealMover to the website
Adds a horizontal and vertical velocity (vector) Adds access to apply forces Checks for Platforms to see what movement is possible Can’t go through ground Can’t walk through blocks ... All Platforms are simple a picture  no code

38 Issue #3 We aren’t going to apply the kind of sophistication to our code that professional enterprises like Microsoft, EA, etc. would There will be bugs but we may not see them For example, if an Actor is falling too fast it may pass through a platform (we are only going to check for collisions after a move, not during)

39 Falling Through

40 Good Enough Most of the time the issue won’t happen
One other solution is to have a TERMINAL_VELOCITY in your World If you set the terminal velocity to be less than your thinnest platform this won’t happen

41 Another - Issue Stacking
We may wish to consider what happens when Actors are stacked that would normally fall Here’s another place you could choose to write a loop

42 Gravity - Demo First, I have to change a couple quick things:
public class Mario extends Actor public class Mario extends RealMover public void move() Movement is now dependent on physical forces Can’t move horizontally unless touching ground Can’t jump unless touching ground Mario, and any Actor that wants to be a RealMover will likely want to invoke the parent class super.move()

43 ScrollingWorld - Demo I’ve uploaded another file for you to look at that can now scroll a background image larger than the window you display To use it you’ll need to subclass the ScrollingWorld with your own

44 How to... Start by making the World the same size as the image itself
In my case 1920 x 1080 Place your Actors in the World Shrink the window size to show a portion of the full image For the demo I’ll use 600 x 400 In your World’s constructor you MUST set the main character so the ScrollingWorld knows who to track You can also set the buffer space which makes the world scroll

45 Your Turn MINIMUM expectation is to become familiar with for/while loops You must implement at least 5 new features (at least two must use a List/ListIterator) to show how you can now use this skill in your code I have given lots of example loops that you could choose from… that’s why I didn’t show you the finished code


Download ppt "Iteration Looping in Java."

Similar presentations


Ads by Google