-
Notifications
You must be signed in to change notification settings - Fork 30
/
Coin.java
51 lines (43 loc) · 1.48 KB
/
Coin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Coin {
// image that represents the coin's position on the board
private BufferedImage image;
// current position of the coin on the board grid
private Point pos;
public Coin(int x, int y) {
// load the assets
loadImage();
// initialize the state
pos = new Point(x, y);
}
private void loadImage() {
try {
// you can use just the filename if the image file is in your
// project folder, otherwise you need to provide the file path.
image = ImageIO.read(new File("images/coin.png"));
} catch (IOException exc) {
System.out.println("Error opening image file: " + exc.getMessage());
}
}
public void draw(Graphics g, ImageObserver observer) {
// with the Point class, note that pos.getX() returns a double, but
// pos.x reliably returns an int. https://stackoverflow.com/a/30220114/4655368
// this is also where we translate board grid position into a canvas pixel
// position by multiplying by the tile size.
g.drawImage(
image,
pos.x * Board.TILE_SIZE,
pos.y * Board.TILE_SIZE,
observer
);
}
public Point getPos() {
return pos;
}
}