-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathPlayer.java
102 lines (88 loc) · 3.04 KB
/
Player.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.awt.event.KeyEvent;
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 Player {
// image that represents the player's position on the board
private BufferedImage image;
// current position of the player on the board grid
private Point pos;
// keep track of the player's score
private int score;
public Player() {
// load the assets
loadImage();
// initialize the state
pos = new Point(0, 0);
score = 0;
}
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/player.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 void keyPressed(KeyEvent e) {
// every keyboard get has a certain code. get the value of that code from the
// keyboard event so that we can compare it to KeyEvent constants
int key = e.getKeyCode();
// depending on which arrow key was pressed, we're going to move the player by
// one whole tile for this input
if (key == KeyEvent.VK_UP) {
pos.translate(0, -1);
}
if (key == KeyEvent.VK_RIGHT) {
pos.translate(1, 0);
}
if (key == KeyEvent.VK_DOWN) {
pos.translate(0, 1);
}
if (key == KeyEvent.VK_LEFT) {
pos.translate(-1, 0);
}
}
public void tick() {
// this gets called once every tick, before the repainting process happens.
// so we can do anything needed in here to update the state of the player.
// prevent the player from moving off the edge of the board sideways
if (pos.x < 0) {
pos.x = 0;
} else if (pos.x >= Board.COLUMNS) {
pos.x = Board.COLUMNS - 1;
}
// prevent the player from moving off the edge of the board vertically
if (pos.y < 0) {
pos.y = 0;
} else if (pos.y >= Board.ROWS) {
pos.y = Board.ROWS - 1;
}
}
public String getScore() {
return String.valueOf(score);
}
public void addScore(int amount) {
score += amount;
}
public Point getPos() {
return pos;
}
}