2

I'm trying to make a simple java game, where a big ball eats smaller balls. I did that. Now I want the big ball to "grow" when it eats smaller balls, but I don't know how to resize an image in Java. Thanks in advance!

MovableBall.java:

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;

public class MovableBall {

    private String craft = "ball.png";

    private int dx;
    private int dy;
    private int x;
    private int y;
    private int width;
    private int height;
    private int mx = 200, my = 150;
    private Image image;

    public MovableBall() {
        ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
        image = ii.getImage();

        x = 5;
        y = 5;
        width = image.getWidth(null);
        height = image.getHeight(null);
    }

    public void move() {
        x += dx;

        y += dy;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Image getImage() {
        return image;
    }

    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        if (key == KeyEvent.VK_LEFT) {
            dx = -1;
        }

        if (key == KeyEvent.VK_RIGHT) {
            dx = 1;
        }

        if (key == KeyEvent.VK_UP) {
            dy = -1;
        }

        if (key == KeyEvent.VK_DOWN) {
            dy = 1;
        }
    }

    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_LEFT) {
            dx = 0;
        }

        if (key == KeyEvent.VK_RIGHT) {
            dx = 0;
        }

        if (key == KeyEvent.VK_UP) {
            dy = 0;
        }

        if (key == KeyEvent.VK_DOWN) {
            dy = 0;
        }
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, width, height);
    }
}

FoodBoard.java:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JPanel;
import javax.swing.Timer;

public class FoodBoard extends JPanel implements ActionListener {

    private Timer timer;
    private MovableBall ball;
    private Food[] foods = { new Food(), new Food(), new Food(), new Food(),
            new Food(), new Food() };
    private int B_WIDTH;
    private int B_HEIGHT;

    public FoodBoard() {
        addKeyListener(new TAdapter());
        setBackground(Color.black);
        setSize(400, 300);
        setDoubleBuffered(true);
        ball = new MovableBall();

        // WURRY important:
        setFocusable(true);
        // every 5 ms the timer will call the actionPerformed() method
        timer = new Timer(5, this);
        timer.start();
    }

    public void addNotify() {
        super.addNotify();
        B_WIDTH = getWidth();
        B_HEIGHT = getHeight();
    }

    public void checkIfEaten() {
        Rectangle r3 = ball.getBounds();

        for (int j = 0; j < foods.length; j++) {
            Food a = foods[j];
            Rectangle r2 = a.getBounds();

            if (r3.intersects(r2)) {
                a.setVisible(false);
            }
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;

        for (int i = 0; i < foods.length; i++) {
            Food f = foods[i];
            if (f.isVisible()) {
                g2d.drawImage(f.getImage(), f.getX(), f.getY(), this);
            }
        }
        g2d.drawImage(ball.getImage(), ball.getX(), ball.getY(), this);

        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ball.move();
        checkIfEaten();
        repaint();
    }

    private class TAdapter extends KeyAdapter {
        public void keyReleased(KeyEvent e) {
            ball.keyReleased(e);
        }

        public void keyPressed(KeyEvent e) {
            ball.keyPressed(e);
        }
    }
}
Charles
  • 50,943
  • 13
  • 104
  • 142
RominaV
  • 3,335
  • 1
  • 29
  • 59
  • 1
    You're close - take a look @ http://docs.oracle.com/javase/tutorial/2d/images/drawimage.html - you have an option of drawing the image scaled, which can simulate growth. It may get pixelated though, so you may want to load a larger resolution image if necessary. – NG. Nov 01 '13 at 12:43

2 Answers2

1

You can resize an image like this,

Image new_image = old_image.getScaledInstance( new_width, new_height,  java.awt.Image.SCALE_SMOOTH ) ;

To make sure the ball does not exceed the maximum size,

if(prevImage.getWidth(null) >= max_width || prevImage.getHeight(null) >= max_height)
{
    System.out.println("MAX Size reached !");
}
else
{
    // increase the size
    Image new_image = old_image.getScaledInstance( new_width, new_height,  java.awt.Image.SCALE_SMOOTH ) ;
}
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
  • Hi. I wrote `Image prevImage = ball.getImage(); ball.setImage(prevImage.getScaledInstance( prevImage.getWidth(null) + 10, prevImage.getWidth(null) + 10, Image.SCALE_DEFAULT));` inside the if of checkIfEaten(), and it results in the ball getting bigger forever. Any idea? Thanks! – RominaV Nov 01 '13 at 13:04
  • You can check if the image has reached a maximum size and then stop increasing its size. See my edit. – Ankit Rustagi Nov 01 '13 at 13:11
  • Thanks. Do you know why it keeps executing the code inside the if? – RominaV Nov 01 '13 at 13:23
  • It should do that till it reaches he maximum size. – Ankit Rustagi Nov 01 '13 at 13:25
  • I'll have to find a way for it to no be called endlessly. Otherwise it will always eat one ball, grow, and never grow again, cause it reached its max size. Thanks again! – RominaV Nov 01 '13 at 13:29
1

If you have an Image object, you really don't need to worry about resizing it, just use

yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

You would want to change the newWidth/newHeight parameters, but other than that, you should be good to go! You can read a lot more here.

Hope this helps!

Community
  • 1
  • 1
user2277872
  • 2,963
  • 1
  • 21
  • 22
  • Hi! I put this in `checkIfEaten()` : `Image im=ball.getImage(); im.getScaledInstance(im.getWidth(null)+5,im.getHeight(null)+5,im.SCALE_DEFAULT);` But it doesn't do anything. Am I writing it in the wrong place? Thanks a lot! – RominaV Nov 01 '13 at 12:56
  • Well, I am not used to this part of Java, but with what I do know, im.SCALE_DEFAULT isn't right. The SCALE_DEFAULT is a defined variablee in the Image class, and so when you use it, you have to do Image.SCALE_DEFAULT and it should work. Also, when doing getWidth(), I don't think you have to put the null, but that isn't going to hurt your game. – user2277872 Nov 01 '13 at 13:53
  • The problem was that, once I scaled it, I didn't set it as the ball's image. Thanks for your response :) I'm now facing the problem I commented in Rustagi's answer :P – RominaV Nov 01 '13 at 14:08
  • you're very welcome :) but don't your resizing code in the for loop because that is most likely why it is constantly resizing itself. – user2277872 Nov 01 '13 at 14:14
  • Thing is, it shouldn't be called always, I wrote it inside the if. I'm stuck, I don't know where to put the ball's method grow. I don't know much about programming, but is it right if I define an event for each food-ball, "visibilityChanged" or something like that, and call the ball's method grow from there? – RominaV Nov 01 '13 at 16:13