# Problem mit Tastatursteuerung



## JLF Entwickler (18. Jul 2009)

Ich versuche das Spiel Little Fighter (vielleicht kennen das einige) mit Java zu programmieren und später auch ein wenig abzuändern und über einen Server laufen zu lassen. Ich stehe noch ganz am Anfang, doch ich habe jetzt folgendes Problem: Wenn eine Taste gedrückt gehalten wird, bewegt sich meine Spielfigur zu lange weiter.
Eigentlich habe ich eine Boolean Variable ("moving"), die dies verhindern sollte, doch irgendwie funktioniert das nicht.
Ich hab mir zuerst noch gedacht, dass ich mit dem KeyReleased Event vielleicht das Gehen abbrechen kann, doch als ich getestet habe, wann dieses Event ausgelöst wird, wurde dies nicht ausgelöst wenn ich die Taste loslasse, sondern erst, wenn die Figur stillsteht.


[Java]package Client;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import java.awt.image.BufferStrategy;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.JPanel;



public class JLF extends Canvas implements KeyListener {
    //Position des Charakters
    int posX;
    int posY;

    //Tastaturbelegung
    int down;
    int up;
    int left;
    int right;
    int attack;
    int jump;
    int defend;

    //Anzeigevariabeln
    final int BREITE=1000;
    final int HOEHE=800;
    public BufferStrategy bf;

    //Schrittzählvariabeln
    int sUp = 0;
    int sDown = 0;
    int sRight = 0;
    int sLeft = 0;

    //Bildwiederholungsrate in ms
    private final int SPEED = 30;

    //Bild-Zwischenspeicher
    public HashMap sprites;

    //Charaktervariabeln
    public String chara;
    public String action;
    public String lastAction;
    boolean moving = false;
    boolean dRight = true;


    public JLF(){
        down = KeyEvent.VK_X;
        up = KeyEvent.VK_W;
        left = KeyEvent.VK_A;
        right = KeyEvent.VK_D;
        attack = KeyEvent.VK_S;
        jump = KeyEvent.VK_TAB;
        defend = KeyEvent.VK_BACK_SLASH;

        sprites = new HashMap();
        JFrame window = new JFrame("Java Little Fighter");
        JPanel panel = (JPanel)window.getContentPane();
        setBounds(0,0,BREITE,HOEHE);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel.setPreferredSize(new Dimension(WIDTH,HOEHE));
        panel.add(this);
        window.setBounds(0,0,BREITE,HOEHE);
        window.setResizable(false);
        window.setVisible(true);
        this.setBackground(Color.BLACK);
        createBufferStrategy(2);
        bf = getBufferStrategy();
        chara = "deep";
        action = "stand";
        this.addKeyListener(this);
        requestFocus();
        game();
        System.out.println("fertig");
    }

//Hauptloop des Spiels
    public void game(){
        int i =0 ;
        while(true){
            draw();
            try {
                Thread.sleep(SPEED);
            } catch (InterruptedException ex) {
                Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
            }
            i++;
        }
    }

    private void draw(){
        Graphics g = bf.getDrawGraphics();
        g.clearRect(0, 0, BREITE, HOEHE);
        BufferedImage img = null;
        try{
            img = getSprite(chara);
        }catch(Exception ex){
                System.out.println("Grafik konnte nicht geladen werden: "+ ex);
        }

        try{
            g.drawImage(img, posX+(img.getWidth()/2), posY+(img.getHeight()/2),null);
        }catch(Exception ex){
            System.out.println("Fehler beim erstellen des Grafikobjekts: " + ex);
        }
        finally{
            g.dispose();
        }

        bf.show();

        Toolkit.getDefaultToolkit().sync();
    }


     public BufferedImage loadImage(String name) {
        BufferedImage image;
        try {
             image = ImageIO.read(new File(name));
             return image;
        } catch (Exception e) {
            System.out.println(name +" konnte nicht geoeffnet werden.");
            System.out.println("Fehler: "+e.getClass().getName()+" "+e.getMessage());
            return null;
        }
     }

     public BufferedImage getSprite(String ch){
         BufferedImage img;
         if(dRight){
             img = (BufferedImage)sprites.get(ch+"."+action);
             if (img == null) {
                 img = loadImage(ch+"."+action+".gif");
                 sprites.put(ch+"."+action,img);
             }
         }else{
             img = (BufferedImage)sprites.get(ch+"."+action+".left");
             if(img == null){
                 img = loadImage(ch+"."+action+".left.gif");
                 sprites.put(ch+"."+action+".left", img);
             }
         }
         return img;
     }

    public void keyTyped(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
        if(!moving){
            if(e.getKeyCode()== up){
                moving = true;
                lastAction = action;
                if(lastAction.equals("stand")){
                    action = "move1";
                    while(sUp<5){
                        posY = posY-2;
                        sUp++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sUp = 0;

                }else if(lastAction.equals("move1")){
                    action = "move2";
                    while(sUp<5){
                       posY = posY-2;
                       sUp++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sUp = 0;
                }else if(lastAction.equals("move2")){
                    action = "move3";
                    while(sUp<5){
                       posY = posY-2;
                       sUp++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sUp = 0;
                }else if(lastAction.equals("move3")){
                    action = "stand";
                    while(sUp<5){
                      posY = posY-2;
                      sUp++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sUp = 0;
                }
                moving = false;
            }


            if(e.getKeyCode()== down){
                moving = true;
                lastAction = action;
                if(lastAction.equals("stand")){
                    action = "move1";
                    while(sDown<5){
                        posY = posY+2;
                        sDown++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sDown = 0;

                }else if(lastAction.equals("move1")){
                    action = "move2";
                    while(sDown<5){
                       posY = posY+2;
                       sDown++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sDown = 0;
                }else if(lastAction.equals("move2")){
                    action = "move3";
                    while(sDown<5){
                       posY = posY+2;
                       sDown++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sDown = 0;
                }else if(lastAction.equals("move3")){
                    action = "stand";
                    while(sDown<5){
                      posY = posY+2;
                      sDown++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sDown = 0;
                }
                moving = false;
            }

            if(e.getKeyCode()== right){
                moving = true;
                dRight = true;
                lastAction = action;
                if(lastAction.equals("stand")){
                    action = "move1";
                    while(sRight<5){
                        posX = posX+2;
                        sRight++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sRight = 0;

                }else if(lastAction.equals("move1")){
                    action = "move2";
                    while(sRight<5){
                       posX = posX+2;
                       sRight++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sRight = 0;
                }else if(lastAction.equals("move2")){
                    action = "move3";
                    while(sRight<5){
                       posX = posX+2;
                       sRight++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sRight = 0;
                }else if(lastAction.equals("move3")){
                    action = "stand";
                    while(sRight<5){
                      posX = posX+2;
                      sRight++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sRight = 0;
                }
                moving = false;
            }

            if(e.getKeyCode()== left){
                moving = true;
                dRight = false;
                lastAction = action;
                if(lastAction.equals("stand")){
                    action = "move1";
                    while(sLeft<5){
                        posX = posX-2;
                        sLeft++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sLeft = 0;

                }else if(lastAction.equals("move1")){
                    action = "move2";
                    while(sLeft<5){
                       posX = posX-2;
                       sLeft++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sLeft = 0;
                }else if(lastAction.equals("move2")){
                    action = "move3";
                    while(sLeft<5){
                       posX = posX-2;
                       sLeft++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sLeft = 0;
                }else if(lastAction.equals("move3")){
                    action = "stand";
                    while(sLeft<5){
                      posX = posX-2;
                      sLeft++;
                        try {
                            Thread.sleep(SPEED);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(JLF.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    sLeft = 0;
                }
                moving = false;
            }

        }
    }

    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode()==up){
            System.out.println("stop up");
        }
        if(e.getKeyCode()==down){
            System.out.println("stop down");
        }
        if(e.getKeyCode()==left){
            System.out.println("stop left");
        }
        if(e.getKeyCode()==right){
            System.out.println("stop right");
        }

    }

   public static void main(String[] args){
        new JLF();
    }
}[/code]

Dies ist mein Quellcode, ich hoffe mir kann jemand helfen.


----------



## Schandro (18. Jul 2009)

du solltest auf keinen Fall direkt in der keyPressed-Methode Thread.sleep aufrufen, da sonst der EDT Blockiert wird... Du bräuchtest en eigenen Thread/Timer/whatever dafür.

Zurzeit macht der moving-Flag keinen Sinn, da er nur in der keyPressed-Methode benutzt wird und er am Anfang und Ende der Methode immer true ist.


----------



## JLF Entwickler (18. Jul 2009)

Vielen Dank, jetzt rennt er nicht mehr davon . Thema kann geschlossen werden.


----------

