import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; class Baloune{ protected int x,y,rayon; // coordonnées du centre private int r2,diametre; Baloune(int x,int y, int rayon){ // création en s'assurant que le rayon est positif // sinon une instance "vide" est créée if (rayon>0) { this.x=x; this.y=y; changeRayon(rayon); } } private void changeRayon(int rayon){ this.rayon=rayon; diametre = 2*rayon; r2=rayon*rayon; } public String toString(){ return "Baloune("+x+","+y+","+rayon+")"; } public boolean gonfler(int r){ // augmente le rayon si la nouvelle valeur reste positive // important car r peut être négatif int r1 = rayon+r; if (r1>0){ // on garantit que le nouveau rayon reste positif changeRayon(r1); return true; } else return false; // indique l'échec du gonflage } public boolean degonfler(int r){ return gonfler(-r); } public void deplacer(int dx, int dy){ x=x+dx; y=y+dy; } public void afficher(Graphics g,String mess){ // dessine la baloune avec un message au centre g.drawOval(x-rayon,y-rayon,diametre,diametre); g.drawString(mess,x,y); } private int sqr(int x){ return x*x;} public boolean contient(int px, int py){ // vérifie si le point px@py est dans la baloune return sqr(px-x)+sqr(py-y) <= r2; } public boolean contient(Baloune b){ // vérifie si b est entièrement contenu dans la baloune return sqr(b.x-x)+sqr(b.y-y)<=sqr(rayon-b.rayon); } public boolean touche(Baloune b){ // vérifie si b touche partiellement la baloune return sqr(b.x-x)+sqr(b.y-y)<=sqr(rayon+b.rayon); } public static void main(String[] args){ Baloune b1=new Baloune(10,10,5); System.out.println("b1:"+b1); b1.gonfler(4); System.out.println("b1.gonfler(4):"+b1); b1.deplacer(20,50); System.out.println("b1.deplacer(20,50):"+b1); b1.degonfler(3); System.out.println("b1.degonfler(3):"+b1); System.out.println("b1.contient(25,62):"+b1.contient(25,62)); System.out.println("b1.contient(30,30):"+b1.contient(30,30)); Baloune b2=new Baloune(50,40,25); System.out.println("b2:"+b2); System.out.println("b1.touche(b2)"+b1.touche(b2)); System.out.println("b1.contient(b2)"+b1.contient(b2)); b2.gonfler(20); System.out.println("b2.gonfler(20):"+b2); System.out.println("b1.touche(b2)"+b1.touche(b2)); System.out.println("b1.contient(b2)"+b1.contient(b2)); // pour l'affichage dans une fenêtre JFrame f = new JFrame(); f.getContentPane().add(new BalounesPanel(b1,b2)); f.setLocation(100,100); f.setSize(400,300); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private static class BalounesPanel extends JPanel{ Baloune b1,b2; BalounesPanel(Baloune b1,Baloune b2){ this.b1=b1; this.b2=b2; } public void paintComponent(Graphics g) { super.paintComponent(g); b1.afficher(g, "b1"); b2.afficher(g, "b2"); } } }