can you see the problem. the thread runs fine but the brick does not want to respond to the key listener. I try to test if the keylistener was at last getting an event but it does not even do the system.out.println
import java.awt.*;//imports
import java.util.*;
import java.applet.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class Start extends Applet implements Runnable, KeyListener// where i put the keylistener in
{
DrawBackground dbg = new DrawBackground();
Brick brick = new Brick();
Thread gameLoop;
public void init() {
addKeyListener(this);// i add the key listener
}
public void start() {
Thread gameLoop = new Thread(this);
gameLoop.start();
}
public void run() {
while (true) {
brick.update(1);
repaint();
try {
Thread.sleep(17);
}
catch (InterruptedException e) {
}
}
}
public void stop() {
}
public void paint(Graphics g)// with out any paint it works if im changing
// somthing like a lable
{
dbg.paint(g, this);
brick.paint(g, this);
}
public void keyPressed(KeyEvent e)// test to see if it works
{
System.out.println("why");
if (e.getKeyCode() == 37) {
brick.left();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
this is the Brick class the thing i'm trying to move
import java.awt.*;
import java.util.*;
import java.applet.*;
public class Brick {
public int dy = 40;
public int yStart = -20;
public int time = 0;
public int dx = 0;
public int xStart = 0;
public int start = 1;
public void paint(Graphics g, Start sp) {
Dimension screenSize = sp.getSize();
int sheight = screenSize.height;
int swidth = screenSize.width;
if (start == 1) {
xStart = swidth - (int) (swidth / 2.5);
start = 0;
}
int bWidth = swidth / 15;
int bHeight = swidth / 15;
int time = 0;
g.setColor(Color.red);
g.fillRect(xStart, yStart, bWidth, bHeight);
}
public void update(int x) {
if (time == 60) {
time = 0;
yStart += dy;
}
else {
time += x;
}
}
public void left() {
xStart -= dx;
}
}
It doesn't look like you have set the keyboard focus. See this question.
I've always used setFocusable(true) after adding the keyListener and its worked for me, but the answer to that question has a better solution.
Related
I am working on a donkey kong type game and like I said I want the player to only jump if he is on the floor.
I made a sort of a gravity mechanic and I check collision so he don't go through a floor and I came up with an idea that your can jump only when you are colliding. But here comes the main problem that I don't know how to tell that information to a method in another class.
Hope it makes some sense, I am a beginner and don't know if I described the problem well.
I tried to separate my code but it makes more problems
Here's a class with a player:
import java.awt.*;
import java.awt.event.KeyEvent;
public class Mario extends Rectangle {
int rychlost = 5;
int xZrychleni;
int gravitace= 5;
int yZrychleni;
int vyskok = 20;
Mario(int x, int y, int SIRKA_MARIA,int VYSKA_MARIA){
super(x, y, SIRKA_MARIA, VYSKA_MARIA);
}
public void nakresli(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, y, width, height);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_A) {
nastavSmerX(-rychlost);
}
if(e.getKeyCode()== KeyEvent.VK_D) {
nastavSmerX(rychlost);
}
if(e.getKeyCode()==KeyEvent.VK_SPACE){
nastavSmerY(vyskok);
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_A) {
nastavSmerX(0);
}
if (e.getKeyCode() == KeyEvent.VK_D) {
nastavSmerX(0);
}
if(e.getKeyCode()==KeyEvent.VK_SPACE){
nastavSmerY(0);
}
}
public void nastavSmerX ( int SmerX){
xZrychleni = SmerX;
}
public void nastavSmerY ( int SmerY){
yZrychleni = SmerY;
}
public void move () {
x = x + xZrychleni;
y = y + gravitace;
y = y - yZrychleni;
}
}
Here is a panel class where I check collisions:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HerniPanel extends JPanel implements Runnable{
static final int HERNI_SIRKA = 1200;
static final int HERNI_VYSKA = 700;
static final Dimension SCREEN_SIZE = new Dimension(HERNI_SIRKA, HERNI_VYSKA);
static final int SIRKA_PLOSINY = 1000;
static final int VYSKA_PLOSINY = 35;
static final int SIRKA_ZEBRIKU = 25;
static final int VYSKA_ZEBRIKU = 180;
static final int MARIO_VELIKOST_XY = 50;
Thread gameThread;
Image image;
Graphics graphics;
Plosina plosina0;
Plosina plosina1;
Plosina plosina2;
Plosina plosina3;
Mario mario;
Zebrik zebrik1;
Zebrik zebrik2;
Zebrik zebrik3;
HerniPanel(){
novaPlosina();
novyMario();
novyZebrik();
this.setFocusable(true);
this.addKeyListener(new AL());
this.setPreferredSize(SCREEN_SIZE);
gameThread = new Thread(this);
gameThread.start();
}
public void novaPlosina() {
plosina0 = new Plosina(0, (HERNI_VYSKA - VYSKA_PLOSINY), HERNI_SIRKA, VYSKA_PLOSINY, 1);
plosina1 = new Plosina((HERNI_SIRKA - SIRKA_PLOSINY),(HERNI_VYSKA - VYSKA_PLOSINY - 180), SIRKA_PLOSINY, VYSKA_PLOSINY, 2 );
plosina2 = new Plosina(0, (HERNI_VYSKA - VYSKA_PLOSINY - 360), SIRKA_PLOSINY, VYSKA_PLOSINY,3 );
plosina3 = new Plosina((HERNI_SIRKA - SIRKA_PLOSINY), (HERNI_VYSKA - VYSKA_PLOSINY - 540), HERNI_SIRKA, VYSKA_PLOSINY,4);
}
public void novyMario(){
mario= new Mario(1000, (HERNI_VYSKA - VYSKA_PLOSINY - MARIO_VELIKOST_XY), MARIO_VELIKOST_XY , MARIO_VELIKOST_XY );
}
public void novyZebrik(){
zebrik1 = new Zebrik(250, (HERNI_VYSKA-VYSKA_PLOSINY-VYSKA_ZEBRIKU),SIRKA_ZEBRIKU,VYSKA_ZEBRIKU);
zebrik2 = new Zebrik(800, (HERNI_VYSKA-VYSKA_PLOSINY-VYSKA_ZEBRIKU-180),SIRKA_ZEBRIKU,VYSKA_ZEBRIKU);
zebrik3 = new Zebrik(300, (HERNI_VYSKA-360-VYSKA_PLOSINY-VYSKA_ZEBRIKU),SIRKA_ZEBRIKU,VYSKA_ZEBRIKU);
}
public void paint(Graphics g) {
image = createImage(getWidth(),getHeight());
graphics = image.getGraphics();
nakresli(graphics);
g.drawImage(image,0,0,this);
}
public void nakresli(Graphics g) {
plosina0.nakresli(g);
plosina1.nakresli(g);
plosina2.nakresli(g);
plosina3.nakresli(g);
mario.nakresli(g);
zebrik1.nakresli(g);
zebrik2.nakresli(g);
zebrik3.nakresli(g);
Toolkit.getDefaultToolkit().sync();
}
public void move() {
mario.move();
}
public void zkontrolujKolizi() {
if(mario.x<=0)
mario.x=0;
if(mario.x >= (HERNI_SIRKA-MARIO_VELIKOST_XY))
mario.x = HERNI_SIRKA-MARIO_VELIKOST_XY;
if (mario.y >= (HERNI_VYSKA-VYSKA_PLOSINY - MARIO_VELIKOST_XY)) {
mario.y = (HERNI_VYSKA - VYSKA_PLOSINY - MARIO_VELIKOST_XY);
}
if(mario.intersects(plosina1)){
mario.y = (HERNI_VYSKA-VYSKA_PLOSINY-MARIO_VELIKOST_XY-180);
}
if(mario.intersects(plosina2)){
mario.y = (HERNI_VYSKA-VYSKA_PLOSINY-MARIO_VELIKOST_XY-360);
}
if(mario.intersects(plosina3)){
mario.y = (HERNI_VYSKA-VYSKA_PLOSINY-MARIO_VELIKOST_XY-540);
}
}
public void run() {
//game loop
long lastTime = System.nanoTime();
double amountOfTicks =60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(true) {
long now = System.nanoTime();
delta += (now -lastTime)/ns;
lastTime = now;
if(delta >=1) {
move();
zkontrolujKolizi();
repaint();
delta--;
}
}
}
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e) {
mario.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
mario.keyReleased(e);
}
}
}
I want it so when my player goes off the platform, (in checkCollision() method PlatformerPanel class) it will fall and then do something when gone off the screen, i haven't set up an end game screen yet but that's what I'm planning to do. Anyway, the problem is that it goes way too fast for some reason and falls too early, and also when an arrow key is pressed while its falling it will go back up to the platform.
Please try to help me overcome this or think of a new, easy to understand, way to do this/make this work the way i am planning.
EDIT 1:
I fixed the thing where it falls too early so don't worry about that
```
public class PlatformerMain {
public static void main(String[] args) {
PlatformerGameFrame platformerGame = new PlatformerGameFrame();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerGameFrame extends JFrame{
PlatformerGamePanel panel;
PlatformerGameFrame() {
panel = new PlatformerGamePanel();
this.add(panel);
this.setTitle("Platformer Game");
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
this.getContentPane().setBackground(new Color(0,0,0));
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerGamePanel extends JPanel implements Runnable{
PlatformerPlayer player1;
PlatformerMap map1;
static final int SCREEN_WIDTH = 1000;
static final int SCREEN_HEIGHT = 600;
static final int PLAYER_WIDTH = 50;
static final int PLAYER_HEIGHT = 60;
static final Dimension SCREEN_SIZE = new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT);
static boolean falling = false;
Image backgroundImage;
Thread gameThread;
Image image;
Graphics graphics;
PlatformerMap map;
public PlatformerGamePanel() {
java.net.URL imgIcon = Main.class.getResource(
"/Resources/spaceImage.jpg");
backgroundImage = new ImageIcon(imgIcon).getImage();
newPlayer();
newMap();
this.setFocusable(true);
this.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
player1.KeyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
player1.KeyReleased(e);
}
});
this.setPreferredSize(SCREEN_SIZE);
this.setOpaque(true);
gameThread = new Thread(this);
gameThread.start();
}
public void paint(Graphics g) {
image = createImage(getWidth(),getHeight());
graphics = image.getGraphics();
draw(graphics);
g.drawImage(image, 0,0, null);
}
public void draw(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(backgroundImage, 0,0, null);
player1.paint(g);
map.paint(g);
}
public void newPlayer() {
player1 = new PlatformerPlayer((SCREEN_WIDTH/2)-(PLAYER_WIDTH/2), (SCREEN_HEIGHT/2)-(PLAYER_WIDTH/2), PLAYER_WIDTH, PLAYER_HEIGHT);
}
public void newMap() {
map = new PlatformerMap();
}
public void checkCollision() {
if(player1.x > SCREEN_WIDTH-PLAYER_WIDTH) {
player1.x = SCREEN_WIDTH-PLAYER_WIDTH;
}
else if(player1.x < 0) {
player1.x = 0;
}
if(!(player1.x >map.PLATFORM_WIDTH)) {
if(player1.y > SCREEN_HEIGHT-250) {
player1.y = SCREEN_HEIGHT-250;
}
} else if(player1.x > map.PLATFORM_WIDTH) {
gravity();
}
}
public void falling() {
}
public void gravity() {
player1.gravity();
}
public void move() {
player1.move();
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 120.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(true) {
long now = System.nanoTime();
delta += (now - lastTime)/ns;
lastTime = now;
if(delta >= 1) {
move();
checkCollision();
gravity();
repaint();
delta--;
}
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerPlayer extends Rectangle {
/*static int playerPosX = 100;
static int playerPosY = 100;*/
static double velocityY = 0;
static double velocityX = 0;
static int vertical_position;
static final int TERMINAL_VELOCITY = 200;
static final int PLAYER_WIDTH = 50;
static final int PLAYER_HEIGHT = 50;
static int speed = 2;
protected boolean falling = true;
protected boolean jumping = false;
double gravity = 0.05;
public PlatformerPlayer(int x, int y, int PLAYERWIDTH, int PLAYERHEIGHT) {
super(x,y,PLAYERWIDTH,PLAYERHEIGHT);
}
public void KeyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT) {
setXDirection(-speed);
move();
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
setXDirection(speed);
move();
}
}
public void KeyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT) {
setXDirection(0);
move();
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
setXDirection(0);
move();
}
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.red);
g2D.fillRect(x, y, PLAYER_WIDTH, PLAYER_HEIGHT);
}
public void setYDirection(int YDirection) {
velocityY = YDirection;
}
public void setXDirection(int XDirection) {
if(speed > 10) {
speed = 10;
}
velocityX = XDirection;
}
public void move() {
y += velocityY;
x += velocityX;
}
public void gravity() {
velocityY += gravity;
if (velocityY > TERMINAL_VELOCITY)
{
velocityY = TERMINAL_VELOCITY;
}
vertical_position -= velocityY;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerMap extends Rectangle {
int PLATFORM_WIDTH = 600;
int PLATFORM_HEIGHT = 150;
public PlatformerMap() {
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.gray);
g2D.fillRect(100,400,PLATFORM_WIDTH,PLATFORM_HEIGHT);
}
}
This question already has answers here:
How to use Key Bindings instead of Key Listeners
(4 answers)
Closed 5 years ago.
When VK_UP or VK_DOWN is pressed the Graphic g I created is not changing its position whatsoever. If someone could look and see if there is something wrong with my move method etc. Would really appreciate it.
Here is all my code so far:
package ping2;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Ping2 extends Applet implements Runnable, KeyListener{
final int WIDTH = 700, HEIGHT = 500;
Thread thread;
UserPaddle user1;
public void init() {
this.resize(WIDTH, HEIGHT);
this.addKeyListener(this);
user1 = new UserPaddle(1);
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
user1.draw(g);
}
public void update(Graphics g) {
paint(g);
}
public void run() {
for(;;) {
user1.move();
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(true);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(true);
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(false);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(false);
}
}
public void keyTyped(KeyEvent arg0) {
}
}
package ping2;
import java.awt.*;
public class UserPaddle implements InterfaceBar{
double y, yVelocity;
boolean upAccel, downAccel;
int player1, x;
final double FRICTION = 0.90;
public UserPaddle(int player1) {
upAccel = false;
downAccel = false;
y = 210;
yVelocity = 0;
if(player1 == 1)
x = 20;
else
x = 660;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, (int)y, 20, 80);
}
public void move() {
if(upAccel) {
yVelocity -= 2;
}else if(downAccel) {
yVelocity += 2;
}
//Automatically slows bar down if key not being pressed.
else if(!upAccel && !downAccel) {
yVelocity *= FRICTION;
}
}
public void setUpAccel(boolean input) {
upAccel = input;
}
public void setDownAccel(boolean input) {
downAccel = input;
}
public int getY() {
return (int)y;
}
}
package ping2;
import java.awt.Graphics;
public interface InterfaceBar {
public void draw(Graphics g);
public void move();
public int getY();
}
I have modified your move() a bit give it a try
move()
public void move() {
if(upAccel) {
yVelocity -= 2;
y = yVelocity;
}else if(downAccel) {
yVelocity += 2;
y = yVelocity;
}
}
I put in a particle system but when i run the program, when I spawn some particles, they don't render. I looked at the ArrayList and its value would always be 0 even when i added a particle to it.
heres the code for main class:
package Main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import me.mango.rendering.Particle;
//do double buffering
public class Game extends JPanel {
private static final long serialVersionUID = 1L;
public static final int height = 400;
public static final int width = height * 16 / 9;
JPanel p;
Game game;
Graphics g;
JFrame frame;
KeyListener kl;
MouseListener ml;
public boolean running = true;
private ArrayList<Particle> particles = new ArrayList<Particle>(500);
public Game(){
kl = new KeyListener(){
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
};
ml = new MouseListener(){
public void mousePressed(MouseEvent e) {
addParticle(true);addParticle(false);addParticle(true);
addParticle(false);addParticle(true);addParticle(false);
}
public void mouseReleased(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
};
}
public void addParticle(boolean b){
int dx,dy;
int x = 100;
int y = 100;
if(b){
dx = (int) (Math.random()*5);
dy = (int) (Math.random()*5);
}else{
dx = (int) (Math.random()*-5);
dy = (int) (Math.random()*-5);
}
int size = (int) (Math.random()*12);
int life = (int) Math.random()*(120)+380;
particles.add(new Particle(x,y,dx,dy,size,life,Color.blue));
}
public void update(double delta){
for(int i = 0; i<= particles.size() - 1;i++){
if(particles.get(i).update()) particles.remove(i);
}
System.out.println(particles.size());
}
#Override
public void paint(Graphics g){
g.clearRect(0, 0, getWidth(), getHeight());
//render here
renderParticles(g);
g.dispose();
}
public void renderParticles(Graphics g){
for(int i =0;i <= particles.size() - 1;i++){
particles.get(i).render(g);
System.out.println("spawned");
}
}
public void run(){
//initialize time loop variables
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
double lastFpsTime = 0;
//Main game loop
while(running)
{
//Calculate since last update
long now = System.nanoTime();
long updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ((double)OPTIMAL_TIME);
//update frame counter
lastFpsTime += updateLength;
//update FPS counter
if(lastFpsTime >= 1000000000)
{
lastFpsTime = 0;
}
//game updates
game.update(delta);
//graphics (gameState)
game.repaint();
try{
Thread.sleep((Math.abs(lastLoopTime - System.nanoTime() + OPTIMAL_TIME)/1000000));
}catch(Exception e){
System.out.println("Error in sleep");
}
}
}
public void start(){
frame = new JFrame("Game");
game = new Game();
frame.add(game);
frame.pack();
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.addKeyListener(kl);
frame.addMouseListener(ml);
frame.setVisible(true);
run();
}
public static void main(String[] args){
new Game().start();
}
}
and for the particle class:
package me.mango.rendering;
import java.awt.Color;
import java.awt.Graphics;
public class Particle {
private int x;
private int y;
private int dx;
private int dy;
private int size;
private int life;
private Color color;
public Particle(int x, int y, int dx, int dy, int size, int life, Color c){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.size = size;
this.life = life;
this.color = c;
}
public boolean update(){
x += dx;
y += dy;
life--;
if(life <= 0){
return true;
}
return false;
}
public void render(Graphics g){
g.setColor(color);
g.fillRect(x-(size/2), y-(size/2), size, size);
g.dispose();
}
}
Thanks!
You have a thing called game inside the class Game: that's not good design at all. Apparently you dont understand the meaning of creating an object.
In main() you created an object game: that should be enough. That thing you have to manipulate.
Therefore calling game.something() inside the class game is a convolution. Get rid of it.
game = new Game();
Game game;
These things must go.
And any reference to game.someMethod()
should be replaced with just someMethod(), if you are inside Game.
Plus you have things like run() and start() etc: do you think you are creating some threads?? by just using those names for your methods?
No.
I am supposed to make a little game simulation. in this game there are three button . when user click start tank and car will close each other in 90 degrees when user click shut button tank will throw bullet to car.
i made and a simulation for this. tank throw bullet to car but when bullet crash car i couldn't this. i just need increase score of how many times tank hit car.
here is the source code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Vehicle extends Thread {
private JPanel box;
private int XSIZE;
private int YSIZE;
private int time;
private int x;
private int y;
private int dx = 5;
private int dy = 5;
private int dim;
public Vehicle(JPanel b, int i) {
box = b;
this.dim = i;
if (i == 0) {
x = 0;
y = 100;
time = 1000;
XSIZE = 9;
YSIZE = 20;
} else {
time = 200;
y = box.getSize().height;
x = box.getSize().width / 2;
XSIZE = 6;
YSIZE = 10;
}
}
public void draw() {
Graphics g = box.getGraphics();
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose();
}
public void moveHorizontal() {
if (!box.isVisible())
return;
Graphics g = box.getGraphics();
g.setColor(Color.BLUE);
g.setXORMode(box.getBackground());
g.fillOval(x, y, XSIZE, YSIZE);
x += dx;
Dimension d = box.getSize();
if (x < 0) {
x = 0;
dx = -dx;
}
if (x + XSIZE >= d.width) {
x = d.width - XSIZE;
dx = -dx;
}
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose();
}
public JPanel getBox() {
return box;
}
public void setBox(JPanel box) {
this.box = box;
}
public void moveVertical() {
if (!box.isVisible())
return;
Graphics g = box.getGraphics();
g.setXORMode(box.getBackground());
g.fillOval(x, y, XSIZE, YSIZE);
y += dy;
Dimension d = box.getSize();
if (y < 0) {
y = 0;
dy = -dy;
}
if (y + YSIZE >= d.height) {
y = d.height - YSIZE;
dy = -dy;
}
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose();
}
public void move(int i) {
if (i == 0) {
moveHorizontal();
} else {
moveVertical();
}
}
public int getYSIZE() {
return YSIZE;
}
public void setYSIZE(int ySIZE) {
YSIZE = ySIZE;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public int getXSIZE() {
return XSIZE;
}
public void setXSIZE(int xSIZE) {
XSIZE = xSIZE;
}
public void setY(int y) {
this.y = y;
}
public void run() {
try {
draw();
for (;;) {
move(dim);
sleep(time);
}
} catch (InterruptedException e) {
}
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Bullet extends Thread {
private JPanel box;
private int XSIZE = 3;
public int getXSIZE() {
return XSIZE;
}
public void setXSIZE(int xSIZE) {
XSIZE = xSIZE;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
private int YSIZE = 1;
private int x;
private int y;
private int dx = 3;
public Bullet(JPanel b, Vehicle tank, Vehicle car) {
box = b;
x = tank.getX() + tank.getXSIZE();
if (x >= tank.getBox().getSize().width / 2)
dx = -dx;
y = tank.getY() + tank.getYSIZE() / 2;
;
}
public void draw() {
Graphics g = box.getGraphics();
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose();
}
public void move() {
if (!box.isVisible())
return;
Graphics g = box.getGraphics();
g.setColor(Color.RED);
g.setXORMode(box.getBackground());
g.fillOval(x, y, XSIZE, YSIZE);
x += dx;
Dimension d = box.getSize();
if (x < 0) {
x = 0;
}
if (x + XSIZE >= d.width) {
x = d.width - XSIZE;
}
g.fillOval(x, y, XSIZE, YSIZE);
g.dispose();
}
public void run() {
try {
draw();
for (;;) {
move();
sleep(20);
}
} catch (InterruptedException e) {
}
}
}
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
#SuppressWarnings("serial")
public class Tank_Shut_Car_ThreadFrame extends JFrame {
private JPanel canvas;
private boolean isOn = false;
private Vehicle tank;
private Vehicle car;
private JLabel score;
public static int sc = 0;
public Tank_Shut_Car_ThreadFrame() {
setResizable(false);
setSize(600, 400);
setTitle("Tank Shut Car");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = getContentPane();
canvas = new JPanel();
contentPane.add(canvas, "Center");
canvas.setLayout(null);
score = new JLabel("0");
score.setBounds(527, 11, 36, 14);
canvas.add(score);
JLabel lblScore = new JLabel("score");
lblScore.setBounds(481, 11, 36, 14);
canvas.add(lblScore);
JPanel p = new JPanel();
addButton(p, "Start", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (!isOn) {
tank = new Vehicle(canvas, 0);
tank.start();
car = new Vehicle(canvas, 1);
car.start();
isOn = true;
}
}
});
addButton(p, "Shut", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (isOn) {
Bullet bullet = new Bullet(canvas, tank, car);
bullet.start();
score.setText("" + sc);
}
}
});
addButton(p, "Close", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
canvas.setVisible(false);
System.exit(0);
}
});
contentPane.add(p, "South");
}
public void addButton(Container c, String title, ActionListener a) {
JButton button = new JButton(title);
c.add(button);
button.addActionListener(a);
}
}
import javax.swing.JFrame;
public class Test {
public static void main(String[] args) {
JFrame frame = new Tank_Shut_Car_ThreadFrame();
frame.setVisible(true);
}
}
Okay, so I had a play around with this (just for fun)
Now, this is far from a "proper" or "complete" game engine, but it provides a basic idea of how it might be possible to mix a core thread engine with UI components.
Rather then pasting the entire code, I've uploaded the source it to Tank.zip
But the basic engine looks like this...
public class GameEngine extends Thread {
public static final Object ASSET_LOCK = new Object();
private List<GameAsset> lstAssets;
private GameScreen screen;
public GameEngine(GameScreen screen) {
// Let the thread die when the JVM closes
setDaemon(true);
// Want to be below the UI thread (personal preference)
setPriority(NORM_PRIORITY - 1);
// A list of game assests
lstAssets = new ArrayList<GameAsset>(25);
// A reference to the screen
this.screen = screen;
// Add global key listener, this is simpler to the trying to attach a key listener
// to the screen.
Toolkit.getDefaultToolkit().addAWTEventListener(new EventHandler(), AWTEvent.KEY_EVENT_MASK);
}
public GameAsset[] getAssets() {
synchronized (ASSET_LOCK) {
return lstAssets.toArray(new GameAsset[lstAssets.size()]);
}
}
/*
* Allows for assets to be added
*/
public void addAsset(GameAsset asset) {
synchronized (ASSET_LOCK) {
lstAssets.add(asset);
}
}
#Override
public void run() {
while (true) {
try {
sleep(40);
} catch (InterruptedException ex) {
}
synchronized (ASSET_LOCK) {
GameAsset[] assets = lstAssets.toArray(new GameAsset[lstAssets.size()]);
for (GameAsset asset : assets) {
if (lstAssets.contains(asset)) {
asset.update(this, screen);
}
}
screen.repaint(new ArrayList<GameAsset>(lstAssets));
}
}
}
/**
* Allows the removal of an asset...
*/
public void removeAsset(GameAsset asset) {
synchronized (ASSET_LOCK) {
lstAssets.remove(asset);
}
}
/**
* Key event handling...
*/
protected class EventHandler implements AWTEventListener {
#Override
public void eventDispatched(AWTEvent event) {
KeyEvent keyEvent = (KeyEvent) event;
if (keyEvent.getID() == KeyEvent.KEY_PRESSED) {
synchronized (ASSET_LOCK) {
GameAsset[] assets = lstAssets.toArray(new GameAsset[lstAssets.size()]);
for (GameAsset asset : assets) {
if (lstAssets.contains(asset)) {
asset.processKeyPressed(GameEngine.this, screen, keyEvent);
}
}
}
} else if (keyEvent.getID() == KeyEvent.KEY_RELEASED) {
synchronized (ASSET_LOCK) {
GameAsset[] assets = lstAssets.toArray(new GameAsset[lstAssets.size()]);
for (GameAsset asset : lstAssets) {
if (lstAssets.contains(asset)) {
asset.processKeyReleased(GameEngine.this, screen, keyEvent);
}
}
}
}
}
}
}
Swing is not thread safe. Events should be fired on the event-dispatching thread.
http://www.javamex.com/tutorials/threads/invokelater.shtml