PROGRAMS OF VOL XII ********** NEW PROGRAM ************* package ejvol12p; /* * Program L3 WormsHD A population of worms is programmed to climb the screen. (Human design). A worm consists of: links plus position plus movers. A mover is an ordered list of instructions to move: which link and in which direction. */ import java.awt.Color; import java.awt.Graphics; import java.util.Random; import javax.swing.JFrame; public class WormsHD extends JFrame { private static final long serialVersionUID = 1L; // Constructor private WormsHD() { } // Instantiation of main class static WormsHD t = new WormsHD(); ///Definition of global variables. //Number of worms private static int nWorms = 8; private static Worm[] worms = new Worm[nWorms]; //Number of links of each worm private static int nLinks = 7; //Initial position over the screen of the head private static int initialRow = 85; // Turn on the random generator static Random r = new Random(); /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must move. */ static private class Move { int x; int y; // The next is a method // that declares // how information is acquired. // It is a constructor. // It is overload by two possibilities. //a) Default method: move to the right Move() { x= 1; y= 1; } //b) copy a couple of numbers Move( int a, int b) { x= a; y= b; } } // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. private class Mover { int link ; Move move ; // Movers can acquired information // in two ways, they are overloaded. // Form 1: by default private Mover() { link= 0; move = new Move(); } // Form 2, from structured data private Mover(int a, Move m) { link= a; move = m; move.x = m.x; move.y = m.y; } } // The class LinkAddress keeps the actual // position of a link. private class LinkAddress { int x; int y; //Constructor: //This is how information is acquired LinkAddress(int a, int b) { x= a; y = b; } } /* Here we define the Bauplan of the worm. A worm is composite: it has links. Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each link has its own color. Each worm keeps record of the actual position of each one of its links, in linkAddress[]. */ private class Worm { Mover mover[ ] ; Color color[]; LinkAddress linkAddress[ ]; //move right (side = 1) else left (side = -1) int side = 2*r.nextInt(2) -1; //Default initialization private Worm( ) { mover = new Mover[nLinks]; linkAddress = new LinkAddress[nLinks]; color = new Color[nLinks]; int c1,c2,c3; //BGR components of color for(int m = 0; m < nLinks; m++) { c1 = r.nextInt(226); c2 = r.nextInt(226); c3 = r.nextInt(226); color[m] = new Color(c1,c2,c3); } //Which direction to move? int link; for(int m = 0; m < nLinks; m++) { //Move the tail first and then the others links. link = nLinks-m-1; Mover mover1; if (side == 1) mover1 = t.new Mover(link,new Move(1,1)); else mover1 = t.new Mover(link,new Move (-1,1)); mover[m]= mover1; } } }//End of Worm class declaration //The application begins here public static void main(String args[]) { int xWin = 200; int yWin = 200; //t is the instance of wormHD t.setSize(xWin,yWin); t.setBackground(Color.lightGray); t.setVisible(true); } //Initial position of worm W at the screen private static Worm start(int W, Graphics g) { int k, a,b; //Auxiliary worm Worm worm = t.new Worm(); //Every link is positioned for(int m = 0; m < nLinks; m++) { // All worms are posited at the same initial row // in vertical position k = initialRow - nLinks; a = 20 + 20 * W; b = k + 12*m; LinkAddress ad = t.new LinkAddress (a,b); worm.linkAddress [m] = ad; // The color is prepared g.setColor( worm.color[m]); // A Rectangle is defined by // the coordinates of the // superior right corner, // width and height. //The link is painted g.fillRect(a,b,4,12); } return worm; } /* If the worm moved to the left, let it move to the right and vice verse. */ private static void updateMoves(Worm worm ) { for(int m = 0; m < nLinks; m++) worm.mover[m].move.x = - worm.mover[m].move.x; } //To climb the screen, the worm //translates each one of its links //according to the information //consigned in mover[] private static Worm translate(Graphics g, Worm worm) { // Reads and execute the // information to move. int n, i, j; for (int m = 0; m < nLinks ; m++) { //Reads the link to be moved n = worm.mover[m].link; //To move a link: //the cell occupied by the link is cleared, //the cell to be occupied is painted. //The occupied cell is cleared: //it is painted in the background color i = worm.linkAddress[n].x; j = worm.linkAddress[n].y; g.setColor(Color.lightGray); g.fillRect(i,j,4,12); // A new place is defined: //The move to be done is read Move move1; move1 = worm.mover[m].move; i = i +4* move1.x; j = j - 6*move1.y; worm .linkAddress[n].x = i; worm .linkAddress[n].y = j; //color for painting g.setColor( worm.color[nLinks-m-1]); g.fillRect(i,j,4,12); //If movement is too fast, nothing can be seen. //To attune the velocity of the worm, //augment or diminish the delay as pleased try { Thread.sleep(1000L); // one second = 1000L } catch (InterruptedException e) {} }//End of the m-loop return worm; } @Override //Master of painting. //It is called automatically after main public void paint(Graphics g) { //initialization: /* The index W distinguishes each worm. Each worm has its color Each worm has nLinks links, each part has its own coordinates on the screen, which are kept in the linkAddress array. The worms are posited at the bottom of the screen. Head is at row InitialRow */ for (int W = 0; W < nWorms; W++) { worms[W]= start(W,g); } // Climbing nSteps int nSteps = 68; for (int l = 0; l < nSteps; l++) { for (int W = 0; W < nWorms; W++) { Worm worm; worm = worms[W]; updateMoves(worm); worm = translate(g,worm); worms[W]= worm ; } } } }//End of main class L3 WormsHD ********** NEW PROGRAM ************* /* * Program L5 WormsRand A population of worms is programmed by randomness to climb the screen. A worm consists of: links plus position plus movers. A mover is an ordered list of instructions to move: which link and in which direction. */ package ejvolu12p; import java.awt.Color; import java.awt.Graphics; import java.util.Random; import javax.swing.JFrame; public class WormsRand extends JFrame { private static final long serialVersionUID = 1L; // Constructor private WormsRand() { } // Instantiation of main class static WormsRand t = new WormsRand(); ///Definition of global variables. //Number of worms private static int nWorms = 8; private static Worm[] worms = new Worm[nWorms]; //Number of links of each worm private static int nLinks = 7; //Initial position over the screen of the head private static int initialRow = 85; //Turn on the random generator static Random r = new Random(); /* Definition of inner classes. * The Move class: A Move says in which direction a link must be moved. */ static private class Move { int x; int y; // The next is a method // that declares // how information is acquired. // It is a constructor. // It is overload by two possibilities. //a) Default method Move() { x= 1; y= 1; } // b) The input is a list Move(int a, int b) { x= a; y= b; } } // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. private class Mover { int link ; Move move ; // Movers can acquired information // in two ways, they are overloaded. // Form 1: by default private Mover() { link = 0; move = new Move(); } // Form 2, from structured data private Mover(int a, Move m) { link = a; move = m; move.x = m.x; move.y = m.y; } } // The class LinkAddress keeps the actual // position of a link. private class LinkAddress { int x; int y; //Constructor: //This is how information is acquired LinkAddress(int a, int b) { x= a; y = b; } } /* Here we define the archetype of worm. A worm is composite: it has links. Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each link has its own color. Each worm keeps record of the actual position of each one of its links, in linkAddress[]. */ private class Worm { Mover mover[ ] ; Color color[]; LinkAddress linkAddress[ ]; int side = r.nextInt(2); //Default initialization private Worm( ) { mover = new Mover[nLinks]; linkAddress = new LinkAddress[nLinks]; color = new Color[nLinks]; int c1,c2,c3; //BGR components of color for(int m = 0; m < nLinks; m++) { c1 = r.nextInt(226); c2 = r.nextInt(226); c3 = r.nextInt(226); color[m] = new Color(c1,c2,c3); } } }//End of Worm class declaration //Vector with the library of allowed moves private static Move[] vectMoves = new Move[10]; //The application begins here public static void main(String args[]) { int xWin = 200; int yWin = 200; //t is the instance of wormHD t.setSize(xWin,yWin); t.setBackground(Color.lightGray); t.setVisible(true); t.setDefaultCloseOperation(EXIT_ON_CLOSE); } //Initial position of worm W at the screen private static Worm start(int W, Graphics g) { int k, a,b; //Auxiliary worm Worm worm = t.new Worm(); //Every link is positioned for(int m = 0; m < nLinks; m++) { // All worms are posited at the same initial row // in vertical position k = initialRow - nLinks; a = 20 + 20 * W; b = k + 12*m; LinkAddress ad = t.new LinkAddress (a,b); worm.linkAddress [m] = ad; // The color is prepared g.setColor( worm.color[m]); // A Rectangle is defined by // the coordinates of the // superior right corner, // width and height. //The link is painted g.fillRect(a,b,4,12); } return worm; } static public void moveDef() { // Here we define 9 cardinal points final Move move0 = new Move(0,1); vectMoves[0] = move0 ; final Move move1 = new Move(1,1); vectMoves[1] = move1 ; final Move move2 = new Move(1,0); vectMoves[2] = move2 ; final Move move3 = new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = new Move(0,0); vectMoves[8] = move8 ; } //There are 8 possible moves //and one is chosen at random. private static void chooseMoves(Worm worm ) { int side = worm.side; int link; for(int m = 0; m < nLinks; m++) { //Move the tail first and then the others links. link = nLinks-m-1; //Choose a move at random Move move = vectMoves[r.nextInt(9)]; Mover mover = t.new Mover(link,move); worm.mover[m]= mover; } //flip direction if ( side == 0) worm.side = 1; else worm.side= 0; } //To climb the screen the worm //moves each one of its links //according to the information //consigned in mover[] private static Worm translate(Graphics g, Worm worm) { // Reads and execute the // information to move. int n, i, j; for (int m = 0; m < nLinks ; m++) { //Reads the link to be moved n = worm.mover[m].link; //To move a link: //the cell occupied by the link is cleared, //the cell to be occupied is painted. //The occupied cell is cleared: //it is painted in the background color i = worm.linkAddress[n].x; j = worm.linkAddress[n].y; g.setColor(Color.lightGray); g.fillRect(i,j,4,12); // A new place is defined: //The move to be done is read Move move1; move1 = worm.mover[m].move; i = i +4* move1.x; j = j - 6*move1.y; worm .linkAddress[n].x = i; worm .linkAddress[n].y = j; //color for painting g.setColor( worm.color[nLinks-m-1]); g.fillRect(i,j,4,12); //If movement is too fast, nothing can be seen. //To attune the velocity of the worm, //augment or diminish the delay as pleased try { Thread.sleep(1000L); // one second = 1000L } catch (InterruptedException e) {} }//End of the m-loop return worm; } @Override //Master of painting. //It is called automatically after main public void paint(Graphics g) { //initialization: /* The index W distinguishes each worm. Each worm has its color Each worm has nLinks links, each part has its own coordinates on the screen, which are kept in the linkAddress array. The worms are posited at the bottom of the screen. Heads are at row InitialRow */ for (int W = 0; W < nWorms; W++) worms[W]= start(W,g); moveDef(); //Climbing nSteps int nSteps = 68; for (int l = 0; l < nSteps; l++) { for (int W = 0; W < nWorms; W++) { Worm worm; worm = worms[W]; //Moves are chosen at random chooseMoves(worm); worm = translate(g,worm); worms[W]= worm ; } } } }//End of main class L5 WormsRand ********** NEW PROGRAM ************* //Program L10 CanvasFX //How to use Canvas of JavaFX //to make drawings. package ejvolu12p; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import javafx.scene.shape.ArcType; import javafx.stage.Stage; public class CanvasFX extends Application { //This method is called automatically to begin with @Override public void start(Stage primaryStage) { //Title primaryStage.setTitle("Canvas gallery"); //Graphics are associated to a tree, //root is declared Group root = new Group(); //CanvasFX is declared Canvas canvas = new Canvas(700, 850); //Canvas' graphical mode GraphicsContext g = canvas.getGraphicsContext2D(); //Make drawings drawings(g); //Centering canvas.setTranslateX(20); //canvas is added to tree root.getChildren().add(canvas); //The tree is addressed to stage primaryStage.setScene(new Scene(root)); //Show begins primaryStage.show(); } //Drawings using CanvasFX private void drawings(GraphicsContext g) { //Shapes with strokes g.setStroke(Color.BLUE); g.setLineWidth(5); //First point = (10,40) g.strokeLine(10,40, 10, 80); //Oval = a point + width and height g.strokeOval(40, 40, 30, 70); //Arc = oval + start angle + extent angle g.strokeArc(120, 40, 30, 30, 45, 240, ArcType.OPEN); g.strokeArc(180, 40, 30, 30, 45, 240, ArcType.ROUND); g.strokeArc(250, 40, 30, 30, 45, 240, ArcType.CHORD); //Broken line //Vector with x-coordinates double[] X1 = new double[]{110, 140, 110, 120}; //Vector with y-coordinates double[] Y1 = new double[]{ 70, 120, 100, 140}; //4 = number of drawn points g.strokePolyline(X1,Y1, 4); //Polygon double[] X2 = new double[]{160, 190, 160}; double[] Y2 = new double[]{ 90, 120, 150}; g.strokePolygon(X2, Y2, 3); //Filled shapes g.setFill(Color.RED); g.fillArc(10, 150, 30, 30, 45, 240, ArcType.OPEN); g.fillArc(60, 150, 30, 30, 45, 240, ArcType.CHORD); g.fillArc(110, 150, 30, 30, 45, 240, ArcType.ROUND); g.fillPolygon(new double[]{160, 190, 160}, new double[]{90, 120, 150}, 3); //Drawing a white figure to make a void g.setFill(Color.WHITE); g.fillOval(160,120,20,50); //Drawing text g.setFill(Color.CADETBLUE); g.fillText("Text in JavaFX Canvas" , 20, 210); //Color resetting g.setFill(Color.GREEN); //Rectangle = a point + width and height. g.fillRect(180, 195, 30, 20); //Clearing out a rectangular area g.clearRect(25, 150, 3, 20); g.setFill(Color.BLACK); g.moveTo(0,170); g.quadraticCurveTo(30,150, 100,170); } public static void main(String[] args) { launch(args); } }//End of main class L10 CanvasFX ********** NEW PROGRAM ************* //Program L12 MovieAWT //This class draws a moving //face with blinking eyes. //Face moves vertically. package ejvolu12p; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class MovieAWT extends JFrame { private static final long serialVersionUID = 1L; private static Long delayLong = 500L; private static Long delayShort = 100L; public void drawFace(Graphics g, int k) { //face g.setColor(Color.pink); g.fillOval(15,15+k,100,150); //hair g.setColor(Color.black); g.fillRect(3,3+k,130,35); //mouth g.setColor(Color.red); g.fillOval(50,120+k,30,20); //eyes g.setColor(Color.blue); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); //nose g.setColor(Color.red); g.drawRect(55,70+k,20,40); } public void eraseface(Graphics g,int k) { // face g.setColor(Color.white); g.fillOval(15,15+k,100,150); //hair //g.setColor(Color.black); g.fillRect(3,3+k,130,35); //mouth //g.setColor(Color.red); g.fillOval(50,120+k,30,20); //eyes //g.setColor(Color.blue); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); //nose //g.setColor(Color.red); g.drawRect(55,70+k,20,40); } public void closeEyes (Graphics g, int k) { // We erase eyes: // eyes are painted in pink g.setColor(Color.pink); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); // We draw smaller eyes g.setColor(Color.blue); g.fillOval(30,65+k,30,5); g.fillOval(70,65+k,30,5); } public void openEyes (Graphics g, int k) { // small eyes are erased // We draw smaller eyes g.setColor(Color.pink); g.fillOval(30,65+k,30,5); g.fillOval(70,65+k,30,5); //We redraw eyes: // eyes are drawn in blue // and normal size g.setColor(Color.blue); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); } public void delay(long l1,int l) { while (System.nanoTime() < l1 + l) {delay(l1,l);} } @Override public void paint(Graphics g) { drawFace(g,0); // This loop controls the numbers // of cycles of the graphic for(int kl = 1; kl<=5; kl++) { // k is the vertical jump int k = 10*kl; //We erase everything g.clearRect(0,0,200,200); // We draw face in the new place drawFace(g,k); // This loop controls the blinking number for(int i=1; i<=2; i++) { // A delay must be introduced to make // movement visible for a human being. System.out.print("Cycle = " + kl); System.out.println(". Blinking = " + i ); try { Thread.sleep(delayLong); } catch (InterruptedException e) {} closeEyes(g, k); try { Thread.sleep(delayShort); // one second = 1000L } catch (InterruptedException e) {} openEyes(g,k); } } System.out.println("Job done."); } public static void main( String args[] ) { MovieAWT m = new MovieAWT(); int xWin = 200; int yWin = 400; m.setSize(xWin,yWin); m.setBackground(Color.lightGray); m.setVisible(true); m.setDefaultCloseOperation(EXIT_ON_CLOSE); } }//End of main class L12 MovieAWT ********** NEW PROGRAM ************* //Program L14 MovieCanvasFX //Attempt of using FXCanvas to make a movie package ejvolu12p; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import javafx.stage.Stage; public class MovieCanvasFX extends Application { private static final Long delayLong = 500L; private static final Long delayShort = 100L; //This method is called automatically to begin with @Override public void start(Stage primaryStage) { //Title primaryStage.setTitle("Canvas gallery"); //Graphics are associated to a tree, //root is declared Group root = new Group(); //CanvasFX is declared Canvas canvas = new Canvas(155, 250); //Canvas' graphical mode GraphicsContext g = canvas.getGraphicsContext2D(); //Make drawings movie(g); //Centering canvas.setTranslateX(20); //canvas is added to tree root.getChildren().add(canvas); //The tree is addressed to stage primaryStage.setScene(new Scene(root)); //Show begins primaryStage.show(); } public void drawFace(GraphicsContext g, int k) { g.setFill(Color.PINK); g.fillOval(15,15+k,100,150); //hair g.setFill(Color.BLACK); g.fillRect(3,3+k,130,35); //mouth g.setFill(Color.RED); g.fillOval(50,120+k,30,20); //eyes g.setFill(Color.BLUE); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); //nose g.setFill(Color.RED); g.fillRect(55,70+k,20,40); } public void eraseface(GraphicsContext g,int k) { g.setFill(Color.WHITE); g.fillOval(15,15+k,100,150); //hair //g.setFill(Color.black); g.fillRect(3,3+k,130,35); //mouth //g.setFill(Color.red); g.fillOval(50,120+k,30,20); //eyes //g.setFill(Color.blue); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); //nose //g.setFill(Color.red); g.fillRect(55,70+k,20,40); } public void closeEyes (GraphicsContext g, int k) { // We erase eyes: // eyes are painted in pink g.setFill(Color.PINK); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); // We draw smaller eyes g.setFill(Color.BLUE); g.fillOval(30,65+k,30,5); g.fillOval(70,65+k,30,5); } public void openEyes (GraphicsContext g, int k) { // small eyes are erased // We draw smaller eyes g.setFill(Color.PINK); g.fillOval(30,65+k,30,5); g.fillOval(70,65+k,30,5); //We redraw eyes: // eyes are drawn in blue // and normal size g.setFill(Color.BLUE); g.fillOval(30,50+k,30,20); g.fillOval(70,50+k,30,20); } public void movie(GraphicsContext g) { drawFace(g,0); // This loop controls the numbers // of cycles of the graphic for(int kl = 1; kl<=2; kl++) { // k is the vertical jump int k = 10*kl; //We erase everything g.clearRect(0,0,200,200); // We draw face in the new place drawFace(g,k); // This loop controls the blinking number for(int i=1; i<=2; i++) { // A delay must be introduced to make // movement visible for a human being. System.out.print("Cycle = " + kl); System.out.println(". Blinking = " + i ); //A delay is inserted try { // one second = 1000L Thread.sleep(delayLong); } catch (InterruptedException e) {} closeEyes(g, k); //A delay is inserted try { // one second = 1000L Thread.sleep(delayShort); } catch (InterruptedException e) {} openEyes(g,k); } } System.out.println("Job done."); } public static void main(String[] args) { launch(args); } }//End of main class L14 MovieCanvasFX ********** NEW PROGRAM ************* /* * Program L17 StaticRectangle Draws a rectangle and a circle using JavaFX */ package ejvolu12p; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class StaticRectangle extends Application { @Override public void start(Stage primaryStage) { //Root of tree Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 260, 140)); //Create a rectangle. Rectangle rect1 = createRectangle(); //rect1 is attached to the root root.getChildren().addAll(rect1); //Create a circle Circle circle1 = createCircle(); //The circle is attached to the root root.getChildren().addAll(circle1); //The scene is shown primaryStage.show(); } //A rectangle ready to be used is built private Rectangle createRectangle() { //Upper left corner at (20,20) //width = 100, hight = 100 Rectangle rect = new Rectangle(20, 20, 100, 100); //Make round corners with span 20 rect.setArcHeight(20); rect.setArcWidth(20); //A color is prepared Color c = Color.DARKCYAN; //The rect is given a color rect.setFill(c); return rect; } //A circle ready to be used is built private Circle createCircle() { //Center at (190,70) //Radious = 50 Circle circle = new Circle(190,70, 50); //A color is prepared Color c = Color.FUCHSIA; //The circle is given a color circle.setFill(c); return circle; } public static void main(String[] args) { launch(args); } }//End of application L17 StaticRectangle ********** NEW PROGRAM ************* //Program L19 MovingRectangle //We learn how to move a rectangle using JavaFX. //To achieve that we manipulate inbuilt macros //called transitions. package ejvolu12p; import java.util.Random; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class MovingRectangle extends Application { //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); //Inbuilt macro: translation TranslateTransition translateTransition ; //Starting the film private void init(Stage primaryStage) { //The stage is organized not as a linear array //but as a tree. Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 300, 600)); //We will work with rectangles Rectangle rect = createRectangle( 40); root.getChildren().addAll(rect); //Translation is instantiated translateTransition = new TranslateTransition(d, rect); //Vertical shift from initial position translateTransition.setByY(100); //Number of repetitions. translateTransition.setCycleCount(2); } //Create a rectangle private static Rectangle createRectangle(int x) { //Upper left corner at (20,20) //width = 100, hight = 100 Rectangle rect = new Rectangle(x, 100, 10, 10); //Make round corners rect.setArcHeight(5); rect.setArcWidth(5); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The color is applied rect.setFill(c); return rect; } public void play() { translateTransition.play(); } @Override public void stop() { translateTransition .stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L19 MovingRectangle ********** NEW PROGRAM ************* //Program L20 MovingCircle //JavaFX makes a circle move horizontally package movingcircle; import java.util.Random; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class MovingCircle extends Application { //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); //Inbuilt macro: translation TranslateTransition translateTransition ; private void init(Stage primaryStage) { Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 270, 120)); //We will work with circles Circle circle = createCircle(); root.getChildren().addAll(circle); //Translation is instantiated translateTransition = new TranslateTransition(d, circle); //Vertical shift from initial position translateTransition.setByX(100); //Turn on Autoreverse translateTransition.setAutoReverse(true); //Number of repetitions. translateTransition.setCycleCount(5); } //A circle ready to be used is built private Circle createCircle() { //Center at (100,70) //Radius = 50 Circle circle = new Circle(100,70, 50); //A color is prepared Color c = Color.FUCHSIA; //The circle is given a color circle.setFill(c); return circle; } public void play() { translateTransition.play(); } @Override public void stop() { translateTransition .stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L20 MovingCircle ********** NEW PROGRAM ************* //Program L21 ManyTransitions //A transition is a change in a graphic. //Transitions can be nested. package ejvolu12p; import java.util.Random; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class ManyTransitions extends Application { //Many transition, possibly on different objects, //happen synchronically private static ParallelTransition goDown; //Many transition, possibly on different objects, //happen sequentially. private static SequentialTransition goRight; //The overall movie is organized sequentially. private static SequentialTransition all; //Turn on the random generator private static Random r = new Random(); //Duration of events private static Duration d = Duration.millis(2000); //Starting the film private void init(Stage primaryStage) { //Root of FavaFX objects that conform to a tree Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 300, 600)); //We will work with rectangles Rectangle Rect[] = new Rectangle[20]; int nRects = 5; //Rectangles are created, positioned and booked for(int i = 0; i < nRects; i++) { Rect[i] = createRectangle((i+1)* 40); root.getChildren().addAll(Rect[i]); } //Synchronous movement goDown = new ParallelTransition(); //All rectangles are moved for (int i = 0; i < nRects; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Rect[i]); //Vertical movement translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goDown.getChildren().addAll(translateTransition); } //A sequence of movements goRight = new SequentialTransition(); //All rectangles are moved for (int i = 0; i < nRects; i++) { TranslateTransition tT = new TranslateTransition(d, Rect[i]); //Horizontal movement tT.setByX(20); //Vertical movement: direction flips tT.setByY(Math.pow(-1, i)*20); tT.setCycleCount(1); goRight.getChildren().addAll(tT); } //Choreography: general organization all = new SequentialTransition(); all.getChildren().addAll(goDown,goRight); } //Create a rectangle private static Rectangle createRectangle(int x) { //Upper left corner at (20,20) //width = 100, hight = 100 Rectangle rect = new Rectangle(x, 100, 10, 10); //Make round corners rect.setArcHeight(5); rect.setArcWidth(5); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The color is applied rect.setFill(c); return rect; } public void play() { all.play(); } @Override public void stop() { all.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L21 ManyTransitions ********** NEW PROGRAM ************* //Program L22 FiveCircles //Five circles move in zigzag. package ejvolu12p; import java.util.Random; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class FiveCircles extends Application { //Everything is organized sequentially. private static SequentialTransition zigzag; //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); //Starting the film private void init(Stage primaryStage) { //JavaFX objects are organized as a tree. Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 350, 600)); //We will work with circles Circle Circle[] = new Circle[20]; int nCircles = 5; //Circles are created, positioned and booked for(int i = 0; i < nCircles; i++) { Circle[i] = createCircle((i+1)* 40); root.getChildren().addAll(Circle[i]); } //Choreography: general organization zigzag = new SequentialTransition(); //Two cycles of zigzag for(int j = 0; j < 2; j++) { //Synchronous movement to the right ParallelTransition goRight = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circle[i]); //Diagonal movement translateTransition.setByX(100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goRight.getChildren(). addAll(translateTransition); } //Synchronous movement to the left ParallelTransition goLeft = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circle[i]); //Diagonal movement translateTransition.setByX(-100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goLeft.getChildren(). addAll(translateTransition); } zigzag.setAutoReverse(true); zigzag.getChildren().addAll(goRight,goLeft); } } //A circle ready to be used is built private Circle createCircle(int x) { //Center at (x,100) //Radius = 10 Circle circle = new Circle(x, 100, 10); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The circle is given a color circle.setFill(c); return circle; } public void play() { zigzag.play(); } @Override public void stop() { zigzag.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L22 FiveCircles ********** NEW PROGRAM ************* //Program L23 MoveRect //A timeline is a personalized schedule of action. //This program presents a movies with //a moving rectangle along a timeline. package ejvolu12p; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class MoveRect extends Application { //A movie needs a clock and a schedule private final Timeline timeline = new Timeline(); //Turn on the random generator static Random r = new Random(); //Starting the movie private void init(Stage primaryStage) { //Tree of JavaFX objects Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 300, 120)); //Create a rectangle that can move. //The type of movement is dictated by //the interpolator: it is linear. Rectangle rect = createMovingRectangle(Interpolator.LINEAR); //Rect1 is attached to the film root.getChildren().addAll(rect); } //How a moving rectangle is built. //Interpolator: the law for movement. private Rectangle createMovingRectangle(Interpolator interpolator) { //Upper left corner at (20,20) //width = 100, hight = 100 Rectangle rect = new Rectangle(20, 20, 100, 100); //Make round corners with span 20 rect.setArcHeight(20); rect.setArcWidth(20); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); //Create a timeline for moving the rectangle: //cycle over and over timeline.setCycleCount(Timeline.INDEFINITE); //Go forth and back timeline.setAutoReverse(true); //Define in Keyvalue what to do with rect: //move it along the X axis 155 pixels //according to the law given by the interpolator KeyValue keyValue = new KeyValue(rect.translateXProperty(), 155, interpolator); //Execute the keyValue using prescribed duration KeyFrame keyFrame = new KeyFrame(Duration.seconds(4), keyValue); //Add the keyframe to the timeline timeline.getKeyFrames().add(keyFrame); return rect; } public void play() { timeline.play(); } @Override public void stop() { timeline.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } public static void main(String[] args) { launch(args); } }//End of main class L23 MoveRect ********** NEW PROGRAM ************* //Program L18 Move2Rect //A movie with two rectangles //that move synchronically //along a timeline. package move2rect; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class Move2Rect extends Application { //A movie needs a clock and a schedule private final Timeline timeline = new Timeline(); //Turn on the random generator static Random r = new Random(); //Starting the film private void init(Stage primaryStage) { //Tree of space-like JavaFX objects. Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 300, 300)); //Create rectangles that can move. //The type of movement is dictated by //the interpolator: it is linear. Rectangle rect1 = createMovingRectangle(Interpolator.LINEAR,20,20); Rectangle rect2 = createMovingRectangle(Interpolator.LINEAR,20,140); //Rects are attached to the root root.getChildren().addAll(rect1, rect2); } //How a moving rectangle is built. //Interpolator: the law for movement. private Rectangle createMovingRectangle(Interpolator interpolator, int x, int y) { //Upper left corner at (x,y) //width = 100, hight = 100 Rectangle rect = new Rectangle(x,y, 100, 100); //Make round corners with span 20 rect.setArcHeight(20); rect.setArcWidth(20); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); //Create a timeline for moving the rectangle: //cycle over and over timeline.setCycleCount(Timeline.INDEFINITE); //Go forth and back timeline.setAutoReverse(true); //Define in Keyvalue what to do with rect: //move it along the X axis 155 units //according to the law given by the interpolator KeyValue keyValue = new KeyValue(rect.translateXProperty(), 155, interpolator); //Execute the keyValue using prescribed duration KeyFrame keyFrame = new KeyFrame(Duration.seconds(4), keyValue); //Add the keyframe to the timeline timeline.getKeyFrames().add(keyFrame); return rect; } public void play() { timeline.play(); } @Override public void stop() { timeline.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } public static void main(String[] args) { launch(args); } }//End of main class L18 Move2Rect ********** NEW PROGRAM ************* //Program L26 Move3Rect //A timeline choreography with 3 rectangles. //Processes that happen at the same time are attached //to the same timeline. //Processes that happen sequencially are attached to //a sequentialTransition. package ejvolu12p; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class Move3Rect extends Application { //Our film has two processes or scenes and two schedules private final Timeline timeline1 = new Timeline(); private final Timeline timeline2 = new Timeline(); //This is the time marshall: //it dictates how scenes appear along the movie private SequentialTransition animation; //Turn on the random generator static Random r = new Random(); //Starting the movie private void init(Stage primaryStage) { //JavaFX tree of space-like objects Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 300, 420)); //Create rectangles. Rectangle rect1 = createRectangle(20,20); Rectangle rect2 = createRectangle(20,140); Rectangle rect3 = createRectangle(20,260); //Set timeline1 with two cycles timeline1.setCycleCount(2); //Go forth and back timeline1.setAutoReverse(true); //Define in Keyvalue what to do with rect1: //move it along the X axis 155 pixels //according to the law given by the interpolator KeyValue keyValue1 = new KeyValue(rect1.translateXProperty(), 155, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect2.translateXProperty(), 155, Interpolator.LINEAR); //Execute synchronically keyValues //using prescribed duration KeyFrame keyFrame1 = new KeyFrame(Duration.seconds(4), keyValue1,keyValue2); //Add keyframe1 to timeline1 timeline1.getKeyFrames().add(keyFrame1); //Set timeline2 timeline2.setCycleCount(2); timeline2.setAutoReverse(true); //Define in Keyvalue what to do with rect3: //move it along the X axis 155 pixels //according to the law given by the interpolator KeyValue keyValue3 = new KeyValue(rect3.translateXProperty(), 155, Interpolator.LINEAR); //Execute keyValue2 using prescribed duration KeyFrame keyFrame2 = new KeyFrame(Duration.seconds(4), keyValue3); //Add the keyframe to the timeline timeline2.getKeyFrames().add(keyFrame2); //Rects are attached to the film root.getChildren().addAll(rect1, rect2, rect3); animation = new SequentialTransition(); animation.getChildren().addAll(timeline1,timeline2); animation.setCycleCount(2); } //A rectangle is returned. private Rectangle createRectangle( int x, int y) { //Upper left corner at (x,y) //width = 100, hight = 100 Rectangle rect = new Rectangle(x,y, 100, 100); //Make round corners with span 20 rect.setArcHeight(20); rect.setArcWidth(20); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); return rect; } public void play() { animation.play(); } @Override public void stop() { animation.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } public static void main(String[] args) { launch(args); } }//End of main class L26 Move3Rect ********** NEW PROGRAM ************* /* * Program L27 Move4Figures * A timeline choreography with 3 rects and one circle. * Processes that happen at the same time are attached * to the same timeline. * Processes that happen sequencially are attached to * a sequentialTransition. */ package ejvolu12p; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class Move4Figures extends Application { //Our movie has three processes or scenes //and three schedules private final Timeline timeline1 = new Timeline(); private final Timeline timeline2 = new Timeline(); private final Timeline timeline3 = new Timeline(); //This is the time marshall: //it dictates how scenes appear along the film private final SequentialTransition animation = new SequentialTransition(); //Turn on the random generator static Random r = new Random(); //Starting the movie private void init(Stage primaryStage) { //Root of the tree of space-like objects. Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 300, 600)); //Create rectangles. Rectangle rect1 = createRectangle(20,20); Rectangle rect2 = createRectangle(20,140); Rectangle rect3 = createRectangle(20,260); //Create a circle Circle circle1 = createCircle(); //Figures are booked root.getChildren().addAll(rect1, rect2, rect3, circle1); //Define in Keyvalue what to do with rect1: //move it along the X axis 155 pixels //according to the law given by the interpolator KeyValue keyValue1 = new KeyValue(rect1.translateXProperty(), 155, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect2.translateXProperty(), 155, Interpolator.LINEAR); //Execute synchronically keyValues using prescribed time KeyFrame keyFrame1 = new KeyFrame(Duration.seconds(4), keyValue1,keyValue2); //Set timeline1 with two cycles timeline1.setCycleCount(2); //Go forth and back timeline1.setAutoReverse(true); //Add keyframe1 to timeline1. //All keyValues attached to keyFrame1 //are executed synchronically because they //belong in the same timeline. timeline1.getKeyFrames().add(keyFrame1); //Set timeline2 timeline2.setCycleCount(2); timeline2.setAutoReverse(true); //Define in Keyvalue what to do with rect3: //move it along the X axis 155 pixels //according to the law given by the interpolator KeyValue keyValue3 = new KeyValue(rect3.translateXProperty(), 155, Interpolator.LINEAR); //Execute keyValue3 using prescribed time KeyFrame keyFrame2 = new KeyFrame(Duration.seconds(4), keyValue3); //Add keyframe2 to timeline2 timeline2.getKeyFrames().add(keyFrame2); //Define the movement of circle1: //shift it upwards 450 pixels. KeyValue keyValue4 = new KeyValue(circle1.translateYProperty(), -450, Interpolator.LINEAR); //Execute keyValue4 using prescribed time KeyFrame keyFrame3 = new KeyFrame(Duration.seconds(4), keyValue4); //Set timeline3 with two cycles timeline3.setCycleCount(2); //Go forth and back timeline3.setAutoReverse(true); //Add keyframe3 to timeline3 timeline3.getKeyFrames().add(keyFrame3); //Organization of scenes along the movie: //animation is not a timeline, //it is a sequenticalTransition so, //listed timelines are executed in sequence. animation.getChildren().addAll(timeline1, timeline2, timeline3); //Repetition mode animation.setCycleCount(2); } //A rectangle is returned. private Rectangle createRectangle( int x, int y) { //Upper left corner at (x,y) //width = 100, hight = 100 Rectangle rect = new Rectangle(x,y, 100, 100); //Make round corners with span 20 rect.setArcHeight(20); rect.setArcWidth(20); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); return rect; } //A circle ready to be used is built private Circle createCircle() { //Center at (70,520) //Radious = 50 Circle circle = new Circle(70,520, 50); //A color is prepared Color c = Color.FUCHSIA; //The circle is given a color circle.setFill(c); return circle; } public void play() { animation.play(); } @Override public void stop() { animation.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } public static void main(String[] args) { launch(args); } }//End of main class L27 Move4Figures ********** NEW PROGRAM ************* //Program L28 SixCircles //This codes is intended to implement the //following plan: //six circles must move in zigzag and //on finished a new circle must appear //and move downwards. //Everyhing is OK with just one problem: //the sixth circle appears from start //and not after the stopping of the five circles. //In general, when a new actor is created, //it is created and shown at the pure beginning //and not when one expects it to appear. package sixcircles; import java.util.Random; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class SixCircles extends Application { //Everything is organized sequentially. private static SequentialTransition all; private static SequentialTransition zigzag; //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); //Starting the movie private void init(Stage primaryStage) { //Root of tree of space-like objects Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 400, 600)); //We will work with circles Circle Circle[] = new Circle[20]; int nCircles = 5; //Circles are created, positioned and booked for(int i = 0; i < nCircles; i++) { Circle[i] = createCircle((i+1)* 40); root.getChildren().addAll(Circle[i]); } //Choreography: general organization zigzag = new SequentialTransition(); //Two cycles of zigzag for(int j = 0; j < 2; j++) { //Synchronous movement to the right ParallelTransition goRight = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circle[i]); //Diagonal movement translateTransition.setByX(100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goRight.getChildren(). addAll(translateTransition); } //Synchronous movement to the left ParallelTransition goLeft = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circle[i]); //Diagonal movement translateTransition.setByX(-100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goLeft.getChildren(). addAll(translateTransition); } zigzag.setAutoReverse(true); zigzag.getChildren().addAll(goRight,goLeft); } all = new SequentialTransition(); //A new actor is created and booked Circle circle6 = createCircle(300); root.getChildren().addAll(circle6); //circle6 is translated TranslateTransition translateTransition = new TranslateTransition(d, circle6); translateTransition.setByY(400); translateTransition.setCycleCount(1); //translateTransition is used here and dies. all.getChildren().addAll(zigzag,translateTransition); } //A circle ready to be used is built private Circle createCircle(int x) { //Center at (x,100) //Radius = 10 Circle circle = new Circle(x, 100, 10); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The circle is given a color circle.setFill(c); return circle; } public void play() { all.play(); } @Override public void stop() { all.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L28 SixCircles ********** NEW PROGRAM ************* //Program L30 SixbCircles //Five circles must move in zigzag and //on finished a new circle must appear //and move downwards. //Since the sixth circle is created and booked //at the beginning, //it is given radius 0 until the moment //when it is scheduled to appear: //at that time it is given a positive radius //and its performance begins. package ejvolu12p; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class SixbCircles extends Application { //Everything is organized sequentially. private static SequentialTransition all; private static SequentialTransition zigzag; //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); //Starting the movie private void init(Stage primaryStage) { Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 400, 600)); //We will work with circles Circle Circle[] = new Circle[20]; int nCircles = 5; //Circles are created, positioned and booked for(int i = 0; i < nCircles; i++) { Circle[i] = createCircle((i+1)* 40); root.getChildren().addAll(Circle[i]); } //A new actor is created Circle circle6 = createCircle(300); //Actor is hidden circle6.setRadius(0); //Actor is booked root.getChildren().addAll(circle6); //Choreography: general organization of scenes zigzag = new SequentialTransition(); //Two cycles of zigzag for(int j = 0; j < 2; j++) { //Synchronous movement to the right ParallelTransition goRight = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circle[i]); //Diagonal movement translateTransition.setByX(100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goRight.getChildren(). addAll(translateTransition); } //Synchronous movement to the left ParallelTransition goLeft = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circle[i]); //Diagonal movement translateTransition.setByX(-100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goLeft.getChildren(). addAll(translateTransition); } zigzag.setAutoReverse(true); zigzag.getChildren().addAll(goRight,goLeft); } //Hidden circle6 is shown SequentialTransition s = showST(circle6); //Visible circle6 is translated TranslateTransition translateTransition = new TranslateTransition(d, circle6); translateTransition.setByY(400); translateTransition.setCycleCount(1); all = new SequentialTransition(); //translateTransition is used here and dies. all.getChildren(). addAll(zigzag,s,translateTransition); } //A circle ready to be used is built private Circle createCircle(int x) { //Center at (x,100) //Radius = 10 Circle circle = new Circle(x, 100, 10); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The circle is given a color circle.setFill(c); return circle; } //The new actor circle6 is shown: //Its radius is scaled from 0 to 100 private SequentialTransition showST(Circle circle6) { Duration d2 = Duration.millis(1); //Circle must be shown at true scale KeyValue keyValue1 = new KeyValue(circle6.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(circle6.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); //Radius of circle6 is enlarged and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause of one millisecond is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(Duration.ONE).onFinished ((ActionEvent t) -> {circle6.setRadius(100);}).build(),b)); return s; } public void play() { all.play(); } @Override public void stop() { all.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L30 SixbCircles ********** NEW PROGRAM ************* //Program L32 SixcCircles //Five circles move in zigzag and //on finished a new circle appears //and moves downwards. //To end, the newcomer is left alone in the stage. //Since the sixth circle is created and booked //at the beginning, //it is given radius 0 until the moment //when it is scheduled to appear: //at that time it is given a positive radius //and its role begins. //The five former circles are scaled down to zero //and in that way they disappear. package ejvolu12p; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class SixcCircles extends Application { //Everything is organized sequentially. private static SequentialTransition all; private static SequentialTransition zigzag; //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); //Starting the movie private void init(Stage primaryStage) { Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 400, 600)); //We will work with circles Circle[] Circles = new Circle[20]; int nCircles = 5; //Circles are created, positioned and booked for(int i = 0; i < nCircles; i++) { Circles[i] = createCircle((i+1)* 40); root.getChildren().addAll(Circles[i]); } //A new actor is created Circle circle6 = createCircle(300); //The new actor is hidden circle6.setRadius(0); //Actor is booked root.getChildren().addAll(circle6); //Choreography: general organization of scenes zigzag = new SequentialTransition(); //Two cycles of zigzag for(int j = 0; j < 2; j++) { //Synchronous movement to the right ParallelTransition goRight = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circles[i]); //Diagonal movement translateTransition.setByX(100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goRight.getChildren(). addAll(translateTransition); } //Synchronous movement to the left ParallelTransition goLeft = new ParallelTransition(); //All circles are moved for (int i = 0; i < nCircles; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Circles[i]); //Diagonal movement translateTransition.setByX(-100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goLeft.getChildren(). addAll(translateTransition); } zigzag.setAutoReverse(true); zigzag.getChildren().addAll(goRight,goLeft); } //Hidden circle6 is shown SequentialTransition show = showST(circle6); //Visible circle6 is translated TranslateTransition translateTransition = new TranslateTransition(d, circle6); translateTransition.setByY(400); translateTransition.setCycleCount(1); //Some actors are removed from the stage SequentialTransition remove = removeST(Circles); all = new SequentialTransition(); //translateTransition is used here and dies. all.getChildren(). addAll(zigzag,show,translateTransition,remove); } //A circle ready to be used is built private Circle createCircle(int x) { //Center at (x,100) //Radius = 10 Circle circle = new Circle(x, 100, 10); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The circle is given a color circle.setFill(c); return circle; } //The new actor circle6 is shown: //Its radius is scaled from 0 to 100 private SequentialTransition showST(Circle circle6) { Duration d2 = Duration.millis(1); //Circle must be shown at true scale KeyValue keyValue1 = new KeyValue(circle6.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(circle6.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); //Radius of circle6 is enlarged and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause of one millisecond is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(Duration.ONE).onFinished ((ActionEvent t) -> {circle6.setRadius(100);}).build(),b)); return s; } //Five former circles are removed: //they are scaled down to zero. private SequentialTransition removeST(Circle[] Circles) { Duration d2 = Duration.millis(1); SequentialTransition ss = new SequentialTransition(); for(int i = 0; i < 5; i++) { //Circles are scaled down to zero KeyValue keyValue1 = new KeyValue(Circles[i].scaleXProperty(), 0, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(Circles[i].scaleYProperty(), 0, Interpolator.LINEAR); //KeyValue2 is inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); //Timeline is inserted into a transition ss.getChildren().addAll(b); } return ss; } public void play() { all.play(); } @Override public void stop() { all.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L32 SixcCircles ********** NEW PROGRAM ************* //Program L33 SixRects //Five rectangles move in zigzag and //on finished a new rectangle appears //and moves downwards. //To end, the newcomer is left alone in the stage. //Since the sixth rectangle is created and booked //at the beginning, //it is given width 0 until the moment //when it is scheduled to appear: //at that time it is given a positive width //and its performance begins. //The five former rectangles are scaled down to zero //and in that way they disappear. package ejvolu12p; import javafx.scene.shape.Rectangle; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.util.Duration; public class SixRects extends Application { //Everything is organized sequentially. private static SequentialTransition all; private static SequentialTransition zigzag; //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); private void init(Stage primaryStage) { Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 400, 600)); //We will work with rectangles Rectangle[] Rectangles = new Rectangle[20]; int nRects = 5; //Rectangles are created, positioned and booked for(int i = 0; i < nRects; i++) { Rectangles[i] = createRectangle((i+1)* 40); root.getChildren().addAll(Rectangles[i]); } //A new actor is created Rectangle rect6 = createRectangle(300); //The new actor is hidden rect6.setHeight(0); rect6.setWidth(0); //Actor is booked root.getChildren().addAll(rect6); //Choreography: general organization zigzag = new SequentialTransition(); //Two cycles of zigzag for(int j = 0; j < 2; j++) { //Synchronous movement to the right ParallelTransition goRight = new ParallelTransition(); //All rects are moved for (int i = 0; i < nRects; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Rectangles[i]); //Diagonal movement translateTransition.setByX(100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goRight.getChildren(). addAll(translateTransition); } //Synchronous movement to the left ParallelTransition goLeft = new ParallelTransition(); //All rects are moved for (int i = 0; i < nRects; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Rectangles[i]); //Diagonal movement translateTransition.setByX(-100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goLeft.getChildren(). addAll(translateTransition); } zigzag.setAutoReverse(true); zigzag.getChildren().addAll(goRight,goLeft); } //Hidden rect6 is shown SequentialTransition show = showST(rect6); //Visible rect6 is translated TranslateTransition translateTransition = new TranslateTransition(d, rect6); translateTransition.setByY(400); translateTransition.setCycleCount(1); //Some actors are removed from the stage SequentialTransition remove = removeST(Rectangles); all = new SequentialTransition(); //translateTransition is used here and dies. all.getChildren(). addAll(zigzag,show,translateTransition,remove); } //A rectangle is created private static Rectangle createRectangle(int x ) { //Upper left corner at (x,100) //width = 10, hight = 10. //Hidden rect is shown later. Rectangle rect = new Rectangle(x, 100, 10, 10); //Make round corners with span 20 //rect.setArcHeight(20); //rect.setArcWidth(20); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); return rect; } //The new actor rect6 is shown: //Its width is scaled from 0 to 100 private SequentialTransition showST(Rectangle rect6) { Duration d2 = Duration.millis(1); //Rect6 must be shown at true scale KeyValue keyValue1 = new KeyValue(rect6.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect6.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); //Width of rect6 is enlarged and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause of one millisecond is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(Duration.ONE).onFinished ((ActionEvent t) -> {rect6.setWidth(100); rect6.setHeight(100);}).build(),b)); return s; } //Five former rectangles are removed: //they are scaled down to zero. private SequentialTransition removeST(Rectangle[] Rectangles) { Duration d2 = Duration.millis(1); SequentialTransition ss = new SequentialTransition(); for(int i = 0; i < 5; i++) { //Rectangles are scaled down to zero KeyValue keyValue1 = new KeyValue(Rectangles[i].scaleXProperty(), 0, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(Rectangles[i].scaleYProperty(), 0, Interpolator.LINEAR); //KeyValue2 is inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); //Timeline is inserted into a transition ss.getChildren().addAll(b); } return ss; } public void play() { all.play(); } @Override public void stop() { all.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L33 SixRects ********** NEW PROGRAM ************* //Program L34 Textual //Texts are included in a scene. package ejvolu12p; import javafx.application.Application; import javafx.stage.Stage; import javafx.animation.AnimationTimer; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.Text; public class Textual extends Application { //Counter (of instants of time) private Integer i = 0; @Override public void start(Stage stage) { Group p = new Group(); Scene scene = new Scene(p); stage.setScene(scene); stage.setWidth(500); stage.setHeight(500); stage.show(); //A circle at the upper left corner final Circle circle = new Circle(20, Color.BISQUE); //Constant text final Text text = new Text ("Welcome!" ); text.setStroke(Color.BLACK); text.setLayoutX(20); text.setLayoutY(20); //A changing text that simulates //a chronometer final Text watch = new Text (""); watch.setLayoutX(40); watch.setLayoutY(40); //Watch is bound to a chronometer in arbitrary units AnimationTimer timer = new AnimationTimer() { @Override public void handle(long l) { watch.setText("Time = " + i.toString()); i++; } }; timer.start(); p.getChildren().addAll(circle, text, watch); } public static void main(String[] args) { Application.launch(args); } } //End of main class L34 Textual ********** NEW PROGRAM ************* //Program L35 Textual2 //Some informative text is added to a scene: //Five rectangles move in zigzag and //on finished a new rectangle appears //and moves downwards. //To end, the newcomer is left alone in the stage. //Since the sixth rectangle is created and booked //at the beginning, //it is given width 0 until the moment //when it is scheduled to appear: //at that time it is given a positive width //and its role begins. //The five former rectangles are scaled down to zero //and it that way they disappear. package textual2; import javafx.scene.shape.Rectangle; import java.util.Random; import javafx.animation.AnimationTimer; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; public class Textual2 extends Application { //Everything is organized sequentially. private static SequentialTransition all; private static SequentialTransition zigzag; //Turn on the random generator private static final Random r = new Random(); //Duration of events private static final Duration d = Duration.millis(2000); //Counter (of instants of time) private Integer counter = 0; //Starting the film private void init(Stage primaryStage) { Group root = new Group(); primaryStage.setResizable(false); //Dimensions of the screen primaryStage.setScene(new Scene(root, 400, 600)); //A circle at the upper left corner final Circle circle = new Circle(20, Color.BISQUE); //Constant text final Text text = new Text ("Welcome!" ); text.setStroke(Color.BLACK); text.setLayoutX(20); text.setLayoutY(20); //A changing text that simulates //a chronometer final Text watch = new Text (""); watch.setLayoutX(40); watch.setLayoutY(40); //Watch is bound to a chronometer in arbitrary units AnimationTimer timer = new AnimationTimer() { @Override public void handle(long l) { watch.setText("Time = " + counter.toString()); counter++; } }; timer.start(); root.getChildren().addAll(circle, text, watch); //Moving rectangles Rectangle[] Rectangles = new Rectangle[20]; int nRects = 5; //Rectangles are created, positioned and booked for(int i = 0; i < nRects; i++) { Rectangles[i] = createRectangle((i+1)* 40); root.getChildren().addAll(Rectangles[i]); } //A new actor is created Rectangle rect6 = createRectangle(300); //The new actor is hidden rect6.setHeight(0); rect6.setWidth(0); //Actor is booked root.getChildren().addAll(rect6); //Choreography: general organization of scenes zigzag = new SequentialTransition(); //Two cycles of zigzag for(int j = 0; j < 2; j++) { //Synchronous movement to the right ParallelTransition goRight = new ParallelTransition(); //All rects are moved for (int i = 0; i < nRects; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Rectangles[i]); //Diagonal movement translateTransition.setByX(100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goRight.getChildren(). addAll(translateTransition); } //Synchronous movement to the left ParallelTransition goLeft = new ParallelTransition(); //All rects are moved for (int i = 0; i < nRects; i++) { //Translation TranslateTransition translateTransition = new TranslateTransition(d, Rectangles[i]); //Diagonal movement translateTransition.setByX(-100); translateTransition.setByY(100); translateTransition.setCycleCount(1); //translateTransition is used here and dies. goLeft.getChildren(). addAll(translateTransition); } zigzag.setAutoReverse(true); zigzag.getChildren().addAll(goRight,goLeft); } //Hidden rect6 is shown SequentialTransition show = showST(rect6); //Visible rect6 is translated TranslateTransition translateTransition = new TranslateTransition(d, rect6); translateTransition.setByY(400); translateTransition.setCycleCount(1); //Some actors are removed from the stage SequentialTransition remove = removeST(Rectangles); all = new SequentialTransition(); //translateTransition is used here and dies. all.getChildren(). addAll(zigzag,show,translateTransition,remove); } //A rectangle is created private static Rectangle createRectangle(int x ) { //Upper left corner at (x,100) //width = 10, hight = 10. //Hidden rect is shown later. Rectangle rect = new Rectangle(x, 100, 10, 10); //Make round corners with span 20 //rect.setArcHeight(20); //rect.setArcWidth(20); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared javafx.scene.paint.Color c = javafx.scene.paint.Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); return rect; } //The new actor rect6 is shown: //Its width is scaled from 0 to 100 private SequentialTransition showST(Rectangle rect6) { Duration d2 = Duration.millis(1); //Rect6 must be shown at true scale KeyValue keyValue1 = new KeyValue(rect6.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect6.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); //Width of rect6 is enlarged and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause of one millisecond is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(Duration.ONE).onFinished ((ActionEvent t) -> {rect6.setWidth(100); rect6.setHeight(100);}).build(),b)); return s; } //Five former rectangles are removed: //they are scaled down to zero. private SequentialTransition removeST(Rectangle[] Rectangles) { Duration d2 = Duration.millis(1); SequentialTransition ss = new SequentialTransition(); for(int i = 0; i < 5; i++) { //Rectangles are scaled down to zero KeyValue keyValue1 = new KeyValue(Rectangles[i].scaleXProperty(), 0, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(Rectangles[i].scaleYProperty(), 0, Interpolator.LINEAR); //KeyValue2 is inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); //Timeline is inserted into a transition ss.getChildren().addAll(b); } return ss; } public void play() { all.play(); } @Override public void stop() { all.stop(); } //This method is automatically called at the beginnig. @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }//End of main class L35 Textual2 ********** NEW PROGRAM ************* //Program L36 Ride //A ride is simulated package ejvolu12p; import javafx.animation.PathTransition; import javafx.animation.PathTransitionBuilder; import javafx.animation.Timeline; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.PathBuilder; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class Ride extends Application { private PathTransition pathTransition; private void init(Stage primaryStage) { Group root = new Group(); primaryStage.setResizable(false); primaryStage.setScene(new Scene(root, 250,400)); //The machine Rectangle rect = new Rectangle (0, 0, 15, 10); rect.setArcHeight(4); rect.setArcWidth(4); rect.setFill(Color.RED); root.getChildren().add(rect); //The road has two cubic segments Path path = PathBuilder.create() .elements ( new MoveTo(50, 200), new CubicCurveTo(10, 30, 100, 150, 200, 120), new CubicCurveTo(220, 140, 28, 350, 50, 200) ) .build(); path.setStroke(Color.DARKBLUE); path.getStrokeDashArray().setAll(7d,7d); root.getChildren().add(path); //Special JavaFX tool for rides pathTransition = PathTransitionBuilder.create() .duration(Duration.seconds(5)) .path(path) .node(rect) .orientation(PathTransition .OrientationType.NONE.ORTHOGONAL_TO_TANGENT) .cycleCount(Timeline.INDEFINITE) //.autoReverse(true) .build(); } public void play() { pathTransition.play(); } @Override public void stop() { pathTransition.stop(); } @Override public void start(Stage primaryStage) throws Exception { init(primaryStage); primaryStage.show(); play(); } public static void main(String[] args) { launch(args); } }//End of main class L36 Ride ********** NEW PROGRAM ************* //Program L38 Jumps1 //For every tic of a clock, //a random jump happens. package ejvolu12p; import java.util.Random; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class Jumps1 extends Application { //Clock private Timeline timeline; //Generator of pseudo random numbers private final Random r = new Random(); @Override public void start(Stage stage) { Group p = new Group(); Scene scene = new Scene(p); stage.setScene(scene); stage.setWidth(150); stage.setHeight(150); //create a rectangle Rectangle rect = new Rectangle(0,0,20,20); rect.setFill(Color.BURLYWOOD); p.getChildren().add(rect); stage.show(); //Instanciate the clock timeline = new Timeline(); //Automatic repetition of tics timeline.setCycleCount(Timeline.INDEFINITE); //Duration in within tics Duration duration = Duration.millis(2000); //A jump is programmed at random EventHandler jumpTo; jumpTo = (EventHandler) (ActionEvent t) -> { int toX = r.nextInt(100); int toY = r.nextInt(100); System.out.println("toX = " + toX + " toY = " + toY); rect.setTranslateX(toX); rect.setTranslateY(toY); }; //Tic and jump are synchronized KeyFrame keyFrame = new KeyFrame(duration, jumpTo); //The new ensemble is booked timeline.getKeyFrames().add(keyFrame); timeline.play(); } public static void main(String[] args) { Application.launch(args); } } //End of main class L38 Jumps1 ********** NEW PROGRAM ************* //Program L40 Jumps2 //For every tic of a clock, //random jumps happen. //There are tree actors: two permanent //but a third is transient: //he enters at some time, //makes a performance and leaves. package ejvolu12p; import java.util.Random; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class Jumps2 extends Application { //Clock private Timeline timeline; //Generator of pseudo random numbers private final Random r = new Random(); //Counter of tics private static Integer nTics = 0; @Override public void start(Stage stage) { Group p = new Group(); Scene scene = new Scene(p); stage.setScene(scene); stage.setWidth(200); stage.setHeight(200); //first actor Rectangle rect1 = new Rectangle(0,0,20,20); rect1.setFill(Color.BURLYWOOD); //Second actor Rectangle rect2 = new Rectangle(30,30,20,20); rect2.setFill(Color.CHOCOLATE); //The third actor is hidden: //it has no width nor height Rectangle rect3 = new Rectangle(50,50,0,0); rect3.setFill(Color.DEEPPINK); //Actors are booked p.getChildren().addAll(rect1, rect2, rect3); stage.show(); //Instanciate the clock timeline = new Timeline(); //Automatic repetition of tics timeline.setCycleCount(Timeline.INDEFINITE); //Duration in within tics Duration duration = Duration.millis(2000); //A jump is programmed at random EventHandler jumpTo; jumpTo = (EventHandler) (ActionEvent t) -> { //Jump of rect1 int toX1 = r.nextInt(100); int toY1 = r.nextInt(100); rect1.setTranslateX(toX1); rect1.setTranslateY(toY1); //Jump of rect2 int toX2 = r.nextInt(100); int toY2 = r.nextInt(100); rect2.setTranslateX(toX2); rect2.setTranslateY(toY2); //Performance of the third actor if ((5 < nTics) & (nTics < 10)) { //Appearance rect3.setHeight(20); rect3.setWidth(20); //Jump int toX3 = r.nextInt(100); int toY3 = r.nextInt(100); rect3.setTranslateX(toX3); rect3.setTranslateY(toY3); } else { //Disappearance rect3.setHeight(0); rect3.setWidth(0); } //Tic is counted nTics++; }; //Tic and jump are synchronized KeyFrame keyFrame = new KeyFrame(duration, jumpTo); //The new ensemble is booked timeline.getKeyFrames().add(keyFrame); timeline.play(); } public static void main(String[] args) { Application.launch(args); } } //End of main class L40 Jumps2 ********** NEW PROGRAM ************* //Program L41 Jumps3 //A planet spins along a circular orbit //around a sun. package ejvolu12p; import java.util.Random; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class Jumps3 extends Application { //Clock private Timeline timeline; //Generator of pseudo random numbers private final Random r = new Random(); //Counter of tics private static Integer nTics = 0; //The radius of the sun private static Integer rSun = 100; //The radius of the orbit private static Integer radiusOrbit = 100; //Angular velocity private static double omega = 0.005; //Initial position of the planet private static double x = 0; private static double y = radiusOrbit; //Time is discrete private static Integer t = 0; @Override public void start(Stage stage) { Group p = new Group(); Scene scene = new Scene(p, 420, 420); stage.setScene(scene); //The sun is centered Circle sun = new Circle(0, 0,rSun); sun.setFill(Color.GOLD); //The planet begins down under the sun Circle planet = new Circle(0,radiusOrbit,3); planet.setFill(Color.LIGHTSTEELBLUE); //Pane to place the ensemble sun + planet final StackPane stack = new StackPane(); stack.getChildren().addAll(sun, planet); //Centering int shiftX = 200; int shiftY = 200; stack.setLayoutX(shiftX); stack.setLayoutY(shiftY); //This was found by trial and error y = y - shiftY/2; x = x + shiftX/2; p.getChildren().add(stack); stage.show(); //Instanciate the clock timeline = new Timeline(); //Automatic repetition of tics timeline.setCycleCount(Timeline.INDEFINITE); //Duration in within tics = dt = 1 = one unit of time Duration duration = Duration.millis(1); //A jump is programmed along a circle EventHandler jumpTo; jumpTo = (EventHandler) (ActionEvent e) -> { //tic //Jump of the planet x = x - omega*radiusOrbit * Math.sin(omega* t); y = y + omega*radiusOrbit * Math.cos(omega* t); planet.setTranslateX(x); planet.setTranslateY(y); //The tic is counted t++; }; //Tic and jump are synchronized KeyFrame keyFrame = new KeyFrame(duration, jumpTo); //The new ensemble is booked timeline.getKeyFrames().add(keyFrame); timeline.play(); } public static void main(String[] args) { Application.launch(args); } } //End of main class L41 Jumps3 ********** NEW PROGRAM ************* //Program L43 Jumps4 //A planet spins along an elliptical orbit //around a sun. //An ellipse is a deformation of a circle: //it is enlarged a times in the x-direction //and b times in the y-direction. //The sun is at the left focus. //x-coordinate of the left focus //c= sqrt(a^2- b^2) package ejvolu12p; import java.util.Random; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class Jumps4 extends Application { //Clock private Timeline timeline; //Generator of pseudo random numbers private final Random r = new Random(); //Counter of tics private static Integer nTics = 0; //The radius of the sun private static Integer rSun = 10; //The radius of the mother circular orbit private static Integer radiusOrbit = 100; //Angular velocity private static double omega = 0.005; //Initial position of the planet private static double x = 0; private static double y = radiusOrbit; //Paramters of the ellipse private static double a = 2; private static double b = 1; private static double c = Math.sqrt(a+a-b*b); //Time is discrete private static Integer t = 0; @Override public void start(Stage stage) { Group p = new Group(); Scene scene = new Scene(p, 520, 420); stage.setScene(scene); //The sun is centered Circle sun = new Circle(0, c,rSun); sun.setFill(Color.GOLD); //The planet begins down under the sun Circle planet = new Circle(0,radiusOrbit,3); planet.setFill(Color.LIGHTSTEELBLUE); //Pane with ensemble sun + planet final StackPane stack = new StackPane(); stack.getChildren().addAll(sun, planet); //Centering int shiftX = 300; int shiftY = 200; stack.setLayoutX(shiftX); stack.setLayoutY(shiftY); //This was found by trial and error y = y - shiftY/2; x = x + shiftX/2; p.getChildren().add(stack); stage.show(); //Instanciate the clock timeline = new Timeline(); //Automatic repetition of tics timeline.setCycleCount(Timeline.INDEFINITE); //Duration in within tics = dt = 1 = one unit of time Duration duration = Duration.millis(1); //A jump is programmed along an ellipse EventHandler jumpTo; jumpTo = (EventHandler) (ActionEvent e) -> { //tic //Jump of the planet x = x - a*omega*radiusOrbit * Math.sin(omega* t); y = y + b*omega*radiusOrbit * Math.cos(omega* t); planet.setTranslateX(x); planet.setTranslateY(y); //The tic is counted t++; }; //Tic and jump are synchronized KeyFrame keyFrame = new KeyFrame(duration, jumpTo); //The new ensemble is booked timeline.getKeyFrames().add(keyFrame); timeline.play(); } public static void main(String[] args) { Application.launch(args); } } //End of main class L43 Jumps4 ********** NEW PROGRAM ************* //Program L44 Jumps5 //A planet spins along an elliptical orbit //around a sun. //An ellipse is a deformation of a circle: //it is elarged a times in the x-direction //and b times in the y-direction. //x-coordinate of the left focus (the sun) //c= sqrt(a^2- b^2). //Jumps were changed by soft transitions. package ejvolu12p; import static javafx.animation.Animation.INDEFINITE; import javafx.animation.SequentialTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class Jumps5 extends Application { //Counter of tics private static final Integer nTics = 0; //The radius of the sun private static final Integer rSun = 10; //The radius of the mother circular orbit private static final Integer radiusOrbit = 100; //Angular velocity private static final double omega = 0.001; //Initial position of the planet private static double x = 0; private static double y = radiusOrbit; //Paramters of the ellipse private static final double a = 2; private static final double b = 1; private static final double c = Math.sqrt(a+a-b*b); //Time is discrete private static Integer t = 0; @Override public void start(Stage stage) { //The scene Group p = new Group(); Scene scene = new Scene(p, 520, 420); stage.setScene(scene); //The sun is centered Circle sun = new Circle(0, c,rSun); sun.setFill(Color.GOLD); //The planet begins down under the sun Circle planet = new Circle(0,radiusOrbit,3); planet.setFill(Color.LIGHTSTEELBLUE); //Ensemble sun + planet final StackPane stack = new StackPane(); stack.getChildren().addAll(sun, planet); //Centering int shiftX = 300; int shiftY = 200; stack.setLayoutX(shiftX); stack.setLayoutY(shiftY); //This was found by trial and error y = y - shiftY/2; x = x + shiftX/2; planet.setTranslateX(x); planet.setTranslateY(y); //Booking p.getChildren().add(stack); stage.show(); //Duration of each iteration Duration duration = Duration.millis(1); //Transitions are nested: //a translation tT is nested into //a sequential transition s //that defines the kinematics //for one cycle = one year. SequentialTransition s = new SequentialTransition(); s.setCycleCount(INDEFINITE); //Iterations for one cycle. //6275 found by trial and error to complete a cycle for(int i = 0; i < 6275; i++) { //Shifting values for an ellipse double byX = - a*omega*radiusOrbit * Math.sin(omega* t); double byY = b*omega*radiusOrbit * Math.cos(omega* t); //Translation of the planet TranslateTransition tT = new TranslateTransition(duration, planet); tT.setByX(byX); tT.setByY(byY); tT.setCycleCount(1); //Nesting of tT into s s.getChildren().add(tT); t++; } s.play(); } public static void main(String[] args) { Application.launch(args); } } //End of main class L44 Jumps5 ********** NEW PROGRAM ************* //Program L48 WormsHDJFX //A population of worms is programmed //by human design to //climb the screen. //Program is written in JavaFX. package ejvolu12p; import java.util.Random; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class WormsHDJFX extends Application { private static WormsHDJFX w = new WormsHDJFX(); private static Group p = new Group(); //Number of steps int nSteps = 10; //Number of worms private static final int nWorms = 8; //Worms are kept in an array private static Worm[] Worms = new Worm[nWorms]; //Number of links of each worm private static final int nLinks = 7; //Initial position over the screen of the head private static int initialRow = 150; //Generator of pseudo random numbers private static final Random r = new Random(); private static final boolean print1 = false; //Each worm has nMovers movers, //instructions to move. private static int nMovers = nLinks; //Width of the worm = width of each link private static int width = 4; //Height of each link private static int height = 12; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must be moved. */ private class Move { int x; int y; //Default initialization: go to the northeast Move() { x= 1; y= 1; } // Initialize wth a list of two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: from numbers private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, from structured data private Mover(int l, Move m) { link= l; move = m; move.x = m.x; move.y = m.y; } // Form 3, from structured data private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover private static Rectangle createRectangle() { //Upper left corner at (20,20) Rectangle rect = new Rectangle(20,20,width,height); //Make round corners with span 20 //rect.setArcHeight(20); //rect.setArcWidth(20); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated ractangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //mover[] keeps movers Mover mover[ ] = new Mover[nLinks]; //The shape of each link Rectangle rect[] = new Rectangle[20]; //move right (side = 1) else left (side = -1) int side = 2*r.nextInt(2) -1; //Default initialization private Worm( ) { //Rects are created. //A color is assigned to each link //but different than white for(int i = 0; i < numberOfLinks; i++) rect[i] = createRectangle(); //The know how to climb the screen int link; for(int m = 0; m < nLinks; m++) { //Move the tail first and then the others links. link = nLinks-m-1; Mover mover1; //Flip horizontal direction of movement, //Move each link in the y-direction if (side == 1) mover1 = new Mover(link,new Move(1,1)); else mover1 = new Mover(link,new Move (-1,1)); mover[m]= mover1; } }//End of Worm() } @Override public void start(Stage stage) { //The scene Scene scene = new Scene(p, 200,200); stage.setScene(scene); stage.setTitle("Human design"); stage.show(); //Worms are posited at the start line startLine(); //Worms climb the screen climb(); } // All worms are posited at the same initial row // in vertical position static private void startLine() { for (int W = 0; W < nWorms; W++) { int k, x,y; //Auxiliary worm Worm worm = w.new Worm(); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 20 * W; k = initialRow - nLinks; //Vertical position y = k + height*link; //Position is updated worm.rect[link].setX(x); worm.rect[link].setY(y); //Link is booked p.getChildren().add(worm.rect[link]); } Worms[W]= worm; } } //To climb the screen the worm W //translates each one of its links //according to the information //consigned in mover[]. //Move m is executed: it moves link m. private static TranslateTransition translate( int W, int m) { if (print1) System.out.println("\n Worm = " + W + " move = " + m); //Reads the link to be moved int link = Worms[W].mover[m].link; //The move to be done is read Move move1; move1 = Worms[W].mover[m].move; //Move is interpreted int byX = 4* move1.x; int byY = -6* move1.y; //Reads position int x = (int) Worms[W].rect[link].getX(); int y = (int) Worms[W].rect[link].getY(); if (print1) System.out.println(" x = " + x + " y = " + y); // A new place is defined: x = x + byX; y = y + byY; if (print1) System.out.println(" byX = " + byX + " byY = " + byY); //Address is updated Worms[W].rect[link].setX(x); Worms[W].rect[link].setY(y); //Duration in within tics Duration d = Duration.millis(500); //A soft movement is programmed TranslateTransition translateTransition = new TranslateTransition(d, Worms[W].rect[link]); //Movement is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); return translateTransition; } //Worms climb the screen. //Various transitions are nested to achieve that. private void climb() { //Overall process SequentialTransition allST = new SequentialTransition(); allST.setCycleCount(1); //worms advance nSteps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move in mover[] SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (int W = 0; W < nWorms; W++) { //Direction is flipped Worms[W].mover[m].move.x = - Worms[W].mover[m].move.x; //A translation of some link //is programmed for worm W //according to move m TranslateTransition tT = translate(W,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked allST.getChildren().add(oneStepST); } //Dynamics is played allST.play(); } public static void main(String[] args) { Application.launch(args); } } //End of main class L48 WormsHDJFX ********** NEW PROGRAM ************* package ejvolu12p; //Program L52 WormsRandJFX2 //A population of worms is programmed //by randomness to //climb the screen. //Repetitions are allowed. To that aim, //worms are repositioned at the //start line to begin a new try. //Program is written in JavaFX. import java.util.Random; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class WormsRandJFX2 extends Application { private static WormsRandJFX2 w = new WormsRandJFX2(); //Overall process private static SequentialTransition nRepetitionsST = new SequentialTransition(); //Number of repetitions private static int nRepetitions = 5; private static int repCounter = 0; private static Group p = new Group(); //Number of steps int nSteps = 3; //Number of worms private static final int nWorms = 5; //Worms are kept in an array private static Worm[] Worms = new Worm[nWorms]; //Number of links of each worm private static final int nLinks = 9; //Initial position of the head private static int initialRow = 180; //Generator of pseudo random numbers private static final Random r = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 3; //Width of the worm = width of each link private static int width = 4; //Height of each link private static int height = 12; //Vector with 9 possible moves private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; //Initial position of worms private static int[][][] xy = new int[nWorms][nLinks][2]; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must be moved. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize wth coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data private Mover(int l, Move m) { link= l; move = m; move.x = m.x; move.y = m.y; } // Form 3, by structured data private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover private static Rectangle createRectangle() { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated ractangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //mover[] keeps movers Mover mover[ ] = new Mover[nLinks]; //The shape of each link Rectangle rect[] = new Rectangle[20]; //move right (side = 1) else left (side = -1) int side = 2*r.nextInt(2) -1; //Default initialization private Worm( ) { //Rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) rect[i] = createRectangle(); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(numberOfLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization mover[m]= w.new Mover(l,move); } }//End of constructor Worm() }//End of class Worm @Override public void start(Stage stage) { //The scene Scene scene = new Scene(p, 500,500); stage.setScene(scene); stage.setTitle("Links move at random"); stage.show(); //Definition of possible moves moveDef(); nRepetitionsST.setCycleCount(1); for(int i = 0; i < nRepetitions; i++) { repCounter = i; //Worms are posited at the start line startLine(); //Worms climb the screen SequentialTransition oneTrialST = climb(); nRepetitionsST.getChildren().add(oneTrialST); } //Movie is played nRepetitionsST.play(); } //Nine basic moves = coordinates where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } //All worms are posited at the same initial row //in vertical position. //There is one procedure for the first time //(all links must be booked), //and another procedure for later times: //no booking but worms must be repositioned //at the start line. static public void startLine() { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm; if (repCounter == 0) worm = w.new Worm(); else worm = Worms[W]; //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 50 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.rect[link].setX(x); worm.rect[link].setY(y); //Link is booked for the 0-th trial if (repCounter == 0) { p.getChildren().add(worm.rect[link]); xy[W][link][0] = x; xy[W][link][1] = y; } else //link is repositioned { //Duration Duration d = Duration.millis(1); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, worm.rect[link]); //Repositioning at initial position translateTransition.setToX(0); translateTransition.setToY(0); //Number of repetitions translateTransition.setCycleCount(1); //Repositioning is booked nRepetitionsST.getChildren() .add(translateTransition); } } Worms[W]= worm; } } //To climb the screen the worm W //translates each one of its links //according to the information //consigned in mover[]. //Move m is executed: it moves link m. private static TranslateTransition translate( int W, int m) { if (print1) System.out.println("\n Worm = " + W + " move = " + m); //Read the link to be moved int link = Worms[W].mover[m].link; //Read position int x = (int) Worms[W].rect[link].getX(); int y = (int) Worms[W].rect[link].getY(); if (print1) System.out.println(" x = " + x + " y = " + y); //The move to be done is read Move move1; move1 = Worms[W].mover[m].move; //Move is interpreted int byX = 4* move1.x; int byY = -6* move1.y; // A new place is defined: x = x + byX; y = y + byY; if (print1) System.out.println(" byX = " + byX + " byY = " + byY); //Address is updated Worms[W].rect[link].setX(x); Worms[W].rect[link].setY(y); //Duration in within tics Duration d = Duration.millis(500); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, Worms[W].rect[link]); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); return translateTransition; } //Worms climb the screen. //Various transitions are nested to achieve that. public SequentialTransition climb() { //Overall process SequentialTransition oneTrialST = new SequentialTransition(); oneTrialST.setCycleCount(1); //worms give nSteps steps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move in mover[] SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (int W = 0; W < nWorms; W++) { Worm worm; worm = Worms[W]; //Direction is flipped worm.mover[m].move.x = - worm.mover[m].move.x; //A translation of some link //is programmed for worm W //according to move m TranslateTransition tT = translate(W,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked oneTrialST.getChildren().add(oneStepST); } return oneTrialST; } public static void main(String[] args) { Application.launch(args); } } //End of main class L52 WormsRandJFX2 ********** NEW PROGRAM ************* //Program L53 WormsRandJFX3 //A population of worms is programmed //by randomness to //climb the screen. //Repetitions are allowed. To that aim, //worms are repositioned at the //start line to begin a new try. //Program is written in JavaFX. package ejvolu12p; import java.util.Random; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class WormsRandJFX3 extends Application { private static WormsRandJFX3 w = new WormsRandJFX3(); //Overall process private static SequentialTransition nRepetitionsST = new SequentialTransition(); //Number of repetitions private static int nRepetitions = 5; private static int repCounter = 0; private static Group p = new Group(); //Number of steps int nSteps = 3; //Number of worms private static final int nWorms = 5; //Worms are kept in an array private static Worm[] Worms = new Worm[nWorms]; //Number of links of each worm private static final int nLinks = 9; //Initial position of the head private static int initialRow = 180; //Generator of pseudo random numbers private static final Random r = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 3; //Width of the worm = width of each link private static int width = 4; //Height of each link private static int height = 12; //Vector with 9 possible moves private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; //Initial position of worms private static int[][][] xy = new int[nWorms][nLinks][2]; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must move. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data private Mover(int l, Move m) { link= l; move = m; move.x = m.x; move.y = m.y; } // Form 3, by structured data private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover private static Rectangle createRectangle() { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated ractangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //mover[] keeps movers Mover mover[ ] = new Mover[nLinks]; //The shape of each link Rectangle rect[] = new Rectangle[20]; //move right (side = 1) else left (side = -1) int side = 2*r.nextInt(2) -1; //Default initialization private Worm( ) { //Rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) rect[i] = createRectangle(); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization mover[m]= w.new Mover(l,move); } }//End of constructor Worm() }//End of class Worm @Override public void start(Stage stage) { //The scene Scene scene = new Scene(p, 500,500); stage.setScene(scene); stage.setTitle("Links move at random"); stage.show(); //Definition of possible moves moveDef(); nRepetitionsST.setCycleCount(1); for(int i = 0; i < nRepetitions; i++) { repCounter = i; //Worms are posited at the start line startLine(); //Worms climb the screen SequentialTransition oneTrialST = climb(); nRepetitionsST.getChildren().add(oneTrialST); } //Film is played nRepetitionsST.play(); } //Nine basic moves = coordinates where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } // All worms are posited at the same initial row // in vertical position. static public void startLine() { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm; if (repCounter == 0) worm = w.new Worm(); else worm = Worms[W]; //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 50 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.rect[link].setX(x); worm.rect[link].setY(y); //Link is booked for the 0-th trial if (repCounter == 0) { p.getChildren().add(worm.rect[link]); xy[W][link][0] = x; xy[W][link][1] = y; } else //link is repositioned { //Duration Duration d = Duration.millis(1); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, worm.rect[link]); //Repositioning at initial position. //Instruction found by serendipity. translateTransition.setToX(0); translateTransition.setToY(0); //Number of repetitions translateTransition.setCycleCount(1); //Repositioning is booked nRepetitionsST.getChildren() .add(translateTransition); } //Moves are redefined worm = resetMoves(worm); } Worms[W]= worm; } } //Moves at random are created private static Worm resetMoves(Worm worm) { //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization worm.mover[m]= w.new Mover(l,move); } return worm; } //To climb the screen the worm W //translates each one of its links //according to the information //consigned in mover[]. //Move m is executed: it moves link m. private static TranslateTransition translate( int W, int m) { if (print1) System.out.println("\n Worm = " + W + " move = " + m); //Read the link to be moved int link = Worms[W].mover[m].link; //Read position int x = (int) Worms[W].rect[link].getX(); int y = (int) Worms[W].rect[link].getY(); if (print1) System.out.println(" x = " + x + " y = " + y); //The move to be done is read Move move1; move1 = Worms[W].mover[m].move; //Move is interpreted int byX = 4* move1.x; int byY = -6* move1.y; // A new place is defined: x = x + byX; y = y + byY; if (print1) System.out.println(" byX = " + byX + " byY = " + byY); //Address is updated Worms[W].rect[link].setX(x); Worms[W].rect[link].setY(y); //Duration in within tics Duration d = Duration.millis(500); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, Worms[W].rect[link]); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); return translateTransition; } //Worms climb the screen. //Various transitions are nested to achieve that. public SequentialTransition climb() { //Overall process SequentialTransition oneTrialST = new SequentialTransition(); oneTrialST.setCycleCount(1); //worms advance nSteps steps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move in mover[] SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (int W = 0; W < nWorms; W++) { //A translation of some link //is programmed for worm W //according to move m TranslateTransition tT = translate(W,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked oneTrialST.getChildren().add(oneStepST); } return oneTrialST; } public static void main(String[] args) { Application.launch(args); } } //End of main class L53 WormsRandJFX3 ********** NEW PROGRAM ************* //Program L54 WormsRandJFX4 //A population of worms is programmed //by randomness to //climb the screen. //Repetitions are allowed for a certain //number of generations. //Each generations has its own //population of worms. //Program is written in JavaFX. package ejvolu12p; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class WormsRandJFX4 extends Application { private static WormsRandJFX4 w = new WormsRandJFX4(); //Overall process private static SequentialTransition nGenerationsST = new SequentialTransition(); //Number of repetitions or generations private static int nGenerations = 5; private static int gen = 0; //The scene private static Group p = new Group(); //Number of steps int nSteps = 3; //Number of worms private static final int nWorms = 5; //Worms are kept in an array private static Worm[] Worms = new Worm[nWorms]; //Number of links of each worm private static final int nLinks = 9; //Initial position of the head private static int initialRow = 180; //Generator of pseudo random numbers private static final Random r = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 3; //Width of the worm = width of each link private static int width = 4; //Height of each link private static int height = 12; //Vector with 9 possible moves private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must move. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data private Mover(int l, Move m) { link= l; move = m; move.x = m.x; move.y = m.y; } // Form 3, by structured data private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //Rects that belongs in the worms of the first generation //are ready to move. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are ready to move, //otherwise they got hidden if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated ractangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //mover[] keeps movers Mover mover[ ] = new Mover[nLinks]; //The shape of each link Rectangle rect[] = new Rectangle[20]; //move right (side = 1) else left (side = -1) int side = 2*r.nextInt(2) -1; //Default initialization: //worms of the first generation are //ready to move. Others get hidden. private Worm(int gen ) { // Rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) rect[i] = createRectangle(gen); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization mover[m]= w.new Mover(l,move); } }//End of constructor Worm(int gen) }//End of class Worm @Override public void start(Stage stage) { //The scene Scene scene = new Scene(p, 500,500); stage.setScene(scene); stage.setTitle("Links move at random"); stage.show(); //Definition of possible moves moveDef(); nGenerationsST.setCycleCount(1); for(int i = 0; i < nGenerations; i++) { gen = i; //Worms are posited at the start line startLine(gen); //Worms climb the screen SequentialTransition oneGenST = climb(); nGenerationsST.getChildren().add(oneGenST); //Worms get hidden ParallelTransition hideST = hideST(); if (gen < nGenerations-1) nGenerationsST.getChildren().add(hideST); } //Film is played nGenerationsST.play(); } //Nine basic moves = coordinates where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } // All worms are posited at the same initial row // in vertical position. static public void startLine(int gen) { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm = w.new Worm(gen); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 50 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.rect[link].setX(x); worm.rect[link].setY(y); //Link is booked p.getChildren().add(worm.rect[link]); //Link is shown SequentialTransition show = showST(worm.rect[link]); //Show transition is booked nGenerationsST.getChildren().add(show); } Worms[W]= worm; } } //To climb the screen the worm W //translates each one of its links //according to the information //consigned in mover[]. //Move m is executed: it moves link m. private static TranslateTransition translate( int W, int m) { if (print1) System.out.println("\n Worm = " + W + " move = " + m); //Read the link to be moved int link = Worms[W].mover[m].link; //Read position int x = (int) Worms[W].rect[link].getX(); int y = (int) Worms[W].rect[link].getY(); if (print1) System.out.println(" x = " + x + " y = " + y); //The move to be done is read Move move1; move1 = Worms[W].mover[m].move; //Move is interpreted int byX = 4* move1.x; int byY = -6* move1.y; // A new place is defined: x = x + byX; y = y + byY; if (print1) System.out.println(" byX = " + byX + " byY = " + byY); //Address is updated Worms[W].rect[link].setX(x); Worms[W].rect[link].setY(y); //Duration in within tics Duration d = Duration.millis(500); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, Worms[W].rect[link]); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); return translateTransition; } //Worms climb the screen. //Various transitions are nested to achieve that. public SequentialTransition climb() { //Overall process SequentialTransition oneGenST = new SequentialTransition(); oneGenST.setCycleCount(1); //worms advance nSteps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move in mover[] SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (int W = 0; W < nWorms; W++) { //A translation of some link //is programmed for worm W //according to move m TranslateTransition tT = translate(W,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked oneGenST.getChildren().add(oneStepST); } return oneGenST; } //A hidden rect gets shown private static SequentialTransition showST(Rectangle rect) { Duration d2 = Duration.millis(1); //Rect must be shown at true scale KeyValue keyValue1 = new KeyValue(rect.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); //Width of rect is enlarged //and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause of one millisecond is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(Duration.ONE) .onFinished ((ActionEvent t) -> { if (gen > 0)//Hidden -> show { rect.setWidth(width); rect.setHeight(height); } }) .build(),b)); return s; } //Worms are hidden after their performance. private static ParallelTransition hideST() { ParallelTransition hidePT = new ParallelTransition(); hidePT.setCycleCount(1); //Hide all worms for (int W = 0; W < nWorms; W++) { //Hide each link for(int link = 0; link < nLinks; link++) { Duration d2 = Duration.millis(1); SequentialTransition ss = new SequentialTransition(); //Rectangles are scaled down to zero KeyValue keyValue1 = new KeyValue(Worms[W].rect[link] .scaleXProperty(), 0, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(Worms[W].rect[link] .scaleYProperty(), 0, Interpolator.LINEAR); //KeyValues are inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); //Timeline is inserted into a transition ss.getChildren().addAll(b); hidePT.getChildren().add(ss); } } return hidePT; } public static void main(String[] args) { Application.launch(args); } } //End of main class L54 WormsRandJFX4 ********** NEW PROGRAM ************* //Program L55 WormsRandJFX5 //A population of worms is programmed //by randomness to //climb the screen. //Repetitions are allowed for a certain //number of generations. //Each generations has its own //population of worms. //One link is added for each new generation. //Program is written in JavaFX. package ejvolu12p; import java.util.ArrayList; import java.util.List; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class WormsRandJFX5 extends Application { private static WormsRandJFX5 w = new WormsRandJFX5(); //Overall process private static SequentialTransition nGenerationsST = new SequentialTransition(); //Number of repetitions or generations private static int nGenerations = 5; private static int gen = 0; //The scene private static Group p = new Group(); //Number of steps int nSteps = 1; //Number of worms private static int nWorms = 5; //Worms are kept in a list private static List Worms = new ArrayList<>(); //Number of links of each worm private static int nLinks = 4; //Initial position of the head private static int initialRow = 180; //Generator of pseudo random numbers private static final Random r = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 3; //Width of the worm = width of each link private static int width = 4; //Height of each link private static int height = 12; //Array with 9 possible moves private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = true; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must move. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data private Mover(int l, Move m) { link= l; move = new Move(m); } // Form 3, by structured data private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //Rects that belongs in the worms of the first generation //are ready to move. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are ready to move, //otherwise they got hidden if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated ractangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //List mover keeps movers List Mover = new ArrayList<>(); //The shape of each link List Rect = new ArrayList<>(); //move right (side = 1) else left (side = -1) int side = 2*r.nextInt(2) -1; //Default initialization: //worms of the first generation are //ready to move. Others get hidden. private Worm(int gen ) { //Rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(gen)); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } }//End of constructor Worm(int gen) }//End of class Worm @Override public void start(Stage stage) { Scene scene = new Scene(p, 500,500); stage.setScene(scene); stage.setTitle("Links move at random"); stage.show(); //Definition of possible moves moveDef(); nGenerationsST.setCycleCount(1); for(int i = 0; i < nGenerations; i++) { gen = i; if (print1) System.out.println("\nGen = " + gen); //Worms are posited at the start line startLine(gen); //Worms express their information to move SequentialTransition oneGenST = express(); nGenerationsST.getChildren().add(oneGenST); //Worms get hidden ParallelTransition hideST = hideST(); if (gen < nGenerations-1) { //Clear Worms as list and hide drawn worms Worms.clear(); nGenerationsST.getChildren().add(hideST); } //Add a new link nLinks = nLinks+1; } //Movie is played nGenerationsST.play(); } //Nine basic moves = coordinates where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } // All worms are posited at the same initial row // in vertical position. static public void startLine(int gen) { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm = w.new Worm(gen); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 100 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.Rect.get(link).setX(x); worm.Rect.get(link).setY(y); //Link is shown SequentialTransition show = showST(worm.Rect.get(link)); //Link is booked p.getChildren().add(worm.Rect.get(link)); //Show transition is booked nGenerationsST.getChildren().add(show); } //worm is located at position W in list Worms Worms.add(worm); } } //To climb the screen the worm W //translates each one of its links //according to the information //consigned in the list mover. //Move m is executed: it moves link m. private static TranslateTransition translate( int W, int m) { if (print1) System.out.println(); //Reads the link to be moved int link = Worms.get(W).Mover.get(m).link; //Reads position int x = (int) Worms.get(W).Rect.get(link).getX(); int y = (int) Worms.get(W).Rect.get(link).getY(); //The move to be done is read Move move1; move1 = Worms.get(W).Mover.get(m).move; //Move is interpreted int byX = 4* move1.x; int byY = -6* move1.y; // A new place is defined: x = x + byX; y = y + byY; if (print1) System.out.println("\n Worm = " + W + " move = " + m + " link = " + link + " \n x = " + x + " y = " + y + " \nbyX = " + byX + " byY = " + byY); //Address is updated Worms.get(W).Rect.get(link).setX(x); Worms.get(W).Rect.get(link).setY(y); //Duration in within tics Duration d = Duration.millis(500); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, Worms.get(W).Rect.get(link)); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); return translateTransition; } //Worms express their information to move. //Various transitions are nested to achieve that. public SequentialTransition express() { //Overall process SequentialTransition oneGenST = new SequentialTransition(); oneGenST.setCycleCount(1); //worms advance nSteps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move in mover[] SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (int W = 0; W < nWorms; W++) { //A translation of some link //is programmed for worm W //according to move m TranslateTransition tT = translate(W,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked oneGenST.getChildren().add(oneStepST); } return oneGenST; } //A hidden rect gets shown private static SequentialTransition showST(Rectangle rect) { Duration d1 = Duration.millis(1); //Rect must be shown at true scale KeyValue keyValue1 = new KeyValue(rect.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d1,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); Duration d2 = Duration.millis(1); //Width of rect is enlarged //and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(d2) .onFinished ((ActionEvent t) -> { if (gen > 0)//Hidden -> show { rect.setWidth(width); rect.setHeight(height); } }) .build(),b)); return s; } //Worms are hidden after their performance. private static ParallelTransition hideST() { ParallelTransition hidePT = new ParallelTransition(); hidePT.setCycleCount(1); //Hide all worms for (int W = 0; W < nWorms; W++) { //Hide each link for(int link = 0; link < nLinks; link++) { Duration d2 = Duration.millis(1); SequentialTransition ss = new SequentialTransition(); //Rectangles are scaled down to zero KeyValue keyValue1 = new KeyValue(Worms.get(W).Rect.get(link) .scaleXProperty(), 0, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(Worms.get(W).Rect.get(link) .scaleYProperty(), 0, Interpolator.LINEAR); //KeyValues are inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); //Timeline is inserted into a transition ss.getChildren().addAll(b); hidePT.getChildren().add(ss); } } return hidePT; } public static void main(String[] args) { Application.launch(args); } } //End of main class L55 WormsRandJFX5 ********** NEW PROGRAM ************* //Program L56 WormsRandJFX6 //A population of worms is programmed //by randomness to //climb the screen. //Repetitions are allowed for a certain //number of generations. //For each new generation: //worms are repositioned at startLine, //the information to move is reset and //one link is added. //Program is written in JavaFX. package ejvolu12p; import java.util.ArrayList; import java.util.List; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class WormsRandJFX6 extends Application { private static WormsRandJFX6 w = new WormsRandJFX6(); //Overall process private static SequentialTransition nGenerationsST = new SequentialTransition(); //Number of repetitions or generations private static int nGenerations = 3; private static int gen = 0; //The tree of spacelike JavaFX objects private static Group p = new Group(); //Number of steps int nSteps = 3; //Number of worms private static int nWorms = 3; //Worms are kept in a list private static List Worms = new ArrayList<>(); //Number of links of each worm private static int nLinks = 6; //Initial position over the screen of the head private static int initialRow = 180; //Generator of pseudo random numbers private static final Random r = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 3; //Width of the worm = width of each link private static int width = 4; //Height of each link private static int height = 12; //Array with 9 possible moves private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must move. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data private Mover(int l, Move m) { link= l; move = new Move(m); } // Form 3, by structured data private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //Rects that belongs in the worms of the first generation //are ready to move. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are ready to move, //otherwise they got hidden if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated ractangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //List mover keeps movers List Mover = new ArrayList<>(); //The shape of each link List Rect = new ArrayList<>(); //move right (side = 1) else left (side = -1) int side = 2*r.nextInt(2) -1; //Default initialization: //worms of the first generation are //ready to move. Others get hidden. private Worm() { //Rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(gen)); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } }//End of constructor Worm(int gen) }//End of class Worm //Nine basic moves = directions where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } @Override public void start(Stage stage) { Scene scene = new Scene(p, 500,400); stage.setScene(scene); stage.setTitle("Links move at random"); stage.show(); //Definition of possible moves moveDef(); //Run the overall process only once nGenerationsST.setCycleCount(1); //This functions well nLinks--; for(int i = 0; i < nGenerations; i++) { gen = i; //Worms are posited at the start line startLine(); //One link is added to all worms addLink(); //Worms climb the screen SequentialTransition oneGenST = express(); nGenerationsST.getChildren().add(oneGenST); } //Film is played nGenerationsST.play(); } //The head of all worms are posited at the same initial row //in vertical position. //There is one procedure for the first time //(all links must be booked), //and another procedure for later times: //no booking but worms must be repositioned //at the start line. static public void startLine() { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm; if (gen == 0) //initial generation worm = w.new Worm(); else //Subsequent generations worm = Worms.get(W); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 100 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.Rect.get(link).setX(x); worm.Rect.get(link).setY(y); //Link is booked for the 0-th generation if (gen == 0) { p.getChildren().add(worm.Rect.get(link)); } else //link is repositioned at startLine { //Duration Duration d = Duration.millis(1); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, worm.Rect.get(link)); //Repositioning at initial position. //Instruction found by serendipity. translateTransition.setToX(0); translateTransition.setToY(0); //Number of repetitions translateTransition.setCycleCount(1); //Repositioning is booked nGenerationsST.getChildren() .add(translateTransition); //Invent new moves worm = resetMoves(worm); } } //worm is added at position W in list Worms Worms.add(worm); } } //Moves at random are created private static Worm resetMoves(Worm worm) { //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization worm.Mover.set(m, w.new Mover(l,move)); } return worm; } //Move m of worm W is executed. private static TranslateTransition translate( int W, int m) { if (print1) System.out.println(); //Read the link to be moved int link = Worms.get(W).Mover.get(m).link; //Read position int x = (int) Worms.get(W).Rect.get(link).getX(); int y = (int) Worms.get(W).Rect.get(link).getY(); //The move to be done is read Move move1; move1 = Worms.get(W).Mover.get(m).move; //Move is interpreted int byX = 4* move1.x; int byY = -6* move1.y; // A new place is defined: x = x + byX; y = y + byY; if (print1) System.out.println("\n Worm = " + W + " move = " + m + " link = " + link + " \n x = " + x + " y = " + y + " \nbyX = " + byX + " byY = " + byY); //Address is updated Worms.get(W).Rect.get(link).setX(x); Worms.get(W).Rect.get(link).setY(y); //Duration in within tics Duration d = Duration.millis(500); //A soft jump is programmed TranslateTransition translateTransition = new TranslateTransition(d, Worms.get(W).Rect.get(link)); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); return translateTransition; } //Worms express their information to move. public SequentialTransition express() { //Overall process SequentialTransition oneTrialST = new SequentialTransition(); oneTrialST.setCycleCount(1); //worms advance nSteps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (int W = 0; W < nWorms; W++) { //A translation of some link //is programmed for worm W //according to move m TranslateTransition tT = translate(W,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked oneTrialST.getChildren().add(oneStepST); } return oneTrialST; } //One link is added to all worms public static void addLink() { //All worms are visited for (int W = 0; W < nWorms; W++) { //New rect is created and added to the worm Worms.get(W).Rect.add(createRectangle(gen)); //Rect is booked p.getChildren().add(Worms.get(W) .Rect.get(nLinks)); //Horizontal position int x = 30 + 150 * W; //Vertical position int y = initialRow + height*nLinks; //Position is updated Worms.get(W).Rect.get(nLinks).setX(x); Worms.get(W).Rect.get(nLinks).setY(y); //Link is shown SequentialTransition show = showST(Worms.get(W) .Rect.get(nLinks)); //Show transition is booked nGenerationsST.getChildren().add(show); } //Bookkeeping nLinks++; } //A hidden rect gets shown private static SequentialTransition showST(Rectangle rect) { Duration d1 = Duration.millis(1); //Rect must be shown at true scale KeyValue keyValue1 = new KeyValue(rect.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d1,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); Duration d2 = Duration.millis(1); //Width of rect is enlarged to get it visible //and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(d2) .onFinished ((ActionEvent t) -> { if (gen > 0)//Hidden -> show { rect.setWidth(width); rect.setHeight(height); } }) .build(),b)); return s; } public static void main(String[] args) { Application.launch(args); } } //End of main class L56 WormsRandJFX6 ********** NEW PROGRAM ************* //Program L57 WormsRandJFX7 //A population of worms is programmed //by twisted randomness to //climb the screen. //Each generations has its own //population of worms. //All worms have two links at the start. //One link is added when some worm is shown //to climb the screen. //Program is written in JavaFX. package ejvolu12p; import static java.lang.Math.pow; import java.util.ArrayList; import java.util.List; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.PauseTransitionBuilder; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; public class WormsRandJFX7 extends Application { private static WormsRandJFX7 w = new WormsRandJFX7(); //Overall process private static SequentialTransition nGenerationsST = new SequentialTransition(); //Number of repetitions or generations private static int nGenerations = 10; //Actual generation private static int gen = 0; //Duration of events private static final Duration d = Duration.millis(100); private static Group p = new Group(); //Number of steps given for each try int nSteps = 8; //Number of worms private static int nWorms = 8; //Worms are kept in a list private static List Worms = new ArrayList<>(); //Number of links of each worm private static int nLinks = 2; //Initial position of the head private static int initialRow = 280; //Generator of pseudo random numbers private static final Random r = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 3; //Width of the worm = width of each link private static int width = 6; //Height of each link private static int height = 6; //Array with 9 possible moves private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; private static final boolean print2 = false; //Text to be drawn private static Text genCount = new Text (""); //Two links cannot occupy the same place static boolean isOccupied[][] = new boolean[600][300]; //Is a worm capable of climbing the screen? private static int Fitness[] = new int[21]; //Was climbing good enough? private static boolean bullseye = false; //List of generations at which success was made private static String record = ""; //Measures of the screen private static int xWin = 1200; private static int yWin = 850; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must move. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list of numbers private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data: link + move private Mover(int l, Move m) { link= l; move = new Move(m); } // Form 3, by structured data: mover private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //Rects that belong in the worms of the first generation //are visible. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are ready to move, //otherwise they got hidden if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated rectangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //List mover keeps movers List Mover = new ArrayList<>(); //The shape of each link List Rect = new ArrayList<>(); //Default initialization: //worms of the first generation are //ready to move. Others get hidden. private Worm(int gen ) { // Rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(gen)); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } }//End of constructor Worm(int gen) }//End of class Worm //General setting @Override public void start(Stage stage) { Scene scene = new Scene(p, xWin,yWin); stage.setScene(scene); stage.setTitle("Links move at random"); stage.show(); //Definition of possible moves moveDef(); //Text to draw genCount = new Text (""); genCount.setLayoutX(40);genCount.setLayoutY(40); p.getChildren().addAll(genCount); nGenerationsST.setCycleCount(1); //Many attempts are allowed for(int i = 0; i < nGenerations; i++) { voidOccupationMatrix();//Voidness gen = i; if (print2) System.out.println("\nGen = " + gen); //Generation number is drawn Timeline timeline = drawGen(gen); nGenerationsST.getChildren().addAll( timeline ); //Worms are posited at the start line startLine(gen); //Worms express their information to move SequentialTransition oneGenST = express(); nGenerationsST.getChildren().add(oneGenST); //Is some worm able to climb? assessFitness(); //Worms get hidden ParallelTransition hideST = hideST(); if (gen < nGenerations - 1 ) { //Clear Worms as list and hide drawn worms Worms.clear(); nGenerationsST.getChildren().add(hideST); } //Success? Integer genI = gen; if (bullseye) { //If climbing was successful, add a new link nLinks = nLinks+1; //List of generations with sucess record = record + " " + genI.toString(); } } //Movie is played nGenerationsST.play(); System.out.println("Successful generations = " + record); } // To avoid overwriting of worms, // an occupation record is kept: // The screen is divided in cells 6x6. // At the beginning every cell is empty=false. // Occupancy is recorded in isOccupied[][], // which is a boolean matrix. // A boolean variable can be // true= occupied, else false= not occupied. private static void voidOccupationMatrix() { //System.out.println("occupationMatrix"); for(int i = 0; i < 600; i++) for(int j = 0; j < 300; j++) isOccupied[i][j]= false; } //Nine basic moves = coordinates where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } // All worms are posited at the same initial row // in vertical position. static public void startLine(int gen) { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm = w.new Worm(gen); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 150 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.Rect.get(link).setX(x); worm.Rect.get(link).setY(y); //Link is shown SequentialTransition show = showST(worm.Rect.get(link)); //Link is booked p.getChildren().add(worm.Rect.get(link)); //Show transition is booked nGenerationsST.getChildren().add(show); } //worm is located at position W in list Worms Worms.add(worm); } } //Draws the generation number private static Timeline drawGen(int gen) { Integer genI = gen; String message = "Generation = " + genI.toString(); //A JavaFX event committed to print a text is generated EventHandler printText = (EventHandler) (ActionEvent t ) -> { genCount.setText(message); }; //Presentation of printText must be //synchronized with the overall film so, //duration d is specified KeyFrame keyFrame = new KeyFrame(d, printText); Timeline timeline = new Timeline(); timeline.setCycleCount(1); //add the keyframe to the timeline timeline.getKeyFrames().add(keyFrame); return timeline; } //Is move m disruptive? //(A worm is and must remain as a whole, //nevertheless, some elasticity is allowed.) private static boolean isDisruptive(int m, Worm worm ) { // A move is disruptive if the target address // is farther than certain distance // from the neighboring links. boolean isDisruptive = false; int link; int x,y, x1,y1, x2,y2, x3,y3; double d1; double d2; //Read the link to be moved link = worm.Mover.get(m).link; //Read the address of the link; x = (int) worm.Rect.get(link).getX(); y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move = w.new Move(worm.Mover.get(m).move); //The target address is calculated x1 = x + width*move.x; y1 = y - width*move.y; //The addresses of the two neighboring links are read //The disruption is calculated //Case: intermediate link if ((0 < link) & (link < nLinks-1)) { x2 = (int) worm.Rect.get(link-1).getX(); y2 = (int) worm.Rect.get(link-1).getY(); d1 = pow( ( pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); x3 = (int) worm.Rect.get(link+1).getX(); y3 = (int) worm.Rect.get(link+1).getY(); d2 = pow( (pow( (x3 - x1),2) + pow((y3 - y1),2)),0.5); // Here we decide whether or not // a move is disruptive. //To augment elasticity, augment the threshold if ((d1 > 1.415*width) || (d2 > 1.415*width)) isDisruptive = true; } //First link if (link == 0) { x2 = (int) worm.Rect.get(1).getX(); y2 = (int) worm.Rect.get(1).getY(); d1 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if( d1 > 1.1*width) isDisruptive = true; } //Last link if( link == nLinks-1 ) { x2 = (int) worm.Rect.get(nLinks - 2).getX(); y2 = (int) worm.Rect.get(nLinks - 2).getY(); d2 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if ( d2 > 1.1*width ) isDisruptive = true; } return isDisruptive; } //Is the move m of worm W not disruptive? //If it is not, execute it. private static SequentialTransition exeIf( Worm worm, int m) { if (print1) System.out.println(" exeIf"); //Reads the link to be moved int link = worm.Mover.get(m).link; //Reads position int x = (int) worm.Rect.get(link).getX(); int y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move; move = worm.Mover.get(m).move; //Move is interpreted int byX = width* move.x; int byY = -height* move.y; //Target address is calculated: int x1 = x + byX; int y1 = y + byY; if (x1 < 0 ) x1 = 0; if (y1 < 0 ) y1 = 0; if (print1) System.out.println( " move = " + m + " link = " + link + " \n x = " + x + " y = " + y + " \nbyX = " + byX + " byY = " + byY); //Occupied cell int i = (int) x / width; int j = (int) y / height; //Target cell int k =(int) x1/width; int l = (int) y1/height; //Move is always executed SequentialTransition a = new SequentialTransition(); TranslateTransition translateTransition = new TranslateTransition(d, worm.Rect.get(link)); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); a.getChildren().add(translateTransition); //Is the move disruptive? boolean isMoveDisruptive = isDisruptive(m,worm); if (print2) { if (isMoveDisruptive) System.out.println("move is Disruptive"); else System.out.println("move is not Disruptive"); } //Disruptive moves are undone if (((isOccupied[k][l])) || ((isMoveDisruptive))) { byX = -byX; byY = -byY; } else //move is not disruptive -> it is not undone { byX = 0; byY = 0; worm.Rect.get(link).setX(x1); worm.Rect.get(link).setY(y1); isOccupied[i][j]= false; isOccupied[k][l]= true; } //Move is possibly undone TranslateTransition translateTransition2 = new TranslateTransition(d, worm.Rect.get(link)); //Jump is programmed translateTransition2.setByX(byX); translateTransition2.setByY(byY); //Number of repetitions translateTransition2.setCycleCount(1); a.getChildren().add(translateTransition2); return a; } //Worms express their information to move. public SequentialTransition express() { //Overall process SequentialTransition expressST = new SequentialTransition(); expressST.setCycleCount(1); //Worms advance nSteps steps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { if (print1) System.out.println("nMovers = " + nMovers); //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (Worm worm: Worms) { //A translation of some link //is programmed for worm W //according to move m. //If it is not disruptive, //it is executed SequentialTransition tT = exeIf(worm,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked expressST.getChildren().add(oneStepST); } return expressST; } //A hidden rect gets shown private static SequentialTransition showST(Rectangle rect) { Duration d1 = Duration.millis(1); //Rect must be shown at true scale KeyValue keyValue1 = new KeyValue(rect.scaleXProperty(), 1, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(rect.scaleYProperty(), 1, Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d1,keyValue1,keyValue2 )); SequentialTransition s = new SequentialTransition(); Duration d2 = Duration.millis(1); //Width of rect is enlarged //and after this //it is shown according to the //instructions given by timeline b. //To do this, a pause is added. s.getChildren().add( new SequentialTransition( PauseTransitionBuilder.create(). duration(d2) .onFinished ((ActionEvent t) -> { if (gen > 0)//Hidden -> show { rect.setWidth(width); rect.setHeight(height); } }) .build(),b)); return s; } //Worms are hidden after their performance. private static ParallelTransition hideST() { ParallelTransition hidePT = new ParallelTransition(); hidePT.setCycleCount(1); //Hide all worms for (int W = 0; W < nWorms; W++) { //Hide each link for(int link = 0; link < nLinks; link++) { Duration d2 = Duration.millis(1); SequentialTransition ss = new SequentialTransition(); //Rectangles are scaled down to zero KeyValue keyValue1 = new KeyValue(Worms.get(W).Rect.get(link) .scaleXProperty(), 0, Interpolator.LINEAR); KeyValue keyValue2 = new KeyValue(Worms.get(W).Rect.get(link) .scaleYProperty(), 0, Interpolator.LINEAR); //KeyValues are inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue1,keyValue2 )); //Timeline is inserted into a transition ss.getChildren().addAll(b); hidePT.getChildren().add(ss); } } return hidePT; } // Every worm is assigned a fitness //The nearer to the top, the fitter. //If climbing has been significative, //the complexity of the game rises up one level: //a true bullseye is reported (to add //next a new link to all worms). private static void assessFitness() { int yOfTail; double yOfHead; bullseye = false; for(int W = 0; W < nWorms; W++) { // We get the y-coordinate of the tail yOfTail = (int) Worms.get(W).Rect.get(nLinks-1).getY(); yOfHead = Worms.get(W).Rect.get(0).getY(); //Climbing up is worth a point Fitness[W] = 100*(yWin - yOfTail); if(print1) System.out.println("Fitness of worm " + W + " = " + Fitness[W] + " head = " + yOfHead); //if (headPosition < initialRow - width*nLinks) if (yOfHead < initialRow - 2 * height) { bullseye = true; if (print1) System.out.println( "There was advance W = " + W ); } } } public static void main(String[] args) { Application.launch(args); } } //End of main class L57 WormsRandJFX7 ********** NEW PROGRAM ************* //Program L61 WormsRandJFX8 //A population of worms is programmed //by twisted randomness to //climb the screen. //All moves are executed //but nondisruptive moves are //not undone. //Each generations has its own //population of worms. //All worms have two links at the start. //One link is added when some worm is shown //to climb the screen. //Program is written in JavaFX. package ejvolu12p; import static java.lang.Math.pow; import java.util.ArrayList; import java.util.List; import java.util.Random; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; public class WormsRandJFX8 extends Application { private static WormsRandJFX8 w = new WormsRandJFX8(); //Overall process private static SequentialTransition nGenerationsST = new SequentialTransition(); //Number of repetitions or generations private static int nGenerations = 10; //Actual generation private static int gen = 0; //Duration of events private static final Duration d = Duration.millis(100); private static Group p = new Group(); //Number of steps given for each try int nSteps = 8; //Number of worms private static int nWorms = 8; //Worms are kept in a list private static List Worms = new ArrayList<>(); //Number of links of each worm private static int nLinks = 2; //Initial position over the screen of the head private static int initialRow = 280; //Generator of pseudo random numbers private static final Random r = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 3; //Width of the worm = width of each link private static int width = 6; //Height of each link private static int height = 6; //Array with 9 possible moves private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; private static final boolean print2 = false; //Text to be drawn private static Text genCount = new Text (""); //Two links cannot occupy the same place static boolean isOccupied[][] = new boolean[600][300]; //Is a worm capable of climbing the screen? private static int Fitness[] = new int[21]; //Was climbing good enough? private static boolean bullseye = false; //List of generations at which success was made private static String record = ""; //Size of the screen private static int xWin = 1200; private static int yWin = 850; //Grouping in order to ease erasing private static List allRects = new ArrayList<>(); /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must move. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list of numbers private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data: link + move private Mover(int l, Move m) { link= l; move = new Move(m); } // Form 3, by structured data: mover private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //Rects that belong in the worms of the first generation //are visible. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //Color is defined as a random //mix of red, green and blue int rr,gg,bb; rr = r.nextInt(226); gg = r.nextInt(226); bb = r.nextInt(226); //The color is prepared Color c = Color.rgb(rr,gg,bb); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are ready to move, //otherwise they got hidden if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color, which is defined by three numbers. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated rectangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //List mover keeps movers List Mover = new ArrayList<>(); //The shape of each link List Rect = new ArrayList<>(); //Default initialization: //worms of the first generation are //ready to move. Others get hidden. private Worm(int gen ) { //Rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(gen)); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = r.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[r.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } }//End of constructor Worm(int gen) }//End of class Worm //General setting @Override public void start(Stage stage) { Scene scene = new Scene(p, xWin,yWin); stage.setScene(scene); stage.setTitle("Links move at random"); stage.show(); //Definition of possible moves moveDef(); //Text to draw genCount = new Text (""); genCount.setLayoutX(40);genCount.setLayoutY(40); p.getChildren().addAll(genCount); nGenerationsST.setCycleCount(1); //Many attempts are allowed for(int i = 0; i < nGenerations; i++) { voidOccupationMatrix();//Voidness gen = i; if (print2) System.out.println("\nGen = " + gen); //Generation number is drawn Timeline timeline = drawGen(gen); nGenerationsST.getChildren().addAll( timeline ); //Worms are posited at the start line startLine(gen); //Worms express their information to move SequentialTransition oneGenST = express(); nGenerationsST.getChildren().add(oneGenST); //Is some worm able to climb? assessFitness(); //Worms get hidden ParallelTransition hideST = hideST(); if (gen < nGenerations - 1 ) { //Clear Worms as list and hide drawn worms Worms.clear(); nGenerationsST.getChildren().add(hideST); } //Success? Integer genI = gen; if (bullseye) { //If climbing was successful, add a new link nLinks = nLinks+1; //List of generations with sucess record = record + " " + genI.toString(); } } //Film is played nGenerationsST.play(); System.out.println("Successful generations = " + record); } // To avoid overwriting of worms, // an occupation record is kept: // The screen is divided in cells 6x6. // At the beginning every cell is empty=false. // Occupancy is recorded in isOccupied[][], // which is a boolean matrix. // A boolean variable can be // true = occupied, else false= not occupied. private static void voidOccupationMatrix() { //System.out.println("occupationMatrix"); for(int i = 0; i < 600; i++) for(int j = 0; j < 300; j++) isOccupied[i][j]= false; } //Nine basic moves = coordinates where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } // All worms are posited at the same initial row // in vertical position. static public void startLine(int gen) { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm = w.new Worm(gen); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 30 + 150 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.Rect.get(link).setX(x); worm.Rect.get(link).setY(y); //Link is shown SequentialTransition show = showST(worm.Rect.get(link)); //Link is booked p.getChildren().add(worm.Rect.get(link)); allRects.add(worm.Rect.get(link)); //Show transition is booked nGenerationsST.getChildren().add(show); } //worm is located at position W in list Worms Worms.add(worm); } } //Draws the generation number private static Timeline drawGen(int gen) { Integer genI = gen; String message = "Generation = " + genI.toString(); //A JavaFX event committed to print a text is generated EventHandler printText = (EventHandler) (ActionEvent t ) -> { genCount.setText(message); }; //Presentation of printText must be //synchronized with the overall film so, //duration d is specified KeyFrame keyFrame = new KeyFrame(d, printText); Timeline timeline = new Timeline(); timeline.setCycleCount(1); //add the keyframe to the timeline timeline.getKeyFrames().add(keyFrame); return timeline; } //Is move m disruptive? //(A worm is and must remain as a whole, //nevertheless, some elasticity is allowed.) private static boolean isDisruptive(int m, Worm worm ) { // A move is disruptive if the target address // is farther than certain distance // from the neighboring links. boolean isDisruptive = false; int link; int x,y, x1,y1, x2,y2, x3,y3; double d1; double d2; //Read the link to be moved link = worm.Mover.get(m).link; //Read the address of the link; x = (int) worm.Rect.get(link).getX(); y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move = w.new Move(worm.Mover.get(m).move); //The target address is calculated x1 = x + width*move.x; y1 = y - width*move.y; //The addresses of the two neighboring links are read //The disruption is calculated //Case: intermediate link if ((0 < link) & (link < nLinks-1)) { x2 = (int) worm.Rect.get(link-1).getX(); y2 = (int) worm.Rect.get(link-1).getY(); d1 = pow( ( pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); x3 = (int) worm.Rect.get(link+1).getX(); y3 = (int) worm.Rect.get(link+1).getY(); d2 = pow( (pow( (x3 - x1),2) + pow((y3 - y1),2)),0.5); // Here we decide whether or not // a move is disruptive. //To augment elasticity, augment the threshold if ((d1 > 1.415*width) || (d2 > 1.415*width)) isDisruptive = true; } //First link if (link == 0) { x2 = (int) worm.Rect.get(1).getX(); y2 = (int) worm.Rect.get(1).getY(); d1 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if( d1 > 1.1*width) isDisruptive = true; } //Last link if( link == nLinks-1 ) { x2 = (int) worm.Rect.get(nLinks - 2).getX(); y2 = (int) worm.Rect.get(nLinks - 2).getY(); d2 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if ( d2 > 1.1*width ) isDisruptive = true; } return isDisruptive; } //Is the move m of worm W not disruptive? //If it is not, execute it. private static SequentialTransition exeIf( Worm worm, int m) { if (print1) System.out.println(" exeIf"); //Read the link to be moved int link = worm.Mover.get(m).link; //Read position int x = (int) worm.Rect.get(link).getX(); int y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move; move = worm.Mover.get(m).move; //Move is interpreted int byX = width* move.x; int byY = -height* move.y; //Target address is calculated: int x1 = x + byX; int y1 = y + byY; if (x1 < 0 ) x1 = 0; if (y1 < 0 ) y1 = 0; if (print1) System.out.println( " move = " + m + " link = " + link + " \n x = " + x + " y = " + y + " \nbyX = " + byX + " byY = " + byY); //Occupied cell int i = (int) x / width; int j = (int) y / height; //Target cell int k =(int) x1/width; int l = (int) y1/height; //Move is always executed SequentialTransition a = new SequentialTransition(); TranslateTransition translateTransition = new TranslateTransition(d, worm.Rect.get(link)); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); a.getChildren().add(translateTransition); //Is the move disruptive? boolean isMoveDisruptive = isDisruptive(m,worm); if (print2) { if (isMoveDisruptive) System.out.println("move is Disruptive"); else System.out.println("move is not Disruptive"); } //Disruptive moves are undone if (((isOccupied[k][l])) || ((isMoveDisruptive))) { byX = -byX; byY = -byY; } else //move is not disruptive -> it is not undone { byX = 0; byY = 0; worm.Rect.get(link).setX(x1); worm.Rect.get(link).setY(y1); isOccupied[i][j]= false; isOccupied[k][l]= true; } //Move is possibly undone TranslateTransition translateTransition2 = new TranslateTransition(d, worm.Rect.get(link)); //Jump is programmed translateTransition2.setByX(byX); translateTransition2.setByY(byY); //Number of repetitions translateTransition2.setCycleCount(1); a.getChildren().add(translateTransition2); return a; } //Worms express their information to move. public SequentialTransition express() { //Overall process SequentialTransition expressST = new SequentialTransition(); expressST.setCycleCount(1); //Worms advance nSteps steps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information is read and decoded for (int m = 0; m < nMovers; m++) { if (print1) System.out.println("nMovers = " + nMovers); //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); for (Worm worm: Worms) { //A translation of some link //is programmed for worm W //according to move m. //If it is not disruptive, //it is executed SequentialTransition tT = exeIf(worm,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked expressST.getChildren().add(oneStepST); } return expressST; } //A hidden rect gets shown private static SequentialTransition showST(Rectangle rect) { SequentialTransition s = new SequentialTransition(); Duration d2 = Duration.millis(1); //Rect is enlarged KeyValue keyValue3 = new KeyValue(rect.widthProperty(),width, Interpolator.LINEAR); KeyValue keyValue4 = new KeyValue(rect.heightProperty(),height, Interpolator.LINEAR); //KeyValues are inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue3,keyValue4 )); //Timeline is inserted into a transition s.getChildren().addAll(b); return s; } //Worms are hidden after their performance. private static ParallelTransition hideST() { ParallelTransition hidePT = new ParallelTransition(); hidePT.setCycleCount(1); Duration d2 = Duration.millis(1); //Hide all rects for(Rectangle rect: allRects) { //Rects are made unvisible KeyValue keyValue = new KeyValue(rect .visibleProperty(), false ,Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue)); hidePT.getChildren().add(b); } return hidePT; } // Every worm is assigned a fitness //The nearer to the top, the fitter. //If climbing has been significative, //the complexity of the game rises up one level: //a true bullseye is reported (to add //next a new link to all worms). private static void assessFitness() { int yOfTail; double yOfHead; bullseye = false; for(int W = 0; W < nWorms; W++) { // We get the y-coordinate of the tail yOfTail = (int) Worms.get(W).Rect.get(nLinks-1).getY(); yOfHead = Worms.get(W).Rect.get(0).getY(); //Climbing up is worth a point Fitness[W] = 100*(yWin - yOfTail); if(print1) System.out.println("Fitness of worm " + W + " = " + Fitness[W] + " head = " + yOfHead); //if (headPosition < initialRow - width*nLinks) if (yOfHead < initialRow - 2 * height) { bullseye = true; if (print1) System.out.println( "There was advance W = " + W ); } } } public static void main(String[] args) { Application.launch(args); } } //End of main class L61 WormsRandJFX8 ********** NEW PROGRAM ************* /* Program L64 PositiveSelection. An element is chosen for reproduction according to its fitness. Based on Program E153 whateverD */ package ejvolu12p; import java.util.Random; public class PositiveSelection { //Vector of fitnesses in arbitrary units private static final int Fitness[] = {3, 1, 6, 1, 4}; //Number of individuals private static final int nWorms = Fitness.length; //Cumulative distribution private static final int cumulate[] = new int[nWorms]; // Counters are in count private static final int count[] = new int[nWorms]; //Number of trials private static final int nTrials = 10000; //printing flag private static final boolean print = false; // Turn on of the random generator static Random r = new Random(); public static void main(String[] args) { //Initialization for (int i=0; i< nWorms; i++) count[i]=0; /* for (int i=0; i< nWorms; i++) Fitness[i]=r.nextInt(10); */ cumulate[0] = Fitness[0]; for (int i = 1; i < nWorms; i++) cumulate[i]= cumulate[i-1] + Fitness[i]; System.out.println( "i \tfitness cumulate "); for (int i = 0; i < nWorms; i++) System.out.println( i + "\t" + Fitness[i] + " \t " + cumulate[i]); //Maximal value int max = cumulate[nWorms-1]; //System.out.println("Generated numbers: "); for (int i = 0; i < nTrials;i++) { //A random integer less than max is generated //with a uniform distribution int n = r.nextInt(max); if (print) System.out.println("n = " + n); //The uniform distribution is transformed according //to the cumulate distribution if (n < cumulate[0]) { if (print) System.out.println( "chosen individual = 0 "); count[0]++; } for (int j=0; j < nWorms-1;j++) { int l = j+1; if ( ( cumulate[j] <= n) & (n < cumulate[l]) ) { if (print) System.out.println( "Chosen individual = " + l); count[l]++; } } } //Output System.out.println("\nEvents and their observed " + "and expected frequencies: "); int sum1 = 0; int sum2 = 0; for (int i=0; i Worms = new ArrayList<>(); //Helping files private static List WormsTwo = new ArrayList<>(); private static Worm[] OldWorms ; //Number of links of each worm private static int nLinks = 2; //Initial position of the head private static int initialRow = 280; //Generator of pseudo random numbers private static final Random rd = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 5; //Width of the worm = width of each link private static int width = 6; //Height of each link private static int height = 6; //Array with 9 possible moves, //9 possible directions of movement private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; private static final boolean print2 = false; private static final boolean printReproduction = true; //Text to be drawn private static Text genCount = new Text (""); //Two links cannot occupy the same place static boolean isOccupied[][] = new boolean[600][300]; //Is a worm capable of climbing the screen? private static int Fitness[] = new int[21]; //Was climbing good enough? private static boolean bullseye = false; //List of generations at which success was made private static String record = ""; //Measures of the screen private static int xWin = 1260; private static int yWin = 850; //Grouping of links in order to ease erasing private static List allRects = new ArrayList<>(); //The number of point mutations of the offspring private static int numbPointMutations = 5; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must be moved. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by numbers private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data: link + move private Mover(int l, Move m) { link= l; move = new Move(m); } // Form 3, by structured data: mover private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //A random color is synthesized private static Color randomColor() { //Color is defined as a random //mix of red, green and blue int r,g,b; r = rd.nextInt(226); g = rd.nextInt(226); b = rd.nextInt(226); //The color is prepared Color c = Color.rgb(r,g,b); return c; } //Rects that belong in the worms of the first generation //are visible. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //The color is prepared Color c = randomColor(); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are visible, otherwise they are not if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated rectangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //List mover keeps movers List Mover = new ArrayList<>(); //The shape of each link List Rect = new ArrayList<>(); //Default initialization: //worms of the first generation are //visible. Others not. private Worm() { //Visible rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(0)); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = rd.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } }//End of constructor Worm() //Worm W is read from the old population public Worm(int W) { numberOfLinks = nLinks; numberOfMovers = nMovers; //Fake initialization for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(1)); for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = rd.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } //Read true color for(int i = 0; i < OldWorms[W].numberOfLinks; i++) { Rect.get(i).setFill( OldWorms[W] .Rect.get(i).getFill()); } //Read true movers for(int i = 0; i < OldWorms[W].numberOfMovers; i++) Mover.set(i, OldWorms[W].Mover.get(i)); } }//End of class Worm //General setting @Override public void start(Stage stage) { Scene scene = new Scene(p, xWin,yWin); stage.setScene(scene); stage.setTitle("Evolution teaches worms " + "to climb the screen"); stage.show(); //Definition of possible moves moveDef(); //Text to draw genCount = new Text (""); genCount.setLayoutX(40);genCount.setLayoutY(40); p.getChildren().addAll(genCount); evolutionST.setCycleCount(1); //A sequential loop for(int i = 0; i < nGenerations; i++) { //Record of occupancy = void voidOccupationMatrix(); //Generation gen = i; if (print2) System.out.println("\nGen = " + gen); //Generation number is drawn Timeline timeline = drawGen(gen); evolutionST.getChildren().addAll( timeline ); //Worms are created and posited at the start line startLine(); //Worms express their information to move SequentialTransition oneGenST = oneGeneration(); evolutionST.getChildren().add(oneGenST); //Drawn worms get hidden ParallelTransition hideST = hideST(); if (gen < nGenerations - 1 ) { //Helping array Worm[] file1 = new Worm[50]; //Information is recorded in an array OldWorms = Worms.toArray(file1); //Destroy everything //for the sake of a new beginning Worms.clear(); WormsTwo.clear(); evolutionST.getChildren().add(hideST); } //Success? Integer genI = gen; if (bullseye) { //If climbing was successful, add a new link nLinks = nLinks+1; //List of generations with sucess record = record + " " + genI.toString(); } } //Movie is played evolutionST.play(); System.out.println("Successful gens = " + record); } // To avoid overwriting of worms, // an occupation record is kept: // The screen is divided in cells width x height. // At the beginning every cell is empty=false. // Occupancy is recorded in isOccupied[][], // which is a boolean matrix. // A boolean variable can be // true= occupied, else false= not occupied. private static void voidOccupationMatrix() { //System.out.println("occupationMatrix"); for(int i = 0; i < 600; i++) for(int j = 0; j < 300; j++) isOccupied[i][j]= false; } //Nine basic moves = irections where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } //All worms are posited at the same initial row //in vertical position. static public void startLine() { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm; if (gen == 0)//Create worm worm = w.new Worm(); else //Copy worm W from old generation worm = w.new Worm(W); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 140 + 140 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.Rect.get(link).setX(x); worm.Rect.get(link).setY(y); //Link is shown ParallelTransition show = showPT(worm.Rect.get(link)); //Link is booked p.getChildren().add(worm.Rect.get(link)); //Link is grouped allRects.add(worm.Rect.get(link)); //Show-transition is booked evolutionST.getChildren().add(show); } //worm is located at position W in lists Worms Worms.add(worm); if (print1) System.out.println("W = " + W + " nLinks = " + Worms.get(W).numberOfLinks ); } } //Draw the generation number private static Timeline drawGen(int gen) { Integer genI = gen; String message = "Generation = " + genI.toString(); //A JavaFX event committed to print a text is generated EventHandler printText = (EventHandler) (ActionEvent t ) -> { genCount.setText(message); }; //Presentation of printText must be //synchronized with the overall movie so, //duration d is specified KeyFrame keyFrame = new KeyFrame(d, printText); Timeline timeline = new Timeline(); timeline.setCycleCount(1); //add the keyframe to the timeline timeline.getKeyFrames().add(keyFrame); return timeline; } //Is move m disruptive for the worm? //(A worm is and must remain as a whole, //nevertheless, some elasticity is allowed.) private static boolean isDisruptive(int m, Worm worm ) { //A move is disruptive if the target address //is farther than certain distance //from the neighboring links. boolean isDisruptive = false; int link; int x,y, x1,y1, x2,y2, x3,y3; double d1; double d2; //Read the link to be moved link = worm.Mover.get(m).link; //Read the address of the link; x = (int) worm.Rect.get(link).getX(); y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move = w.new Move(worm.Mover.get(m).move); //The target address is calculated x1 = x + width*move.x; y1 = y - width*move.y; //The addresses of the two neighboring links are read //The disruption is calculated //Case: intermediate link if ((0 < link) & (link < nLinks-1)) { x2 = (int) worm.Rect.get(link-1).getX(); y2 = (int) worm.Rect.get(link-1).getY(); d1 = pow( ( pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); x3 = (int) worm.Rect.get(link+1).getX(); y3 = (int) worm.Rect.get(link+1).getY(); d2 = pow( (pow( (x3 - x1),2) + pow((y3 - y1),2)),0.5); // Here we decide whether or not // a move is disruptive. //To augment elasticity, augment the threshold if ((d1 > 1.415*width) || (d2 > 1.415*width)) isDisruptive = true; } //First link if (link == 0) { x2 = (int) worm.Rect.get(1).getX(); y2 = (int) worm.Rect.get(1).getY(); d1 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if( d1 > 1.1*width) isDisruptive = true; } //Last link if( link == nLinks-1 ) { x2 = (int) worm.Rect.get(nLinks - 2).getX(); y2 = (int) worm.Rect.get(nLinks - 2).getY(); d2 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if ( d2 > 1.1*width ) isDisruptive = true; } return isDisruptive; } //Execute move m for worm W. //If it is disruptive, undo it. private static SequentialTransition exeIf( Worm worm, int m) { if (print1) System.out.println(" exeIf"); //Reads the link to be moved int link = worm.Mover.get(m).link; //Reads position int x = (int) worm.Rect.get(link).getX(); int y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move; move = worm.Mover.get(m).move; //Move is interpreted int byX = width* move.x; int byY = -height* move.y; //Target address is calculated: int x1 = x + byX; int y1 = y + byY; if (x1 < 0 ) x1 = 0; if (y1 < 0 ) y1 = 0; if (print1) System.out.println( " move = " + m + " link = " + link + " \n x = " + x + " y = " + y + " \nbyX = " + byX + " byY = " + byY); //Occupied cell int i = (int) x / width; int j = (int) y / height; //Target cell int k =(int) x1/width; int l = (int) y1/height; //Move is always executed SequentialTransition a = new SequentialTransition(); TranslateTransition translateTransition = new TranslateTransition(d, worm.Rect.get(link)); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); a.getChildren().add(translateTransition); //Is the move disruptive? boolean isMoveDisruptive = isDisruptive(m,worm); if (print1) { if (isMoveDisruptive) System.out.println("move is Disruptive"); else System.out.println("move is not Disruptive"); } //Disruptive moves are undone if (((isOccupied[k][l])) || ((isMoveDisruptive))) { byX = -byX; byY = -byY; } else //move is not disruptive -> it is not undone { byX = 0; byY = 0; worm.Rect.get(link).setX(x1); worm.Rect.get(link).setY(y1); isOccupied[i][j]= false; isOccupied[k][l]= true; } //Move is possibly undone TranslateTransition translateTransition2 = new TranslateTransition(d, worm.Rect.get(link)); //Jump is programmed translateTransition2.setByX(byX); translateTransition2.setByY(byY); //Number of repetitions translateTransition2.setCycleCount(1); a.getChildren().add(translateTransition2); return a; } // Every worm is assigned a fitness //The nearer to the top, the fitter. //If climbing has been significative, //the complexity of the game rises up one level: //a true bullseye is reported (to add //next a new link to all worms). private static void assessFitness() { int yOfTail; double yOfHead; bullseye = false; for(int W = 0; W < nWorms; W++) { // We get the y-coordinate of the tail yOfTail = (int) Worms.get(W) .Rect.get(nLinks-1).getY(); yOfHead = Worms.get(W).Rect.get(0).getY(); //Fitness measures how much the head has been lifted Fitness[W] = (yWin - yOfTail); if(print1) System.out.println("Fitness of worm " + W + " = " + Fitness[W] + " head = " + yOfHead); //If worm W is good for climbing //its head must be high enough if (yOfHead < initialRow - 2 * height) { //Worms that climb are rewarded Fitness[W] = 100 * Fitness[W]; bullseye = true; if (printReproduction) System.out.println( "There was advance W = " + W ); } } } //Worms express their information to move. public SequentialTransition express() { //Overall process SequentialTransition expressST = new SequentialTransition(); expressST.setCycleCount(1); //Worms advance nSteps steps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information to move is read and decoded for (int m = 0; m < nMovers; m++) { if (print1) System.out.println("nMovers = " + nMovers); //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); //This is a parallel loop for a list for (Worm worm: Worms) { //A translation of some link //is programmed for worm W //according to move m. //If it is not disruptive, //it is executed SequentialTransition tT = exeIf(worm,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked expressST.getChildren().add(oneStepST); } return expressST; } //A hidden rect gets shown private static ParallelTransition showPT(Rectangle rect) { ParallelTransition s = new ParallelTransition(); Duration d2 = Duration.millis(1); //Rect is enlarged KeyValue keyValue3 = new KeyValue(rect.widthProperty(),width, Interpolator.LINEAR); KeyValue keyValue4 = new KeyValue(rect.heightProperty(),height, Interpolator.LINEAR); //KeyValues are inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue3,keyValue4 )); //Timeline is inserted into a transition s.getChildren().addAll(b); return s; } //Worms are hidden after their performance. private static ParallelTransition hideST() { ParallelTransition hidePT = new ParallelTransition(); hidePT.setCycleCount(1); Duration d2 = Duration.millis(1); //Hide all rects for(Rectangle rect: allRects) { //Rects are made unvisible KeyValue keyValue = new KeyValue(rect .visibleProperty(), false ,Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue)); hidePT.getChildren().add(b); } return hidePT; } //===================================== //=========Evolutionary part=========== //===================================== //One generation = expression + assessement //+ reproduction, recombination and mutation. public SequentialTransition oneGeneration() { SequentialTransition oneGenST = new SequentialTransition(); //Worms express their information to move SequentialTransition expressST = express(); oneGenST.getChildren().addAll(expressST); //Fitness is measured assessFitness(); //Reproduction is proportional to fitness reproduction(); //Population is replaced by a recombinat one recombination(); //Information to move suffers mutation mutation(); return oneGenST; } /* To generate a worm of the next generation, an individual is sampled at random from the old population and cloned with a probability that is proportional to its fitness. */ private static void reproduction() { if (printReproduction) System.out.println( "\nGeneration = " + gen); //Cumulative distribution Double cumulate[] = new Double[nWorms]; // Counters int count[] = new int[nWorms]; //Number of trials int nTrials = nWorms; //Initialization WormsTwo.clear(); WormsTwo.addAll(Worms); for (int i=0; i< nWorms; i++) count[i]=0; //Cumulative distribution cumulate[0] = (double) Fitness[0]; for (int i=1; i< nWorms; i++) cumulate[i]= cumulate[i-1] + Fitness[i]; //Report if (printReproduction) { System.out.println( "\ni \tfitness cumulate "); for (int i = 0; i < nWorms; i++) System.out.println( i + "\t" + Fitness[i] + " \t " + cumulate[i]); } //Maximal value double max = cumulate[nWorms-1]; //Counter of chosen worms int W = 0; //System.out.println("Generated numbers: "); for (int i = 0; i < nTrials; i++) { //A random integer less than max is generated //with a uniform distribution int n = rd.nextInt((int) max); //System.out.println("n = " + n); //Probability of cloning is made //in proportion to fitness. //Is worm 0 to be chosen? if (n < cumulate[0]) { /* if (printReproduction) System.out.println( "chosen individual = 0 "); */ WormsTwo.set(W, Worms.get(0)); count[0]++; W++; } //Is worm l to be chosen? for (int l = 1; l < nWorms; l++) { if ( ( cumulate[l-1] <= n) & (n < cumulate[l]) ) { /* if (printReproduction) System.out.println( "Chosen individual = " + l); */ count[l]++; WormsTwo.set(W, Worms.get(l)); W++; } } } if (printReproduction) { System.out.println("\nEvents and their observed " + "and expected frequencies: "); for (int i=0; i allRects = new ArrayList<>(); //The number of point mutations of the offspring private static int numbPointMutations = 5; //Gene amplification follows: //nSourceMovers is the number of different Movers //to be copied. private static int nSourceMovers = 2; //ncopies is the number of new copies //of each copied Mover in //the gene amplification method. private static int nCopies = 2; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must be moved. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with a list of two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list of numbers private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data: link + move private Mover(int l, Move m) { link= l; move = new Move(m); } // Form 3, by structured data: mover private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //A random color is synthesized private static Color randomColor() { //Color is defined as a random //mix of red, green and blue int r,g,b; r = rd.nextInt(226); g = rd.nextInt(226); b = rd.nextInt(226); //The color is prepared Color c = Color.rgb(r,g,b); return c; } //Rects that belong in the worms of the first generation //are visible. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //The color is prepared Color c = randomColor(); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are visible, otherwise they are not if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated rectangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //List mover keeps movers List Mover = new ArrayList<>(); //The shape of each link List Rect = new ArrayList<>(); //Default initialization: //worms of the first generation are //visible. Others not. private Worm() { //Visible rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(0)); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = rd.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } }//End of constructor Worm() //Worm W is read from the old population public Worm(int W) { numberOfLinks = nLinks; numberOfMovers = nMovers; //Fake initialization for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(1)); for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = rd.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } //Read true color for(int i = 0; i < OldWorms[W].numberOfLinks; i++) { Rect.get(i).setFill( OldWorms[W] .Rect.get(i).getFill()); } //Read true movers for(int i = 0; i < OldWorms[W].numberOfMovers; i++) Mover.set(i, OldWorms[W].Mover.get(i)); } }//End of class Worm //General setting @Override public void start(Stage stage) { //The scene Scene scene = new Scene(p, xWin,yWin); stage.setScene(scene); stage.setTitle("Evolution teaches worms " + "to climb the screen"); stage.show(); //Definition of possible moves moveDef(); //Text to draw genCount = new Text (""); genCount.setLayoutX(40);genCount.setLayoutY(40); p.getChildren().addAll(genCount); evolutionST.setCycleCount(1); //A sequential loop for(int i = 0; i < nGenerations; i++) { //The scene is void voidOccupationMatrix(); //Generation gen = i; if (print2) System.out.println("\nGen = " + gen); //Generation number is drawn Timeline timeline = drawGen(gen); evolutionST.getChildren().addAll( timeline ); //Worms are created and posited at the start line startLine(); //Worms express their information to move SequentialTransition oneGenST = oneGeneration(); evolutionST.getChildren().add(oneGenST); //Drawn worms get hidden ParallelTransition hideST = hideST(); if (gen < nGenerations - 1 ) { //Helping array Worm[] file1 = new Worm[50]; //Information is recorded in an array OldWorms = Worms.toArray(file1); //Destroy everything //for the sake of a new beginning Worms.clear(); WormsTwo.clear(); evolutionST.getChildren().add(hideST); } //Success? Integer genI = gen; if (bullseye) { //If climbing was successful, add a new link nLinks = nLinks+1; //List of generations with sucess record = record + " " + genI.toString(); } } //Film is played evolutionST.play(); System.out.println("Successful gens = " + record); } // To avoid overwriting of worms, // an occupation record is kept: // The screen is divided in cells width x hight. // At the beginning every cell is empty=false. // Occupancy is recorded in isOccupied[][], // which is a boolean matrix. // A boolean variable can be // true= occupied, else false= not occupied. private static void voidOccupationMatrix() { //System.out.println("occupationMatrix"); for(int i = 0; i < 600; i++) for(int j = 0; j < 300; j++) isOccupied[i][j]= false; } //Nine basic moves = irections where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } //All worms are posited at the same initial row //in vertical position. static public void startLine() { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm; if (gen == 0)//Create worm worm = w.new Worm(); else //Copy worm W from old generation worm = w.new Worm(W); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 140 + 140 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.Rect.get(link).setX(x); worm.Rect.get(link).setY(y); //Link is shown ParallelTransition show = showPT(worm.Rect.get(link)); //Link is booked p.getChildren().add(worm.Rect.get(link)); //Link is grouped allRects.add(worm.Rect.get(link)); //Show-transition is booked evolutionST.getChildren().add(show); } //worm is located at position W in lists Worms Worms.add(worm); if (print1) System.out.println("W = " + W + " nLinks = " + WormsTwo.get(W).numberOfLinks ); } } //Draw the generation number private static Timeline drawGen(int gen) { Integer genI = gen; String message = "Generation = " + genI.toString(); //A JavaFX event committed to print a text is generated EventHandler printText = (EventHandler) (ActionEvent t ) -> { genCount.setText(message); }; //Presentation of printText must be //synchronized with the overall film so, //duration d is specified KeyFrame keyFrame = new KeyFrame(d, printText); Timeline timeline = new Timeline(); timeline.setCycleCount(1); //add the keyframe to the timeline timeline.getKeyFrames().add(keyFrame); return timeline; } //Is move m disruptive for the worm? //(A worm is and must remain as a whole, //nevertheless, some elasticity is allowed.) private static boolean isDisruptive(int m, Worm worm ) { //A move is disruptive if the target address //is farther than certain distance //from the neighboring links. boolean isDisruptive = false; int link; int x,y, x1,y1, x2,y2, x3,y3; double d1; double d2; //Read the link to be moved link = worm.Mover.get(m).link; //Read the address of the link; x = (int) worm.Rect.get(link).getX(); y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move = w.new Move(worm.Mover.get(m).move); //The target address is calculated x1 = x + width*move.x; y1 = y - width*move.y; //The addresses of the two neighboring links are read //The disruption is calculated //Case: intermediate link if ((0 < link) & (link < nLinks-1)) { x2 = (int) worm.Rect.get(link-1).getX(); y2 = (int) worm.Rect.get(link-1).getY(); d1 = pow( ( pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); x3 = (int) worm.Rect.get(link+1).getX(); y3 = (int) worm.Rect.get(link+1).getY(); d2 = pow( (pow( (x3 - x1),2) + pow((y3 - y1),2)),0.5); // Here we decide whether or not // a move is disruptive. //To augment elasticity, augment the threshold if ((d1 > 1.415*width) || (d2 > 1.415*width)) isDisruptive = true; } //First link if (link == 0) { x2 = (int) worm.Rect.get(1).getX(); y2 = (int) worm.Rect.get(1).getY(); d1 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if( d1 > 1.1*width) isDisruptive = true; } //Last link if( link == nLinks-1 ) { x2 = (int) worm.Rect.get(nLinks - 2).getX(); y2 = (int) worm.Rect.get(nLinks - 2).getY(); d2 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if ( d2 > 1.1*width ) isDisruptive = true; } return isDisruptive; } //Execute move m for worm W. //If it is disruptive, undo it. private static SequentialTransition exeIf( Worm worm, int m) { if (print1) System.out.println(" exeIf"); //Reads the link to be moved int link = worm.Mover.get(m).link; //Reads position int x = (int) worm.Rect.get(link).getX(); int y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move; move = worm.Mover.get(m).move; //Move is interpreted int byX = width* move.x; int byY = -height* move.y; //Target address is calculated: int x1 = x + byX; int y1 = y + byY; if (x1 < 0 ) x1 = 0; if (y1 < 0 ) y1 = 0; if (print1) System.out.println( " move = " + m + " link = " + link + " \n x = " + x + " y = " + y + " \nbyX = " + byX + " byY = " + byY); //Occupied cell int i = (int) x / width; int j = (int) y / height; //Target cell int k =(int) x1/width; int l = (int) y1/height; //Move is always executed SequentialTransition a = new SequentialTransition(); TranslateTransition translateTransition = new TranslateTransition(d, worm.Rect.get(link)); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); a.getChildren().add(translateTransition); //Is the move disruptive? boolean isMoveDisruptive = isDisruptive(m,worm); if (print1) { if (isMoveDisruptive) System.out.println("move is Disruptive"); else System.out.println("move is not Disruptive"); } //Disruptive moves are undone if (((isOccupied[k][l])) || ((isMoveDisruptive))) { byX = -byX; byY = -byY; } else //move is not disruptive -> it is not undone { byX = 0; byY = 0; worm.Rect.get(link).setX(x1); worm.Rect.get(link).setY(y1); isOccupied[i][j]= false; isOccupied[k][l]= true; } //Move is possibly undone TranslateTransition translateTransition2 = new TranslateTransition(d, worm.Rect.get(link)); //Jump is programmed translateTransition2.setByX(byX); translateTransition2.setByY(byY); //Number of repetitions translateTransition2.setCycleCount(1); a.getChildren().add(translateTransition2); return a; } // Every worm is assigned a fitness //The nearer to the top, the fitter. //If climbing has been significative, //the complexity of the game rises up one level: //a true bullseye is reported (to add //next a new link to all worms). private static void assessFitness() { int yOfTail; double yOfHead; bullseye = false; for(int W = 0; W < nWorms; W++) { // We get the y-coordinate of the tail yOfTail = (int) Worms.get(W) .Rect.get(nLinks-1).getY(); yOfHead = Worms.get(W).Rect.get(0).getY(); //Fitness measures how much the head has been lifted Fitness[W] = (yWin - yOfTail); if(print1) System.out.println("Fitness of worm " + W + " = " + Fitness[W] + " head = " + yOfHead); //If worm W is good for climbing //its head must be high enough if (yOfHead < initialRow - 2 * height) { //Worms that climb are rewarded Fitness[W] = 100 * Fitness[W]; bullseye = true; if (printReproduction) System.out.println( "There was advance W = " + W ); } } } //Worms express their information to move. public SequentialTransition express() { //Overall process SequentialTransition expressST = new SequentialTransition(); expressST.setCycleCount(1); //Worms advance nSteps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information to move is read and decoded for (int m = 0; m < nMovers; m++) { if (print1) System.out.println("nMovers = " + nMovers); //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); //This is a parallel loop for a list for (Worm worm: Worms) { //A translation of some link //is programmed for worm W //according to move m. //If it is not disruptive, //it is executed SequentialTransition tT = exeIf(worm,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked expressST.getChildren().add(oneStepST); } return expressST; } //A hidden rect gets shown private static ParallelTransition showPT(Rectangle rect) { ParallelTransition s = new ParallelTransition(); Duration d2 = Duration.millis(1); //Rect is enlarged KeyValue keyValue3 = new KeyValue(rect.widthProperty(),width, Interpolator.LINEAR); KeyValue keyValue4 = new KeyValue(rect.heightProperty(),height, Interpolator.LINEAR); //KeyValues are inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue3,keyValue4 )); //Timeline is inserted into a transition s.getChildren().addAll(b); return s; } //Worms are hidden after their performance. private static ParallelTransition hideST() { ParallelTransition hidePT = new ParallelTransition(); hidePT.setCycleCount(1); Duration d2 = Duration.millis(1); //Hide all rects for(Rectangle rect: allRects) { //Rects are made unvisible KeyValue keyValue = new KeyValue(rect .visibleProperty(), false ,Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue)); hidePT.getChildren().add(b); } return hidePT; } //===================================== //=========Evolutionary part=========== //===================================== //One generation = expression + assessement //+ reproduction, recombination and mutation. public SequentialTransition oneGeneration() { SequentialTransition oneGenST = new SequentialTransition(); //Worms express their information to move SequentialTransition expressST = express(); oneGenST.getChildren().addAll(expressST); //Fitness is measured assessFitness(); //Reproduction is proportional to fitness reproduction(); //Population is replaced by a recombinat one recombination(); //Information to move suffers mutation mutation(); return oneGenST; } /* To generate a worm of the next generation, an individual is sampled at random from the old population and cloned with a probability that is proportional to its fitness. */ private static void reproduction() { if (printReproduction) System.out.println( "\nGeneration = " + gen); //Cumulative distribution Double cumulate[] = new Double[nWorms]; // Counters int count[] = new int[nWorms]; //Number of trials int nTrials = nWorms; //Initialization WormsTwo.clear(); WormsTwo.addAll(Worms); for (int i=0; i< nWorms; i++) count[i]=0; //Cumulative distribution cumulate[0] = (double) Fitness[0]; for (int i=1; i< nWorms; i++) cumulate[i]= cumulate[i-1] + Fitness[i]; //Report if (printReproduction) { System.out.println( "\ni \tfitness cumulate "); for (int i = 0; i < nWorms; i++) System.out.println( i + "\t" + Fitness[i] + " \t " + cumulate[i]); } //Maximal value double max = cumulate[nWorms-1]; //Counter of chosen worms int W = 0; //System.out.println("Generated numbers: "); for (int i = 0; i < nTrials; i++) { //A random integer less than max is generated //with a uniform distribution int n = rd.nextInt((int) max); //System.out.println("n = " + n); //Probability of cloning is made //in proportion to fitness. //Is worm 0 to be chosen? if (n < cumulate[0]) { /* if (printReproduction) System.out.println( "chosen individual = 0 "); */ WormsTwo.set(W, Worms.get(0)); count[0]++; W++; } //Is worm l to be chosen? for (int l = 1; l < nWorms; l++) { if ( ( cumulate[l-1] <= n) & (n < cumulate[l]) ) { /* if (printReproduction) System.out.println( "Chosen individual = " + l); */ count[l]++; WormsTwo.set(W, Worms.get(l)); W++; } } } if (printReproduction) { System.out.println("\nEvents and their observed " + "and expected frequencies: "); for (int i=0; i Worms = new ArrayList<>(); //Helping files private static List WormsTwo = new ArrayList<>(); private static Worm[] OldWorms ; //Every worm leaves a fossil private static List Fossils = new ArrayList<>(); //Number of fossils private static int nFossils = 0; //Number of sampled fossils private static int nSampledFossils = 4; //Number of links of each worm private static int nLinks = 2; //Initial position over the screen of the head private static int initialRow = 280; //Generator of pseudo random numbers private static final Random rd = new Random(); //Each worm has nMovers movers, //instructions to move. private static int nMovers = 5; //Width of the worm = width of each link private static int width = 6; //Height of each link private static int height = 6; //Array with 9 possible moves, //9 possible directions of movement private static Move vectMoves[ ] = new Move[9]; private static final boolean print1 = false; private static final boolean print2 = false; private static final boolean printReproduction = true; //Text to be drawn private static Text genCount = new Text (""); //Two links cannot occupy the same place static boolean isOccupied[][] = new boolean[600][300]; //Is a worm capable of climbing the screen? private static int Fitness[] = new int[21]; //Was climbing good enough? private static boolean bullseye = false; //List of generations at which success was made private static String record = ""; //Measures of the screen private static int xWin = 1260; private static int yWin = 850; //Grouping of links in order to ease erasing private static List allRects = new ArrayList<>(); private static List lastRects = new ArrayList<>(); //The number of point mutations of the offspring private static int numbPointMutations = 5; //Gene amplification follows: //nSourceMovers is the number of different Movers //to be copied. private static int nSourceMovers = 2; //ncopies is the number of new copies //of each copied Mover in // the gene amplification method. private static int nCopies = 2; /* Definition of inner classes. * The Move class: A Move says in which direction a link of the worm must be moved. */ private class Move { int x; int y; //Default initialization Move() { x= 0; y= 0; } // Initialize with a list of two coordinates Move(int a, int b) { x= a; y= b; } // Copy a move Move(Move move) { x= move.x; y= move.y; } }//End of class Move // Definition of the class Mover: // A Mover keeps two types of information: // a) the link of the worm to be moved and // b) the direction or move to be chosen. // private class Mover { int link ; Move move; // Movers can acquired information // in three ways, they are overloaded. // Form 1: by a list of numbers private Mover(int l, int mx, int my) { link= l; move.x = mx; move.y = my; } // Form 2, by structured data: link + move private Mover(int l, Move m) { link= l; move = new Move(m); } // Form 3, by structured data: mover private Mover(Mover mover) { link= mover.link; move = new Move(mover.move); } }//End of class Mover //A random color is synthesized private static Color randomColor() { //Color is defined as a random //mix of red, green and blue int r,g,b; r = rd.nextInt(226); g = rd.nextInt(226); b = rd.nextInt(226); //The color is prepared Color c = Color.rgb(r,g,b); return c; } //Rects that belong in the worms of the first generation //are visible. Others are hidden. private static Rectangle createRectangle(int gen) { //Upper left corner at (0,0) Rectangle rect = new Rectangle(0,0,width,height); //The color is prepared Color c = randomColor(); //The rect is painted rect.setFill(c); //Rects of the first generation (gen = 0) //are visible, otherwise they are not if (gen > 0) { rect.setHeight(0); rect.setWidth(0); } return rect; } /* Here we define the class worm. A worm is composite: it has links. Each link has a rectangular shape and its own color. The vector Mover[ ] keeps the information on how to move its links: which link and in which order (in the order that they appear in the vector Mover[]), and in which direction. Each worm keeps record of the actual position of each one of its links, in the associated rectangle. */ private class Worm { //Number of links int numberOfLinks = nLinks; //Number of movers = instructions to move int numberOfMovers = nLinks; //List mover keeps movers List Mover = new ArrayList<>(); //The shape of each link List Rect = new ArrayList<>(); //Default initialization: //worms of the first generation are //visible. Others not. private Worm() { //Visible rects are created. // A color is assigned to each link // but different than white for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(0)); //Instructions to move at random for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = rd.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } }//End of constructor Worm() //Constructor from worm W of the old generation. private Worm(int W) { numberOfLinks = nLinks; numberOfMovers = nMovers; //Fake initialization for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(1)); for(int m = 0; m < nMovers; m++) { //Select at random which link to move: int l = rd.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } //Read true color for(int i = 0; i < OldWorms[W].numberOfLinks; i++) { Rect.get(i).setFill( OldWorms[W] .Rect.get(i).getFill()); } //Read true movers for(int m = 0; m < OldWorms[W].numberOfMovers; m++) Mover.set(m, OldWorms[W].Mover.get(m)); } //Constructor from a fossil. private Worm(Fossil fossil) { numberOfLinks = fossil.numberOfLinks; numberOfMovers = fossil.numberOfMovers; //Rects are initialized, 1 = unvisible for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(1)); //Symbolic initalization of movers for(int m = 0; m < numberOfMovers; m++) { //Select at random which link to move: int l = rd.nextInt(nLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } //Get true movers for(int m = 0; m < numberOfMovers; m++) Mover.set(m, fossil.Mover.get(m)); } }//End of class Worm //Inner class Fossil. //Fossils keep relevant information about worms private class Fossil { int numberOfLinks; int numberOfMovers; //The shape of each link List Rect = new ArrayList<>(); //List mover keeps movers List Mover = new ArrayList<>(); public Fossil(Worm worm) { numberOfLinks = worm.numberOfLinks; numberOfMovers = worm.numberOfMovers; //Rects are created for(int i = 0; i < numberOfLinks; i++) Rect.add(createRectangle(1)); //Symbolic initialziation of movers for(int m = 0; m < numberOfMovers; m++) { //Select at random which link to move: int l = rd.nextInt(numberOfLinks) ; //Select at random which direction to move on Move move = w.new Move (vectMoves[rd.nextInt(9)]); //Memorization Mover.add(w.new Mover(l,move)); } //True initialization of movers for(int m = 0; m < numberOfMovers; m++) Mover.set(m, worm.Mover.get(m)); } }//End of Fossil //General setting @Override public void start(Stage stage) { //The scene Scene scene = new Scene(p, xWin,yWin); stage.setScene(scene); stage.setTitle("Evolution teaches worms " + "to climb the screen"); stage.show(); //Definition of possible moves moveDef(); //Text to draw genCount = new Text (""); genCount.setLayoutX(40);genCount.setLayoutY(40); p.getChildren().addAll(genCount); evolutionST.setCycleCount(1); //Evolution for nGenerations for(int i = 0; i < nGenerations; i++) { //The scene is void voidOccupationMatrix(); //Generation gen = i; if (print2) System.out.println("\nGen = " + gen); //Generation number is drawn Timeline timeline = drawGen(gen); evolutionST.getChildren().addAll( timeline ); //Worms are created and posited at the start line startLine(); //Worms express their information to move SequentialTransition oneGenST = oneGeneration(); evolutionST.getChildren().add(oneGenST); //Drawn worms get hidden ParallelTransition hideST = hideST(); evolutionST.getChildren().add(hideST); //Helping array Worm[] file1 = new Worm[50]; //Information is recorded in an array OldWorms = Worms.toArray(file1); //Every worm leaves a fossil fossilization(); //Destroy everything //for the sake of a new beginning Worms.clear(); WormsTwo.clear(); //Success? Integer genI = gen; if (bullseye) { //If climbing was successful, add a new link nLinks = nLinks+1; //List of generations with sucess record = record + " " + genI.toString(); } } //EvolutionST is booked allST.getChildren().add(evolutionST); System.out.println("Successful gens = " + record); //Fossil study SequentialTransition fsST = fossilSampling(); allST.getChildren().add(fsST); //Film is played allST.play(); } // To avoid overwriting of worms, // an occupation record is kept: // The screen is divided in cells width x hight. // At the beginning every cell is empty=false. // Occupancy is recorded in isOccupied[][], // which is a boolean matrix. // A boolean variable can be // true= occupied, else false= not occupied. private static void voidOccupationMatrix() { //System.out.println("occupationMatrix"); for(int i = 0; i < 600; i++) for(int j = 0; j < 300; j++) isOccupied[i][j]= false; } //Nine basic moves = irections where to move in static private void moveDef() { final Move move0 = w.new Move(0,1); vectMoves[0] = move0 ; final Move move1 = w.new Move(1,1); vectMoves[1] = move1 ; final Move move2 = w.new Move(1,0); vectMoves[2] = move2 ; final Move move3 = w.new Move(1,-1); vectMoves[3] = move3 ; final Move move4 = w.new Move(0,-1); vectMoves[4] = move4 ; final Move move5 = w.new Move(-1,-1); vectMoves[5] = move5 ; final Move move6 = w.new Move(-1,0); vectMoves[6] = move6 ; final Move move7 = w.new Move(-1,1); vectMoves[7] = move7 ; final Move move8 = w.new Move(0,0); vectMoves[8] = move8 ; } //All worms are posited at the same initial row //in vertical position. static public void startLine() { for (int W = 0; W < nWorms; W++) { int x,y; //Auxiliary worm Worm worm; if (gen == 0)//Create worm worm = w.new Worm(); else //Copy worm W from old generation worm = w.new Worm(W); //Each link is positioned for(int link = 0; link < nLinks; link++) { //Horizontal position x = 140 + 140 * W; //Vertical position y = initialRow + height*link; //Position is updated worm.Rect.get(link).setX(x); worm.Rect.get(link).setY(y); //Link is shown ParallelTransition show = showPT(worm.Rect.get(link)); //Link is booked p.getChildren().add(worm.Rect.get(link)); //Link is grouped allRects.add(worm.Rect.get(link)); //Show-transition is booked evolutionST.getChildren().add(show); } //worm is located at position W in lists Worms Worms.add(worm); if (print1) System.out.println("W = " + W + " nLinks = " + WormsTwo.get(W).numberOfLinks ); } } //Draw the generation number private static Timeline drawGen(int gen) { Integer genI = gen; String message = "Generation = " + genI.toString(); //A JavaFX event committed to print a text is generated EventHandler printText = (EventHandler) (ActionEvent t ) -> { genCount.setText(message); }; //Presentation of printText must be //synchronized with the overall film so, //duration d is specified KeyFrame keyFrame = new KeyFrame(d, printText); Timeline timeline = new Timeline(); timeline.setCycleCount(1); //add the keyframe to the timeline timeline.getKeyFrames().add(keyFrame); return timeline; } //Is move m disruptive for the worm? //(A worm is and must remain as a whole, //nevertheless, some elasticity is allowed.) private static boolean isDisruptive(int m, Worm worm ) { //A move is disruptive if the target address //is farther than certain distance //from the neighboring links. boolean isDisruptive = false; int link; int x,y, x1,y1, x2,y2, x3,y3; double d1; double d2; //Read the link to be moved link = worm.Mover.get(m).link; //Read the address of the link; x = (int) worm.Rect.get(link).getX(); y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move = w.new Move(worm.Mover.get(m).move); //The target address is calculated x1 = x + width*move.x; y1 = y - width*move.y; //The addresses of the two neighboring links are read //The disruption is calculated //Case: intermediate link if ((0 < link) & (link < nLinks-1)) { x2 = (int) worm.Rect.get(link-1).getX(); y2 = (int) worm.Rect.get(link-1).getY(); d1 = pow( ( pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); x3 = (int) worm.Rect.get(link+1).getX(); y3 = (int) worm.Rect.get(link+1).getY(); d2 = pow( (pow( (x3 - x1),2) + pow((y3 - y1),2)),0.5); // Here we decide whether or not // a move is disruptive. //To augment elasticity, augment the threshold if ((d1 > 1.415*width) || (d2 > 1.415*width)) isDisruptive = true; } //First link if (link == 0) { x2 = (int) worm.Rect.get(1).getX(); y2 = (int) worm.Rect.get(1).getY(); d1 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if( d1 > 1.1*width) isDisruptive = true; } //Last link if( link == nLinks-1 ) { x2 = (int) worm.Rect.get(nLinks - 2).getX(); y2 = (int) worm.Rect.get(nLinks - 2).getY(); d2 = pow( (pow( (x2 - x1),2) + pow((y2 - y1),2)),0.5); if ( d2 > 1.1*width ) isDisruptive = true; } return isDisruptive; } //Execute move m for worm W. //If it is disruptive, undo it. private static SequentialTransition exeIf( Worm worm, int m) { if (print1) System.out.println(" exeIf"); //Reads the link to be moved int link = worm.Mover.get(m).link; //Reads position int x = (int) worm.Rect.get(link).getX(); int y = (int) worm.Rect.get(link).getY(); //The move to be done is read Move move; move = worm.Mover.get(m).move; //Move is interpreted int byX = width* move.x; int byY = -height* move.y; //Target address is calculated: int x1 = x + byX; int y1 = y + byY; if (x1 < 0 ) x1 = 0; if (y1 < 0 ) y1 = 0; if (print1) System.out.println( " move = " + m + " link = " + link + " \n x = " + x + " y = " + y + " \nbyX = " + byX + " byY = " + byY); //Occupied cell int i = (int) x / width; int j = (int) y / height; //Target cell int k =(int) x1/width; int l = (int) y1/height; //Move is always executed SequentialTransition moveRect = new SequentialTransition(); TranslateTransition translateTransition = new TranslateTransition(d, worm.Rect.get(link)); //Jump is executed translateTransition.setByX(byX); translateTransition.setByY(byY); //Number of repetitions translateTransition.setCycleCount(1); moveRect.getChildren().add(translateTransition); //Is the move disruptive? boolean isMoveDisruptive = isDisruptive(m,worm); if (print1) { if (isMoveDisruptive) System.out.println("move is Disruptive"); else System.out.println("move is not Disruptive"); } //Disruptive moves are undone if (((isOccupied[k][l])) || ((isMoveDisruptive))) { byX = -byX; byY = -byY; } else //move is not disruptive -> it is not undone { byX = 0; byY = 0; worm.Rect.get(link).setX(x1); worm.Rect.get(link).setY(y1); isOccupied[i][j]= false; isOccupied[k][l]= true; } //Move is possibly undone TranslateTransition translateTransition2 = new TranslateTransition(d, worm.Rect.get(link)); //Jump is programmed translateTransition2.setByX(byX); translateTransition2.setByY(byY); //Number of repetitions translateTransition2.setCycleCount(1); moveRect.getChildren().add(translateTransition2); return moveRect; } // Every worm is assigned a fitness //The nearer to the top, the fitter. //If climbing has been significative, //the complexity of the game rises up one level: //a true bullseye is reported (to add //next a new link to all worms). private static void assessFitness() { int yOfTail; double yOfHead; bullseye = false; for(int W = 0; W < nWorms; W++) { // We get the y-coordinate of the tail yOfTail = (int) Worms.get(W) .Rect.get(nLinks-1).getY(); yOfHead = Worms.get(W).Rect.get(0).getY(); //Fitness measures how much the head has been lifted Fitness[W] = (yWin - yOfTail); if(print1) System.out.println("Fitness of worm " + W + " = " + Fitness[W] + " head = " + yOfHead); //If worm W is good for climbing //its head must be high enough if (yOfHead < initialRow - 2 * height) { //Worms that climb are rewarded Fitness[W] = 100 * Fitness[W]; bullseye = true; if (printReproduction) System.out.println( "There was advance W = " + W ); } } } //Worms express their information to move. public SequentialTransition express() { //Overall process SequentialTransition expressST = new SequentialTransition(); expressST.setCycleCount(1); //Worms advance nSteps for (int i = 0; i < nSteps; i++) { //Worms advance one step: //To move all links, each worm must execute //instructions to move SequentialTransition oneStepST = new SequentialTransition(); oneStepST.setCycleCount(1); //Information to move is read and decoded for (int m = 0; m < nMovers; m++) { if (print1) System.out.println("nMovers = " + nMovers); //All worms execute move m ParallelTransition moveMPT = new ParallelTransition(); moveMPT.setCycleCount(1); //This is a parallel loop for a list for (Worm worm: Worms) { //A translation of some link //is programmed for worm W //according to move m. //If it is not disruptive, //it is executed SequentialTransition tT = exeIf(worm,m); tT.setCycleCount(1); //Translation is booked moveMPT.getChildren().add(tT); } //The ensamble of translations is booked oneStepST.getChildren().add(moveMPT); } //The movement of worms in one step is booked expressST.getChildren().add(oneStepST); } return expressST; } //A hidden rect gets shown private static ParallelTransition showPT(Rectangle rect) { ParallelTransition s = new ParallelTransition(); Duration d2 = Duration.millis(1); //Rect is enlarged KeyValue keyValue3 = new KeyValue(rect.widthProperty(),width, Interpolator.LINEAR); KeyValue keyValue4 = new KeyValue(rect.heightProperty(),height, Interpolator.LINEAR); //KeyValues are inserted into a timeline Timeline b = new Timeline( new KeyFrame(d2,keyValue3,keyValue4 )); //Timeline is inserted into a transition s.getChildren().addAll(b); return s; } //Worms are hidden after their performance. private static ParallelTransition hideST() { ParallelTransition hidePT = new ParallelTransition(); hidePT.setCycleCount(1); Duration d2 = Duration.millis(1); //Hide all rects for(Rectangle rect: allRects) { //Rects are made unvisible KeyValue keyValue = new KeyValue(rect .visibleProperty(), false ,Interpolator.LINEAR); Timeline b = new Timeline( new KeyFrame(d2,keyValue)); hidePT.getChildren().add(b); } return hidePT; } //===================================== //=========Evolutionary part=========== //===================================== //One generation = expression + assessement //+ reproduction, recombination and mutation. public SequentialTransition oneGeneration() { SequentialTransition oneGenST = new SequentialTransition(); //Worms express their information to move SequentialTransition expressST = express(); oneGenST.getChildren().addAll(expressST); //Fitness is measured assessFitness(); //Reproduction is proportional to fitness reproduction(); //Population is replaced by a recombinat one recombination(); //Information to move suffers mutation mutation(); return oneGenST; } /* To generate a worm of the next generation, an individual is sampled at random from the old population and cloned with a probability that is proportional to its fitness. */ private static void reproduction() { if (printReproduction) System.out.println( "\nGeneration = " + gen); //Cumulative distribution Double cumulate[] = new Double[nWorms]; // Counters int count[] = new int[nWorms]; //Number of trials int nTrials = nWorms; //Initialization WormsTwo.clear(); WormsTwo.addAll(Worms); for (int i=0; i< nWorms; i++) count[i]=0; //Cumulative distribution cumulate[0] = (double) Fitness[0]; for (int i=1; i< nWorms; i++) cumulate[i]= cumulate[i-1] + Fitness[i]; //Report if (printReproduction) { System.out.println( "\ni \tfitness cumulate "); for (int i = 0; i < nWorms; i++) System.out.println( i + "\t" + Fitness[i] + " \t " + cumulate[i]); } //Maximal value double max = cumulate[nWorms-1]; //Counter of chosen worms int W = 0; //System.out.println("Generated numbers: "); for (int i = 0; i < nTrials; i++) { //A random integer less than max is generated //with a uniform distribution int n = rd.nextInt((int) max); //System.out.println("n = " + n); //Probability of cloning is made //in proportion to fitness. //Is worm 0 to be chosen? if (n < cumulate[0]) { /* if (printReproduction) System.out.println( "chosen individual = 0 "); */ WormsTwo.set(W, Worms.get(0)); count[0]++; W++; } //Is worm l to be chosen? for (int l = 1; l < nWorms; l++) { if ( ( cumulate[l-1] <= n) & (n < cumulate[l]) ) { /* if (printReproduction) System.out.println( "Chosen individual = " + l); */ count[l]++; WormsTwo.set(W, Worms.get(l)); W++; } } } if (printReproduction) { System.out.println("\nEvents and their observed " + "and expected frequencies: "); for (int i=0; i