CodeWalrus

Development => PC, Mac & Vintage Computers => Topic started by: kotu on November 01, 2016, 07:45:22 AM

Title: Simple key stuff in java [java] [tutorial]
Post by: kotu on November 01, 2016, 07:45:22 AM
This topic was suggested by @p2 and focusses on getting keypress events in java.
It also features some tile rendering code which I made previously.
It features a little walrii, who you can walk around a map.
Also pressing space will change the terrain.

Here is the code.... hopefully it will explain itself.... if not then just ask what you want explaining!

Many thanks

Here is the source code....... the first file contains all the keypress stuff, the second two files are the tile rendering stuff. Feel free to use both if you want

TileTestApp.java
package tiletest;

import javax.swing.JFrame;
import tiletest.TileArea;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class TileTestApp implements KeyListener
{
private int m_walriix = 280, m_walriiy = 180;
private boolean m_keyDown = false;
private boolean m_keyUp = false;
private boolean m_keyLeft = false;
private boolean m_keyRight = false;
private int m_bgTile = 0;

public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
m_bgTile++;
if (m_bgTile > 7) {
m_bgTile = 0;
}
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) m_keyLeft = true;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) m_keyRight = true;
else if (e.getKeyCode() == KeyEvent.VK_UP) m_keyUp = true;
else if (e.getKeyCode() == KeyEvent.VK_DOWN) m_keyDown = true;
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) m_keyLeft = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) m_keyRight = false;
else if (e.getKeyCode() == KeyEvent.VK_UP) m_keyUp = false;
else if (e.getKeyCode() == KeyEvent.VK_DOWN) m_keyDown = false;
}
public void keyTyped(KeyEvent e)
{
}

TileTestApp()
{
JFrame frame = new JFrame("kotu java demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// add TileArea to the JFrame here
TileArea tileArea = new TileArea(600, 408);
frame.add("Center", tileArea);
frame.pack();
    frame.setVisible(true);
    frame.addKeyListener(this);

// load tileset
TileSource tiles = new TileSource("all-3.png", 24);

//----
for (;;)
{
if (m_keyRight) m_walriix += 4;
if (m_keyLeft) m_walriix -= 4;
if (m_keyUp) m_walriiy -= 4;
if (m_keyDown) m_walriiy += 4;

for (int x = 0; x < 25; x++) {
for (int y = 0; y < 17; y++) {
tileArea.drawTile(tiles, m_bgTile, 3, tiles.getTileSize()*x, tiles.getTileSize()*y);
}
}

tileArea.drawTile(tiles,  2,  1, m_walriix, m_walriiy);

frame.repaint();

try { // wait 10ms to avoid any flicker
    Thread.sleep(10);
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
}

}

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


TileArea.java
package tiletest;

import java.awt.*;
import java.awt.image.*;

public class TileArea extends Component
{
private static final long serialVersionUID = 1L;
private BufferedImage m_image;
private int m_width, m_height;

public TileArea(int width, int height)
{
m_width = width;
m_height = height;
m_image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}

public Dimension getPreferredSize()
{
        return new Dimension(m_width, m_height);
    }

public void paint(Graphics g)
{
g.drawImage(m_image, 0, 0, null);
}

public void drawTile(TileSource tileSource, int tilex, int tiley, int x, int y)
{
Graphics2D g = m_image.createGraphics();
    g.drawImage(tileSource.getTile(tilex, tiley), x, y, null);
}
}


TileSource.java
package tiletest;

import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;

public class TileSource extends Component
{
private static final long serialVersionUID = 1L;
private BufferedImage m_tiles;
private int m_tileSize;

public TileSource(String filename, int tileSize)
{
m_tileSize = tileSize;
try {
m_tiles = ImageIO.read(new File(filename));
}
catch (IOException e) { // no need to do anything here
} // m_tiles will be null anyway

if (m_tiles == null) {
JOptionPane.showMessageDialog(null, "p2, no! could not load tileset.");
return;
}
}

public int getTileSize()
{
return m_tileSize;
}

public BufferedImage getTile(int tilex, int tiley)
{
if (m_tiles == null) {
return null;
}
return m_tiles.getSubimage(tilex*(m_tileSize+1)+1, tiley*(m_tileSize+1)+1, m_tileSize, m_tileSize);
}
}


You will also need to include this image in your project (from p2's game)
(https://s21.postimg.org/jxaa7fvpz/all_3.png)

Title: Re: Simple key stuff in java [java] [tutorial]
Post by: kotu on November 01, 2016, 09:39:55 AM
https://www.youtube.com/watch?v=_x6N6_1-0TA

me and p2 are using eclipse Mars
Title: Re: Simple key stuff in java
Post by: Dream of Omnimaga on November 02, 2016, 02:26:20 AM
You should make the Walrii so that he is animated when walking and facing all directions. :)
Title: Re: Simple key stuff in java [java] [tutorial]
Post by: kotu on November 02, 2016, 03:07:27 AM
ahh

that's p2's job

im only the technical assist!
Title: Re: Simple key stuff in java
Post by: Scipi on November 02, 2016, 10:44:55 PM
Tbh, I really dislike how Java handles it's inputs. Asynchronous input handling means that program state could change at any point in the frame unpredictably.

Also, granted this is supposed to be a simple implementation, it won't work very well when gui's are thrown into the mix (because gui's should get priority handling of events and should be able to "consume" them to stop the event from propagating). I mention this only because it's the exact issue that stopped my progress on Walriimon ;)

I've been trying to find the time to put together a small demo of this for a while now, actually.
Title: Re: Simple key stuff in java [java] [tutorial]
Post by: kotu on November 02, 2016, 11:25:35 PM
i've totally given up on java now due to its seeming inability to be able to handle arrays  ???

*edit*
working with java again, it was working  :D
Title: Re: Simple key stuff in java
Post by: c4ooo on November 02, 2016, 11:57:59 PM
Quote from: Scipi on November 02, 2016, 10:44:55 PM
Tbh, I really dislike how Java handles it's inputs. Asynchronous input handling means that program state could change at any point in the frame unpredictably.

Also, granted this is supposed to be a simple implementation, it won't work very well when gui's are thrown into the mix (because gui's should get priority handling of events and should be able to "consume" them to stop the event from propagating). I mention this only because it's the exact issue that stopped my progress on Walriimon ;)

I've been trying to find the time to put together a small demo of this for a while now, actually.
I don't see how. Just make the mouse moved event set an X and Y position var and make your game code check that. A graphical game should have nothing to do with GUIs / swing / awt.

Also, with LWJGL you can just get the mouse position as integers, no event handling required.
Title: Re: Simple key stuff in java [java] [tutorial]
Post by: p2 on November 03, 2016, 08:59:28 AM
for whatever reasons I couldnt implement the code @kotu

I added another class named KeyControls with the following code:
package CodeW;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class KeyControls implements KeyListener {
public static boolean m_keyDown = false;
public static boolean m_keyUp = false;
public static boolean m_keyLeft = false;
public static boolean m_keyRight = false;

public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT) {
System.out.println("LEFT ################################################################");
Player.move("left");
} else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
Player.move("right");
} else if(e.getKeyCode()==KeyEvent.VK_UP) {
Player.move("up");
} else if(e.getKeyCode()==KeyEvent.VK_DOWN) {
Player.move("up");
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) m_keyLeft = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) m_keyRight = false;
else if (e.getKeyCode() == KeyEvent.VK_UP) m_keyUp = false;
else if (e.getKeyCode() == KeyEvent.VK_DOWN) m_keyDown = false;
}
public void keyTyped(KeyEvent e)
{
}
}

How should I call this function in the main ?
anything I try results in an error as KeyEvent e isnt defined

I know the code so far makes not much sense but I'm only testing if its even triggered right now (the LEFT#### text)
Title: Re: Simple key stuff in java
Post by: Scipi on November 03, 2016, 03:31:36 PM
You don't call the KeyListener functions yourself, instead you register them with your canvas and they get called for you by the system when certain things happen.
Adding it looks something like this:

//...
frame.addKeyListener(keyControls);
//...