Timer is crashing my LibGdx app? - java

I am making a 2D game in Libgdx and when I try to make a player shoot every X seconds it crashes and that happens only if I call addBullet() inside a timer.
Here is code for Controller.class:
public class Controller {
private LinkedList<Bullet> b = new LinkedList<Bullet>();
private Bullet tempBullet;
private LinkedList<Zombie> z = new LinkedList<Zombie>();
private Zombie tempZombie;
private API api;
private Player p;
private World w;
public void create() {
api = new API();
w = new World();
p = new Player(100, 40);
Timer t = new Timer( );
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Crashes when this is executed
addBullet(new Bullet(p.getX() + p.getTex().getWidth(), p.getY() + p.getTex().getHeight()));
}
}, 500,2500);
}
public void tick() {
p.tick();
for(int i = 0; i < b.size(); i++){
tempBullet = b.get(i);
tempBullet.tick();
}
for(int i = 0; i < z.size(); i++){
tempZombie = z.get(i);
tempZombie.tick();
for(int j = 0; j < b.size(); j++){
tempBullet = b.get(j);
if(api.getCollisionBox(tempZombie.getX(), tempZombie.getY(), tempZombie.getTex().getWidth(), tempZombie.getTex().getHeight(), tempBullet.getX(), tempBullet.getY(), 10, 10)){
tempZombie.damage();
b.remove(tempBullet);
if(tempZombie.getHealth() <= 0){
z.remove(tempZombie);
}
}
}
}
}
public void render() {
w.render(); // Mora biti na pocetku ove funkcije
p.render();
for(int i = 0; i < b.size(); i++){
tempBullet = b.get(i);
tempBullet.render();
}
for(int i = 0; i < z.size(); i++){
tempZombie = z.get(i);
tempZombie.render();
}
}
public void dispose() {
w.dispose();
p.dispose();
for(int i = 0; i < b.size(); i++){
tempBullet = b.get(i);
tempBullet.dispose();
}
for(int i = 0; i < z.size(); i++){
tempZombie = z.get(i);
tempZombie.dispose();
}
}
public void keyInput() {
//if(Gdx.input.isButtonPressed(Input.Keys.W))
}
public void mouseInput() {
//if(Gdx.input.isButtonPressed(Input.Buttons.LEFT))
if(Gdx.input.isTouched())
addBullet(new Bullet(p.getX() + p.getTex().getWidth(), p.getY() + p.getTex().getHeight()));
}
public void addBullet(Bullet block){
b.add(block);
}
public void removeBullet(Bullet block){
b.remove(block);
}
public void addZombie(Zombie block){
z.add(block);
}
public void removeZombie(Zombie block){
z.remove(block);
}
}
Here is the code for the bullet.class:
public class Bullet {
private Texture tex;
private SpriteBatch batch;
private int x;
private int y;
public Bullet(int x, int y){
this.x = x;
this.y = y;
batch = new SpriteBatch();
tex = new Texture(Gdx.files.internal(("bullet.png")));
}
public void tick(){
x += 10;
}
public void render(){
batch.begin();
batch.draw(tex, x, y, 100, 100);
batch.end();
}
public void dispose() {
tex.dispose();
batch.dispose();
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}

Without seeing the full exception, my guess is that there might be something wrong with the loading of the image.
ps. Why the extra brackets?
tex = new Texture(Gdx.files.internal(("bullet.png")));
One set of brackets is enough:
tex = new Texture(Gdx.files.internal("bullet.png"));

Related

How to implement MouseMotionListener in Java Swing for list of objects to follow mouse?

My question is how can i implement the MouseMotionListener for list of objects can follow my mouse? I guess, I couldn't get the idea so far. I tried to do that my second part of the worm will follow the head. So it will become like a train. But in first second seems like Ok but all objects suddenly converge to a point.
Basically my code is above;
My Worm.class is like that;
public class Worm {
Random rd = new Random();
int xWorm;
int yWorm;
int Speed = 100;
int size = 10; // default
Worm()
{
xWorm = rd.nextInt(250);
yWorm = rd.nextInt(250);
}
Worm(int xNew, int yNew){
xWorm = xNew;
yWorm = yNew;
}
public int getxWorm() {
return xWorm;
}
public void setxWorm(int xWorm) {
this.xWorm = xWorm;
}
public int getyWorm() {
return yWorm;
}
public void setyWorm(int yWorm) {
this.yWorm = yWorm;
}
public int getSpeed() {
return Speed;
}
public void setSpeed(int speed) {
Speed = speed;
}
public void move (int dx, int dy) {
xWorm+=dx;
yWorm+=dy;
}
public void setPosition(int x,int y) {
this.xWorm = x;
this.yWorm = y;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D Ellipse= new Ellipse2D.Double(xWorm,yWorm,10,10);
g2.setColor(Color.GREEN);
g2.draw(Ellipse);
g2.fill(Ellipse);
// g.fillOval(this.xWorm, this.yWorm, 30, 30);
}
public boolean iscollision(Food f) {
Rectangle2D RectangleforFood = new Rectangle2D.Double(f.xFood,f.yFood,5,5);
Rectangle2D RectangleforWormHead = new Rectangle2D.Double(this.xWorm,this.yWorm,10,10);
if (RectangleforWormHead.intersects(RectangleforFood)) {
return true;
}
else {
return false;
}
}
}
and my Panel.class the tracker function like that ;
public void createlongworm() {
for(int i = 0; i < 100 ; i++) {
wormBody.add(new Worm(wormBody.get(i).xWorm+10,wormBody.get(i).yWorm));
}}
public void tracker(ArrayList <Worm> TracktheWorm) {
for(int i = 0; i < TracktheWorm.size()-1 ; i++) {
TracktheWorm.get(i+1).xWorm = TracktheWorm.get(i).xWorm;
TracktheWorm.get(i+1).yWorm = TracktheWorm.get(i).yWorm;
}
repaint();
}

Breakout Program only shows 1 Brick

To be frank i have not the slightest clue how to fix this whats so ever. It works until you get to the part that only 1 brick shows and its kinda frustrating... If anyone could help me i would appreciate it. I did look up how to fix this but i didn't even find anyone that had this problem. Google searching isn't really that good. Oh and i used Eclipse for this program.
Board Class
package Final;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
public class Board extends JPanel implements Commons {
private Timer timer;
private String message = "Your Fired";
private Ball ball;
private Paddle paddle;
private Brick bricks[];
private boolean ingame = true;
public Board() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setFocusable(true);
bricks = new Brick[N_OF_BRICKS];
setDoubleBuffered(true);
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), DELAY, PERIOD);
}
#Override
public void addNotify() {
super.addNotify();
gameInit();
}
private void gameInit() {
ball = new Ball();
paddle = new Paddle();
int k = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
bricks[k] = new Brick(j * 40 + 30, i * 10 + 50);
k++;
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
if (ingame) {
drawObjects(g2d);
} else {
gameFinished(g2d);
}
Toolkit.getDefaultToolkit().sync();
}
private void drawObjects(Graphics2D g2d) {
g2d.drawImage(ball.getImage(), ball.getX(), ball.getY(),
ball.getWidth(), ball.getHeight(), this);
g2d.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(),
paddle.getWidth(), paddle.getHeight(), this);
for (int i = 0; i < N_OF_BRICKS; i++) {
if (!bricks[i].isDestroyed()) {
g2d.drawImage(bricks[i].getImage(), bricks[i].getX(),
bricks[i].getY(), bricks[i].getWidth(),
bricks[i].getHeight(), this);
}
}
}
private void gameFinished(Graphics2D g2d) {
Font font = new Font("Verdana", Font.BOLD, 18);
FontMetrics metr = this.getFontMetrics(font);
g2d.setColor(Color.BLACK);
g2d.setFont(font);
g2d.drawString(message,
(Commons.WIDTH - metr.stringWidth(message)) / 2,
Commons.WIDTH / 2);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
paddle.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
paddle.keyPressed(e);
}
}
private class ScheduleTask extends TimerTask {
#Override
public void run() {
ball.move();
paddle.move();
checkCollision();
repaint();
}
}
private void stopGame() {
ingame = false;
timer.cancel();
}
private void checkCollision() {
if (ball.getRect().getMaxY() > Commons.BOTTOM_EDGE) {
stopGame();
}
for (int i = 0, j = 0; i < N_OF_BRICKS; i++) {
if (bricks[i].isDestroyed()) {
j++;
}
if (j == N_OF_BRICKS) {
message = "Pay Day";
stopGame();
}
}
if ((ball.getRect()).intersects(paddle.getRect())) {
int paddleLPos = (int) paddle.getRect().getMinX();
int ballLPos = (int) ball.getRect().getMinX();
int first = paddleLPos + 8;
int second = paddleLPos + 16;
int third = paddleLPos + 24;
int fourth = paddleLPos + 32;
if (ballLPos < first) {
ball.setXDir(-1);
ball.setYDir(-1);
}
if (ballLPos >= first && ballLPos < second) {
ball.setXDir(-1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos >= second && ballLPos < third) {
ball.setXDir(0);
ball.setYDir(-1);
}
if (ballLPos >= third && ballLPos < fourth) {
ball.setXDir(1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos > fourth) {
ball.setXDir(1);
ball.setYDir(-1);
}
}
for (int i = 0; i < N_OF_BRICKS; i++) {
if ((ball.getRect()).intersects(bricks[i].getRect())) {
int ballLeft = (int) ball.getRect().getMinX();
int ballHeight = (int) ball.getRect().getHeight();
int ballWidth = (int) ball.getRect().getWidth();
int ballTop = (int) ball.getRect().getMinY();
Point pointRight = new Point(ballLeft + ballWidth + 1, ballTop);
Point pointLeft = new Point(ballLeft - 1, ballTop);
Point pointTop = new Point(ballLeft, ballTop - 1);
Point pointBottom = new Point(ballLeft, ballTop + ballHeight + 1);
if (!bricks[i].isDestroyed()) {
if (bricks[i].getRect().contains(pointRight)) {
ball.setXDir(-1);
} else if (bricks[i].getRect().contains(pointLeft)) {
ball.setXDir(1);
}
if (bricks[i].getRect().contains(pointTop)) {
ball.setYDir(1);
} else if (bricks[i].getRect().contains(pointBottom)) {
ball.setYDir(-1);
}
bricks[i].setDestroyed(true);
}
}
}
}
}
Brick Class
package Final;
import javax.swing.ImageIcon;
public class Brick extends Sprite {
private boolean destroyed;
public Brick(int x, int y) {
ImageIcon ii = new ImageIcon("images/bricks.png");
image = ii.getImage();
i_width = image.getWidth(null);
i_heigth = image.getHeight(null);
destroyed = false;
}
public boolean isDestroyed() {
return destroyed;
}
public void setDestroyed(boolean val) {
destroyed = val;
}
}
Commons Class
package Final;
public interface Commons {
public static final int WIDTH = 300;
public static final int HEIGTH = 400;
public static final int BOTTOM_EDGE = 390;
public static final int N_OF_BRICKS = 30;
public static final int INIT_PADDLE_X = 200;
public static final int INIT_PADDLE_Y = 360;
public static final int INIT_BALL_X = 230;
public static final int INIT_BALL_Y = 355;
public static final int DELAY = 1000;
public static final int PERIOD = 10;
}
Sprite Class
package Final;
import java.awt.Image;
import java.awt.Rectangle;
public class Sprite {
protected int x;
protected int y;
protected int i_width;
protected int i_heigth;
protected Image image;
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public int getWidth() {
return i_width;
}
public int getHeight() {
return i_heigth;
}
Image getImage() {
return image;
}
Rectangle getRect() {
return new Rectangle(x, y,
image.getWidth(null), image.getHeight(null));
}
}
Breakout Class
package Final;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Breakout extends JFrame {
public Breakout() {
initUI();
}
private void initUI() {
add(new Board());
setTitle("Lord Carl's Demolition Job");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(Commons.WIDTH, Commons.HEIGTH);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Breakout game = new Breakout();
game.setVisible(true);
}
});
}
}
The problem is in checkCollision(). Inside the loop, j will never equal N_OF_BRICKS because of the loop condition. You could change to:
private void checkCollision() {
if (ball.getRect().getMaxY() > Commons.BOTTOM_EDGE) {
stopGame();
}
int j = 0;
for (int i = 0; i < N_OF_BRICKS; i++) {
if (bricks[i].isDestroyed()) {
j++;
}
}
if (j == N_OF_BRICKS) {
message = "Pay Day";
stopGame();
}
}
Also, in the Brick class you neglect to store the x,y coords:
public class Brick extends Sprite {
....
public Brick(int x, int y) {
ImageIcon ii = new ImageIcon("images/bricks.png");
image = ii.getImage();
i_width = image.getWidth(null);
i_heigth = image.getHeight(null);
destroyed = false;
// Save these
this.x = x;
this.y = y
}
....
}
Or, add a constructor to the Sprite class and call that from the Brick constructor:
public class Sprite {
....
public Sprite(int x, int y) {
this.x = x;
this.y = y;
}
....
}
public class Brick extends Sprite {
....
public Brick(int x, int y) {
// Call the sprite constructor
super(x, y);
ImageIcon ii = new ImageIcon("images/bricks.png");
image = ii.getImage();
i_width = image.getWidth(null);
i_heigth = image.getHeight(null);
destroyed = false;
}
....
}

Typing game: choosing two words

I'm creating a game like zType
and I have a problem in validating the input. As you can see in the picture below it select two words. How can I fix this problem, please help.
This is My Game class
import java.awt.Canvas;
import java.awt.event.KeyListener;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener
{
public static final int WIDTH = 640;
public static final int HEIGHT = 680;
public final String TITLE = "Game";
private boolean running = false;
private Thread thread;
private BufferedImage spriteSheet = null;
private BufferedImage background = null;
public int level = 1;
public int fps = 0;
public int score = 0;
private int enemy_count = 15;
private int enemy_killed = 0;
private int enemy_notkilled = 0;
private boolean target = false;
public String t = "";
private Controller c;
private Textures tex;
private LinkedList<Enemy> e = new LinkedList<Enemy>();
private Enemy enemy;
public void init()
{
requestFocus();
try
{
spriteSheet = ImageIO.read(getClass().getResource("/sprite_sheet.png"));
background = ImageIO.read(getClass().getResource("/background.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
tex = new Textures(this);
c = new Controller(tex, this);
addKeyListener(this);
c.createEnemy(enemy_count);
e = c.getEnemy();
}
private synchronized void start()
{
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop()
{
if(!running)
return;
running = false;
try
{
thread.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.exit(1);
}
public void run()
{
init();
long lastTime = System.nanoTime();
final double amountOfTicks= 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1)
{
update();
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
fps = frames;
frames = 0;
}
}
stop();
}
private void update()
{
c.update();
if(enemy_killed + enemy_notkilled >= enemy_count)
{
e.clear();
t = "";
level++;
enemy_killed = 0;
enemy_notkilled = 0;
c.createEnemy(enemy_count);
}
}
private void render()
{
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(background, 0, 0, null);
c.render(g);
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent ek)
{
int key = ek.getKeyCode();
char character = Character.toLowerCase(ek.getKeyChar());
boolean result = isValid(key);
if(result && !target)
{
for(int i = 0; i < e.size(); i++)
if(e.get(i).getFirstLetter() == character && e.get(i).getOnScreen())
{
enemy = e.get(i);
t = enemy.getText();
if(enemy.getCurrentIndex() == 0)
enemy.addCurrentIndex();
target = true;
System.out.println("---"+enemy.text);
break;
}
}
else if(result && t.charAt(enemy.getCurrentIndex()) == character)
enemy.addCurrentIndex();
}
public void keyReleased(KeyEvent ek){ }
public void keyTyped(KeyEvent ek){ }
public static void main(String[] args)
{
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
game.setMinimumSize(new Dimension(WIDTH, HEIGHT));
JFrame frame = new JFrame(game.TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
public boolean isValid(int key)
{
return key >= 65 && key <= 90 ? true : false;
}
public BufferedImage getSpriteSheet()
{
return spriteSheet;
}
public int getEnemy_count()
{
return enemy_count;
}
public void setEnemy_count(int enemy_count)
{
this.enemy_count = enemy_count;
}
public int getEnemy_killed()
{
return enemy_killed;
}
public void setEnemy_killed(int enemy_killed)
{
this.enemy_killed = enemy_killed;
}
public int getEnemy_notkilled()
{
return enemy_notkilled;
}
public void setEnemy_notkilled(int enemy_notkilled)
{
this.enemy_notkilled = enemy_notkilled;
}
public void addScore(int k)
{
score += k;
}
public void falseTarget()
{
target = false;
}
public String getT()
{
return t;
}
public void setT(String k)
{
t = k;
}
}
This is my Enemy Class
import java.awt.*;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
public class Enemy
{
private double x ,y;
public String text;
private char firstLetter;
private AttributedString as;
private Controller c;
private Textures tex;
private Game game;
private int currentIndex = 0;
private int textLength = 0;
private double speed = 0.0;
private int stringWidth = 0;
private boolean onScreen = false;
public Enemy(double x, double y, double speed, Textures tex, Controller c, Game game, String text, int stringWidth)
{
this.x = x;
this.y = y;
this.tex = tex;
this.text = text;
this.game = game;
this.c = c;
this.speed = speed;
firstLetter = this.text.charAt(0);
textLength = this.text.length();
this.stringWidth = stringWidth;
}
public void update()
{
y += speed;
if(y >= 0)
onScreen = true;
if(currentIndex >= textLength)
{
game.addScore(5);
game.setT("");
c.removeEnemy(this);
game.setEnemy_killed(game.getEnemy_killed() + 1);
game.falseTarget();
}
if(y >= Game.HEIGHT - 50)
{
//game.decreaseHealth();
game.setT("");
c.removeEnemy(this);
game.setEnemy_notkilled(game.getEnemy_notkilled() + 1);
game.falseTarget();
game.t ="";
}
}
public void render(Graphics g)
{
g.drawImage(tex.enemy, (int)x, (int)y, null);
as = new AttributedString(text);
if(currentIndex >= 1)
as.addAttribute(TextAttribute.FOREGROUND, Color.WHITE, 0, currentIndex);
as.addAttribute(TextAttribute.FONT, new Font("Consolas", Font.BOLD, 12), 0, text.length());
g.drawString(as.getIterator(), (int)x + getAdd(stringWidth), (int)y + 13);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public String getText()
{
return text;
}
public char getFirstLetter()
{
return firstLetter;
}
public void addCurrentIndex()
{
currentIndex++;
}
public int getCurrentIndex()
{
return currentIndex;
}
public int getTextLength()
{
return textLength;
}
public int getAdd(int width)
{
return (96 / 2) - (width / 2);
}
public boolean getOnScreen()
{
return onScreen;
}
}
The problem is that you're calling falseTarget() whenever an enemy moves out of the screen. In your example, you assigned target = true when you pressed the 'o' (for the enemy named "owe"), but then a different enemy (maybe "jet", maybe an enemy that is no longer visible) finished "dropping" out of the screen (y >= Game.HEIGHT - 50), so you called falseTarget() - and thus, when you pressed 'i' you started a new enemy ("ice").
What you want to do is call falseTarget() in this case only if the enemy that dropped out of the screen is the one that's currently being targeted:
if(y >= Game.HEIGHT - 50)
{
//game.decreaseHealth();
//game.setT(""); // <-- Commented this line out
c.removeEnemy(this);
game.setEnemy_notkilled(game.getEnemy_notkilled() + 1);
if(game.getT().equals(text)) // <-- Added this if before calling falseTarget()
{ // and clearing the game's current enemy text
game.falseTarget();
game.t ="";
}
}

Getting values to compare from 2 very different classes

I have these two classes, Bullet and EnemyJet. The Bullet class extends the Player class and the EnemyJet class extends an EnemyControl class. They are both using an arraylist which I'm trying to store and get their positions from.
public class Player extends Mob {
public List<Bullet> bullets = new ArrayList<Bullet>();
}
public class EnemyControl extends Mob {
public List<EnemyJet> enemyJet = new ArrayList<EnemyJet>();
}
Would I need to make a new class to store and test the two positions, or maybe use the Mob class they extend? How would I get the same values from the lists to compare them inside the new class?
For example, test for a collision with the bullet and the enemy jet. If so,remove the jet.
EnemyJet Class:
public class EnemyJet extends EnemyControl{
Random rdm = new Random();
private int destx, desty;
private Sprite sprite;
private int counter = 0;
private boolean dead = false;
private boolean setPos = false;
private void newPosition(){
destx = rdm.nextInt(963);
desty = rdm.nextInt(500);
//System.out.println(destx + " " + desty);
}
private void move(){
if(x > destx) x-=3;
if(y > desty) y-=3;
if(x < destx) x+=3;
if(y < desty) y+=3;
// if(x >= )
}
private void setPos(){
if(!setPos){
x = rdm.nextInt(500);
y = rdm.nextInt(100);
setPos = true;
}
}
public void update(){
setPos();
move();
if(counter > rdm.nextInt(20000)){
newPosition();
counter = 0;
}
counter++;
}
public void render(Screen screen){
sprite = Sprite.enemyjet;
screen.renderMob(x, y, sprite);
}
}
Bullet Class:
public class Bullet {
private Sprite sprite;
private boolean removed = false;
public int y = 0, x = 0;
public Bullet(int x, int y){
this.x = x;
this.y = y;
}
public boolean isRemoved(){
return removed;
}
public void update(){
y -= 15;
}
public void render(Screen screen){
sprite = Sprite.jetbullet;
screen.drawBullet(x, y, sprite);
}
}
Player Class:
public class Player extends Mob {
public List<Bullet> bullets = new ArrayList<Bullet>();
private Keyboard input;
private Sprite sprite;
private int counter = 0;
private int fireRate = 4;
public Player(Keyboard input){
this.input = input;
}
public void update(){
int xa = 0, ya = 0;
if(input.up) ya=-7;
if(input.down) ya =+7;
if(input.left) xa=-7;
if(input.right) xa=+7;
if(!input.up && !input.down && !input.left && !input.right)
intensity = 0; else intensity = 8;
move(xa, ya);
if(input.shoot && counter > fireRate){
bullet = new Bullet(x, y);
bullets.add(bullet);
counter = 0;
}
if(bullets.size() > 0){
for(int i = 0; i < bullets.size(); i++){
bullets.get(i).update();
if(bullets.get(i).y < 0){
bullets.remove(i);
}
}
}
counter++;
}
public void render(Screen screen){
sprite = Sprite.jet;
if(bullets.size()>0)
for(int i = 0; i < bullets.size(); i++){
bullets.get(i).render(screen);
}
screen.renderMob(x, y, sprite);
screen.setIntensity(intensity);
}
}
Added all classes Player, EnemyJet and Bullet.
you could go through all bullets and check if they have the same position as the enemyjet and implement a method in Mob that compares them if you will use the comparison repeatedly. Or you just do the compare yourself in your driver class that controls both during runtime, e.g. the main() or where the events are caught and synchronized and presented on screen.

why wont my program paintComponent() if I set an ImageIcon and Image?

I've tried to find similar questions, but I think I have a unique situation here.
I am programming a game in java, my main class creates a frame which adds a component class which is an extension of JPanel. Basically, I draw these ovals and they move around and do different things, and I want to implement a method inside of one my classes which will use an image instead of an oval. However, anytime I try to create and image from a file, the program will not run the overridden "paintComponent(Graphics g)" method.
My main:
package mikeengine;
import javax.swing.JFrame;
public class MikeEngine {
static final int fx = 1300;
static final int fy = 800;
static final int px = 1292;
static final int py = 767;
static interactivePanel levelPanel;
public static void pause() {
try {
Thread.sleep(10); // wait 10ms
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MEngine");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(fx, fy);
frame.setResizable(false);
frame.setVisible(true);
levelPanel = new interactivePanel();
addship();
frame.getContentPane().add(levelPanel);
levelPanel.requestFocusInWindow();
while (true) {
pause();
levelPanel.move();
levelPanel.repaint();
}
}
static void addship() {
PlayerShip ship = new PlayerShip(100, 25, 25, px, 0, py, 0);
ship.setGraphic("C:/Users/asdf/Documents/NetBeansProjects/mikeEngine/src/mikeengine/res/right-arrow.jpg");
levelPanel.addObject(ship);
for (int i = 0; i < 5; i++) {
PlayerShip ship2 = new PlayerShip((int) (Math.random() * 1000) + 100, (int) (Math.random() * 1000) + 100, 25, px, px / 2, py, 0);
ship2.setMovement((int) (Math.random() * 10) / 5, (int) (Math.random() * 10) / 2);
levelPanel.addObject(ship2);
}
}
}
now, if I comment out the line:
ship.setGraphic("C:/Users/asdf/Documents/NetBeansProjects/mikeEngine/src/mikeengine/res/right-arrow.jpg");
everything renders perfectly.
I don't even paint the image that is going to be created. The image variable is just part of a class and it is currently just being created and doing nothing, so I don't understand how it affects the paintcomponentMethod(), if the paintComponent() isn't even told to try to paint the image ever.
The "PlayerShip" class extends the abstract "OnScreenObject" class (you really shouldn't need to see the code for PlayerShip, it only overrides one irrelevant method).
OnScreenObject looks like so:
package mikeengine;
import java.awt.Color;
import java.awt.Image;
import javax.swing.ImageIcon;
public abstract class OnScreenObject {
private ImageIcon graphic;
Image g;
protected int xmin;
protected int ymin;
protected int xsize;
protected int ysize;
protected int rise;
protected int run;
protected int containerYMax;
protected int containerYMin;
protected int containerXMax;
protected int containerXMin;
protected boolean visible;
protected boolean allowedOffscreen;
protected boolean isSelected;
protected Color color;
OnScreenObject(int x, int y, int sizeX, int sizeY, int cxMax, int cxMin, int cyMax, int cyMin) {
xmin = x;
ymin = y;
xsize = sizeX;
ysize = sizeY;
containerXMax = cxMax;
containerXMin = cxMin;
containerYMax = cyMax;
containerYMin = cyMin;
//
rise = 0;
run = 0;
visible = true;
allowedOffscreen = false;
isSelected = false;
}
public int getXMin() {
return xmin;
}
public int getYMin() {
return ymin;
}
public int getXMax() {
return xmin + xsize;
}
public int getYMax() {
return ymin + ysize;
}
public int getXSize() {
return xsize;
}
public int getYSize() {
return ysize;
}
public Color getColor() {
return color;
}
public boolean getAllowedOffscreen() {
return allowedOffscreen;
}
public boolean getVisible() {
return visible;
}
public int getRun() {
return run;
}
public ImageIcon getGraphic() {
return graphic;
}
public boolean isWithin(int x, int y) {
return x >= xmin && x <= getXMax() && y >= ymin && y <= getYMax();
}
public void setXMin(int x) {
xmin = x;
}
public void setYMin(int y) {
ymin = y;
}
public void setXSize(int x) {
xsize = x;
}
public void setYSize(int y) {
ysize = y;
}
public void setGraphic(String setto) {
try{
graphic = new ImageIcon("setto");
g=graphic.getImage();
System.out.println("tried");
} catch(Exception e){
System.out.println("caught:" + e);
}
}
public void setAllowedOffscreen(boolean allowed) {
allowedOffscreen = allowed;
}
public void setMovement(int riseM, int runM) {
rise = riseM * -1;//rise means to go up, and negative will move it up
run = runM;
}
public void nudge(boolean horizontal, int amount) {
if (horizontal) {
run += amount;
} else {
rise += amount;
}
}
public void setVisible(boolean vis) {
visible = vis;
}
public void setColor(Color c) {
color = c;
}
public boolean checkCollide(OnScreenObject other) {
if (other.getYMax() < getYMin()) { //if other object is above this
return false;
}
if (other.getYMin() > getYMax()) {//if other object is below this
return false;
}
if (other.getXMax() < getXMin()) {//if other is to the left
return false;
}
if (other.getXMin() > getXMax()) {//if other is to the right
return false;
}
return true;
}
public void move() {
if (!allowedOffscreen) {
checkEdge();
}
xmin += run;
ymin += rise;
}
protected abstract void checkEdge();
}
The interactivePanel class is the one that extends JPanel:
package mikeengine;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JPanel;
public class interactivePanel extends JPanel {
ArrayList<OnScreenObject> objects;
IClick myClick;
Ipress myType;
PlayerShip currentShip;
interactivePanel() {
objects = new ArrayList<>();
myClick = new IClick();
myType = new Ipress();
this.addMouseListener(myClick);
this.addKeyListener(myType);
}
#Override
public void paintComponent(Graphics g) {
System.out.println("painting");
paintBackground(g);
paintObjects(g);
checkClick();
checkPress();
}
public void move() {
System.out.println("here2");
checkDeadShip();//also sets current ship
moveObjects();//also removes invisible
checkCollisions();
} // end method move
private void checkClick() {
if (!myClick.getClicked()) {
return;
}
for (int i = 0; i < objects.size(); i++) {
OnScreenObject current = objects.get(i);
if (current.isWithin(myClick.getX(), myClick.getY())) {
System.out.println("CLICKED");
}
}
}
private void paintBackground(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
}
private void paintObjects(Graphics g) {
for (int i = 0; i < objects.size(); i++) {
OnScreenObject current = objects.get(i);
g.setColor(current.getColor());
g.fillOval(current.getXMin(), current.getYMin(), current.getXSize(), current.getYSize());
}
}
public void addObject(OnScreenObject toAdd) {
objects.add(toAdd);
}
private void checkPress() {
if (myType.getDown()) {
objects.get(0).nudge(false, 3);
}
if (myType.getUp()) {
objects.get(0).nudge(false, -3);
}
if (myType.getLeft()) {
objects.get(0).nudge(true, -3);
}
if (myType.getRight()) {
objects.get(0).nudge(true, 3);
}
if (myType.getSpace()) {
fire();
}
}
private void fire() {
OnScreenObject shotBullet = new Bullet(currentShip.getXMax(), ((currentShip.getYMax() - currentShip.getYMin()) / 2) + currentShip.getYMin(), 5, getWidth(), 0, getHeight(), 0);
int shipBonus = 0;
if (currentShip.getRun() > 0) {
shipBonus = currentShip.getRun();
}
shotBullet.setMovement(0, shipBonus + 5);
addObject(shotBullet);
}
private void checkCollisions() {
for (int i = 0; i < objects.size() - 1; i++) {
for (int j = 0; j < objects.size(); j++) {
if (j != i) {
OnScreenObject current = objects.get(i);
OnScreenObject next = objects.get(j);
if (current.checkCollide(next)) {
objects.remove(i);
if (i < j) {
objects.remove(j - 1);
} else {
objects.remove(j);
}
}
}
}
}
}
private void checkDeadShip() {
if (objects.size() > 0) {
try {
currentShip = (PlayerShip) objects.get(0);
} catch (Exception e) {
System.out.println("GAME OVER!");
}
}
}
private void moveObjects() {
for (int i = 0; i < objects.size(); i++) {
OnScreenObject current = objects.get(i);
current.move();
if (!current.getVisible()) {
objects.remove(i);
}
}
}
}
if I do not have that line commented out, the
System.out.println("painting"); inside of my public void paintComponent(Graphics g) is never run, which is why I assume that paintComponent isn't running.
(I cant post images since I don't have 10 rep, but its just a JFrame with the beige empty panel look when it is not commented out).
EDIT:
In your setGraphic() method, replace the line
graphic = new ImageIcon("setto");
with this:
graphic = new ImageIcon(this.getClass()
.getResource(setto));

Categories