The shoutbox is currently out of service. Join us on Discord instead.
You can help CodeWalrus stay online by donating here.

Simple key stuff in java [java] [tutorial]

Started by kotu, November 01, 2016, 07:45:22 am

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

kotu

November 01, 2016, 07:45:22 am Last Edit: November 01, 2016, 09:33:01 am by kotu
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)


SUBSCRIBE TO THE FUTURERAVE.UK MAILING LIST
http://futurerave.uk

kotu

November 01, 2016, 09:39:55 am #1 Last Edit: November 01, 2016, 01:33:23 pm by kotu


me and p2 are using eclipse Mars
SUBSCRIBE TO THE FUTURERAVE.UK MAILING LIST
http://futurerave.uk

DJ Omnimaga

You should make the Walrii so that he is animated when walking and facing all directions. :)

kotu

ahh

that's p2's job

im only the technical assist!
SUBSCRIBE TO THE FUTURERAVE.UK MAILING LIST
http://futurerave.uk

Scipi

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.




kotu

November 02, 2016, 11:25:35 pm #5 Last Edit: November 09, 2016, 03:57:48 am by kotu
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
SUBSCRIBE TO THE FUTURERAVE.UK MAILING LIST
http://futurerave.uk

c4ooo

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.

p2

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)
Anyway war sucks. Just bring us your food instead of missiles  :P ~ DJ Omnimaga (11.10.2016 20:21:48)
if you cant get a jframe set up, draw stuff to it, and receive input, i can only imagine how horrible your game code is _._   ~ c4ooo (14.11.2016 22:44:07)
If they pull a Harambe on me tell my family I love them ~ u/Pwntear37d (AssangeWatch /r/)
make Walrii great again ~ DJ Omnimaga (28.11.2016 23:01:31)
God invented the pc, satan the smartphone I guess ~ p4nix (16.02.2017 22:51:49)

Scipi

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);
//...




Powered by EzPortal