Skip to content

Instantly share code, notes, and snippets.

@ybakos
Created February 28, 2014 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ybakos/9272925 to your computer and use it in GitHub Desktop.
Save ybakos/9272925 to your computer and use it in GitHub Desktop.
// TODO: Your Name
// Homework 14. Practicing using a loop to remove repetitive code.
// Improving drawAllForts with a loop.
final int TEXT_SIZE = 32;
color green = color(0, 200, 0);
color white = color(255);
int shipsLeft = 4;
int credit = 0;
void setup() {
size(640, 480);
background(0);
}
void draw() {
drawBottomStatusBar();
drawAllForts();
}
void drawAllForts() {
drawFort(0);
drawFort(1);
drawFort(2);
}
void drawFort(int fortNumber) {
final int BASE_X = 120;
final int BASE_Y = height - 170;
noStroke();
fill(green);
rect(BASE_X + (150 * fortNumber), BASE_Y, 70, 25, 20, 20, 0, 0);
rect(BASE_X + (150 * fortNumber), BASE_Y + 25, 25, 25);
rect(BASE_X + 45 + (150 * fortNumber), BASE_Y + 25, 25, 25);
}
void drawBottomStatusBar() {
drawBottomStatusBarLine();
drawCreditLeft();
drawNumberOfShipsLeft();
drawShipsLeft();
}
void drawBottomStatusBarLine() {
stroke(green);
line(0, height - 50, width, height - 50);
}
void drawNumberOfShipsLeft() {
setBottomBarTextStyle();
text(shipsLeft, 10, height - 20);
}
void drawShipsLeft() {
drawRemainingShip(0);
drawRemainingShip(1);
drawRemainingShip(2);
drawRemainingShip(3);
}
void drawRemainingShip(int shipNumber) {
final int BASE_X = 50;
final int BASE_Y = height - 40;
noStroke();
fill(green);
rect(BASE_X + (shipNumber * 50), BASE_Y, 40, 20, 10, 10, 0, 0);
rect(BASE_X + 17 + (shipNumber * 50), BASE_Y - 5, 5, 5);
}
// Draws 0X when X, the credit left, is less than 10.
// Otherwise draws the amount of credit left.
void drawCreditLeft() {
setBottomBarTextStyle();
text("CREDIT", width - (TEXT_SIZE * 6), height - 20);
if (credit < 10) {
text("0" + credit, width - (TEXT_SIZE * 2), height - 20);
} else {
text(credit, width - (TEXT_SIZE * 2), height - 20);
}
}
// Notice how this function just encapsulates repetitive
// code that is used by both drawShipsLeft and drawCreditLeft.
void setBottomBarTextStyle() {
fill(white);
textSize(TEXT_SIZE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment