Wie kann ich das grafisch darstellen anstatt in der Konsole?

bob651

Aktives Mitglied
Hi, ich habe hier ein Code für das Spiel "Türme von Hanoi". Sollten manche kennen.
Mein Code zeigt die Spielzüge in der Konsole an. Wie mache ich es so, dass man es grafisch darstellen kann, z.B. mit Rechtecken whatever.

Hier mein Code:
Code:
public class TuermeVonHanoi {
static void ziehe_scheibe(int nummer, String von, String nach) {
System.out.println("Scheibe " + nummer + " wird von " + von +
" nach " + nach + " verschoben ");
}
static void hanoi(int N, String platz1, String hilfsplatz, String platz2)
{
if (N == 1) {
ziehe_scheibe(N, platz1, platz2);
} else {
hanoi(N-1, platz1, platz2, hilfsplatz);
ziehe_scheibe(N, platz1, platz2);
hanoi(N-1, hilfsplatz, platz1, platz2);
}
}
public static void main(String[] args) {
hanoi(4, "A", "B", "C");
}
}

Wie soll ich vorgehen. Pseudocode etc wäre gut :) ty
 

Robat

Top Contributor
Pseudocode werde ich dir hier nicht schreiben - bisschen Arbeit musst du schon noch selbst machen :p

Hier ein Paar Stichworte:
-JFrame Klasse, --> Um ein Fenster zuerzeugen
-JPanel Klasse --> Um ein Panel zuerzeugen, worauf du zeichnen kannst
-paintComponent(Graphics g) - Methode --> in der Methode wird gezeichnet. Bsp: g.drawRect(50, 50, 100, 100);
-Rectangle Klasse --> um (falls nötig) deine eigenen Rectangles zu erstellen.
 

bob651

Aktives Mitglied
also wie man fenster etc erstellt weiß ich, aber nicht, wie ich mein Code oben integrieren soll. if==1{ ziehe scheibe} z.b, soll ich das aufzeichnen lassen?
 

Robat

Top Contributor
Du machst dir bswp. ein Array mit N Rectangles. Anstatt (siehe deine main-Methode) dir ausgeben zu lassen dass Scheibe n auf Turm n gelegt wird schreibst du dir eine Methode in der du dir das Element des Arrays suchst was verschoben wurde, änderst die x (und falls nötig y) Kordinate ab, lässt das Bild neu zeichnen und baust am besten noch einen kleinen Timer ein, damit du das ganze als User schön mitverfolgen kannst.
 

bob651

Aktives Mitglied
OK, also ich bin schon etwas weiter gekommen, aber so ganz richtig klappts doch nicht. Ich mache es mit verschieden großen Rechtecken(insgesamt 3 bei mir).
Ich weiß nicht ganz, wie ich die paint-Methode implementieren soll.
Ich habe es mit g.drawRect probiert, aber es passiert nichts weiter. Kannste mir da weiterhelfen?

Hier komplett alles und sry für die Störung :D
Java:
import java.io.*;
import java.util.*;
import java.awt.*;

public class hanoi {

  public static void ziehe_scheibe(MyFrame f,Pole von, Pole nach) {
    int hs = von.onPole.size();
    int ht = nach.onPole.size();
    int hy = -25*(ht-hs+1);
    int hx = (nach.xPos - von.xPos);

    String d = von.scheibenehmen();
    nach.scheibelegen(d);
    f.moveDisk(d,hx,hy);
  }


  public static void hanoi(MyFrame f,int n, Pole platz1, Pole platz2, Pole hilfsplatz) {
  
      if ( n==1 )
      ziehe_scheibe(f,platz1,platz2);
    else
    { hanoi(f,n-1,platz1,hilfsplatz,platz2);
      ziehe_scheibe(f,platz1,platz2);
      hanoi(f,n-1,hilfsplatz,platz2,platz1);
    }
  }

  public static int xSize(String d) {
    if ( d == "klein" ) return 30;
    if ( d == "mittel" ) return 40;
    else return 50;
  }

  public static void main(String args[]) {

    Pole p1 = new Pole("a",60);
    Pole p2 = new Pole("b",180);
    Pole p3 = new Pole("c",300);

    p1.scheibelegen("groß");
    p1.scheibelegen("mittel");
    p1.scheibelegen("klein");
  
    Rectangle r1 = new Rectangle(p1.xPos-50,50,100,20);  
    Rectangle r2 = new Rectangle(p1.xPos-40,25,80,20);  
    Rectangle r3 = new Rectangle(p1.xPos-30,0,60,20);
  
    MyFrame fff = new MyFrame(r1,r2,r3);
    fff.setSize(800,600);
    fff.setVisible(true); 
  
    hanoi(fff,3,p1,p3,p2);
  }

}

Java:
// Frame-Klasse zur Anzeige des Zustandes
class MyFrame extends Frame {
  
  public Rectangle s1, s2, s3;


  public MyFrame(Rectangle a, Rectangle b, Rectangle c) {
    s1 = a; s2 = b; s3 = c;
  
  }

  public void paint(Graphics g) {
 

  }

  public Rectangle xRect(String d) {
    if ( d == "klein" ) return s3;
    if ( d == "mittel" ) return s2;
    else return s1;
  }

  public void moveDisk(String name,int dx,int dy)
  { xRect(name).translate(dx,dy);
    repaint();
    try
    { System.in.read();System.in.read(); }
    catch (Exception e) {}
  }
}

Java:
// Pole-Klasse: Repräsentation eines Stabes       
class Pole {
  public String label;
  public Vector onPole;
  public int xPos;

  public Pole(String s, int i) {
    onPole=new Vector();
    label = s; xPos = i;
  }

  public void scheibelegen(String d) {
    this.onPole.addElement(d);
  }

  public String scheibenehmen() {
    Object lastEl = this.onPole.lastElement();
    String lastElStr = lastEl.toString();
    this.onPole.removeElement(lastEl);
    return lastElStr;
  }
}
 
Zuletzt bearbeitet von einem Moderator:

bob651

Aktives Mitglied
Hi, also ich habe hier eine Möglichkeit wie man es lösen könnte (Programmiert von ROBAT!:) ). Ich habe mal versucht die Rechtecke verschieden groß und farbig zu machen, aber hat nicht wirklich geklappt, aber naja. Vielleicht hilft es ja euch weiter :))



Code:
 public HanoiFrameMethode() {
      
        hanoiPanel = new HanoiPanelZeichnen('a', 'b', 'c', 6);
      
        frame = new JFrame("HanoiTurme");
        frame.setSize(600, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(hanoiPanel);
        frame.setVisible(true);
       
       
        TuermeVonHanoi(6, 'a', 'b', 'c');
    }
  
  
   
   
    /**
     * Bewegt n Scheiben von Turm a nach Turm c und benutzt als
     * Zwischenspeicher Turm b.
     */
    private void TuermeVonHanoi (int n, char platz1, char hilfsplatz, char platz2)
    {
    if (n == 1) {
     
                   hanoiPanel.moveRect(platz1, platz2);
        }
    else {
            TuermeVonHanoi(n-1,platz1, platz2, hilfsplatz);
            TuermeVonHanoi(1,platz1, hilfsplatz, platz2);
            TuermeVonHanoi(n-1, hilfsplatz, platz1, platz2);
    }
    }

Code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JPanel;
/**
* klasse für Panel
* @author Ömer
*
*/
public class HanoiPanelZeichnen extends JPanel
{

    private final static String TITLE = "HanoiPanel";
    private final ArrayList<Rectangle> arrListLeft;
    private final ArrayList<Rectangle> arrListMid;
    private final ArrayList<Rectangle> arrListRight;
  
    private char a;
    private char b;
    private char c;
  
    private int len; //anzahl der rechtecke

    private int arrListLeftX = 20;
    private int arrListMidX = 130;
    private int arrListRightX = 240;
  
    private final static int bottomY = 180;
  
    ///////////////////////////////////////
    // Constructor
    ///////////////////////////////////////
     public HanoiPanelZeichnen(char a, char b, char c, int len)
    { 
        this.a = a;
        this.b = b;
        this.c = c;
        this.len = len;
      
        arrListLeft = new ArrayList<>();
        arrListRight = new ArrayList<>();
        arrListMid = new ArrayList<>();
      
        for(int i = 0; i < len; i++)
        {
            arrListLeft.add(new Rectangle(arrListLeftX, bottomY-(20*(i+1)), 100, 10));
        }
    }
    

    private void moveSpecificRect(ArrayList<Rectangle> from, ArrayList<Rectangle>to, int posX, int deltaX)
    {
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(HanoiPanelZeichnen.class.getName()).log(Level.SEVERE, null, ex);
        }
        Rectangle r = new Rectangle(posX+deltaX, bottomY-(to.size()+1)*20, 100, 10);
        from.remove(from.size()-1);

       try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(HanoiPanelZeichnen.class.getName()).log(Level.SEVERE, null, ex);
        }

        to.add(r);
        repaint();
    }

     public void moveRect(char from, char to)
     {
        switch (from) {
            case 'a':
                if(to == 'b')
                {
                    moveSpecificRect(arrListLeft, arrListMid, arrListMidX, 100);
                } else if(to == 'c')
                {
                    moveSpecificRect(arrListLeft, arrListRight, arrListRightX, 200);
                }  break;
            case 'b':
                if(to == 'a')
                {
                    moveSpecificRect(arrListMid, arrListLeft, arrListLeftX, 0);
                }
                else if(to == 'c')
                {
                    moveSpecificRect(arrListMid, arrListRight, arrListRightX, 200);
                }  break;
            default:
                if(to == 'b')
                {
                    moveSpecificRect(arrListRight, arrListMid, arrListMidX, 100);
                }
                else if(to == 'a')
                {
                    moveSpecificRect(arrListRight, arrListLeft, arrListLeftX, 0);
                }  break;
        }
     }
     /**
      * alle Arrays werden ducrhlaufen und Elemente werden gezeichnet.
      */
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
      
        Graphics2D g2d = (Graphics2D) g;
      
        g2d.drawString(String.valueOf(a), arrListLeftX+45, 200);
      
        for(Rectangle r : arrListLeft)
        {
            g2d.draw(r);
        }
      
        g2d.drawString(String.valueOf(b), arrListMidX+145, 200);
      
        for(Rectangle r: arrListMid)
        {
            g2d.draw(r);
        }
      
        g2d.drawString(String.valueOf(c), arrListRightX+245, 200);
      
        for(Rectangle r: arrListRight)
        {
            g2d.draw(r);
        }
      
      
    }
}
 

Oben