Balken, der Ball zurückschießt

Status
Nicht offen für weitere Antworten.
G

Guest

Gast
Hallo!

schreibe gerade ein ping pong spiel. der ball prallt schon an den wänden ab. mein problem ist nun, dass ich nicht weiß wie ich das machen soll, dass der ball abprallt wenn er den balken berührt.
habs so versucht, ist aber ein blöder ansatz:

Code:
			if(x_pos + 60 == x_posb && y_pos == y_posb) {
			    x_speed = -1;
			    y_speed = -1;
			    sc = sc + 5;
			}


hier das ganze programm:

Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Game extends Applet implements Runnable, KeyListener {
	
	int x_pos = 20;
	int y_pos = 100;
	int radius = 20;
	int appletsize_x = 200;
	int appletsize_Y = 200;
	int x_speed = 1;
	int y_speed = 1;
	int currentLine;
	
	int x_posb = 100;
	int y_posb = 180;
	int x_speedb = 1;
	int radiusb = 100;
	
	AudioClip bumb;
	
	private Image dbgImage;
	private Graphics dbg;
	private Image hintergrund;
	private int sc;
	private String score;
	
	
	public void init() {
		setBackground(Color.LIGHT_GRAY);
		bumb = getAudioClip(getCodeBase(), "bump.wav");
		hintergrund = getImage(getCodeBase(), "hintergrund.jpg");
		
		this.addKeyListener(this);
		
	} // ende init()

	
	public void keyPressed(KeyEvent en) {
		int k = en.getKeyCode();
		if (k == KeyEvent.VK_LEFT) {
            x_speedb = -1;
        }
		else if(k == KeyEvent.VK_RIGHT) {
			x_speedb = +1;
		}
		else if(k == KeyEvent.VK_SPACE) {
			x_speedb = 0;
		}
	}
	// ende Aktionen
	
	public void keyReleased(KeyEvent ke)  { ; }
	public void keyTyped(KeyEvent ke) { ; } 
	
	
	public void start() {
		Thread th = new Thread(this);
		th.start();
		
		
	} // ende start()
	
	
	public void stop() {
		
	} // ende stop()
	
	
	public void destroy() {
		
	} // ende destroy()
	
	
	public void run () {
		// Erniedrigen der ThreadPriority um zeichnen zu erleichtern
		Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

		// Solange true ist läuft der Thread weiter
		while (true)
		{
			// Wenn der Ball den rechten Rand berührt, dann prallt er ab
			if (x_pos > appletsize_x - radius) {
				x_speed = -1;
			}
			// Ball brührt linken Rand und prallt ab
			else if (x_pos < radius) {
				x_speed = +1;
			}
			else if(y_pos > appletsize_Y - radius) {
				y_speed = -1;
				sc = sc - 20;	
				bumb.play();
			}
			else if(y_pos < radius) {
				y_speed = +1;
			}

			// Ball
			x_pos += x_speed;
			y_pos += y_speed;
			
			
			// Balken
			x_posb += x_speedb;
			
			if(x_posb > appletsize_x - 60) {
			    x_speedb -= 1; // -
			}
			else if(x_posb < radius - radius) {
			    x_speedb += 1; // +
			}
			

			// Wenn balken ball berührt
			if(x_pos + 60 == x_posb && y_pos == y_posb) {
			    x_speed = -1;
			    y_speed = -1;
			    sc = sc + 5;
			}

			
			x_posb += x_speedb;
			
			
			repaint();

			try
			{
				// Stoppen des Threads für in Klammern angegebene Millisekunden
				Thread.sleep (10);
			}
			catch (InterruptedException ex)
			{
				// do nothing
			}

			// Zurücksetzen der ThreadPriority auf Maximalwert
			Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		}
	}
	
	
	// Bildschirmflimmern beseitigen (Doppelbufferung)
	public void update(Graphics g) {
		if(dbgImage == null) {
			dbgImage = createImage(this.getSize().width, this.getSize().height);
			dbg = dbgImage.getGraphics();
		}
		// Bildschirm in Hintergrund löschen
		dbg.setColor(getBackground());
		dbg.fillRect(0,0,this.getSize().width, this.getSize().height);
		
		// Bildschirm in Vordergrund zeichnen
		dbg.setColor(getForeground());
		paint(dbg);
		
		// Ausgeben
		g.drawImage(dbgImage,0,0,this);
		
	} // ende update
	
	
	public void paint(Graphics g) {
		g.drawImage(hintergrund,0,0,this);
		
		g.setColor(Color.white);
		g.drawString("Score: "+sc,10,20);
		
		// Balken
		g.setColor(Color.MAGENTA);
		g.fillRect(x_posb  ,y_posb, 60,10);
		
		g.setColor(Color.red);
		// Kugel zeichen
		g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
		
	} // ende paint()

}
 

Wildcard

Top Contributor
Mir war gerade langweilig, also hab ich dir schnell ein OOP Beispiel zusammengezimmert:

Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


/**
 * TODO short description for Pong.
 * 


 * Long description for Pong.
 * 
 * @author Wildcard
 * @version $Revision: $
 */
public class Pong extends JFrame implements Runnable
{
    
    private Ball ball = new Ball(18,Color.RED);
    private Stick stick = new Stick(50,Color.BLUE);
    private Point speed = new Point(3,3);
    private static final int LEFT = -5;
    private static final int RIGHT = 5;
    private int direction=0;
    
    public Pong()
    {
        JPanel panel = new JPanel((LayoutManager)null);
        add(panel);
        
        panel.addKeyListener(new KeyAdapter()
        {
            public void keyTyped(KeyEvent e)
            {
                if(e.getKeyChar()=='a')
                    direction=LEFT;
                else if(e.getKeyChar()=='d')
                    direction=RIGHT;

            }

            public void keyReleased(KeyEvent e)
            {
                direction=0;
            }
        });


        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        stick.setLocation(getWidth()/2-25,getHeight()-80);
        ball.setLocation(50,50);
        
        panel.add(stick);
        panel.add(ball);
        
        new Thread(this).start();
        setVisible(true);
        panel.requestFocus();
        
    }

    /**
     * @see java.lang.Runnable#run()
     */
    public void run()
    {
        // TODO Auto-generated method stub
        Rectangle frame = new Rectangle(0,0,getContentPane().getWidth(),getContentPane().getHeight());
        Rectangle ballRect;
        final Point ballLocation = ball.getLocation(); 
        
        while(true)
        {
            repaint();
            if (!(stick.getLocation().x<=5) && !(stick.getLocation().x+50>=getContentPane().getWidth()-5))
                stick.setLocation(stick.getLocation().x+direction,stick.getLocation().y);
            else if (stick.getLocation().x<50)
                stick.setLocation(stick.getLocation().x+1,stick.getLocation().y);
            else
                stick.setLocation(stick.getLocation().x-1,stick.getLocation().y);
            
            ballRect = new Rectangle(ball.getBounds());
            if (!frame.contains(ballRect))
            {
                if (ball.getLocation().x<0 || ball.getLocation().x+ball.durchmesser>getWidth())
                    speed.x=-speed.x;
                else if (ball.getLocation().y<0 || ball.getLocation().y+ball.durchmesser>getContentPane().getHeight())
                    speed.y=-speed.y;
            }
            
            if(stick.getBounds().intersects(ball.getBounds()))
            {
                speed.y=-speed.y;
            }
            
            try
            {
                Thread.sleep(8);
            } catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
            ballLocation.x=ballLocation.x+speed.x;
            ballLocation.y=ballLocation.y+speed.y;
            ball.setLocation(ballLocation);
            

                     
        }      
    }
    
    public static void main(String[] args)
    {
        Pong pong = new Pong();
    }
}

class Ball extends JComponent
{
    int durchmesser;
    private Color color;
   
    
    public Ball(int durchmesser, Color color)
    {
        this.durchmesser=durchmesser;
        this.color=color;
        setSize(durchmesser,durchmesser);
    }
    
    
    protected void paintComponent(Graphics g)
    {
       
        g.setColor(color);
        g.fillOval(0,0,durchmesser,durchmesser);
    }
    
}

class Stick extends JComponent
{
    int length;
    private Color color;
   
    
    public Stick(int length, Color color)
    {
        this.length=length;
        this.color=color;
        setSize(length,10);
    }
    
    
    protected void paintComponent(Graphics g)
    {
        g.setColor(color);
        g.fillRoundRect(0,0,length,10,5,5);
    }
}
 
G

Gast

Gast
danke!
ist dieser teil dafür zuständig, dass der ball am balken abprallt?
 
G

Guest

Gast
tschuldigung:

hier der teil:
Code:
            if (!frame.contains(ballRect))
            {
                if (ball.getLocation().x<0 || ball.getLocation().x+ball.durchmesser>getWidth())
                    speed.x=-speed.x;
                else if (ball.getLocation().y<0 || ball.getLocation().y+ball.durchmesser>getContentPane().getHeight())
                    speed.y=-speed.y;
            }
           
            if(stick.getBounds().intersects(ball.getBounds()))
            {
                speed.y=-speed.y;
            }

da dass mein erstes spiel ist, weiß ich noch nicht so ganz genau wie das in meinem applet aussehen soll.

danke im voraus!
 

Wildcard

Top Contributor
da dass mein erstes spiel ist, weiß ich noch nicht so ganz genau wie das in meinem applet aussehen soll.

kP was du meinst? Hab dir doch was lauffähiges gegeben, hab eben nur eine Application draus gemacht weil ich keine Applets mag. Kannst du doch aber trotzdem genauso übernehmen?
 
G

Guest

Gast
ich meine den teil mit dem balken. ich habs jetzt so versucht:
Code:
if ((oben >= x_posb - radius) && (unten <= y_posb + radius)) {
	x_speed = - x_speed;
}

geht aber nicht richtig. der ball geht immer grad hoch, aber ohne, dass ich ihn mit dem balken berühr habe.

hier nochmal der neue quelltext:
Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class game extends Applet 
			implements Runnable, KeyListener, MouseListener {
	
    private int x_pos = 20;
    private int y_pos = 100;
    private int radius = 20;
    private int appletsize_x = 462;
    private int appletsize_Y = 366;
    private int x_speed = 2;
    private int y_speed = 2;
    private int currentLine;
    // Balken
    int x_posb = 100;
    int y_posb = 310;
    double x_speedb = 1;
    int radiusb = 100;
	
    private int oben = y_pos - radius;
    private int unten = y_pos + radius;
    private int links = x_pos - radius;
    private int rechts = x_pos + radius;
	
	AudioClip bumb;
	
	private Image dbgImage;
	private Graphics dbg;
	private int sc;
	private int live = 10;
	private Image hintergrund, ball, bat;
	private boolean gestoppt = true;
	// Zufall
	private final int MIN = 0;
	private final int MAX = 4;
	private Random generator = new Random();
	private int zufall;
	private Graphics gr;
	private double neu;
	
	
	public void init() {
		setBackground(Color.LIGHT_GRAY);
		bumb = getAudioClip(getCodeBase(), "bump.wav");
		hintergrund = getImage(getCodeBase(), "yankeestadium.jpg");
		ball = getImage(getCodeBase(), "ball copy.gif");
		bat = getImage(getCodeBase(), "baseballbat.gif");
		
		//this.addMouseListener(this);
		this.addKeyListener(this);
		this.addMouseListener(this);
		
	} // ende init()
	
	
	
	public void keyPressed(KeyEvent en) {
		int k = en.getKeyCode();
		if (k == KeyEvent.VK_LEFT) {
            x_speedb = - 2;
        }
		else if(k == KeyEvent.VK_RIGHT) {
			x_speedb = + 2;
		}
		else if(k == KeyEvent.VK_SPACE) {
			x_speedb = 0;
		}
		// Geschwindigkeit bestimmen
		else if(k == KeyEvent.VK_1) {
		    neu = x_speedb + 5;
		}
		else if(k == KeyEvent.VK_2) {
		    neu = x_speedb - 6;
		}
	}
	public void keyReleased(KeyEvent ke){}
	public void keyTyped(KeyEvent ke){} 
	//	 ende Aktionen
	
	
	public void start() {
		Thread th = new Thread(this);
		th.start();
		
		
	} // ende start()
	
	
	public void stop() {
		
	} // ende stop()
	
	
	public void destroy() {
		
	}
	
	
	public void run () {
		// Erniedrigen der ThreadPriority um zeichnen zu erleichtern
		Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

		// Solange true ist läuft der Thread weiter
		while (true)
		{
			// Wenn der Ball den rechten Rand berührt, dann prallt er ab
			if (x_pos > appletsize_x - radius) {
				x_speed = -(zufall = generator.nextInt(MAX-MIN + 1) + MIN);
			}
			// Ball brührt linken Rand und prallt ab
			else if (x_pos < radius) {
				x_speed = +(zufall = generator.nextInt(MAX-MIN + 1) + MIN);
			}
			else if(y_pos > appletsize_Y - radius) {
				y_speed = -(zufall = generator.nextInt(MAX-MIN + 1) + MIN);
				sc = sc - 20;	
				live = live - 1;
				bumb.play();
			}
			else if(y_pos < radius) {
				y_speed = +(zufall = generator.nextInt(MAX-MIN + 1) + MIN);
			}

			// Ball
			x_pos += x_speed;
			y_pos += y_speed;
			
			
			// Balken
			x_posb += x_speedb;
			
			if(x_posb > appletsize_x - 100) {
			    x_speedb -= 2; // -
			}
			else if(x_posb < radius - radius) {
			    x_speedb += 2;
			}
			
			// Wenn balken ball berührt
			if ((oben >= x_posb - radius) && (unten <= y_posb + radius)) {
					x_speed = - x_speed;
			}
			
			
			// Neuzeichnen des Applets
			
			x_posb += x_speedb;
			
			
			repaint();

			try
			{
				// Stoppen des Threads für in Klammern angegebene Millisekunden
				Thread.sleep (10);
			}
			catch (InterruptedException ex)
			{
				// do nothing
			}

			// Zurücksetzen der ThreadPriority auf Maximalwert
			Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		}
	}
	
	
	// Bildschirmflimmern beseitigen (Doppelbufferung)
	public void update(Graphics g) {
		if(dbgImage == null) {
			dbgImage = createImage(this.getSize().width, this.getSize().height);
			dbg = dbgImage.getGraphics();
		}
		// Bildschirm in Hintergrund löschen
		dbg.setColor(getBackground());
		dbg.fillRect(0,0,this.getSize().width, this.getSize().height);
		
		// Bildschirm in Vordergrund zeichnen
		dbg.setColor(getForeground());
		paint(dbg);
		
		// Ausgeben
		g.drawImage(dbgImage,0,0,this);
		
	} // ende update
	

	// Spiel neu starten, wenn es zu ende ist
    public void mouseClicked(MouseEvent e) {
        if(e.getClickCount() == 3) {
            sc = 0;
            live = 11;
            x_speed = 1;
            y_speed = 1;
            x_speedb = 1;
        }
    }
    public void mouseEntered(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void mouseExited(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    
    
	public void paint(Graphics g) {
		g.drawImage(hintergrund,0,0,this);
		
		// Leben < 0 = stop
		if(live <= 0) {
		    //Graphics gr;
		    g.setColor(Color.white);
		    g.drawString("Game Over, Score: "+sc, 160,200);
		    g.drawString("Dreifachklick um das Spiel neu zu starten",100,215);
		    x_speed = 0;
		    y_speed = 0;
		    x_speedb = 0;
		}
		
		
		g.setColor(Color.white);
		g.drawString("Score: "+sc+"  Lives: "+live,10,20);
		g.drawString("Geschwindigkeit: "+zufall, 340, 20);
		
		// Balken
		g.setColor(Color.MAGENTA);
		g.drawImage(bat, x_posb  ,y_posb, this);
		
		g.setColor(Color.red);
		// Kugel zeichen
		g.drawImage(ball,x_pos - radius, y_pos - radius, 2 * radius, 2 * radius, this);
		
	} // ende paint()

}
 
Status
Nicht offen für weitere Antworten.

Ähnliche Java Themen

Neue Themen


Oben