Merry Christmas, everyone
In the last post, we cleaned up the code. This makes it now very simple to add an intro to the game:
class IntroState extends State { Player p; Enemy e; Step playerStep; Step enemyStep; void setup() { playerStep = new Step(); playerStep.x += + 3*tileSize; p = new Player(); e = new Enemy("Kenny"); enemyStep = new Step(); frameRate(10); }
The class Step adds a very simple movement algorithm to the player and enemy we created in setup():
class Step { int minX = tileSize * 3; int minY = tileSize * 3; int maxX = width - (tileSize * 3); int maxY = height - (tileSize * 3); int x = minX; int y = minY; int dx = tileSize; int dy = 0; void next() { int newX = x + dx; int newY = y + dy; if(newX > maxX) { newX = maxX; dx = 0; dy = tileSize; newY += dy; } else if(newY > maxY) { newY = maxY; dx = -tileSize; dy = 0; newX += dx; } else if(newX < minX) { newX = minX; dx = 0; dy = -tileSize; newY += dy; } else if(newY < minY) { newY = minY; dx = tileSize; dy = 0; newX += dx; } x = newX; y = newY; } }
The code simply moves a coordinate along the outline of a rectangle. Using this code, we can move the player and enemy and then render the screen:
void draw() { movePlayer(); moveEnemy(); drawBackground(); p.draw(); e.draw(); } void movePlayer() { playerStep.next(); p.x = playerStep.x; p.y = playerStep.y; } void moveEnemy() { enemyStep.next(); e.x = enemyStep.x; e.y = enemyStep.y; }
drawBackground() is similar to the code in the main game code. Only this time, we display the game title and a short explanation what the game is about.
We could also use this to display a high score list, etc.
void drawBackground() { fill(174, 204, 27); rect(0, 0, width, height); textAlign(CENTER, TOP); textSize(40); color outline = color(255,255,255); color fill = color(0,0,0); int y = height/2 - 60; textWithOutline("Run, Platty, Run!", width/2, y, outline, fill); y += 50; textSize(20); textWithOutline("Use cursor keys to evade the hungry crocodiles", width/2, y, outline, fill); y += 40; outline = color(0,0,255); fill = color(255,255,255); textWithOutline("Press any key to start", width/2, y, outline, fill); y += 20; }
The last element we need is a key handler which starts the game itself:
void keyPressed() { changeState(new MainGame()); }
Easy, isn’t it? Just imagine how complex this might have been without the refactoring. We might have ended up with a draw() method with several if(), checking for the current state of the game, trying to avoid messing with the wrong variables, …
By splitting the game into steps, each step can do it’s own thing. This is the major goal of refactoring: Cutting down dependencies.
The whole project can be cloned from here. The version of this blog post is tagged with v9.
Cool, our game is almost complete. One last thing is missing: Displaying the high score table.
Previous: Cleaning Up
First post: Getting Started
Tagged: Game, Games, Processing