java swing keylistener 2d boulderdash -


i'm looking make boulderdash problem first i'm trying player move around, he's allowed move space not rock(1) or wall(0).

my , left motions work fine right , down screwed up, they're moving multiple spaces if key pressed once. here's visualization if helps, i'm posting relevant code i'm guessing bug in keylistener section

here's code uploaded on website http://textuploader.com/13k1

i spent several minutes trying copy paste code here code function not code being classified code , wasn't allowed submit it

here links other relevant classes , files

first of never use numeric constants instead of field constants,

public void keypressed(keyevent k) {     int keycode = k.getkeycode();                if(keycode == keyevent.vk_r) // not keycode == 82 } 

what better approach use inputmap , actionmap, think called "key binding" (as suggested madprogrammer). input map maps key stroke action name, , action map maps action name action want take.

replace line (and whole keylistener extended class)

this.addkeylistener(new mykeylistener()); 

with like

this.getinputmap().put(keystroke.getkeystroke("control l"), "link"); 

where need refer documentation of keystroke.getkeystroke modify specified key stroke needs. in example "link" name of action taken when ctrl+l pressed. need specify "link does"

this.getactionmap().put("link", new linkaction()); 

where linkaction class extending abstractaction in case should includes methods such levelreaderobject.setcurrentlevel(presentlevel);.

note don't need create action every key. movement (up, down, left, right) bind of movement buttons different action names ("move up" etc.), map action names same action , let methods inside action work:

this.getactionmap().put("move up", new moveaction(0)); this.getactionmap().put("move down", new moveaction(1)); this.getactionmap().put("move right", new moveaction(2)); this.getactionmap().put("move left", new moveaction(3)); 

with

class moveaction extends abstractaction {      int direction;      public moveaction (int direction) {          this.direction = direction;     }      @override     public void actionperformed(actionevent e) {          switch(direction) // perform action according direction     } } 

please note suggestion grouping movement actions design decision , should decide how structure bindings (you use 1 action or 1 action each).


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -