Writing Games with Processing: Setup and a Simple Player Character

16. December, 2013

We have an idea, now we need to write the game. Let’s use a screen size of 640 x 480:

void setup() {
  size(640, 480); //VGA for those old enough to remember
}

The next item on the task list is to render the game area. Let’s create a nice grass background:

void draw() {
  fill(174, 204, 27);
  rect(0, 0, width, height);
}

Too boring? Well, we can always add a more complex background later. Right now, we’re in development mode: We want to test some game ideas, quickly prototype something and play. Fancy graphics is our least priority right now.

What else do we need? The player character, Platty, the platypus:

int px = 320, py = 240;

void drawPlatty() {
  fill(235,220,160);
  rect(px, py, 20, 20);
  
  fill(0);
  textSize(18);
  textAlign(CENTER, CENTER);
  text("P", px+10, py+10);
}

void drawBackground() {
  fill(174, 204, 27); // green
  rect(0, 0, width, height); // fill whole screen
}

void draw() {
  drawBackground();
  drawPlatty();
}

That’s it. Again nothing fancy, just the bare minimum.

You will notice that some of the numbers are related but it’s not obvious from the code. At this point, we’ll have to make our first design decision: Can the player move freely (pixel by pixel) or is the movement tile base (as in chess)?

At this stage, both are equally simple to implement. An ego shooter or a jump&run would use fluid movement while a puzzle type game often uses tiles.

Let’s use tiles:

int px = 320, py = 240;
int tileSize = 20;

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);
}

Much better.

Note how I split tasks into different helper methods to keep the code readable. I could have done the player character rendering inside of the main draw() method. But by moving the code into different methods, I can keep things together that belong together while at the same time documenting my code. drawBackground() is like a comment explaining what the code in the method does. But unlike a comment, it can’t become outdated.

You can find the final version of the code here.

Next: Enemies!

First post in the series: Getting Started