* WalrusIRC

You need to have 5 posts and not be part of restricted usergroups in order to use the WalrusIRC embedded shoutbox. However, you can also access our IRC channel called #CodeWalrus via EFnet.

Author Topic: Simple key stuff in java  (Read 658 times)

0 Members and 1 Guest are viewing this topic.

Online kotu

  • blank space here pls
  • Super User
  • Join Date: Aug 2016
  • Location: UK
  • Posts: 994
  • Post Rating Ratio: +7/-7
  • I read bytecode for cash
    • profile.php?id=100010378444176
    • dj_kotu
    • @UCAy2ZF4hbc08iStnTn6jgxQ
    • rowanmedhurst
    • @djkotu
    • @romanov-psyco
    • futurerave.uk
  • Gender: Male
Simple key stuff in java
« 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
Code: [Select]
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
Code: [Select]
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
Code: [Select]
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)


« Last Edit: November 01, 2016, 09:33:01 am by kotu »


  • Calculators owned: TI 84+CE-T
  • Consoles, mobile devices and vintage computers owned: Sega Master System, Sony PS3
mateo patio.

Online kotu

  • blank space here pls
  • Super User
  • Join Date: Aug 2016
  • Location: UK
  • Posts: 994
  • Post Rating Ratio: +7/-7
  • I read bytecode for cash
    • profile.php?id=100010378444176
    • dj_kotu
    • @UCAy2ZF4hbc08iStnTn6jgxQ
    • rowanmedhurst
    • @djkotu
    • @romanov-psyco
    • futurerave.uk
  • Gender: Male
Re: Simple key stuff in java
« Reply #1 on: November 01, 2016, 09:39:55 am »


me and p2 are using eclipse Mars
« Last Edit: November 01, 2016, 01:33:23 pm by kotu »
  • Calculators owned: TI 84+CE-T
  • Consoles, mobile devices and vintage computers owned: Sega Master System, Sony PS3
mateo patio.

Offline xlibman

  • Omni founder & CW co-founder
  • CodeWalrus Staff
  • Super User
  • Original 5
  • CodeWalrus Supporter
  • *
  • Join Date: Nov 2014
  • Location: Quebec, Canada
  • Posts: 18431
  • Post Rating Ratio: +93/-4
    • dj_omnimaga
    • DJOmnimaga.music
    • @DJOmnimaga
    • dj_omnimaga
    • @DJOmnimaga
    • /u/DJ_Omnimaga
    • DJOmnimaga
    • 112/11286
    • @djomnimaga
    • @DJOmnimaga
    • DJ Omnimaga music store
  • Gender: Male
Re: Simple key stuff in java
« Reply #2 on: November 02, 2016, 02:26:20 am »
You should make the Walrii so that he is animated when walking and facing all directions. :)
  • Calculators owned: TI-57, 73, TI-80 (broken), TI-81, TI-82, TI-83, TI-83+ (broken), TI-83+ (broken), TI-83+SE (broken), TI-84+, TI-84+CSE, TI-84+CE, TI-85, TI-86, TI-89T, TI-92, TI-Nspire, TI-Nspire CX (semi-broken), HP 39gII, HP Prime, Casio fx-7000G, fx-7400G+, fx-7700GE, fx-9750G+, fx-9750GII, fx-9860G, cfx-9850G, FX-1.0+, fx-CG10, fx-CP400
  • Consoles, mobile devices and vintage computers owned: Samsung i5510, Nexus 5, Atari 2600, Lynx, SMS, Game Gear, Genesis, Dreamcast, NES, SNES, N64, GCN, Wii, Wii U, GBA, DS, 3DS, PS2, PS3, PS4, PSP, PSVita, XBox 360, XBOne

Bandcamp|Reverbnation|Facebook|Youtube|Twitter
Retired Omnimaga admin (2001-11) and editor (2012-14)

Online kotu

  • blank space here pls
  • Super User
  • Join Date: Aug 2016
  • Location: UK
  • Posts: 994
  • Post Rating Ratio: +7/-7
  • I read bytecode for cash
    • profile.php?id=100010378444176
    • dj_kotu
    • @UCAy2ZF4hbc08iStnTn6jgxQ
    • rowanmedhurst
    • @djkotu
    • @romanov-psyco
    • futurerave.uk
  • Gender: Male
Re: Simple key stuff in java
« Reply #3 on: November 02, 2016, 03:07:27 am »
ahh

that's p2's job

im only the technical assist!
  • Calculators owned: TI 84+CE-T
  • Consoles, mobile devices and vintage computers owned: Sega Master System, Sony PS3
mateo patio.

Offline Scipi

  • Full User
  • Domain Name Owner
  • CW 4x3 challenge - 3rd place
  • *
  • Join Date: Nov 2014
  • Location: Lost Town
  • Posts: 164
  • Post Rating Ratio: +1/-0
  • CodeKitten ^w^
    • s1ay3r44
    • Scipii
    • _Scipi
    • Scipi
    • ScipiSoftware
  • Gender: Male
Re: Simple key stuff in java
« Reply #4 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.
  • Calculators owned: TI-83+, Nspire, Nspire CX, Casio Prizm




Online kotu

  • blank space here pls
  • Super User
  • Join Date: Aug 2016
  • Location: UK
  • Posts: 994
  • Post Rating Ratio: +7/-7
  • I read bytecode for cash
    • profile.php?id=100010378444176
    • dj_kotu
    • @UCAy2ZF4hbc08iStnTn6jgxQ
    • rowanmedhurst
    • @djkotu
    • @romanov-psyco
    • futurerave.uk
  • Gender: Male
Re: Simple key stuff in java
« Reply #5 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
« Last Edit: November 09, 2016, 03:57:48 am by kotu »
  • Calculators owned: TI 84+CE-T
  • Consoles, mobile devices and vintage computers owned: Sega Master System, Sony PS3
mateo patio.

Offline c4ooo

  • Super User
  • CW Contest II Winner
  • *
  • Join Date: Aug 2015
  • Location: 127.0.0.1
  • Posts: 945
  • Post Rating Ratio: +10/-2
  • Advanced forumer
  • Gender: Male
Re: Simple key stuff in java
« Reply #6 on: November 02, 2016, 11:57:59 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.

Offline p2

  • CodeWalrus Staff
  • Super User
  • Moderator
  • CodeWalrus Supporter
  • *
  • Join Date: Aug 2016
  • Location: Germany
  • Posts: 2259
  • Post Rating Ratio: +8/-0
  • *Wubba lubba dub dub*
    • KaliPhobos
  • Gender: Male
Re: Simple key stuff in java
« Reply #7 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:
Code: [Select]
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)
  • Calculators owned: ti-83+, ti-84+, ti-84+, ti-84+se, ti-84+se(te), ti-nsphire, ti-nsphire CX-CAS, ti-voyage, ti-voyage, Who reads this list anyways...?
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)

Offline Scipi

  • Full User
  • Domain Name Owner
  • CW 4x3 challenge - 3rd place
  • *
  • Join Date: Nov 2014
  • Location: Lost Town
  • Posts: 164
  • Post Rating Ratio: +1/-0
  • CodeKitten ^w^
    • s1ay3r44
    • Scipii
    • _Scipi
    • Scipi
    • ScipiSoftware
  • Gender: Male
Re: Simple key stuff in java
« Reply #8 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:

Code: [Select]
//...
frame.addKeyListener(keyControls);
//...
  • Calculators owned: TI-83+, Nspire, Nspire CX, Casio Prizm




 


You can also use the following HTML or bulletin board code to share it on your page or forum signature!


Also do not forget to check our affiliates below.
Planet Casio TI-Planet Calc.news BroniesQC BosaikNet Velocity Games