Modify a text file: $/players4331a.java
$/players4331a.java
//// Exercise 4331a: Defining and using objects - part 1. String title= "Exercise 4331a: Defining and using objects"; int left=20, right= left+600; // Boundaries of a rectangular field. int top=50, bottom= top+400; // (Leave room for text). Player george; //// Declare an object. //// void setup() { //// Set up the screen and reset everything else. size( right+20, bottom+30 ); reset(); // New players. } void reset() { //// Create new object //// george= new Player(); george.name= "George"; } void draw() { //// Next frame: move the players, then draw them. background( 200, 200, 255 ); // Sky blue; scene(); george.move(); george.show(); } void scene() { //// Draw a light-brown field, plus some grass at the bottom. fill( 200, 150, 100 ); noStroke(); rectMode(CORNERS); rect( left, top, right, bottom ); // Field. text( title, width/4, 25 ); } class Player { //////// Player HAS: has position, velocity, etc. and drawing characteristics. //// Player DOES: move(), show() float x=100,y=100; // Position on the screen (i.e. "coordinates") float dx=3,dy=2; // How far to move in one flame (i.e. "velocity") String name="Whatever"; // Name of this player int r1=100, g1=150, b1=50; // Color of this player (body); int w=30,h=50; // Width and height of this player's body (with default values). //// METHODS //// void move() { //// Move this player. //// if (x
right-w/2) dx= -dx; // Bounce off boundaries. if (y
bottom-h/2) dy= -dy; x += dx; y += dy; } void show() { //// Display this player on the screen (at x,y, with color rgb, etc.) rectMode( CENTER ); fill( r1,g1,b1 ); rect( x,y, w,h ); // Body. ellipseMode( CENTER ); ellipse( x, y-h/2-12, 24, 24 ); // Head. fill(0); text( name, x-w/2+3, y-10 ); } }// END OF class Player. //