Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (498)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Game Loop and Keyboard inut  (Read 932 times)
0 Members and 1 Guest are viewing this topic.
Offline ChUrP

Junior Newbie





« Posted 2007-10-01 16:53:17 »

Hey,

I have a problem with my keyboard event dispatchment. I thought Thread.yield() would be enough to give the keyboard time to react but I thought wrong. Is it possible to give the eventhread/ eventlistener ( not sure what it's called) more time?
Without my loop the keyboard work great.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
package net.tangledcode.mtm_game.game;

import java.awt.AWTEvent;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

import net.tangledcode.mtm_game.entities.Player;

public class Game {
   private static boolean[] keys = new boolean[1024];
   
   private JFrame frame;
   private Canvas canvas;
   private BufferStrategy buffer;
   private BufferedImage bi;
   
   private GraphicsEnvironment ge;
   private GraphicsDevice gd;
   private GraphicsConfiguration gc;
   
   public Game(JFrame frame) {
      this.frame = frame;
      this.frame.getContentPane().removeAll();
      this.frame.update(this.frame.getGraphics());
      this.frame.setIgnoreRepaint(true);
     
      this.canvas = new Canvas();
      this.canvas.setIgnoreRepaint(true);
      this.canvas.setBounds(0, 0, 1200, 800);

      this.frame.add(this.canvas);
      this.frame.pack();
      this.frame.setVisible(true);
     
      this.canvas.createBufferStrategy(2);
      this.buffer = this.canvas.getBufferStrategy();
     
      this.ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      this.gd = this.ge.getDefaultScreenDevice();
      this.gc = this.gd.getDefaultConfiguration();
     
      this.bi = this.gc.createCompatibleImage(1200, 800);
     
      this.canvas.requestFocus();
      Keyboard.init();
   }
   
   public void start() {
      Graphics graphics = null;
       Graphics2D g2d = null;
       Color background = Color.BLACK;
         
       int fps = 0;
       int frames = 0;
       long totalTime = 0;
       long timeDiff = 0;
       long currentTime = System.currentTimeMillis();
       long lastTime = currentTime;
       
       Player player = new Player("../data/images/ships/player_01.png", 600, 400);
       
      while(true) {
         try {
            lastTime = currentTime;
              currentTime = System.currentTimeMillis();
              timeDiff = currentTime - lastTime;
              totalTime += currentTime - lastTime;
            if(totalTime > 1000) {
               totalTime -= 1000;
               fps = frames;
               frames = 0;
            }
              ++frames;
             
              g2d = this.bi.createGraphics();
              g2d.setColor(background);
              g2d.fillRect(0, 0, 1200, 800);
             
              // draw Stuff here
             player.draw(g2d);
                 
              player.doLogic(timeDiff);
              player.doMovement(timeDiff); // checks if keys are pressed
             
              g2d.setFont( new Font( "Helvetica", Font.PLAIN, 14 ) );
              g2d.setColor( Color.GREEN );
              g2d.drawString( String.format( "FPS: %s", fps ), 20, 20 );
           
              graphics = this.buffer.getDrawGraphics();
              graphics.drawImage(this.bi, 0, 0, null );
              if(!this.buffer.contentsLost()) {
                 this.buffer.show();
              }
             
         } finally {
            if(graphics != null) {
               graphics.dispose();
            }
            if(g2d != null) {
               g2d.dispose();
            }
         }
      }
   }
}


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
package net.tangledcode.mtm_game.game;

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Keyboard {
   private static boolean[] keys = new boolean[1024];

   public static void init() {
      Toolkit.getDefaultToolkit().addAWTEventListener(new KeyHandler(), AWTEvent.KEY_EVENT_MASK);        
   }

   public static void init(Component comp) {
      comp.addKeyListener(new KeyHandler());        
   }

   public static boolean isPressed(int key) {
      return Keyboard.keys[key];
   }

   public static void setPressed(int key,boolean pressed) {
      Keyboard.keys[key] = pressed;
   }

   private static class KeyHandler extends KeyAdapter implements AWTEventListener {
      public void keyPressed(KeyEvent e) {
          if (e.isConsumed()) {
            return;
         }
         Keyboard.keys[e.getKeyCode()] = true;
      }

      public void keyReleased(KeyEvent e) {
         if (e.isConsumed()) {
            return;
         }

         KeyEvent nextPress = (KeyEvent) Toolkit.getDefaultToolkit().getSystemEventQueue().peekEvent(KeyEvent.KEY_PRESSED);

         if ((nextPress == null) || (nextPress.getWhen() != e.getWhen())) {
            Keyboard.keys[e.getKeyCode()] = false;
         }

      }

      public void eventDispatched(AWTEvent e) {
         System.out.println("event dispatched");
         if (e.getID() == KeyEvent.KEY_PRESSED) {
            keyPressed((KeyEvent) e);
         }
         if (e.getID() == KeyEvent.KEY_RELEASED) {
            keyReleased((KeyEvent) e);
         }
      }
   }
}
Offline fletchergames

Senior Member





« Reply #1 - Posted 2007-10-01 17:47:12 »

Thread.yield() should be enough, but it doesn't actually appear anywhere in your code.

I think all the painting should be on the Awt Event Thread, not on the main thread.

Are you sure that the "start" method is being called on the main thread, not the Awt Event Thread?  It doesn't get called in the code you posted.  If the start method is called as the result of pressing a button somewhere, it's probably on the Awt Event Thread.  If it's on the Awt Event Thread, it would prevent any other code on the Awt Event Thread from running because it runs forever once called.

Also, the keyboard handler itself sort of surprises me.  Usually, keyboard handlers store whether the key WAS pressed (i.e. was released), as well as whether it IS pressed.  But if this works for you, that's fine.
Offline ChUrP

Junior Newbie





« Reply #2 - Posted 2007-10-01 18:14:29 »

I'm starting the game through a button click. So, I know now where to look now, thanks.

I haven't thought of implementing the function to save if a key was pressed. I will have a look at that, thanks again.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline broumbroum

Junior Member





« Reply #3 - Posted 2007-10-01 23:08:15 »

your keyboard might be faster if it implemented the KeyEventDispatcher interface, thereby it can be used on some KeyBoardFocusManager. Wink

::::... :..... :::::: ;;;:::™ b23:production 2006 GNU/GPL @ http://b23prodtm.webhop.info
on sf.net: /projects/sf3jswing
Java (1.6u10 plz) Web Start pool
dev' VODcast[/ur
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

BurntPizza (19 views)
2014-09-20 17:42:18

BurntPizza (14 views)
2014-09-20 16:30:30

moogie (14 views)
2014-09-20 15:26:15

UprightPath (25 views)
2014-09-20 11:14:06

BurntPizza (27 views)
2014-09-18 18:14:18

Dwinin (40 views)
2014-09-12 00:08:26

Norakomi (73 views)
2014-09-10 04:57:51

TehJavaDev (96 views)
2014-09-09 21:39:09

Tekkerue (49 views)
2014-09-08 17:24:56

mitcheeb (70 views)
2014-09-07 21:06:29
List of Learning Resources
by Longor1996
2014-08-16 01:40:00

List of Learning Resources
by SilverTiger
2014-08-05 10:33:27

Resources for WIP games
by CogWheelz
2014-08-01 07:20:17

Resources for WIP games
by CogWheelz
2014-08-01 07:19:50

List of Learning Resources
by SilverTiger
2014-07-31 07:29:50

List of Learning Resources
by SilverTiger
2014-07-31 07:26:06

List of Learning Resources
by SilverTiger
2014-07-31 02:54:12

HotSpot Options
by dleskov
2014-07-07 16:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!