Instantly share code, notes, and snippets.

Embed
What would you like to do?
Writing Games with Processing: Hunting Platty
// Version 4: Hunting Platty
int px = 320, py = 240;
int tileSize = 20;
int signum(float value) {
return value < 0 ? -1 : value > 0 ? 1 : 0;
}
class Enemy {
color c;
int x, y;
String name;
Enemy(String name) {
this.name = name;
c = color(222,40,107);
}
void draw() {
fill(c);
ellipse(x + tileSize/2, y + tileSize/2, tileSize, tileSize);
fill(0);
textAlign(CENTER, TOP);
textSize(12);
text(name, x + tileSize/2, y + tileSize + 2);
}
void hunt() {
int dx = signum(px - x) * tileSize;
int dy = signum(py - y) * tileSize;
x += dx;
y += dy;
}
}
ArrayList<Enemy> enemies = new ArrayList<Enemy>();
void addEnemy(int x, int y, String name) {
Enemy enemy = new Enemy(name);
enemy.x = x;
enemy.y = y;
enemies.add(enemy);
}
void drawEnemies() {
for(Enemy e: enemies) {
e.draw();
}
}
void mousePressed() {
saveFrame("frame-######.png");
println("Saved frame.");
}
void setup() {
size(640, 480); //VGA for those old enough to remember
addEnemy(20, 20, "Kenny");
addEnemy(600, 20, "Benny");
}
void drawPlatty() {
fill(235,220,160);
rect(px, py, tileSize, tileSize);
fill(0);
textSize(tileSize-2);
textAlign(CENTER, CENTER);
text("P", px+tileSize/2, py+tileSize/2-2);
}
void drawBackground() {
fill(174, 204, 27);
rect(0, 0, width, height);
}
void draw() {
drawBackground();
drawPlatty();
drawEnemies();
}
void moveEnemies() {
for(Enemy e: enemies) {
e.hunt();
}
}
void movePlayer(int dx, int dy) {
dx *= tileSize;
dy *= tileSize;
int newX = px + dx;
int newY = py + dy;
if(newX >= 0
&& newX < width
&& newY >= 0
&& newY < height
) {
px = newX;
py = newY;
}
moveEnemies();
}
void keyPressed() {
if(key == CODED) {
if(keyCode == UP) {
movePlayer(0, -1);
} else if(keyCode == DOWN) {
movePlayer(0, 1);
} else if(keyCode == LEFT) {
movePlayer(-1, 0);
} else if(keyCode == RIGHT) {
movePlayer(1, 0);
}
} else if(key == ' ') {
movePlayer(0, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment