0
\$\begingroup\$

Currently working on a Genetic Algorithm in Java where I'm using a JPanel to draw my population and my target. The technical code works (generate population, mutate, crossover, get genes, etc...) but I'm stuck with the code to draw all my population.

Currently each individuals have x, y, x velocity ,y velocity and an array of directions ["up", "up", "down", ...] as attributes.

Tried to do:

// Draw the destination square in Red, individuals in Black
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.red);
    g2.fill(new Rectangle2D.Double(destinationX(),destinationY(), 10,10));
    g2.setColor(Color.black);
    // Draw each Individual in black
    for (Individual ind : Population)
      // read their genes one by one and repaint everytime to see the square move
}

But it's extremely messy, ugly and hard to debug.

How should I go from here? Should all individuals be JPanels that I'll add to the main JPanel? Do I need to use Threads? Any suggestion would be appreciated.

\$\endgroup\$
  • \$\begingroup\$ This question doesn't seem to be GameDev specific - it should probably be posted on stack overflow instead \$\endgroup\$ – UnholySheep Jan 23 '17 at 9:43
1
\$\begingroup\$

If you are finding your code hard to read or debug you either need to abstract or encapsulate more. Each individual should be responsible for drawing itself, but does not need to be its own JFrame. Simply pass the graphics to each individual. Try splitting your code up like so:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
  
    drawDestiation(g2);
  
    drawIndividuals(g2);
}

private void drawIndividuals(Graphics2D g){
  for(Individual ind : Population){
      ind.drawSelf(g);
    }
  
}

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.