Code Verstehen

Status
Nicht offen für weitere Antworten.

aggro600

Mitglied
Hey Leute
bin im Internet auf diesen Code gestoßen.
Es ist ein Java PacMan Spiel
Ich würde gerne den Code versuchen zu verstehn nur bin ich leider noch ein Anfänger.
Könntet ihr ein paar Lines erläutern oder Kommentieren oder so?
Muss ja nicht alles aufeinmal sein :toll:
Board.java:

Code:
package pacman;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;


public class Board extends JPanel implements ActionListener {

    Dimension d;
    Font smallfont = new Font("Helvetica", Font.BOLD, 14);

    FontMetrics fmsmall, fmlarge;
    Image ii;
    Color dotcolor = new Color(192, 192, 0);
    Color mazecolor;

    boolean ingame = false;
    boolean dying = false;

    final int blocksize = 24;
    final int nrofblocks = 15;
    final int scrsize = nrofblocks * blocksize;
    final int pacanimdelay = 2;
    final int pacmananimcount = 4;
    final int maxghosts = 12;
    final int pacmanspeed = 6;

    int pacanimcount = pacanimdelay;
    int pacanimdir = 1;
    int pacmananimpos = 0;
    int nrofghosts = 6;
    int pacsleft, score;
    int deathcounter;
    int[] dx, dy;
    int[] ghostx, ghosty, ghostdx, ghostdy, ghostspeed;

    Image ghost;
    Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down;
    Image pacman3up, pacman3down, pacman3left, pacman3right;
    Image pacman4up, pacman4down, pacman4left, pacman4right;

    int pacmanx, pacmany, pacmandx, pacmandy;
    int reqdx, reqdy, viewdx, viewdy;

    final short leveldata[] =
    { 19, 26, 26, 26, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 22,
      21, 0,  0,  0,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20,
      21, 0,  0,  0,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 
      21, 0,  0,  0,  17, 16, 16, 24, 16, 16, 16, 16, 16, 16, 20, 
      17, 18, 18, 18, 16, 16, 20, 0,  17, 16, 16, 16, 16, 16, 20,
      17, 16, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 16, 24, 20, 
      25, 16, 16, 16, 24, 24, 28, 0,  25, 24, 24, 16, 20, 0,  21, 
      1,  17, 16, 20, 0,  0,  0,  0,  0,  0,  0,  17, 20, 0,  21,
      1,  17, 16, 16, 18, 18, 22, 0,  19, 18, 18, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 20, 0,  21, 
      1,  17, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 0,  21,
      1,  25, 24, 24, 24, 24, 24, 24, 24, 24, 16, 16, 16, 18, 20,
      9,  8,  8,  8,  8,  8,  8,  8,  8,  8,  25, 24, 24, 24, 28 };

    final int validspeeds[] = { 1, 2, 3, 4, 6, 8 };
    final int maxspeed = 6;

    int currentspeed = 3;
    short[] screendata;
    Timer timer;


    public Board() {

        GetImages();

        addKeyListener(new TAdapter());

        screendata = new short[nrofblocks * nrofblocks];
        mazecolor = new Color(5, 100, 5);
        setFocusable(true);

        d = new Dimension(400, 400);

        setBackground(Color.black);
        setDoubleBuffered(true);

        ghostx = new int[maxghosts];
        ghostdx = new int[maxghosts];
        ghosty = new int[maxghosts];
        ghostdy = new int[maxghosts];
        ghostspeed = new int[maxghosts];
        dx = new int[4];
        dy = new int[4];
        timer = new Timer(40, this);
        timer.start();
    }

    public void addNotify() {
        super.addNotify();
        GameInit();
    }


    public void DoAnim() {
        pacanimcount--;
        if (pacanimcount <= 0) {
            pacanimcount = pacanimdelay;
            pacmananimpos = pacmananimpos + pacanimdir;
            if (pacmananimpos == (pacmananimcount - 1) || pacmananimpos == 0)
                pacanimdir = -pacanimdir;
        }
    }


    public void PlayGame(Graphics2D g2d) {
        if (dying) {
            Death();
        } else {
            MovePacMan();
            DrawPacMan(g2d);
            MoveGhosts(g2d);
            CheckMaze();
        }
    }


    public void ShowIntroScreen(Graphics2D g2d) {

        g2d.setColor(new Color(0, 32, 48));
        g2d.fillRect(50, scrsize / 2 - 30, scrsize - 100, 50);
        g2d.setColor(Color.white);
        g2d.drawRect(50, scrsize / 2 - 30, scrsize - 100, 50);

        String s = "Press s to start.";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = this.getFontMetrics(small);

        g2d.setColor(Color.white);
        g2d.setFont(small);
        g2d.drawString(s, (scrsize - metr.stringWidth(s)) / 2, scrsize / 2);
    }


    public void DrawScore(Graphics2D g) {
        int i;
        String s;

        g.setFont(smallfont);
        g.setColor(new Color(96, 128, 255));
        s = "Score: " + score;
        g.drawString(s, scrsize / 2 + 96, scrsize + 16);
        for (i = 0; i < pacsleft; i++) {
            g.drawImage(pacman3left, i * 28 + 8, scrsize + 1, this);
        }
    }


    public void CheckMaze() {
        short i = 0;
        boolean finished = true;

        while (i < nrofblocks * nrofblocks && finished) {
            if ((screendata[i] < 48) != 0)
                finished = false;
            i++;
        }

        if (finished) {
            score += 50;

            if (nrofghosts < maxghosts)
                nrofghosts++;
            if (currentspeed < maxspeed)
                currentspeed++;
            LevelInit();
        }
    }

    public void Death() {

        pacsleft--;
        if (pacsleft == 0)
            ingame = false;
        LevelContinue();
    }


    public void moveGhosts(Graphics2D g2d) {
        short i;
        int pos;
        int count;

        for (i = 0; i < nrofghosts; i++) {
            if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) {
                pos =
 ghostx[i] / blocksize + nrofblocks * (int)(ghosty[i] / blocksize);

                count = 0;
                if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) {
                    dx[count] = -1;
                    dy[count] = 0;
                    count++;
                }
                if ((screendata[pos] & 2) == 0 && ghostdy[i] != 1) {
                    dx[count] = 0;
                    dy[count] = -1;
                    count++;
                }
                if ((screendata[pos] & 4) == 0 && ghostdx[i] != -1) {
                    dx[count] = 1;
                    dy[count] = 0;
                    count++;
                }
                if ((screendata[pos] & 8) == 0 && ghostdy[i] != -1) {
                    dx[count] = 0;
                    dy[count] = 1;
                    count++;
                }
 
                if (count == 0) {
                    if ((screendata[pos] & 15) == 15) {
                        ghostdx[i] = 0;
                        ghostdy[i] = 0;
                    } else {
                        ghostdx[i] = -ghostdx[i];
                        ghostdy[i] = -ghostdy[i];
                    }
                } else {
                    count = (int)(Math.random() * count);
                    if (count > 3)
                        count = 3;
                    ghostdx[i] = dx[count];
                    ghostdy[i] = dy[count];
                }

            }
            ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]);
            ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]);
            drawGhost(g2d, ghostx[i] + 1, ghosty[i] + 1);

            if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12) &&
                pacmany > (ghosty[i] - 12) && pacmany < (ghosty[i] + 12) &&
                ingame) {

                dying = true;
                deathcounter = 64;

            }
        }
    }


    public void DrawGhost(Graphics2D g2d, int x, int y) {
        g2d.drawImage(ghost, x, y, this);
    }


    public void MovePacMan() {
        int pos;
        short ch;

        if (reqdx == -pacmandx && reqdy == -pacmandy) {
            pacmandx = reqdx;
            pacmandy = reqdy;
            viewdx = pacmandx;
            viewdy = pacmandy;
        }
        if (pacmanx % blocksize == 0 && pacmany % blocksize == 0) {
            pos =
 pacmanx / blocksize + nrofblocks * (int)(pacmany / blocksize);
            ch = screendata[pos];

            if ((ch & 16) != 0) {
                screendata[pos] = (short)(ch & 15);
                score++;
            }

            if (reqdx != 0 || reqdy != 0) {
                if (!((reqdx == -1 && reqdy == 0 && (ch & 1) != 0) ||
                      (reqdx == 1 && reqdy == 0 && (ch & 4) != 0) ||
                      (reqdx == 0 && reqdy == -1 && (ch & 2) != 0) ||
                      (reqdx == 0 && reqdy == 1 && (ch & 8) != 0))) {
                    pacmandx = reqdx;
                    pacmandy = reqdy;
                    viewdx = pacmandx;
                    viewdy = pacmandy;
                }
            }

            // Check for standstill
            if ((pacmandx == -1 && pacmandy == 0 && (ch & 1) != 0) ||
                (pacmandx == 1 && pacmandy == 0 && (ch & 4) != 0) ||
                (pacmandx == 0 && pacmandy == -1 && (ch & 2) != 0) ||
                (pacmandx == 0 && pacmandy == 1 && (ch & 8) != 0)) {
                pacmandx = 0;
                pacmandy = 0;
            }
        }
        pacmanx = pacmanx + pacmanspeed * pacmandx;
        pacmany = pacmany + pacmanspeed * pacmandy;
    }


    public void DrawPacMan(Graphics2D g2d) {
        if (viewdx == -1)
            DrawPacManLeft(g2d);
        else if (viewdx == 1)
            DrawPacManRight(g2d);
        else if (viewdy == -1)
            DrawPacManUp(g2d);
        else
            DrawPacManDown(g2d);
    }

    public void DrawPacManUp(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2up, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3up, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4up, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }


    public void DrawPacManDown(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2down, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3down, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4down, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }


    public void DrawPacManLeft(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2left, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3left, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4left, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }


    public void DrawPacManRight(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2right, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3right, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4right, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }


    public void DrawMaze(Graphics2D g2d) {
        short i = 0;
        int x, y;

        for (y = 0; y < scrsize; y += blocksize) {
            for (x = 0; x < scrsize; x += blocksize) {
                g2d.setColor(mazecolor);
                g2d.setStroke(new BasicStroke(2));

                if ((screendata[i] & 1) != 0) // draws left
                {
                    g2d.drawLine(x, y, x, y + blocksize - 1);
                }
                if ((screendata[i] & 2) != 0) // draws top
                {
                    g2d.drawLine(x, y, x + blocksize - 1, y);
                }
                if ((screendata[i] & 4) != 0) // draws right
                {
                    g2d.drawLine(x + blocksize - 1, y, x + blocksize - 1,
                                 y + blocksize - 1);
                }
                if ((screendata[i] & 8) != 0) // draws bottom
                {
                    g2d.drawLine(x, y + blocksize - 1, x + blocksize - 1,
                                 y + blocksize - 1);
                }
                if ((screendata[i] & 16) != 0) // draws point
                {
                    g2d.setColor(dotcolor);
                    g2d.fillRect(x + 11, y + 11, 2, 2);
                }
                i++;
            }
        }
    }

    public void GameInit() {
        pacsleft = 3;
        score = 0;
        LevelInit();
        nrofghosts = 6;
        currentspeed = 3;
    }


    public void LevelInit() {
        int i;
        for (i = 0; i < nrofblocks * nrofblocks; i++)
            screendata[i] = leveldata[i];

        LevelContinue();
    }


    public void LevelContinue() {
        short i;
        int dx = 1;
        int random;

        for (i = 0; i < nrofghosts; i++) {
            ghosty[i] = 4 * blocksize;
            ghostx[i] = 4 * blocksize;
            ghostdy[i] = 0;
            ghostdx[i] = dx;
            dx = -dx;
            random = (int)(Math.random() * (currentspeed + 1));
            if (random > currentspeed)
                random = currentspeed;
            ghostspeed[i] = validspeeds[random];
        }

        pacmanx = 7 * blocksize;
        pacmany = 11 * blocksize;
        pacmandx = 0;
        pacmandy = 0;
        reqdx = 0;
        reqdy = 0;
        viewdx = -1;
        viewdy = 0;
        dying = false;
    }

    public void GetImages()
    {

      ghost = new ImageIcon(Board.class.getResource("../pacpix/ghost.png")).getImage();
      pacman1 = new ImageIcon(Board.class.getResource("../pacpix/pacman.png")).getImage();
      pacman2up = new ImageIcon(Board.class.getResource("../pacpix/up1.png")).getImage();
      pacman3up = new ImageIcon(Board.class.getResource("../pacpix/up2.png")).getImage();
      pacman4up = new ImageIcon(Board.class.getResource("../pacpix/up3.png")).getImage();
      pacman2down = new ImageIcon(Board.class.getResource("../pacpix/down1.png")).getImage();
      pacman3down = new ImageIcon(Board.class.getResource("../pacpix/down2.png")).getImage(); 
      pacman4down = new ImageIcon(Board.class.getResource("../pacpix/down3.png")).getImage();
      pacman2left = new ImageIcon(Board.class.getResource("../pacpix/left1.png")).getImage();
      pacman3left = new ImageIcon(Board.class.getResource("../pacpix/left2.png")).getImage();
      pacman4left = new ImageIcon(Board.class.getResource("../pacpix/left3.png")).getImage();
      pacman2right = new ImageIcon(Board.class.getResource("../pacpix/right1.png")).getImage();
      pacman3right = new ImageIcon(Board.class.getResource("../pacpix/right2.png")).getImage();
      pacman4right = new ImageIcon(Board.class.getResource("../pacpix/right3.png")).getImage();

    }

    public void paint(Graphics g)
    {
      super.paint(g);

      Graphics2D g2d = (Graphics2D) g;

      g2d.setColor(Color.black);
      g2d.fillRect(0, 0, d.width, d.height);

      DrawMaze(g2d);
      DrawScore(g2d);
      DoAnim();
      if (ingame)
        PlayGame(g2d);
      else
        ShowIntroScreen(g2d);

      g.drawImage(ii, 5, 5, this);
      Toolkit.getDefaultToolkit().sync();
      g.dispose();
    }

    class TAdapter extends KeyAdapter {
        public void keyPressed(KeyEvent e) {

          int key = e.getKeyCode();

          if (ingame)
          {
            if (key == KeyEvent.VK_LEFT)
            {
              reqdx=-1;
              reqdy=0;
            }
            else if (key == KeyEvent.VK_RIGHT)
            {
              reqdx=1;
              reqdy=0;
            }
            else if (key == KeyEvent.VK_UP)
            {
              reqdx=0;
              reqdy=-1;
            }
            else if (key == KeyEvent.VK_DOWN)
            {
              reqdx=0;
              reqdy=1;
            }
            else if (key == KeyEvent.VK_ESCAPE && timer.isRunning())
            {
              ingame=false;
            }
            else if (key == KeyEvent.VK_PAUSE) {
                if (timer.isRunning())
                    timer.stop();
                else timer.start();
            }
          }
          else
          {
            if (key == 's' || key == 'S')
          {
              ingame=true;
              GameInit();
            }
          }
      }

          public void keyReleased(KeyEvent e) {
              int key = e.getKeyCode();

              if (key == Event.LEFT || key == Event.RIGHT || 
                 key == Event.UP ||  key == Event.DOWN)
              {
                reqdx=0;
                reqdy=0;
              }
          }
      }

    public void actionPerformed(ActionEvent e) {
        repaint();  
    }
}

Und hier die Main Methode (PacMan.java)

Code:
package packman;

import javax.swing.JFrame;

import pacman.Board;


public class PacMan extends JFrame
{

  public PacMan()
  {
    add(new Board());
    setTitle("Pacman");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(380, 420);
    setLocationRelativeTo(null);
    setVisible(true);
  }

  public static void main(String[] args) {
      new PacMan();
  }
}
 
M

MiDniGG

Gast
Hey Leute
bin im Internet auf diesen Code gestoßen.
Es ist ein Java PacMan Spiel
Ich würde gerne den Code versuchen zu verstehn nur bin ich leider noch ein Anfänger.
Könntet ihr ein paar Lines erläutern oder Kommentieren oder so?
Muss ja nicht alles aufeinmal sein :toll:

Solltest vielleicht sagen was Dir so alles unklar ist... Wenn Du noch gar nichts mit Java gemacht hast würde ich Dir empfehlen wenigstens mal die Grundlagen zu lernen. Und dann mal den Code durchschaun. Was dann noch unklar ist kann Dir dann immer noch jemand erläuter. :)
 

ARadauer

Top Contributor
Methoden schreibt man klein...


public static void main(String[] args).. das ist der Programmeinstieg...
 

aggro600

Mitglied
also son paar sachen kann ich ja schon
keylistener und so standart sachen.
vllt ne erklärung wie der code arbeitet
dann kann ich mir daraus ja selbst schlüsse ziehen
 

Quaxli

Top Contributor
Diesen Code solltest Du nicht verstehn wollen - ehrlich. ;(;(;(

Hauptkomponente eines jeden Spiels ist ein sog. GameLoop. Das ist eine Schleife in der periodisch Dinge ausgeführt werden, wie z. B. Abfrage der Eingabe-Geräte (Keyboard, Maus), Bewegen aller Objekte (Pacman, Geister), Überprüfung von Interaktion (Kollision mit Punkten, Geistern, Wänden) und das Neuzeichnen der Anzeige, so daß die Änderungen sichtbar werden und noch das eine oder andere mehr - je nachdem, was man so vorhat.
Üblicherweise macht man das in einem eigenen Thread (Multithreading wäre also auch ein Thema für Dich).

In dem Code oben wurde das seeeeehr unkonventionell gelöst, um es mal so auszudrücken.
Es gibt einen Swing-Timer, der alle 40 ms (ein zu großer Wert in meinen Augen) einen ActionEvent abfeuert.
Dieser ActionLister ruft ein repaint() des JPanel auf. In der paint-Methode (bei Swing überschreibt man eigentlich paint-Component) ist dann die Logik implementiert die eigentlich in den GameLoop gehört. :eek:
Ich vermute, daß dieses Programm nicht sehr toll läuft. :lol:
- der Intervall 40 ms ist eigentlich zu groß
- repaint() ist nur eine Aufforderung irgendwann mal neu zu zeichnen - wenn man dann noch die sonstige Logik in paint() versteckelt hat, kann es hier zu Stockungen kommen
- etc.

Da ist noch mehr Gewurstel, das ich meinen Augen nicht mehr antun wollte. :autsch:

Wenn Du Dich für Spieleprogrammierung interessierst, guck mal in meine Signatur, da ist ein Link zu einem Tutorial, wo erschöpfend erklärt ist, wie man ein Spiel aufbauen könnte.
 
S

SlaterB

Gast
bitte maximal einmal am Tag derartige Erinnerungen schreiben,

und die Chance ist nunmal gering, erst Java lernen, dann Programme verstehen
 

Spin

Top Contributor
Java:
import javax.swing.JFrame; // importieren von Package

import pacman.Board;


public class Pacman extends JFrame // Klasse und abgeleitet
{

  public Pacman() // Standart Konstruktor
  {
    add(new Board()); // hinzufügen von Board ( alles was da so in der klasse steht)
    setTitle("Pacman"); // Title setzen ( Also spiel bennen)
    
    /**
     * The default behavior is to simply hide the JFrame when the user closes the window. 
     * To change the default behavior, you invoke the method setDefaultCloseOperation(int).
     */
    
    setDefaultCloseOperation(EXIT_ON_CLOSE); // damit darfst du das Frame wieder schließen
    
    setSize(380, 420); // damit setzt die Größe des Frames
    
    /**
     * Sets the location of the window relative to the specified component.
     * If the component is not currently showing, or c is null, the window is centered on the screen.
     */
    setLocationRelativeTo(null); // siehe oben , Fenster wird in die Mitte deines Bildschirms platziert
    setVisible(true); // naja die Methode lässt erst das Frame anzeigen
  }

  public static void main(String[] args) {
      new Pacman(); // damit rufen wir die Klasse Pacman auf // inkl. Konstruktor usw....das heißt spiel funktioniert.
  }
}



Das war der erste Teil :)

Mir macht es Spass anderen zu helfen :) Und besonders bei Java, denn ich habe auch noch viel dazu zu lernen ! Will später noch RUby lernen XD.


Ich hoffe einfach mal , dass meine Kommentare richtig sind. Viele von euch werden, es detalierter beschreiben können, doch reicht es vorerst.


hey aggro, schick doch bitte mal alles von @pacman. Würde es gerne ma compilieren wollen.

Mir fehlt eine Klasse. gruß spin
 

aggro600

Mitglied
scheiß auf den aten code
der is leichter muss den nur kommentieren

Code:
import java.awt.*;				//importieren von Packeten
import java.applet.Applet;

public class Breakout extends Applet implements Runnable
{
  Dimension	d;
  Font 		largefont = new Font("Helvetica", Font.BOLD, 24);
  Font		smallfont = new Font("Helvetica", Font.BOLD, 14);

  FontMetrics	fmsmall, fmlarge;  
  Graphics	goff;
  Image		ii;
  Thread	thethread;

  boolean	ingame=false;
								//Variablen
  int		player1score;		//Score Player 1	
  int		ballx,bally;		//Ball Position	
  int		batpos;				//Balken Position
  int		batdpos=0;			//Balken Position
  int		balldx=0, balldy=0;	//Ball Kooridnaten
  int		dxval;
  int		ballsleft;
  int		count;				//Zähler
  boolean	showtitle=true;		//Title anzeigen
  boolean[]	showbrick;			//Steine
  int		bricksperline;		

  final int	borderwidth=5;		//Rahmenbreite
  final int	batwidth=50;		//Balkenreite
  final int	ballsize=5;			//Ballgröße
  final int	batheight=5;		//Balkenmhöhe
  final int	scoreheight=20;		//Scorehöhe
  final int	screendelay=300;	//Appletgröße
  final int	brickwidth=15;		//Steinbreite
  final int brickheight=8;		//Steinhöhe
  final int	brickspace=2;		//Stein Abstand
  final int	backcol=0x102040;	//Background Farbe
  final int	numlines=4;			//Steine auf der y Koordinate
  final int     startline=32;	//Startlinie

  public String getAppletInfo()
  {
    return("Breakout - by Nils");
  }

  public void init()
  {
    Graphics g;
    d = size();
    setBackground(new Color(backcol));
    bricksperline=(d.width-2*borderwidth)/(brickwidth+brickspace);
    d.width=bricksperline*(brickwidth+brickspace)+(2*borderwidth);
    g=getGraphics();
    g.setFont(smallfont);
    fmsmall = g.getFontMetrics();
    g.setFont(largefont);
    fmlarge = g.getFontMetrics();

    showbrick=new boolean[bricksperline*numlines];
    GameInit();
  }

  public void GameInit()
  {
    batpos=(d.width-batwidth)/2;
    ballx=(d.width-ballsize)/2;
    bally=(d.height-ballsize-scoreheight-2*borderwidth);
    player1score=0;
    ballsleft=3;
    dxval=2;
    if (Math.random()<0.5)
      balldx=dxval;
    else
      balldx=-dxval;
    balldy=-dxval;
    count=screendelay;
    batdpos=0;
    InitBricks();
  }

  public void InitBricks() //Methode zum berchnen der Steinanzahl
  {
    int i;
    for (i=0; i<numlines*bricksperline; i++)
      showbrick[i]=true;
  }

  public boolean keyDown(Event e, int key)
  {
    if (ingame)
    {
      if (key == Event.LEFT)
          batdpos=-3;			//X - Position vom Balken um 3 verringern
      if (key == Event.RIGHT)
        batdpos=3;				//Y - Position vom Balken um 3 erhöhen
      if (key == Event.ESCAPE)
        ingame=false;			//Aus dem Spiel gehen
    }
    else
    {
      if (key == 's' || key == 'S')//S Abfragen
      {
        ingame=true;			//Ins Spiel gehen
        GameInit();				//Methode GameInit() ausführen
      }
    }
    return true;				//True wert zurückgeben
  }

  public boolean keyUp(Event e, int key)
  {
    System.out.println("Key: "+key);
    if (key == Event.LEFT || key == Event.RIGHT)
       batdpos=0;				//Balken Position = 0 stetzen
    return true;
  }

  public void paint(Graphics g)	//Paint Methode
  {
    String s;
    Graphics gg;

    if (goff==null && d.width>0 && d.height>0)
    {
      ii = createImage(d.width, d.height);
      goff = ii.getGraphics();
    }
    if (goff==null || ii==null)
      return;

    goff.setColor(new Color(backcol));
    goff.fillRect(0, 0, d.width, d.height);
    if (ingame)
      PlayGame();
    else
      ShowIntroScreen();
    g.drawImage(ii, 0, 0, this);
  }


  public void PlayGame()
  {
    MoveBall();
    CheckBat();
    CheckBricks();
    DrawPlayField();
    DrawBricks();
    ShowScore();
  }

  public void ShowIntroScreen()
  {
    String s;

    MoveBall();
    CheckBat();
    CheckBricks();
    BatDummyMove();
    DrawPlayField();
    DrawBricks();
    ShowScore();
    goff.setFont(largefont);
    goff.setColor(new Color(96,128,255));

    if (showtitle)
    {
      s="Java Breakout";
      goff.drawString(s,(d.width-fmlarge.stringWidth(s)) / 2, (d.height-scoreheight-borderwidth)/2 - 20);
      s="Nils Kerstan";
      goff.setFont(smallfont);
      goff.setColor(new Color(255,160,64));
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 10);
    }
    else
    {
      goff.setFont(smallfont);
      goff.setColor(new Color(96,128,255));
      s="'S' um das Spiel zu starten";
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 - 10);
      goff.setColor(new Color(255,160,64));
      s="Benutze die Pfeiltasten zum Bewegen";
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 20);
    }
    count--;
    if (count<=0)
    { count=screendelay; showtitle=!showtitle; }
  }


  public void DrawBricks()
  {
    int i,j;
    boolean nobricks=true;
    int colordelta=255/(numlines-1);

    for (j=0; j<numlines; j++)
    {
      for (i=0; i<bricksperline; i++)
      {
        if (showbrick[j*bricksperline+i])
        {
          nobricks=false;
          goff.setColor(new Color(255,j*colordelta,255-j*colordelta));
          goff.fillRect(borderwidth+i*(brickwidth+brickspace), startline+j*(brickheight+brickspace),
               brickwidth, brickheight);
        }
      }
    }
    if (nobricks)
    {
      InitBricks();
      if (ingame)
        player1score+=100;
    }
  }
   
  public void DrawPlayField()			//Spielfeld
  {
    goff.setColor(Color.white);
    goff.fillRect(0,0,d.width,borderwidth);
    goff.fillRect(0,0,borderwidth,d.height);
    goff.fillRect(d.width-borderwidth,0,borderwidth,d.height);
    goff.fillRect(batpos,d.height-2*borderwidth-scoreheight, batwidth,batheight); // bat
    goff.fillRect(ballx,bally,ballsize,ballsize); // ball
  }


  public void ShowScore()
  {
    String s;
    goff.setFont(smallfont);
    goff.setColor(Color.white);

    s="Score: "+player1score;		//Score (Punkte)
    goff.drawString(s,40,d.height-5);
    s="Bälle: "+ballsleft;			//Anzahl der Bälle
    goff.drawString(s,d.width-40-fmsmall.stringWidth(s),d.height-5);
  }


  public void MoveBall()
  {
    ballx+=balldx;
    bally+=balldy;
    if (bally<=borderwidth)
    {
      balldy=-balldy;
      bally=borderwidth;
    }
    if (bally>=(d.height-ballsize-scoreheight))
    {
      if (ingame)
      {
        ballsleft--;
        if (ballsleft<=0)
          ingame=false;
      }
      ballx=batpos+(batwidth-ballsize)/2;
      bally=startline+numlines*(brickheight+brickspace);
      balldy=dxval;
      balldx=0;
    }
    if (ballx>=(d.width-borderwidth-ballsize))
    {
      balldx=-balldx;
      ballx=d.width-borderwidth-ballsize;
    }
    if (ballx<=borderwidth)
    {
      balldx=-balldx;
      ballx=borderwidth;
    }
  }

  public void BatDummyMove()
  {
    if (ballx<(batpos+2))
      batpos-=3;
    else if (ballx>(batpos+batwidth-3))
      batpos+=3;
  }

  public void CheckBat()
  {
    batpos+=batdpos;

    if (batpos<borderwidth)
      batpos=borderwidth;
    else if (batpos>(d.width-borderwidth-batwidth))
      batpos=(d.width-borderwidth-batwidth);
 
    if (bally>=(d.height-scoreheight-2*borderwidth-ballsize) && 
        bally<(d.height-scoreheight-2*borderwidth) &&
        (ballx+ballsize)>=batpos && ballx<=(batpos+batwidth))
    {
      bally=d.height-scoreheight-ballsize-borderwidth*2;
      balldy=-dxval;
      balldx=CheckBatBounce(balldx,ballx-batpos);
    }
  }

  public int CheckBatBounce(int dy, int delta)
  {
    int sign;
    int stepsize, i=-ballsize, j=0;
    stepsize=(ballsize+batwidth)/8;

    if (dy>0)
      sign=1;
    else
      sign=-1;

    while(i<batwidth && delta>i)
    {
      i+=stepsize;
      j++;
    }
    switch(j)
    {
      case 0:
      case 1:
        return -4;
      case 2:
	return -3;
      case 7:
        return 3;
      case 3:
      case 6:
        return sign*2;
      case 4:
      case 5:
        return sign*1;
      default:
        return 4;
    }
  }

  public void CheckBricks()
  {
    int i,j,x,y;
    int xspeed=balldx;
    if (xspeed<0) xspeed=-xspeed;
    int ydir=balldy;

    if (bally<(startline-ballsize) || bally>(startline+numlines*(brickspace+brickheight)))
      return;
    for (j=0; j<numlines; j++)
    {
      for (i=0; i<bricksperline; i++)
      {
        if (showbrick[j*bricksperline+i])
        {
          y=startline+j*(brickspace+brickheight);
          x=borderwidth+i*(brickspace+brickwidth);
          if (bally>=(y-ballsize) && bally<(y+brickheight) &&
              ballx>=(x-ballsize) && ballx<(x+brickwidth))
          {
            showbrick[j*bricksperline+i]=false;
            if (ingame)
              player1score+=(numlines-j);
            // Where did we hit the brick
            if (ballx>=(x-ballsize) && ballx<=(x-ballsize+3))
            { // leftside
              balldx=-xspeed;
            }
            else if (ballx<=(x+brickwidth-1) && ballx>=(x+brickwidth-4))
            { // rightside
              balldx=xspeed;
            }              
            balldy=-ydir;
          }
        }
      }
    }
  }

  public void run()
  {
    long  starttime;
    Graphics g;

    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    g=getGraphics();

    while(true)
    {
      starttime=System.currentTimeMillis();
      try
      {
        paint(g);
        starttime += 20;
        Thread.sleep(Math.max(0, starttime-System.currentTimeMillis()));
      }
      catch (InterruptedException e)
      {
        break;
      }
    }
  }

  public void start()
  {
    if (thethread == null) {
      thethread = new Thread(this);
      thethread.start();
    }
  }

  public void stop()
  {
    if (thethread != null) {
      thethread.stop();
      thethread = null;
    }
  }
}
 

Spin

Top Contributor
Java:
package JavaApplication4;

/**
 *
 * @author Spin
 */

/* Importieren von vielen verschiedenen Java Paketen)*/
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;


/* Anfang von der Klasse */
/* Ableiten von JPanel und implementieren von ActionListener (Interface)*/
public class Board extends JPanel implements ActionListener {

   
    Dimension d; // Dimension Klass beinhaltet die Breite und Höhe einer Komponente
    Font smallfont = new Font("Helvetica", Font.BOLD, 14); // ein Font (Schriftart festlegen)

    FontMetrics fmsmall, fmlarge; // Schriftfamilien
    Image ii; // Bild
    Color dotcolor = new Color(192, 192, 0); // Farbe , in RGB Angabe
    Color mazecolor; // Farbe

    boolean ingame = false; // primitiver Datentyp der true oder false erwartet
    boolean dying = false;

    /*Konstanten*/
    final int blocksize = 24;
    final int nrofblocks = 15;
    final int scrsize = nrofblocks * blocksize;
    final int pacanimdelay = 2;
    final int pacmananimcount = 4;
    final int maxghosts = 12;
    final int pacmanspeed = 6;

    /* Instanzvariablen*/
    int pacanimcount = pacanimdelay;
    int pacanimdir = 1;
    int pacmananimpos = 0;
    int nrofghosts = 6;
    int pacsleft, score;
    int deathcounter;
    /*Array*/
    int[] dx, dy;
    int[] ghostx, ghosty, ghostdx, ghostdy, ghostspeed;
    /* Bilder*/
    Image ghost;
    Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down;
    Image pacman3up, pacman3down, pacman3left, pacman3right;
    Image pacman4up, pacman4down, pacman4left, pacman4right;

    int pacmanx, pacmany, pacmandx, pacmandy;
    int reqdx, reqdy, viewdx, viewdy;
    
    /*leveldata wird mit short Werten gefüllt*/
    final short leveldata[] =
    { 19, 26, 26, 26, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 22,
      21, 0,  0,  0,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20,
      21, 0,  0,  0,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20,
      21, 0,  0,  0,  17, 16, 16, 24, 16, 16, 16, 16, 16, 16, 20,
      17, 18, 18, 18, 16, 16, 20, 0,  17, 16, 16, 16, 16, 16, 20,
      17, 16, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 16, 24, 20,
      25, 16, 16, 16, 24, 24, 28, 0,  25, 24, 24, 16, 20, 0,  21,
      1,  17, 16, 20, 0,  0,  0,  0,  0,  0,  0,  17, 20, 0,  21,
      1,  17, 16, 16, 18, 18, 22, 0,  19, 18, 18, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 0,  21,
      1,  25, 24, 24, 24, 24, 24, 24, 24, 24, 16, 16, 16, 18, 20,
      9,  8,  8,  8,  8,  8,  8,  8,  8,  8,  25, 24, 24, 24, 28 };

    /* Geschwindigkeit*/
    final int validspeeds[] = { 1, 2, 3, 4, 6, 8 };
    final int maxspeed = 6;

    int currentspeed = 3;
    short[] screendata;
    Timer timer;


    public Board() {

        GetImages(); // lade Bild

        addKeyListener(new TAdapter()); // Tastaturereigniss : Adapterklasse ( mach ich auch gerne ) ;)
        
        /* 15*15 gehen in screendata*/
        screendata = new short[nrofblocks * nrofblocks];
        
        mazecolor = new Color(5, 100, 5); // RGB Farbe geben
        /*Swing Komponenten sind so eingestellt dass keinen Fokus erhalten um das zu ändern :*/
        setFocusable(true); // aus der Fensterklasse

        d = new Dimension(400, 400); // siehe oben , wir geben den ganzen Breite und Höhe

        setBackground(Color.black); // Hintergrundfarbe festlegen
        setDoubleBuffered(true); // flackern verhindern

        /* instantiieren der restlichen Array Objekte*/
        ghostx = new int[maxghosts];
        ghostdx = new int[maxghosts];
        ghosty = new int[maxghosts];
        ghostdy = new int[maxghosts];
        ghostspeed = new int[maxghosts];
        dx = new int[4];
        dy = new int[4];
        /*Creates a new timer whose associated thread may be specified to run as a daemon.*/
        /* Das hat was mit dem Thread zu tun , wie genau kann ich dir leider nicht sagen :/ */
        timer = new Timer(40, this);
        timer.start();
    }



Das ist der erste Teil.

Nicht desto trotz , schick mir doch bitte den alten .
Warum wechselst du so schnell?
Das macht doch kein Sinn!
 

aggro600

Mitglied
ja sry das ich wechsel
aber ich musste ein projekt beschreiben und das neue nur noch die hälft an lines hat und das einfacher aufgebaut ist nehme ich das

______________________________NEUER CODE BIS JETZT______________________
Code:
import java.awt.*;				//importieren von Packeten
import java.applet.Applet;

public class Breakout extends Applet implements Runnable
{
  Dimension	d;
  Font 		largefont = new Font("Helvetica", Font.BOLD, 24);
  Font		smallfont = new Font("Helvetica", Font.BOLD, 14);

  FontMetrics	fmsmall, fmlarge;  
  Graphics	goff;
  Image		ii;
  Thread	thethread;

  boolean	ingame=false;
								//Variablen
  int		player1score;		//Score Player 1	
  int		ballx,bally;		//Ball Position	
  int		batpos;				//Balken Position
  int		batdpos=0;			//Balken Position
  int		balldx=0, balldy=0;	//Ball Kooridnaten
  int		dxval;
  int		ballsleft;
  int		count;				//Zähler
  boolean	showtitle=true;		//Title anzeigen
  boolean[]	showbrick;			//Steine
  int		bricksperline;		

  final int	borderwidth=5;		//Rahmenbreite
  final int	batwidth=50;		//Balkenreite
  final int	ballsize=5;			//Ballgröße
  final int	batheight=5;		//Balkenmhöhe
  final int	scoreheight=20;		//Scorehöhe
  final int	screendelay=300;	//Appletgröße
  final int	brickwidth=15;		//Steinbreite
  final int brickheight=8;		//Steinhöhe
  final int	brickspace=2;		//Stein Abstand
  final int	backcol=0x102040;	//Background Farbe
  final int	numlines=4;			//Steine auf der y Koordinate
  final int     startline=32;	//Startlinie

  public String getAppletInfo()
  {
    return("Breakout - by Nils");
  }

  public void init()
  {
    Graphics g;
    d = size();
    setBackground(new Color(backcol));
    bricksperline=(d.width-2*borderwidth)/(brickwidth+brickspace);
    d.width=bricksperline*(brickwidth+brickspace)+(2*borderwidth);
    g=getGraphics();
    g.setFont(smallfont);
    fmsmall = g.getFontMetrics();
    g.setFont(largefont);
    fmlarge = g.getFontMetrics();

    showbrick=new boolean[bricksperline*numlines];
    GameInit();
  }

  public void GameInit()
  {
    batpos=(d.width-batwidth)/2;
    ballx=(d.width-ballsize)/2;
    bally=(d.height-ballsize-scoreheight-2*borderwidth);
    player1score=0;
    ballsleft=3;
    dxval=2;
    if (Math.random()<0.5)
      balldx=dxval;
    else
      balldx=-dxval;
    balldy=-dxval;
    count=screendelay;
    batdpos=0;
    InitBricks();
  }

  public void InitBricks() //Methode zum berchnen der Steinanzahl
  {
    int i;
    for (i=0; i<numlines*bricksperline; i++)
      showbrick[i]=true;
  }

  public boolean keyDown(Event e, int key)
  {
    if (ingame)
    {
      if (key == Event.LEFT)
          batdpos=-3;			//X - Position vom Balken um 3 verringern
      if (key == Event.RIGHT)
        batdpos=3;				//Y - Position vom Balken um 3 erhöhen
      if (key == Event.ESCAPE)
        ingame=false;			//Aus dem Spiel gehen
    }
    else
    {
      if (key == 's' || key == 'S')//S Abfragen
      {
        ingame=true;			//Ins Spiel gehen
        GameInit();				//Methode GameInit() ausführen
      }
    }
    return true;				//True wert zurückgeben
  }

  public boolean keyUp(Event e, int key)
  {
    System.out.println("Key: "+key);//Konsolen ausgabe
    if (key == Event.LEFT || key == Event.RIGHT)
       batdpos=0;				//Balken Position = 0 stetzen
    return true;
  }

  public void paint(Graphics g)	//Paint Methode
  {
    String s;
    Graphics gg;

    if (goff==null && d.width>0 && d.height>0)
    {
      ii = createImage(d.width, d.height);
      goff = ii.getGraphics();
    }
    if (goff==null || ii==null)
      return;

    goff.setColor(new Color(backcol));
    goff.fillRect(0, 0, d.width, d.height);
    if (ingame)
      PlayGame();
    else
      ShowIntroScreen();
    g.drawImage(ii, 0, 0, this);
  }


  public void PlayGame()//Methode die beim Start alle Methoden aufruft
  {
    MoveBall();
    CheckBat();
    CheckBricks();
    DrawPlayField();
    DrawBricks();
    ShowScore();
  }

  public void ShowIntroScreen()
  {
    String s;

    MoveBall();
    CheckBat();
    CheckBricks();
    BatDummyMove();
    DrawPlayField();
    DrawBricks();
    ShowScore();
    goff.setFont(largefont);
    goff.setColor(new Color(96,128,255));

    if (showtitle)//Info vor dem Spiel einblenden
    {
      s="Java Breakout";
      goff.drawString(s,(d.width-fmlarge.stringWidth(s)) / 2, (d.height-scoreheight-borderwidth)/2 - 20);
      s="Nils Kerstan";
      goff.setFont(smallfont);
      goff.setColor(new Color(255,160,64));
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 10);
    }
    else
    {
      goff.setFont(smallfont);
      goff.setColor(new Color(96,128,255));
      s="'S' um das Spiel zu starten";
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 - 10);
      goff.setColor(new Color(255,160,64));
      s="Benutze die Pfeiltasten zum Bewegen";
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 20);
    }
    count--;
    if (count<=0)
    { count=screendelay; showtitle=!showtitle; }
  }


  public void DrawBricks()//Steine zeichnen
  {
    int i,j;
    boolean nobricks=true;
    int colordelta=255/(numlines-1);

    for (j=0; j<numlines; j++)
    {
      for (i=0; i<bricksperline; i++)
      {
        if (showbrick[j*bricksperline+i])
        {
          nobricks=false;
          goff.setColor(new Color(255,j*colordelta,255-j*colordelta));
          goff.fillRect(borderwidth+i*(brickwidth+brickspace), startline+j*(brickheight+brickspace),
               brickwidth, brickheight);
        }
      }
    }
    if (nobricks)
    {
      InitBricks();
      if (ingame)
        player1score+=100;
    }
  }
   
  public void DrawPlayField()			//Spielfeld
  {
    goff.setColor(Color.white);
    goff.fillRect(0,0,d.width,borderwidth);
    goff.fillRect(0,0,borderwidth,d.height);
    goff.fillRect(d.width-borderwidth,0,borderwidth,d.height);
    goff.fillRect(batpos,d.height-2*borderwidth-scoreheight, batwidth,batheight); // bat
    goff.fillRect(ballx,bally,ballsize,ballsize); // ball
  }


  public void ShowScore()
  {
    String s;
    goff.setFont(smallfont);
    goff.setColor(Color.white);

    s="Score: "+player1score;		//Score (Punkte)
    goff.drawString(s,40,d.height-5);
    s="Bälle: "+ballsleft;			//Anzahl der Bälle
    goff.drawString(s,d.width-40-fmsmall.stringWidth(s),d.height-5);
  }


  public void MoveBall()
  {
    ballx+=balldx;
    bally+=balldy;
    if (bally<=borderwidth)
    {
      balldy=-balldy;
      bally=borderwidth;
    }
    if (bally>=(d.height-ballsize-scoreheight))
    {
      if (ingame)
      {
        ballsleft--;
        if (ballsleft<=0)
          ingame=false;
      }
      ballx=batpos+(batwidth-ballsize)/2;
      bally=startline+numlines*(brickheight+brickspace);
      balldy=dxval;
      balldx=0;
    }
    if (ballx>=(d.width-borderwidth-ballsize))
    {
      balldx=-balldx;
      ballx=d.width-borderwidth-ballsize;
    }
    if (ballx<=borderwidth)
    {
      balldx=-balldx;
      ballx=borderwidth;
    }
  }

  public void BatDummyMove()
  {
    if (ballx<(batpos+2))
      batpos-=3;
    else if (ballx>(batpos+batwidth-3))
      batpos+=3;
  }

  public void CheckBat()
  {
    batpos+=batdpos;

    if (batpos<borderwidth)
      batpos=borderwidth;
    else if (batpos>(d.width-borderwidth-batwidth))
      batpos=(d.width-borderwidth-batwidth);
 
    if (bally>=(d.height-scoreheight-2*borderwidth-ballsize) && 
        bally<(d.height-scoreheight-2*borderwidth) &&
        (ballx+ballsize)>=batpos && ballx<=(batpos+batwidth))
    {
      bally=d.height-scoreheight-ballsize-borderwidth*2;
      balldy=-dxval;
      balldx=CheckBatBounce(balldx,ballx-batpos);
    }
  }

  public int CheckBatBounce(int dy, int delta)
  {
    int sign;
    int stepsize, i=-ballsize, j=0;
    stepsize=(ballsize+batwidth)/8;

    if (dy>0)
      sign=1;
    else
      sign=-1;

    while(i<batwidth && delta>i)
    {
      i+=stepsize;
      j++;
    }
    switch(j)
    {
      case 0:
      case 1:
        return -4;
      case 2:
	return -3;
      case 7:
        return 3;
      case 3:
      case 6:
        return sign*2;
      case 4:
      case 5:
        return sign*1;
      default:
        return 4;
    }
  }

  public void CheckBricks()
  {
    int i,j,x,y;
    int xspeed=balldx;
    if (xspeed<0) xspeed=-xspeed;
    int ydir=balldy;

    if (bally<(startline-ballsize) || bally>(startline+numlines*(brickspace+brickheight)))
      return;
    for (j=0; j<numlines; j++)
    {
      for (i=0; i<bricksperline; i++)
      {
        if (showbrick[j*bricksperline+i])
        {
          y=startline+j*(brickspace+brickheight);
          x=borderwidth+i*(brickspace+brickwidth);
          if (bally>=(y-ballsize) && bally<(y+brickheight) &&
              ballx>=(x-ballsize) && ballx<(x+brickwidth))
          {
            showbrick[j*bricksperline+i]=false;
            if (ingame)
              player1score+=(numlines-j);
            //Wo wird der Balken getroffen
            if (ballx>=(x-ballsize) && ballx<=(x-ballsize+3))
            { //linke Seite
              balldx=-xspeed;
            }
            else if (ballx<=(x+brickwidth-1) && ballx>=(x+brickwidth-4))
            { //rechte Seite
              balldx=xspeed;
            }              
            balldy=-ydir;
          }
        }
      }
    }
  }

  public void run()
  {
    long  starttime;
    Graphics g;

    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    g=getGraphics();

    while(true)
    {
      starttime=System.currentTimeMillis();
      try
      {
        paint(g);
        starttime += 20;
        Thread.sleep(Math.max(0, starttime-System.currentTimeMillis()));
      }
      catch (InterruptedException e)
      {
        break;
      }
    }
  }

  public void start()
  {
    if (thethread == null) {
      thethread = new Thread(this);
      thethread.start();
    }
  }

  public void stop()//Thread Anhalten
  {
    if (thethread != null) {
      thethread.stop();
      thethread = null;
    }
  }
}
 

Soulfly

Bekanntes Mitglied
Definitiv NEIN! Keine Hausaufgaben. Gott wollte gerade was nettes posten aber dann das. Geh den Code Schritt fuer Schritt durch, dann verstehst du ihn auch.
 

aggro600

Mitglied
ich bin doch schon dabei siehste doch das ich gerade kommentier oder?
nur ich weiß nicht alles und vllt könntet ihr einfach sn paar kommentare ergenzen
ihr sollt ja nicht alles machen das sag ich doch nicht
faul bin ich ja nicht
 

Schandro

Top Contributor
kleiner Tipp:
return true; //True wert zurückgeben
Solche "Kommentare" will keiner lesen, da sie komplett unnötig sind und einfach nur "java" zurück ins Deutsche übersetzen..

Beim Kommentieren gehts dadrum, die nicht so ganz offensichtlichen Sachen hinzuschreiben bzw. zu erklären WARUM etwas so im Code steht wie es im Code steht.
Bsp.:
foo(); // wird aufgerufen, da die Variable x immer y sein muss bevor z passiert

€dit:
int batpos; //Balken Position
Wär doch schöner, wenn man einfach einen guten Variablennamen nimmt (z.b. "balkenPosition"), das spart
1. Das Kommentar und
2. Weiß man immer für was die Referenz steht und muss nicht immer wieder oben im Quelltext gucken.
 
Zuletzt bearbeitet:

Spin

Top Contributor
Dann mach dir die Mühe und poste die Methoden die du nicht verstehst.

Helfen können wir dir nur , wenn uns sagst was genau. Wenn du den unterschied zwischen Klassen und Instanzvariable nicht kennst, dann solltest du dich an solchen Quellcodes nicht versuchen.

Poste die Methoden und ich erkläre sie dir, soweit wie ich kann. Es hilft aber auch die Java API. Da kann man alles nachlesen. Man muss nur verstanden haben was ein Konstruktor ist , wie man Kapselt, warum man Objekte und Varaiblen braucht.


Der rest ist Mathe! Und da wir hier ein Java Forum joinen, helfen wir nicht in Minus und plus rechnung.

Bsp.:

Java:
public void MoveBall()
  {
    ballx+=balldx;
    bally+=balldy;
    if (bally<=borderwidth)
    {
      balldy=-balldy;
      bally=borderwidth;
    }


Du weißt sicherlich das ballx+= balldx auch ballx = ballx + balldx bedeutet!?
Eine Zuweisung solltest du auch verstanden haben.

ja..... der Rest ist doch eindeutig.

Java:
  int		ballx,bally;		//Ball Position

Da hast du den Variablen 0 zugewisen. ( Macht der Konstruktor automatisch )

Java:
int		balldx=0, balldy=0;	//Ball Kooridnaten

Da auch. Wenn man das zusammenrechnet usw. kommt man zu einen Ergebnis.
Vorab musst du dir aber anschauen, wann welche Methode aufgerufen wird, und was , wo übergeben wird.

Es kann sein dass die Werte nicht mehr 0 besitzen, sondern durch Methoden einen anderen Wert zugewiesen bekommen hat.

Das ist ja , dass tolle an OOP. Man hält alles flexible :)

gruß spin
 

aggro600

Mitglied
Ich hab nie behauptet das ich gut in Java sei.
Darum bitte ich euch um hilfe.
Um nur weil ich es nicht besser kann macht ihr mich hier nieder.
 

Spin

Top Contributor
Wenn du kein Java kannst und die Basics nur schleppend beherschst, dann kann ich mir nicht vorstellen, dass du von deinen Lehrer oder Dozenten die Aufgabe bekommen hast, diesen Code zu interpretieren.

Nicht mal nach einen halben Jahr schaffst du dass, außer du setzt sich Tag und Nacht ran, vernachlässigst das Schlafen und nimmst ...:lol:

<---ich habe es nicht geschafft *zugeb*

Ich kann dir gerne einfacherer Codes posten , die du erstmal interpretieren können musst.

Java:
public class Aufzaehlungen2
{
  public Aufzaehlungen2()
  {
    for(Fahrzeuge fz: Fahrzeuge.values())
      System.out.println(fz + ": " + fz.getPS());
  }

  public static void main(String[] args)
  {
    new Aufzaehlungen2();
  }
}

enum Fahrzeuge
{
  BMW(110), AUDI(100), OPEL(50);

  private int ps;

  Fahrzeuge(int ps)
  {
    this.ps = ps;
  }

  public int getPS()
  {
    return ps;
  }
}


Was passiert den hier?

enum ist dazu da um mehrere Konstanten gleichzeitig zu deklarieren.


PS: Ich möchte dich hier nicht verscheuchen , da ich noch genau so anfänger bin wie du. Manchmal finde ich es auch nicht fair , wie die Leute hier mit einen umgehen.

Ständig bekommt man gesagt : Nutze ein Buch.
Doch kann ich nach und nach die Jungs verstehen. ;)

Ich schaffe es eh nie , so gut wie die zu werden .;) ....daher kannst auf mich zählen, doch hasaufgaben mache ich auch nicht Xd^^

grüße
 

aggro600

Mitglied
doch ich muss mir ein spiel suchen und das beschreiben
in java bin ich nicht so gut ich kann besser php5
aber ich muss es einfach schaffen den zu interpretieren.
ich darf auch das inet als hilfe nehmen und da ich dieses forum bis jetzt eig gut fand habe ich hier gefragt
 

Quaxli

Top Contributor
Und woher kriegst Du den Murks äh die Spiele?

Java:
  public void init()
  {
    Graphics g;
    ....
    g=getGraphics(); //<-------
    g.setFont(smallfont);
    fmsmall = g.getFontMetrics();
    g.setFont(largefont);
    fmlarge = g.getFontMetrics();

    showbrick=new boolean[bricksperline*numlines];
    GameInit();

Wenn jemand getGraphics().;( verwendet, schau ich mir den Rest schon gar nicht mehr an.

Schau' in mein Tutorial, da wird auch ein Spiel aufgebaut und es ist erschöpfend erklärt, was, weshalb, warum. Vielleicht lernst Du dabei sogar noch was. Natürlich ist das mit mehr Arbeit verbunden, als wenn man hier für schlechten Code aus dem Internet den Allerwertesten nachgetragen bekommt.
 

Spin

Top Contributor
Ja, das Tut, con @quaxli ist sehr zu empfehlen , oder ich habe noch ein anderen, denn ich sogar mit kommentaren posten könnte ;)

Aber dann würde ich die ja die ganze Arbeit abnehmen. Wenn du garnicht weiter kommst , denn schick ich dir den Code von nen Pong spiel , da haste Comments mit drin ;)
 
Status
Nicht offen für weitere Antworten.

Ähnliche Java Themen

Neue Themen


Oben