Chapter 6 Game Programming I

Size: px
Start display at page:

Download "Chapter 6 Game Programming I"

Transcription

1 Chapter 6 Game Programming I To this point we've learned to create simple objects such as UFOs on screen and move them around in a controlled manner. Now we'll take a look at the components of basic game programming. In addition to moving objects, various games may include many other techniques such as: detecting mouse clicks and the objects that were clicked on. dragging an object with the mouse or having an object automatically following the mouse. detecting keystrokes. displaying score. detecting collision between objects. In this chapter we'll examine each of these. 6.1 Building Blocks for Game Programming Game programs share some common building blocks, which we examine now the init Method The init( ) method is part of every Java graphics game. It contains code that must be executed before game play actually begins, typically doing things like coloring the application window, putting objects in place and other setup essentials. init( ) must be written in this form. public void init( ) statements //init The init( ) method executes automatically before the run( ) method begins. It is part of standard Java but we must write the code to fill it in. It is typically used like this. Daniel L. Schuster, 2009, all rights reserved Page #1

2 public class AnyProgram extends GraphicsProgram GOval target; public void init( ) target = new GOval(30, 30, 100, 100); target.setfilled(true); target.setcolor(color.green); //init more code //AnyProgram configure target as needed Declaring an identifier such as target inside the public class that defines the entire program but outside the init( ) or any other method gives that identifier global scope. Global scope means we can use it in any method in the program, including for example the init( ) method and the run( ) method, without passing it as an argument. Variables with global scope should be used sparingly but are required in this case. The init( ) method is used to set up the initial game playing conditions create the targets, display the background, set up the scoring variables, etc. If something needs to be done before the play actually begins, it probably should be done in the init( ) method Paying Attention to the Mouse By default an ACM Java graphics program ignores the mouse. We've already modified this somewhat by using the waitforclick( ) method, which causes the program to freeze until the mouse is clicked on the window. But we need more. In particular, we often need to know where the mouse was clicked and what object was clicked on. To access all this information, we need to tell the program to pay full attention to the mouse. The standard Java method we need is: addmouselisteners( ); This method call is usually included in the init( ) method. We might have public void init( ) code to initialize variables addmouselisteners( ); //init Daniel L. Schuster, 2009, all rights reserved Page #2

3 6.1.3 Working with the Mouse When a mouse button is clicked a record of this event, called a mouse event, is created. It records what mouse activity happened and where it happened in the application window. Mouse events are part of standard Java, which provides the MouseEvent object to hold the necessary information. Your program needs import java.awt.event.*; to load the MouseEvent object. We must also write a mousepressed( ) method, which will contain code that automatically executes when the click occurs. The mousepressed( ) method must be written in this form: public void mousepressed(mouseevent e) statements //mousepressed You don't have to name the MouseEvent e. It's just a variable so you could name it anything meaningful. Also, note that the mousepressed( ) method is executed for a click of any mouse button left, right or center An Example Program This program simply counts mouse clicks, displaying the count of the clicks in the application window. CountClicks //CountClicks.java import acm.program.*; import acm.graphics.*; import java.awt.event.*; public class CountClicks extends GraphicsProgram int clickcount; GLabel countlabel; public void init( ) clickcount = 0; countlabel = new GLabel("Click count: " + clickcount); countlabel.setfont("serif-bold-24"); add(countlabel, 5, 30); initialize count and label for displaying the count Daniel L. Schuster, 2009, all rights reserved Page #3

4 //init addmouselisteners( ); waitforclick( ); public void mousepressed(mouseevent e) count the click clickcount++; countlabel.setlabel("click count: " + clickcount); //mousepressed update the count public void run( ) /*nothing to do here */ //CountClicks empty run method because all the action takes place in the mousepressed method Java doesn't care about the order of the methods in the source code but it is convenient to put the standard Java methods (init( ), mousepressed( ), ) above the run( ), and the methods unique to the particular program below the run( ) Detecting the Object That Was Clicked On The program above is not very interesting, partly because it treats all mouse clicks as the same, simply counting each one. Games usually require that we identify the objects we clicked on so that we can move things on screen, shoot the goblins, etc. To do this we need to look more carefully at MouseEvents and the mousepressed( ) method. The location of a mouse click Let us assume a MouseEvent e has already been created. We can then find the window coordinates of the click easily. double x = e.getx( ); double y = e.gety( ); The getx( ) and gety( ) methods extract the coordinate information from the MouseEvent e, which is then assigned to variables x and y. This gives us the point (x, y) on the application window where the click occurred. The object that was clicked on The ACM Java library method getelementat( ) returns the object that was clicked on. Using it is simple. GRect therectangle = getelementat(x, y); these get methods are actually standard Java, not the ACM library methods But in many situations the click could be on a GRect, a GOval or some other object class. Since we often can t predict the particular class of object that will be clicked on, we usually store the object returned by getelementat( ) in a GObject, and not in a more specific class such as GRect. Daniel L. Schuster, 2009, all rights reserved Page #4

5 GObject theobject = getelementat(x, y); Getting the clicked on object usually happens in the automatically executed mousepressed( ) method. Working with null Suppose the click didn t occur on any graphical object within the window. What does the getelementat( ) method return then? Java uses the special value null to indicate there's nothing here or more specifically no object and that s what is returned by getelementat( ) when a click occurs in an empty area of the window. Assume a redball object already exists. Here's a basic mousepressed( ) method that counts clicks on this object, with another count for clicks off the object. public void mousepressed(mouseevent e) double x = e.getx( ); double y = e.gety( ); GObject theobject = getelementat(x, y); if (theobject == redball) clicksonball++; else if (theobject == null) clicksoffball++; //mousepressed if the object that was clicked on was redball then count the click if no object was clicked on count that click separately This implementation of mousepressed( ) follows a common pattern. 1) get the coordinates where the click occurred. 2) find out which object was at those coordinates. 3) take appropriate action based on which object was clicked the Game Loop Action within a game is usually repetitive fly the plane until it lands, move the widget until it is the correct place, etc. Thus basic game activity is executed within a loop called the game loop. The game loop may be written as a while(true) break loop and often takes a form as shown below. while(true) modify objects as needed check for interaction of objects and take appropriate action if some condition is met then the game is over so break Daniel L. Schuster, 2009, all rights reserved Page #5

6 Actions that need to be taken frequently, such as moving an object or checking for collision of objects, execute inside the game loop A Simple Shoot-em-up Game Clicking on a stationary target is not all that interesting, but if we add movement to the object then we've got a challenging target to shoot at and that's a real game. Not fancy, but we've got to start somewhere. Below is a simple game that bounces a ball around the window for a fixed time, counting the successful 'shots' at the ball as it moves around the screen. It uses several techniques we've already explored animation, bouncing, detecting click locations and updating a score. ShootTarget1 //ShootTarget1.java import acm.program.*; import acm.graphics.*; import java.awt.event.*; import java.awt.*; public class ShootTarget1 extends GraphicsProgram public static final int APPLICATION_WIDTH = 800; public static final int APPLICATION_HEIGHT = 500; final int WAIT = 5; final int DIAM = 50; final int MAX_TIME = 10000; //10 seconds int clicksonball, time, redballxjump, redballyjump; GOval redball; GLabel clicksonballlabel; public void init( ) time = 0; set up the movement for the target redballxjump = 1; redballyjump = 1; redball = new GOval(90, 40, DIAM, DIAM); redball.setfilled(true); set up the target redball.setcolor(color.red); add(redball); set up the counter clicksonball = 0; clicksonballlabel = new GLabel("Ball click count: " + clicksonball); Daniel L. Schuster, 2009, all rights reserved Page #6

7 clicksonballlabel.setfont("*-bold-16"); add(clicksonballlabel, 0, 16); //init displayinstructions( ); addmouselisteners( ); public void mousepressed(mouseevent e) double x = e.getx( ); double y = e.gety( ); GObject theobject = getelementat(x, y); count and display the clicks if (theobject == redball) clicksonball++; clicksonballlabel.setlabel("ball click count: "+ clicksonball); //mousepressed public void run( ) while(true) //game loop pause(wait); time = time + WAIT; if (time > MAX_TIME) break; //exit the game loop if (redball.gety( ) <= 0) //at top of window? redballyjump = 1; else if (redball.gety( )+DIAM >= APPLICATION_HEIGHT) //at bottom? redballyjump = -1; else if (redball.getx( ) <= 0) //at left? redballxjump = 1; else if (redball.getx( )+DIAM >= APPLICATION_WIDTH) //at right? redballxjump = -1; Daniel L. Schuster, 2009, all rights reserved Page #7

8 //run redball.move(redballxjump, redballyjump); //game loop public void displayinstructions( ) GLabel sign1 = new GLabel("Click on the moving ball"); GLabel sign2 = new GLabel("-- click to start --"); sign1.setfont("*-bold-20"); sign2.setfont("*-bold-20"); add(sign1, 320, 200); add(sign2, 340, 220); waitforclick( ); remove(sign1); remove(sign2); //displayinstructions //ShootTarget1 6.2 More Game Components More sophisticated games require more tools, so let's take a look at some additional useful techniques Detecting Object Collision Games that involve movement of objects often require that we detect collision between objects. Using the ACM library this is simple. We begin with a discuss of object collision and what it means. Consider the filled rectangles below. Clearly they collide when any of their edges overlap. not a collision definitely a collision But what about this rectangle and circle? What does it mean to say they have collided? not a collision Daniel L. Schuster, 2009, all rights reserved Page #8

9 definitely a collision but what about this? Is this a collision? The third example might not normally be considered a collision. After all, the objects don't actually bump into each other. But consider not just the objects, but the rectangle around the object. yes, that's a collision! These bounding rectangles intersect, and that's the way we will define collision graphic objects collide if and only if their bounding rectangles overlap. It's not the most sophisticated definition, but it's convenient for us because it's easy to use and that's how collision is defined in the ACM library. Note that the bounding rectangles are not GRects. They don't have any color, they can't be moved, they can't otherwise be characterized. We might say that bounding rectangles are purely theoretical rectangles with no characteristics beyond their corner coordinates. A bounding rectangle is known in the ACM library as a GRectangle. Let's assume we have two graphical objects, r1 a GRect and o1 a GOval. The steps for detecting collision are: 1) get the bounding rectangle for r1 using the GRectangle r1box = r1.getbounds( ); getbounds method GRectangle o1box = o1.getbounds( ); 2) store that bounding rectangle in r1box, which is a GRectangle (not a GRect) 3) repeat for o1 Daniel L. Schuster, 2009, all rights reserved Page #9

10 if (r1box.intersects(o1box) == true) steps to perform when intersection occurs if the bounding rectangle around r1 intersects the bounding rectangle around o1, then perform appropriate steps Now, where does this code go in the program? Well, objects collide when they move and typically movement is executed in the run( ) method. So a common application might look like this. while(true) move object 1 move object 2 get bounding rectangle around object 1 get bounding rectangle around object 2 if the bounding rectangles intersect do whatever needs to be done Dragging Objects with the Mouse We can drag a graphical object by using the mousepressed( ) and mousedragged( ) methods together. The key part of the code, shown below, requires some thought. Let s begin our discussion by assuming that the mouse button has been clicked and held down on an object. When the button is pressed, the mousepressed( ) method below runs automatically and gives value to three variables: lastx and lasty contain the click coordinates and gobj stores the object that has been clicked on. This mousepressed( ) method also moves the clicked object to the front to make it easy for us to see. Assume lastx, lasty and gobj exist and have global scope. It is entirely possible that a mouse click will take place in an open area of the window, off of any objects. In this case, the getelementat( ) method will return null. The null object doesn't have any properties and we can't do anything with it, so we must write our code appropriately as shown below. public void mousepressed(mouseevent e) lastx = e.getx( ); lasty = e.gety( ); gobj = getelementat(lastx, lasty); if (gobj!= null) Daniel L. Schuster, 2009, all rights reserved Page #10

11 gobj.sendtofront( ); //mousepressed When the mouse, with the button held down, is moved, another MouseEvent is created and the mousedragged method runs automatically. Below we use the lastx and lasty values set when mousepressed( ) executed. public void mousedragged(mouseevent m) int xdisplacement = (int) (m.getx( ) lastx); int ydisplacement = (int) (m.gety( ) lasty); gobj.move(xdisplacement, ydisplacement); record the amount of movement move the object by the required amount. lastx = m.getx( ); lasty = m.gety( ); //mousedragged and finally, record the new location so that it s ready for the next mouse action. The example below displays a rectangle and an oval, and allows the user to drag them around in the window. DragObjects //DragObjects import acm.graphics.*; import acm.program.*; import java.awt.*; import java.awt.event.*; public class DragObjects extends GraphicsProgram GRect rect; GOval oval; GObject gobj; double lastx, lasty; public void init( ) rect = new GRect(1, 1, 150, 100); rect.setfilled(true); rect.setcolor(color.red); add(rect); oval = new GOval(300, 115, 100, 70); oval.setfilled(true); oval.setcolor(color.green); add(oval); set up the shapes that we will drag around Daniel L. Schuster, 2009, all rights reserved Page #11

12 addmouselisteners( ); //init public void mousepressed(mouseevent e) lastx = e.getx( ); lasty = e.gety( ); gobj = getelementat(lastx, lasty); if (gobj!= null) gobj.sendtofront( ); //mousepressed public void mousedragged(mouseevent m) if (gobj!= null) int xdisplacement = (int) (m.getx( ) lastx); int ydisplacement = (int) m.gety( ) lasty); gobj.move(xdisplacement, ydisplacement); lastx = m.getx( ); lasty = m.gety( ); //mousedragged if null wasn't clicked on, then calculate the amount of movement and then move the object. public void run( ) /*nothing to do here */ Automatically Following the Mouse We can make a graphical object follow the mouse automatically by using the mousemoved( ) method, which is executed every time the mouse is moved, whether or not there is a click. mousemoved( ) is another method that is part of standard Java that we need to fill in. Assume we have a ball of size DIAM. We can make the ball follow the mouse around, centered under the mouse with public void mousemoved(mouseevent e) double x = e.getx( ); double y = e.gety( ); ball.setlocation(x-diam/2, y-diam/2); //offset to the center of the ball //mousemoved Daniel L. Schuster, 2009, all rights reserved Page #12

13 If we just want the upper left corner of the ball to follow the mouse, we would use ball.setlocation(x, y); Reading Keystrokes Sometimes the mouse doesn't do it and a game works better if it is controlled from the keyboard. Let's take a look at reading keystrokes. We begin with import java.awt.event.*; and addkeylisteners( ); which tells the program to pay full attention to the keyboard. This method is called in the init( ) method. When a key is pressed, a KeyEvent object is created and holds a numeric key code of the pressed key. Key codes are named constants in the KeyEvent class. Here's a few of them. KeyEvent.VK_UP KeyEvent.VK_RIGHT KeyEvent.VK_DOWN KeyEvent.VK_LEFT KeyEvent.VK_SPACE KeyEvent.VK_A through KeyEvent.VK_Z KeyEvent.VK_0 through KeyEvent.VK_9 up arrow right arrow down arrow left arrow space bar A Z, a z 0 9 (not on num pad though!) VK_A through VK_Z are ordered, as are VK_0 through VK_9 and we may use that fact in our comparisons as shown in the example below. The program below demonstrate basic reading of the keys. Reading keystrokes can be much more subtle than this, but we'll stay with this blunt instrument since what we really want to do is to control an arcade game. Dig farther into Java if finer control is needed. ReadKeys //ReadKeys.java import acm.graphics.*; import acm.program.*; import java.awt.event.*; //need for KeyEvent public class ReadKeys extends GraphicsProgram GLabel keylabel; Daniel L. Schuster, 2009, all rights reserved Page #13

14 public void init( ) keylabel = new GLabel("none"); keylabel.setfont("*-bold-50"); add(keylabel, 310, 215); addkeylisteners( ); //init pay attention to the keyboard public void keypressed(keyevent k) //read arrows keys and the space bar, ignore everything else int key = k.getkeycode( ); if (key == KeyEvent.VK_UP) keylabel.setlabel("up"); else if (key == KeyEvent.VK_RIGHT) keylabel.setlabel("right"); else if (key == KeyEvent.VK_DOWN) keylabel.setlabel("down"); else if (key == KeyEvent.VK_LEFT) keylabel.setlabel("left"); else if (key == KeyEvent.VK_SPACE) keylabel.setlabel("space"); else if (key == KeyEvent.VK_A) keylabel.setlabel("a"); else if (KeyEvent.VK_B <= key && key <= KeyEvent.VK_Z) keylabel.setlabel("b -> Z"); else if (KeyEvent.VK_0 <= key && key <= KeyEvent.VK_9) keylabel.setlabel("0 -> 9"); //keypressed public void run( ) /*nothing to do here */ //ReadKeys Our next example program demonstrate moving an object under the control of the arrow keys. In the example below the KeyPressed( ) method is used to set the direction of movement, but the actual movement takes place within the game loop. This is typical of the KeyPressed( ) and MousePressed( ) methods. They typically should be very brief and used only to set values that will be used in other methods. KeyMovementControl1 //KeyMovementControl1.java import acm.graphics.*; import acm.program.*; import java.awt.event.*; import java.awt.*; get the code for the key read the arrow keys space key a or A key other letters digits Daniel L. Schuster, 2009, all rights reserved Page #14

15 public class KeyMovementControl1 extends GraphicsProgram final int WAIT = 20; final int MV_AMT = 5; int xmove, ymove; public void init( ) xmove = ymove = 0; addkeylisteners( ); //init public void keypressed(keyevent e) int key = e.getkeycode( ); if (key == KeyEvent.VK_UP) ymove = -MV_AMT; else if (key == KeyEvent.VK_RIGHT) xmove = MV_AMT; else if (key == KeyEvent.VK_DOWN) ymove = MV_AMT; else if (key == KeyEvent.VK_LEFT) xmove = -MV_AMT; //keypressed set direction of movement public void run( ) GOval o = new GOval(40, 40); o.setcolor(color.red); o.setfilled(true); add(o, 100, 100); while(true) //game loop pause(wait); o.move(xmove, ymove); xmove = ymove = 0; //game loop //run //KeyMovementControl1 after the movement, reset x and y movement If you run this program you will note that movement stops as soon as a key is released. Here's another version. This time the object continues to move after the key is released, and the space bar is used to stop movement. Daniel L. Schuster, 2009, all rights reserved Page #15

16 KeyMovementControl2 //KeyMovementControl2.java import acm.graphics.*; import acm.program.*; import java.awt.event.*; import java.awt.*; public class KeyMovementControl2 extends GraphicsProgram final int WAIT = 20; final int MV_AMT = 5; int xmove, ymove; public void init( ) xmove = ymove = 0; addkeylisteners( ); //init public void keypressed(keyevent e) int key = e.getkeycode( ); if (key == KeyEvent.VK_UP) ymove = -MV_AMT; xmove = 0; else if (key == KeyEvent.VK_RIGHT) xmove = MV_AMT; ymove = 0; else if (key == KeyEvent.VK_DOWN) ymove = MV_AMT; xmove = 0; else if (key == KeyEvent.VK_LEFT) xmove = -MV_AMT; ymove = 0; else if (key == KeyEvent.VK_SPACE) xmove = 0; ymove = 0; stop all movement set movement in 1 direction only Daniel L. Schuster, 2009, all rights reserved Page #16

17 //keypressed public void run( ) GOval o = new GOval(40, 40); o.setcolor(color.red); o.setfilled(true); add(o, 100, 100); //run while(true) //game loop pause(wait); o.move(xmove, ymove); //game loop movement is not reset to 0, so motion continues Randomizing the Action Random numbers and other random values are extremely useful for simulations and game software, allowing us to create a game that varies from one play to another. The ACM library provides a simple mechanism for generating several kinds of random values. Creating a random generator Before generating any type of random, we must create a mechanism for generating random values. We begin with import acm.util.*; To create a random generating mechanism, we use RandomGenerator rg = new RandomGenerator( ); where rg is the name of our RandomGenerator. Creating random ints Once a RandomGenerator has been created you may use it to generate a random int in the range minimum value random int maximum value. These example generate random integers. int dicevalue = rg.nextint(1, 6); random numbers from 1 to 6 (inclusive), useful for simulating a throw of a die. Daniel L. Schuster, 2009, all rights reserved Page #17

18 int jumpvalue = rg.nextint(-5, 5); random number from -5 to 5 (inclusive), perhaps using the value to control an object's movement left or right 5 pixels. Now let's look at a console program that generates and displays random integers. RandomInts //RandomInts.java import acm.program.*; import acm.util.*; public class RandomInts extends ConsoleProgram public void run( ) RandomGenerator rg = new RandomGenerator( ); //run //RandomInts A sample run might give us and another might give us for(int i=0; i< 5; i++) print(rg.nextint(-5, 5) + " "); //display 5 random integers Using randoms with graphic objects If ufo1 is a UFO as we've created before and x and y are random integers, then ufo1.move(x, y); moves ufo1 by a random jump from the current location. Setting the random seed A random number is not truly random. A sequence of randoms is automatically initialized with a value taken from the system clock, and the random numbers are actually generated by a formula in Java. Daniel L. Schuster, 2009, all rights reserved Page #18

19 The beginning value is called a seed. Since the system clock continuously changes, the seed continuously changes and thus a generated sequence of randoms changes from one run to the next. This means that for a program using randoms one run of the program will differ from the next. Great for playing a card game, lousy for finding problems in your program. For debugging it is very useful to be able to recreate the same sequence of random numbers and this requires that we supply the seed for the random number generator, instead of it being taken from the system clock. Fortunately this is very simple. Below are two examples. rg.setseed(0); rg.setseed(99); The code segment below will display the same set of random values repeatedly each time it is executed. RandomGenerator rangen = new RandomGenerator( ); rangen.setseed(0); for(int i=0; i<5; i++) println(rangen.nextint(1,10)); The particular value used to set the seed is unimportant. What is important is that you set the seed when you need consistent random values. Remember that you usually want to delete or comment out the setseed( ) statement when bugs are squashed. In the next chapter you'll see how to create other random values doubles, booleans, Colors and other types of random values Keeping Time and Score Many games require keeping time (how long did it take to find the Wumpus?) and keeping score, and that's what we'll look at next. Set up for keeping time and score Set up for timing and score keeping requires declaration and initialization of some global variables as shown in the code segment below. final int WAIT = 50; int time, score; GLabel scorelbl; Daniel L. Schuster, 2009, all rights reserved Page #19

20 public void init( ) time = 0; //game loop hasn't begun create a score label score = 0; //no points have been scored and display it scorelbl.setlabel("score: " + score); scorelbl.setfont("sanserif-bold-30"); add(scorelbl, 2, 26); //position at upper left corner of window remainder of initialization //init Updating the time Basic game execution occurs inside the game loop. This loop may contain many statements, but most of them run so quickly that for our purposes we can consider them as executing instantaneously. The pause( ) statement is different however. In it we use a WAIT value to slow execution to a speed we can play and this adds measurably to the current time. Thus we need to add the WAIT time to the current time value with every loop. while(true) //game loop pause(wait); time = time + WAIT; remainder of game playing code //game loop Updating the score Changing the score value can occur in many places. We consider these in turn. if scoring takes place when the mouse is clicked, then we must increment the score in the mousepressed( ) method. if (the object clicked on was the target) increment the score and display it if scoring takes place when objects collide, we must increment the score where collision is detected, normally in the game loop. while(true) game code if(o1box intersects o2box) increment the score and display it more game code if scoring takes place when a goal is reached, we increment scoring when we have confirmed that the goal has been reached, typically within the game loop. Daniel L. Schuster, 2009, all rights reserved Page #20

21 while(true) game code if (zombies are all dead and hero is still alive) increment the score and display it more game code Displaying the updated score is often done at the time of the score change, but can also be put off to any convenient point. For example, though play in the game loop and the resultant mouse clicks might change a score several times in one pass through the loop, it isn't necessary to display the changed score each time. It would probably change too fast for the player to see the changes anyway. Instead just use a single statement at the end of the game loop to display the net result for that pass through the loop. while(true) game code including statements that change the value of the score scorelbl.setlabel(new value of the score); 6.3 An Example Program Our goal is to write a game that drops balls that we attempt to block. A point is scored each time a ball is blocked. Game objects A ball is simply a colored circle and a blocker is a colored line, so they're easy to code. In fact, we probably don't really need to create these as separate objects. But if we do then later we can very easily could go back and change these objects to make them more interesting. Cannonball //CannonBall.java import acm.graphics.*; import java.awt.*; public class Cannonball extends GCompound final int SIZE = 30; final Color DEFAULT_COLOR = Color.BLACK; private GOval ring1; public Cannonball( ) ring1 = new GOval(SIZE, SIZE); ring1.setfilled(true); Daniel L. Schuster, 2009, all rights reserved Page #21

22 ring1.setcolor(default_color); add(ring1); //Cannonball public Cannonball(Color cv) ring1 = new GOval(SIZE, SIZE); ring1.setfilled(true); ring1.setcolor(cv); add(ring1); //Cannonball //Cannonball Blocker //Blocker.java import acm.graphics.*; import java.awt.*; public class Blocker extends GCompound final int WD = 80; final int HT = 1; private GRect box; public Blocker( ) box = new GRect(WD, HT); box.setcolor(color.orange); box.setfilled(true); add(box, 1, 1); //Blocker //Blocker The game itself is more complex. We'll develop it in two stages, the first implementing some basic functionality and the second adding more objects and features. Stage one development A cannonball is dropped from the top of the window and falls downward. The player moves the blocker by moving the mouse. Play continues with the cannonball reversing direction when it hits the blocker and again reversing direction when it hits the top of the window. Eventually the player misses a block and the cannonball hits the bottom of the window which ends the game. Daniel L. Schuster, 2009, all rights reserved Page #22

23 Cannonade1 //Cannonade1.java import acm.program.*; import acm.graphics.*; import java.awt.*; import java.awt.event.*; public class Cannonade1 extends GraphicsProgram public static final int APPLICATION_WIDTH = 400; public static final int APPLICATION_HEIGHT = 500; final int AW = APPLICATION_WIDTH; final int AH = APPLICATION_HEIGHT; final int WAIT = 5; final int CB_SIZE = 30; Cannonball cb1; Blocker blocker; int time; public void init( ) setbackground(color.blue); time = 0; cb1 = new Cannonball(); add(cb1, AW/2, 0); blocker = new Blocker( ); add(blocker, AW/2, AH/2); set the time to 0 create the cannonball and blocker and put them in the window pay attention to the mouse //init addmouselisteners( ); waitforclick( ); public void mousemoved(mouseevent e) when the mouse is moved double x = e.getx( ); move the blocker with it double y = e.gety( ); blocker.setlocation(x-40, y); //center the blocker under mouse //mousemoved public void run( ) GRectangle cb1box, blockerbox; Daniel L. Schuster, 2009, all rights reserved Page #23

24 int ymove = 1; while(true) //game loop pause(wait); time = time + WAIT; cb1.move(0, ymove); cb1box = cb1.getbounds( ); blockerbox = blocker.getbounds( ); pause a while, increment time, move the cannonball get the bounding rectangles around the blocker and the cannonball //blocked the cannonball? if (cb1box.intersects(blockerbox) == true) ymove = -ymove; if blocked, reverse direction else if (cb1.gety( ) == 0) //top of window if hits top, reverse direction ymove = -ymove; else if (cb1.gety( ) + CB_SIZE == AH) //bottom of window break; //exit game loop if hits bottom, exit loop //game loop //run //Cannonade1 This version implements the basic functionality of the game fire a cannonball, block it when appropriate, bounce it off the blocker and the top of the window, end the game when it hits the bottom. But it's hardly a complete game. Stage two development Our next version adds quite a bit to the game three cannonballs at random locations that fall with different speeds bouncing off the blocker in a random direction, bouncing of the sides of the window and scoring. The cannonball and blocker objects are the same and we'll focus only on the interesting changes within the game program. Cannonade2 //Cannonade2.java import acm.program.*; import acm.graphics.*; import acm.util.*; import java.awt.*; import java.awt.event.*; public class Cannonade2 extends GraphicsProgram Daniel L. Schuster, 2009, all rights reserved Page #24

25 public static final int APPLICATION_WIDTH = 400; public static final int APPLICATION_HEIGHT = 500; final int AW = APPLICATION_WIDTH; final int AH = APPLICATION_HEIGHT; final int WAIT = 10; final int CB_SIZE = 30; Cannonball cb1, cb2, cb3; Blocker blocker; int time, score; GLabel scorelbl; public void init( ) setbackground(color.blue); time = 0; score = 0; scorelbl = new GLabel(""+score); scorelbl.setfont("sanserif-bold-30"); scorelbl.setcolor(color.red); add(scorelbl, 2, 26); create a label for the score cb1 = new Cannonball( ); cb2 = new Cannonball(Color.GREEN); cb3 = new Cannonball(Color.YELLOW); RandomGenerator rg = new RandomGenerator( ); int rand1 = rg.nextint(0, AW-50); int rand2 = rg.nextint(0, AW-50); int rand3 = rg.nextint(0, AW-50); add(cb1, rand1, 0); add(cb2, rand2, 0); add(cb3, rand3, 0); blocker = new Blocker( ); add(blocker, AW/2, AH/2); cannonballs at random locations //init addmouselisteners( ); waitforclick( ); public void mousemoved(mouseevent e) Daniel L. Schuster, 2009, all rights reserved Page #25

26 double x = e.getx( ); double y = e.gety( ); blocker.setlocation(x-40, y); //center blocker under mouse //mousemoved public void run( ) RandomGenerator rg = new RandomGenerator( ); GRectangle cb1box, cb2box, cb3box, blockerbox; int xmove1 = 0, xmove2 = 0, xmove3 = 0; int ymove1 = 3, ymove2 = 4, ymove3 = 5; x and y movements for the 3 cannonballs boolean cb1done = false, cb2done = false, cb3done = false; while(true) //game loop pause(wait); time = time + WAIT; cb1.move(xmove1, ymove1); cb2.move(xmove2, ymove2); cb3.move(xmove3, ymove3); cb1box = cb1.getbounds( ); cb2box = cb2.getbounds( ); cb3box = cb3.getbounds( ); blockerbox = blocker.getbounds( ); track whether the cannonballs have dropped out of the window find the bounding rectangles around the cannonballs and the blocker //blocking if (cb1box.intersects(blockerbox) == true) ymove1 = -ymove1; xmove1 = rg.nextint(-1, 1); score++; if (cb2box.intersects(blockerbox) == true) ymove2 = -ymove2; xmove2 = rg.nextint(-1, 1); score = score + 2; if (cb3box.intersects(blockerbox) == true) ymove3 = -ymove3; xmove3 = rg.nextint(-1, 1); block the cannonballs? Daniel L. Schuster, 2009, all rights reserved Page #26

27 score = score + 3; //at top of window? if (cb1.gety( ) == 0) ymove1 = -ymove1; if (cb2.gety( ) == 0) ymove2 = -ymove2; if (cb3.gety( ) == 0) ymove3 = -ymove3; cannonballs hit top of window? //at left or right side? if ((cb1.getx( ) <= 0) (cb1.getx( ) + CB_SIZE >= AW)) xmove1 = -xmove1; if ((cb2.getx( ) <= 0) (cb2.getx( ) + CB_SIZE >= AW)) xmove2 = -xmove2; if ((cb3.getx( ) <= 0) (cb3.getx( ) + CB_SIZE >= AW)) xmove3 = -xmove3; cannonballs hit left or right side of window? //at bottom of window? if ((cb1done == false) && (cb1.gety( ) + CB_SIZE >= AH)) score--; cb1done = true; cannonballs hit bottom of window? if ((cb2done == false) && (cb2.gety( ) + CB_SIZE >= AH)) score--; cb2done = true; if ((cb3done == false) && (cb3.gety( ) + CB_SIZE >= AH)) score--; cb3done = true;; Daniel L. Schuster, 2009, all rights reserved Page #27

28 scorelbl.setlabel(""+score); if (cb1done == true && cb2done == true && cb3done == true) break; //game loop //end the game GLabel donelbl = new GLabel("Game Over!"); donelbl.setfont("sansserif-bold-50"); donelbl.setcolor(color.red); add(donelbl, 2, AH-35); //run //Cannonade2 You may notice one potential problem. Working with only three cannonballs requires a lot of repetitive code to do the same thing to each cannonball, and this would become very unwieldy if we had many more cannonballs. There s got to be a better way, and there is. Arrays and ArrayLists will be covered in a later chapter and they make it possible to handle large numbers of the objects easily. 6.4 Better Games Now let's look at some of the things that make games that look and play better. Adding levels to the game If you think about the games we've written so far you'll see the same general algorithm every time. initialize variables while(true) game playing code if (some condition) break A game with a second level of play adds another section of code afterwards. reinitialize variables as needed while(true) game playing code if (some condition) break Daniel L. Schuster, 2009, all rights reserved Page #28

29 The only difficulty is that we must be careful about what variables we reinitialize. a score probably does not get reinitialized, allowing us to add points by playing the second level. objects that have moved may need to be put back in place. values that control speed may change in play from one level to the next, giving the player a faster playing environment Multiple levels can also be created with nested loops. while(true) initialize variables while(true) game playing code if (some condition) break out of inner game loop if (some condition) break out of outer game loop However, the actual variable initialization often must change from one level to another. Bar Meters A digital display might count down 3, 2, 1, 0 with 0 representing some important condition. An alternative display that doesn't require reading and is thus probably quicker to understand uses a bar meter to indicate object condition. Using the setsize( ) method to shrink a GRect we might have value represented 100% 75% 50% Even better would be to use setsize( ) and setcolor( ). 100% Daniel L. Schuster, 2009, all rights reserved 75% Page #29 50%

30 Of course we can use meters like this for many purposes. In a lunar lander game, we might use a digital display for the altitude of the lander and bar meters for remaining fuel and condition of the shields. Here's an example dashboard. Alt Fuel Shields 125 More Sophisticated Movement When running some of these programs you may have noticed some unusual behavior. Under some circumstances a moving object might 'hang up' on another object it is supposed to bounce off. Let's figure out why that happens and then discuss a fix for it. Recall the Cannonade games above and consider a cannonball that moves 5 pixels per game loop and the blocker, with a distance of 7 pixels between them as shown. 7 pixels The next iteration of the game loop might put them within 2 pixels of each other. and the next pass through the loop might give us this situation. At this point we detect collision. You may have noticed this overlap. We bounce the cannonball up by the same amount as the last down movement, and again we have. Daniel L. Schuster, 2009, all rights reserved Page #30

31 Everything looks and behaves as we expect. Nothing unusual is happening here. Things change if, just after the collision, we move the blocker upward, perhaps by making it follow the mouse. The bounce moves the cannonball up but the blocker moves up also. We might have which is detected as another collision. The direction changes and now the cannonball moves down. We might have which is another collision. And so on the cannonball is 'hung up' on the blocker. Now that we've identified the problem, what causes it and what can we do about it? The minimum size of the movement of our hypothetical cannonball, known as the movement granularity, is 5 pixels. But if the cannonball is only 1 pixel away from the blocker, the side of the window, or some other object in the game, then after the next movement the edge of the cannonball overlaps the other object, and that's just not physically possible. Our physics model is inaccurate. For many simple games this is not really a problem. We just accept that sometimes the objects on screen behave differently than behavior in the real world. After all, it's just a game. On the other hand, if we want our game to be the best, or if it's more than a game (perhaps it's a simulation used for pilot training), then we'll need to make our physics model more accurate. The correct solution is to move only 1 pixel at a time, even for an object that moves 5 pixels per game loop, and to check for collision with each single pixel movement. This more accurately reflects reality and will thus give us more realistic behavior. We would have something like this. while(true) game code for(the number of pixels of movement per game loop) move the cannonball 1 pixel in the current direction if (there is collision) change direction to allow for bounce exit the loop Daniel L. Schuster, 2009, all rights reserved Page #31

32 more game code Graphics Problem set For all programs below it is assumed that you will create separate objects for elements of the game and use methods where appropriate. 1) ShootTwo modify the ShootTarget1 program above so that a smaller, slightly faster blue rectangle also bounces around in the application window. Clicks on the red ball are worth 1 point, clicks on the blue rectangle are worth 3 points. The score displays only when the game ends. 2) ShootThree Modify ShootTwo to include a second level, where the speeds of the balls increase, and the updated score is displayed continuously. 3) ShootFour write a program that displays four targets to shoot at by clicking on them. The targets are: a. a red ball which moves as it did in ShootTarget above, and is worth 1 point b. a blue ball which moves like the red ball but in another direction. It is slightly faster, slightly smaller and is worth 2 points c. a green ball is twice the size of a red ball and move similarly EXCEPT that they are usually invisible. They are worth 10 points. Use the modulus (%) operator and the setvisible( ) method to make the visibility change in the game loop d. a yellow ball is very fast, ½ the size of a red ball and moves only back and forth (horizontally). It is worth 20 points e. update the displayed score every game loop 4) Survivor1 write a program that puts a red ball and a green ball on screen. The red ball bounces around the screen. The player drags the green ball around, avoiding the red ball as long as possible. When collision finally occurs, display the survival time. 5) Survivor2 same as above, except that the speed of the red ball doubles after 10 seconds, then doubles again after another 10 seconds. 6) Pong1 find a simple Pong game online and implement your own version, moving the player's paddle by moving it with the mouse. The computer's paddle should move automatically. The player s stays near the left end of the table, the computer s paddle stays near the right end of the table. The computer never misses! 7) Pong2 now modify your Pong1 games as follows developing the program in the suggested stages: Daniel L. Schuster, 2009, all rights reserved Page #32

33 a. overall play the player plays games and matches against the computer. But since the computer never misses, the player is really playing against his or her own scores. b. playing a single game: play continues until the player has missed 3 times. During play each successful return by the player is worth 1 pt. Returns by the computer are not scored. The score is clearly displayed as a number in the buttom right corner of the window. Each game is played at one one playing speed. c. playing a single match: a match consists of 3 games. When play moves from one game to another the playing speed increases d. At the end of a match, the players score is prominently displayed. Additionally, a random comment such as Great match or Uhh, you d better keep your day job is displayed. The player has the opportunity to play another match with a click on an appropriately labeled box on the screen. 8) HelicopterInACave create a helicopter in a cave scroller game. The helicopter maneuvers to avoid stalactites and stalagmites. Control the movement with the mouse (clicks for more power) or with the up arrow key (presses for more power). The helicopter falls under the influence of gravity. Points are calculated based on distance traveled before crashing. Provide two levels of play, the first more difficult than the second. 9) BugBot create a playing field with various objects, as shown here. Don't use too many object as you will need to check collision with each one. Daniel L. Schuster, 2009, all rights reserved Page #33

34 Add a BugBot to an open area of the playing field. Your's may certainly be more elaborate than the simple black circle shown below. The BugBot moves around the playing field. When it hits an object (one of the circles or rectangles) or a wall it 1) back up a few pixels 2) turns either left or right randomly 3) continues forward in the new direction. The robot continues to move until it hits the final goal, the red circle marked with a white X, or 30 seconds have elapsed. Above is one possible path from the start to finish. However, it's not a very likely path, since you are turning randomly. Note that your program will have only one BugBot. Many of them are shown above to illustrate the path. 10) UFOEscape Create a UFO object similar to the UFOs we ve created before. Fly the UFO around the window by making it follow the mouse. Asteroids appear at random locations on the edges of the screen and move across the screen. They cause damage to the UFO. Black holes appear randomly but don t move. They kill the UFO. Dilithium crystals appear randomly and don t move. They recharge the UFO s fuel. Asteroids, black holes and Daniel L. Schuster, 2009, all rights reserved Page #34

35 dilithium crystals should also be objects you design. The game ends when the UFO has been damaged beyond repair. Display the status of fuel, shields and survival time (in 1 second increments). Add levels to the game. Use only a few asteroids, black holes and dilithium crystals. 11) YouChoose1 Create an arcade game of your own design or find one online to imitate. Your program must include a. moving object under player control b. scoring c. levels d. use of programmer defined objects Your instructor's approval of your project is required before you begin. This is to protect you from taking on something that's too hard. Daniel L. Schuster, 2009, all rights reserved Page #35

Quick Reference. There are several already named colors which you can use, but you must import the appropriate Java library.

Quick Reference. There are several already named colors which you can use, but you must import the appropriate Java library. Quick Reference This appendix contain information on many of the useful objects and methods related to this book. Some are used in the book, others are just extras you may want to explore to add extra

More information

Chapter 9 Arrays & ArrayLists

Chapter 9 Arrays & ArrayLists Chapter 9 Arrays & ArrayLists One of the things you've probably realized is that so far we are very limited in the number of objects we can work with in a game. To illustrate the problem, assume we've

More information

Programming via Java User interaction

Programming via Java User interaction Programming via Java User interaction We'll now consider programs to get information from the user via the mouse, as supported by the acm.graphics package. Along the way, we'll learn about two more general

More information

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons

More information

Chapter 8 Methods II

Chapter 8 Methods II Chapter 8 Methods II In Chapter 5 we introduced methods. In this chapter we take a much more in depth look at methods and how they are used to deal with complexity in programming. Methods provide a powerful

More information

File: GFace.java /* * File: GFace.java * This class implements a face as a GCompound. */

File: GFace.java /* * File: GFace.java * This class implements a face as a GCompound. */ Steve Cooper Handout #22 CS 106A April 24, 2013 Graphics and Events Examples File: GFace.java * File: GFace.java * This class implements a face as a GCompound. // Note: only need acm.graphics since this

More information

Assignment #3 Breakout!

Assignment #3 Breakout! Eric Roberts Handout #18 CS 106A January 26, 2005 Assignment #3 Breakout! Due: Friday, February 4, 5:00P.M. Your job in this assignment is to write the classic arcade game of Breakout. It is a large assignment,

More information

Chapter 2 ACM Java Graphics

Chapter 2 ACM Java Graphics Chapter 2 ACM Java Graphics The ACM Library provides a big toolkit that makes cool programming accessible to the beginner. But there s a lot to learn. This chapter shows you the most useful tools and techniques,

More information

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons

More information

Adapted from slides by Brahm Capoor. Breakout YEAH hours. Michael (Chung Troute)

Adapted from slides by Brahm Capoor. Breakout YEAH hours. Michael (Chung Troute) Adapted from slides by Brahm Capoor Breakout YEAH hours Michael (Chung Troute) Road Map Lecture Review Graphics Animation Events Using the debugger Assignment Overview Q&A! Graphics GRect rect = new GRect(50,

More information

Programming via Java Subclasses

Programming via Java Subclasses Programming via Java Subclasses Every class in Java is built from another Java class. The new class is called a subclass of the other class from which it is built. A subclass inherits all the instance

More information

Assignment A7 BREAKOUT CS1110 Spring 2011 Due Fri 6 May 1

Assignment A7 BREAKOUT CS1110 Spring 2011 Due Fri 6 May 1 Assignment A7 BREAKOUT CS1110 Spring 2011 Due Fri 6 May 1 This assignment, including much of the wording of this document, is taken from an assignment from Stanford University, by Professor Eric Roberts.

More information

SUBCLASSES IN JAVA - II

SUBCLASSES IN JAVA - II SUBCLASSES IN JAVA - II Subclasses and variables Any instance of a class A can also be treated as an instance of a superclass of A. Thus, if B is a superclass of A, then every A object can also be treated

More information

Events Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Events Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University Events Chris Piech CS106A, Stanford University Catch Me If You Can We ve Gotten Ahead of Ourselves Source: The Hobbit Start at the Beginning Source: The Hobbit Learning Goals 1. Write a program that can

More information

Programming via Java Defining classes

Programming via Java Defining classes Programming via Java Defining classes Our programs so far have used classes, like Turtle and GOval, which were written by other people. In writing larger programs, we often find that another class would

More information

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017 + CS 106A Midterm Review Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017 Details n Only the textbook is allowed n n n The Art and Science of Java Karel Course Reader You will

More information

[ the academy_of_code] Senior Beginners

[ the academy_of_code] Senior Beginners [ the academy_of_code] Senior Beginners 1 Drawing Circles First step open Processing Open Processing by clicking on the Processing icon (that s the white P on the blue background your teacher will tell

More information

5.1. Examples: Going beyond Sequence

5.1. Examples: Going beyond Sequence Chapter 5. Selection In Chapter 1 we saw that algorithms deploy sequence, selection and repetition statements in combination to specify computations. Since that time, however, the computations that we

More information

Breakout YEAH hours. Brahm Capoor & Jared Wolens

Breakout YEAH hours. Brahm Capoor & Jared Wolens Breakout YEAH hours Brahm Capoor & Jared Wolens Road Map YEAH hour schedule Deadline: Due Wednesday, February 8th Lecture Review Using the debugger Assignment Overview Q&A! YEAH hours this quarter Assignment

More information

Nested Loops Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Nested Loops Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University Nested Loops Chris Piech CS106A, Stanford University By Chris Once upon a time X was looking for love! int x = 5; if(lookingforlove()) { int y = 5; println(x + y); 5 x X was looking for love! int x =

More information

CMSC 113: Computer Science I Review Questions for Exam #1

CMSC 113: Computer Science I Review Questions for Exam #1 CMSC 113: Computer Science I Review Questions for Exam #1 During the actual exam, you will have access to whatever printed resources you like, but no electronic resources of any sort. Part I. Each of the

More information

Solutions for Section #4

Solutions for Section #4 Colin Kincaid Section #4 CS 106A July 20, 2018 Solutions for Section #4 1. Warmup: Parameters (MakeBoxes) Portions of this handout by Eric Roberts, Marty Stepp, Chris Piech, Ruchir Rastogi, and Guy Blanc

More information

Pong in Unity a basic Intro

Pong in Unity a basic Intro This tutorial recreates the classic game Pong, for those unfamiliar with the game, shame on you what have you been doing, living under a rock?! Go google it. Go on. For those that now know the game, this

More information

Simple Java YEAH Hours. Brahm Capoor and Vrinda Vasavada

Simple Java YEAH Hours. Brahm Capoor and Vrinda Vasavada Simple Java YEAH Hours Brahm Capoor and Vrinda Vasavada What are YEAH hours? Held soon after each assignment is released Help you to get an early start on your assignments Future dates TBA Slides will

More information

Creating Breakout - Part 2

Creating Breakout - Part 2 Creating Breakout - Part 2 Adapted from Basic Projects: Game Maker by David Waller So the game works, it is a functioning game. It s not very challenging though, and it could use some more work to make

More information

Asteroid Destroyer How it Works

Asteroid Destroyer How it Works Asteroid Destroyer How it Works This is a summary of some of the more advance coding associated with the Asteroid Destroyer Game. Many of the events with in the game are common sense other than the following

More information

Animation. Piech, CS106A, Stanford University

Animation. Piech, CS106A, Stanford University Animation Our story so far Our story so far Learning Goals 1. Write animated programs 2. Center an object You will be able to write Bouncing Ball Learning Goals For Me 1. Speak slower But First! private

More information

Note: Photoshop tutorial is spread over two pages. Click on 2 (top or bottom) to go to the second page.

Note: Photoshop tutorial is spread over two pages. Click on 2 (top or bottom) to go to the second page. Introduction During the course of this Photoshop tutorial we're going through 9 major steps to create a glass ball. The main goal of this tutorial is that you get an idea how to approach this. It's not

More information

Computer Games Development Spring Practical 3 GameCore, Transforms & Collision Detection

Computer Games Development Spring Practical 3 GameCore, Transforms & Collision Detection In this practical we are going to look at the GameCore class in some detail and then move on to examine the use of transforms, collision detection and tile maps. Combined with the material concerning sounds

More information

Interactive Graphics

Interactive Graphics Interactive Graphics Eric Roberts CS 106A January 27, 2010 The acm.graphics Model The acm.graphics package uses a collage model in which you create an image by adding various objects to a canvas. A collage

More information

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created. + Inheritance + Inheritance Classes that we design in Java can be used to model some concept in our program. For example: Pokemon a = new Pokemon(); Pokemon b = new Pokemon() Sometimes we need to create

More information

Additional Practice Problem Solutions

Additional Practice Problem Solutions Chris Piech Handout #extra CS106A March 19, 2017 Additional Practice Problem Solutions 1. Read integers in the console from a user until the user enters a blank like. For each print EVEN if the integer

More information

MORE ON LOOPS IN JAVA

MORE ON LOOPS IN JAVA MORE ON LOOPS IN JAVA In this chapter we look at two new categories of statements the for loop and the break statement. Neither is very complex conceptually, but nonetheless they are convenient enough

More information

ICS 61 Game Systems and Design Introduction to Scratch

ICS 61 Game Systems and Design Introduction to Scratch ICS 61, Winter, 2015 Introduction to Scratch p. 1 ICS 61 Game Systems and Design Introduction to Scratch 1. Make sure your computer has a browser open at the address http://scratch.mit.edu/projects/editor/.

More information

We will start our journey into Processing with creating static images using commands available in Processing:

We will start our journey into Processing with creating static images using commands available in Processing: Processing Notes Chapter 1: Starting Out We will start our journey into Processing with creating static images using commands available in Processing: rect( ) line ( ) ellipse() triangle() NOTE: to find

More information

Assignment 2: Welcome to Java!

Assignment 2: Welcome to Java! CS106A Winter 2011-2012 Handout #12 January 23, 2011 Assignment 2: Welcome to Java! Based on a handout by Eric Roberts and Mehran Sahami Having helped Karel the Robot through the challenges of Assignment

More information

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7 CPS109 Course Notes 7 Alexander Ferworn Unrelated Facts Worth Remembering The most successful people in any business are usually the most interesting. Don t confuse extensive documentation of a situation

More information

Lesson 18: Animation. Computer Programming is Fun!

Lesson 18: Animation. Computer Programming is Fun! Lesson 18: Animation So how do you make your drawings move and change? That's what this section is about. I'd like to introduce you to your new friend, Mr. Timer. A timer gives you the ability to tell

More information

Interactive Graphics. Eric Roberts Handout #23 CS 106A January 25, 2016 Interactive Graphics. Computer Graphics and the Utah Teapot.

Interactive Graphics. Eric Roberts Handout #23 CS 106A January 25, 2016 Interactive Graphics. Computer Graphics and the Utah Teapot. Eric Roberts Handout #23 CS 106A January 25, 2016 Interactive Graphics Interactive Graphics Computer Graphics and the Utah Teapot Eric Roberts CS 106A January 25, 2016 Computer Graphics and the Utah Teapot

More information

CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM

CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM Objectives to gain experience using inheritance Introduction to the Assignment This is the first of a 2-part

More information

CS 106A, Lecture 11 Graphics

CS 106A, Lecture 11 Graphics CS 106A, Lecture 11 Graphics reading: Art & Science of Java, 9.1-9.3 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All

More information

CS106A Handout 15 Winter 2015 February 4, 2015 CS106A Practice Midterm

CS106A Handout 15 Winter 2015 February 4, 2015 CS106A Practice Midterm CS106A Handout 15 Winter 2015 February 4, 2015 CS106A Practice Midterm This exam is closed-book and closed-computer but open-note. You may have a double-sided, 8.5 11 sheet of notes with you when you take

More information

Basic Computer Programming (Processing)

Basic Computer Programming (Processing) Contents 1. Basic Concepts (Page 2) 2. Processing (Page 2) 3. Statements and Comments (Page 6) 4. Variables (Page 7) 5. Setup and Draw (Page 8) 6. Data Types (Page 9) 7. Mouse Function (Page 10) 8. Keyboard

More information

Processing Assignment Write- Ups

Processing Assignment Write- Ups Processing Assignment Write- Ups Exercise 1-1 Processing is not an elaborate series of points like connect the dots or is it? Can t be cause I got it all wrong when I mapped out each and every point that

More information

Com S 227 Spring 2018 Assignment points Due Date: Thursday, September 27, 11:59 pm (midnight) "Late" deadline: Friday, September 28, 11:59 pm

Com S 227 Spring 2018 Assignment points Due Date: Thursday, September 27, 11:59 pm (midnight) Late deadline: Friday, September 28, 11:59 pm Com S 227 Spring 2018 Assignment 2 200 points Due Date: Thursday, September 27, 11:59 pm (midnight) "Late" deadline: Friday, September 28, 11:59 pm (Remember that Exam 1 is MONDAY, October 1.) General

More information

Lab 2: Conservation of Momentum

Lab 2: Conservation of Momentum 3 Lab 2: Conservation of Momentum I. Before you come to lab... II. Background III. Introduction A. This lab will give you an opportunity to explore the conservation of momentum in an interesting physical

More information

Clickteam Fusion 2.5 Creating a Debug System - Guide

Clickteam Fusion 2.5 Creating a Debug System - Guide INTRODUCTION In this guide, we will look at how to create your own 'debug' system in Fusion 2.5. Sometimes when you're developing and testing a game, you want to see some of the real-time values of certain

More information

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the

More information

Getting Familiar with ACM_JTF

Getting Familiar with ACM_JTF Getting Familiar with ACM_JTF PART1: Introduction to the JTF Packages In early 2004, the ACM created the Java Task Force (JTF) to review the Java language, APIs, and tools from the perspective of introductory

More information

CISC 1600, Lab 2.3: Processing animation, objects, and arrays

CISC 1600, Lab 2.3: Processing animation, objects, and arrays CISC 1600, Lab 2.3: Processing animation, objects, and arrays Prof Michael Mandel 1 Getting set up For this lab, we will again be using Sketchpad. sketchpad.cc in your browser and log in. Go to http://cisc1600.

More information

Working with the Dope Sheet Editor to speed up animation and reverse time.

Working with the Dope Sheet Editor to speed up animation and reverse time. Bouncing a Ball Page 1 of 2 Tutorial Bouncing a Ball A bouncing ball is a common first project for new animators. This classic example is an excellent tool for explaining basic animation processes in 3ds

More information

CS 170 Java Programming 1. Week 9: Learning about Loops

CS 170 Java Programming 1. Week 9: Learning about Loops CS 170 Java Programming 1 Week 9: Learning about Loops What s the Plan? Topic 1: A Little Review ACM GUI Apps, Buttons, Text and Events Topic 2: Learning about Loops Different kinds of loops Using loops

More information

CS103 Spring 2018 Mathematical Vocabulary

CS103 Spring 2018 Mathematical Vocabulary CS103 Spring 2018 Mathematical Vocabulary You keep using that word. I do not think it means what you think it means. - Inigo Montoya, from The Princess Bride Consider the humble while loop in most programming

More information

COMP : Practical 9 ActionScript: Text and Input

COMP : Practical 9 ActionScript: Text and Input COMP126-2006: Practical 9 ActionScript: Text and Input This practical exercise includes two separate parts. The first is about text ; looking at the different kinds of text field that Flash supports: static,

More information

Practice Midterm Examination

Practice Midterm Examination Steve Cooper Handout #28 CS106A May 1, 2013 Practice Midterm Examination Midterm Time: Tuesday, May 7, 7:00P.M. 9:00P.M. Portions of this handout by Eric Roberts and Patrick Young This handout is intended

More information

Loops. Variable Scope Remapping Nested Loops. Donald Judd. CS Loops 1. CS Loops 2

Loops. Variable Scope Remapping Nested Loops. Donald Judd. CS Loops 1. CS Loops 2 Loops Variable Scope Remapping Nested Loops CS105 05 Loops 1 Donald Judd CS105 05 Loops 2 judd while (expression) { statements CS105 05 Loops 3 Four Loop Questions 1. What do I want to repeat? - a rect

More information

Animations involving numbers

Animations involving numbers 136 Chapter 8 Animations involving numbers 8.1 Model and view The examples of Chapter 6 all compute the next picture in the animation from the previous picture. This turns out to be a rather restrictive

More information

Practice Midterm Examination #1

Practice Midterm Examination #1 Eric Roberts Handout #35 CS106A May 2, 2012 Practice Midterm Examination #1 Review session: Sunday, May 6, 7:00 9:00 P.M., Hewlett 200 Midterm exams: Tuesday, May 8, 9:00 11:00 A.M., CEMEX Auditorium Tuesday,

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 34 April 13, 2017 Model / View / Controller Chapter 31 How is the Game Project going so far? 1. not started 2. got an idea 3. submitted design proposal

More information

Introduction to Unreal Engine Blueprints for Beginners. By Chaven R Yenketswamy

Introduction to Unreal Engine Blueprints for Beginners. By Chaven R Yenketswamy Introduction to Unreal Engine Blueprints for Beginners By Chaven R Yenketswamy Introduction My first two tutorials covered creating and painting 3D objects for inclusion in your Unreal Project. In this

More information

(Python) Chapter 3: Repetition

(Python) Chapter 3: Repetition (Python) Chapter 3: Repetition 3.1 while loop Motivation Using our current set of tools, repeating a simple statement many times is tedious. The only item we can currently repeat easily is printing the

More information

Major Assignment: Pacman Game

Major Assignment: Pacman Game Major Assignment: Pacman Game 300580 Programming Fundamentals Week 10 Assignment The major assignment involves producing a Pacman style game with Clara using the Greenfoot files that are given to you.

More information

AN INTRODUCTION TO SCRATCH (2) PROGRAMMING

AN INTRODUCTION TO SCRATCH (2) PROGRAMMING AN INTRODUCTION TO SCRATCH (2) PROGRAMMING Document Version 2 (04/10/2014) INTRODUCTION SCRATCH is a visual programming environment and language. It was launched by the MIT Media Lab in 2007 in an effort

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

CS 134 Test Program #2

CS 134 Test Program #2 CS 134 Test Program #2 Sokoban Objective: Build an interesting game using much of what we have learned so far. This second test program is a computer maze game called Sokoban. Sokoban is a challenging

More information

Practice Final Examination #2

Practice Final Examination #2 Eric Roberts Handout #61 CS 106A May 30, 2012 Practice Final Examination #2 Review session: Wednesday, June 6, 7:30 9:30 P.M. (Hewlett 200) Scheduled finals: Friday, June 8, 8:30 11:30 A.M. (Dinkelspiel

More information

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch Purpose: We will take a look at programming this week using a language called Scratch. Scratch is a programming language that was developed

More information

Linked Lists. What is a Linked List?

Linked Lists. What is a Linked List? Linked Lists Along with arrays, linked lists form the basis for pretty much every other data stucture out there. This makes learning and understand linked lists very important. They are also usually the

More information

Platform Games Drawing Sprites & Detecting Collisions

Platform Games Drawing Sprites & Detecting Collisions Platform Games Drawing Sprites & Detecting Collisions Computer Games Development David Cairns Contents Drawing Sprites Collision Detection Animation Loop Introduction 1 Background Image - Parallax Scrolling

More information

Practice Midterm #2. Midterm Time: Monday, July 18 th, 7pm 9pm Midterm Location: Hewlett 200

Practice Midterm #2. Midterm Time: Monday, July 18 th, 7pm 9pm Midterm Location: Hewlett 200 Alisha Adam & Rohit Talreja CS 106A Summer 2016 Practice Midterm #2. Midterm Time: Monday, July 18 th, 7pm 9pm Midterm Location: Hewlett 200. Based on previous handouts by Keith Schwarz, Eric Roberts,

More information

NetLogo Tutorial Series: Langton's Ant. Nicholas Bennett Grass Roots Consulting

NetLogo Tutorial Series: Langton's Ant. Nicholas Bennett Grass Roots Consulting NetLogo Tutorial Series: Langton's Ant Nicholas Bennett Grass Roots Consulting nickbenn@g-r-c.com July 2010 Copyright Copyright 2010, Nicholas Bennett. All rights reserved. NetLogo Tutorial Series: Langton's

More information

Repetition is the reality and the seriousness of life. Soren Kierkegaard

Repetition is the reality and the seriousness of life. Soren Kierkegaard 6 Loops Loops 81 Repetition is the reality and the seriousness of life. Soren Kierkegaard What s the key to comedy? Repetition. What s the key to comedy? Repetition. Anonymous In this chapter: The concept

More information

CS 134 Programming Exercise 9:

CS 134 Programming Exercise 9: CS 134 Programming Exercise 9: Nibbles Objective: To gain experience working with 2 dimensional arrays. The Problem Nibbles is a snake. Nibbles moves around a field, looking for food. Unfortunately, Nibbles

More information

public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public void mouseclicked (MouseEvent e) int x = e.getx(), y = e.gety();

public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public void mouseclicked (MouseEvent e) int x = e.getx(), y = e.gety(); 11 The Jav aawt Part I: Mouse Events 11.1 public void mouseentered (MouseEvent e) setminute(getminute()+increment); 53 public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public

More information

6.001 Notes: Section 17.5

6.001 Notes: Section 17.5 6.001 Notes: Section 17.5 Slide 17.5.1 Now, let's look at one example in which changing the evaluation model allows us to explore a very different kind of computational problem. Our goal is to show how

More information

EEN118 LAB FOUR. h = v t ½ g t 2

EEN118 LAB FOUR. h = v t ½ g t 2 EEN118 LAB FOUR In this lab you will be performing a simulation of a physical system, shooting a projectile from a cannon and working out where it will land. Although this is not a very complicated physical

More information

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes Student Responsibilities Mat 2170 Week 9 Objects and Classes Spring 2014 Reading: Textbook, Sections 6.1 6.3 Lab 9 Attendance 1 2 Recall: Writing Methods 3 Decomposition: break a problem down into smaller

More information

Chapter Fourteen Bonus Lessons: Algorithms and Efficiency

Chapter Fourteen Bonus Lessons: Algorithms and Efficiency : Algorithms and Efficiency The following lessons take a deeper look at Chapter 14 topics regarding algorithms, efficiency, and Big O measurements. They can be completed by AP students after Chapter 14.

More information

Interlude: Expressions and Statements

Interlude: Expressions and Statements Interactive Programming In Java Page 1 Interlude: Expressions and Statements Introduction to Interactive Programming by Lynn Andrea Stein A Rethinking CS101 Project Overview This interlude explores what

More information

Assignment #4 Hangman Due: 11am on Monday, May 14th This assignment may be done in pairs (which is optional, not required)

Assignment #4 Hangman Due: 11am on Monday, May 14th This assignment may be done in pairs (which is optional, not required) Chris Piech Handout #12 CS 106A May 2, 2018 Assignment #4 Hangman Due: 11am on Monday, May 14th This assignment may be done in pairs (which is optional, not required) Based on a handout by Eric Roberts

More information

Programming Project 1

Programming Project 1 Programming Project 1 Handout 6 CSCI 134: Fall, 2016 Guidelines A programming project is a laboratory that you complete on your own, without the help of others. It is a form of take-home exam. You may

More information

EEN118 LAB FOUR. h = v t ½ g t 2

EEN118 LAB FOUR. h = v t ½ g t 2 EEN118 LAB FOUR In this lab you will be performing a simulation of a physical system, shooting a projectile from a cannon and working out where it will land. Although this is not a very complicated physical

More information

Start Visual Studio, create a new project called Helicopter Game and press OK

Start Visual Studio, create a new project called Helicopter Game and press OK C# Tutorial Create a helicopter flying and shooting game in visual studio In this tutorial we will create a fun little helicopter game in visual studio. You will be flying the helicopter which can shoot

More information

CS 106A, Lecture 27 Final Exam Review 1

CS 106A, Lecture 27 Final Exam Review 1 CS 106A, Lecture 27 Final Exam Review 1 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on

More information

CIT 590 Homework 10 Battleship

CIT 590 Homework 10 Battleship CIT 590 Homework 10 Battleship Purposes of this assignment: To give you more experience with classes and inheritance General Idea of the Assignment Once again, this assignment is based on a game, since

More information

Session 4 Starting the Air Raid Game

Session 4 Starting the Air Raid Game Session 4 Starting the Air Raid Game Authored by Brian Cullen (bcullen@rossettschool.co.uk/@mrbcullen) (c) Copyright 2011 Computing At School. This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Practice Midterm Examination

Practice Midterm Examination Mehran Sahami Handout #28 CS106A October 23, 2013 Practice Midterm Examination Midterm Time: Tuesday, October 29th, 7:00P.M. 9:00P.M. Midterm Location (by last name): Last name starts with A-L: go to Dinkelspiel

More information

Assignment #4 Hangman Due: 10:30am on Friday, Febuary 17th This assignment may be done in pairs (which is optional, not required)

Assignment #4 Hangman Due: 10:30am on Friday, Febuary 17th This assignment may be done in pairs (which is optional, not required) Chris Piech Handout #20 CS 106A Feb 8, 2017 Assignment #4 Hangman Due: 10:30am on Friday, Febuary 17th This assignment may be done in pairs (which is optional, not required) Y.E.A.H. hours Thursday from

More information

An object in 3D space

An object in 3D space An object in 3D space An object's viewpoint Every Alice object has a viewpoint. The viewpoint of an object is determined by: The position of the object in 3D space. The orientation of the object relative

More information

Chapter 7 Useful Java Objects

Chapter 7 Useful Java Objects Chapter 7 Useful Java Objects We've already looked at many useful objects from the ACM Java library GRects, GRectangles and so on. In this chapter we look at useful objects from standard Java and then

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 36 November 30, 2018 Mushroom of Doom Model / View / Controller Chapter 31 Announcements Game Project Complete Code Due: Monday, December 10th NO LATE

More information

The Stack, Free Store, and Global Namespace

The Stack, Free Store, and Global Namespace Pointers This tutorial is my attempt at clarifying pointers for anyone still confused about them. Pointers are notoriously hard to grasp, so I thought I'd take a shot at explaining them. The more information

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011 Extending JFrame Dialog boxes Overview

More information

Slide 1 CS 170 Java Programming 1

Slide 1 CS 170 Java Programming 1 CS 170 Java Programming 1 Objects and Methods Performing Actions and Using Object Methods Slide 1 CS 170 Java Programming 1 Objects and Methods Duration: 00:01:14 Hi Folks. This is the CS 170, Java Programming

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 18 17/01/13 11:46 Java Applets 2 of 18 17/01/13 11:46 Java applets embedding Java applications

More information

Critters. Critter #2 Attack.ROAR Attack.POUNCE Attack.SCRATCH. Critter #1

Critters. Critter #2 Attack.ROAR Attack.POUNCE Attack.SCRATCH. Critter #1 Critters This assignment was co-created by Stuart Reges and Marty Stepp. This program focuses on classes, objects, and inheritance. You will write the following files: Ant.java, Bird.java, Crab.java, FireAnt.java,

More information

Programming Lecture 2. Programming by example (Chapter 2) Hello world Patterns Classes, objects Graphical programming

Programming Lecture 2. Programming by example (Chapter 2) Hello world Patterns Classes, objects Graphical programming Five-Minute Review 1. What steps do we distinguish in solving a problem by computer? 2. What are essential properties of an algorithm? 3. What is a definition of Software Engineering? 4. What types of

More information

MITOCW watch?v=0jljzrnhwoi

MITOCW watch?v=0jljzrnhwoi MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information