Kodeck

Lesson 6 of 7

High score

Dodge the falling blocks for as long as you can. The record stays even after the console is switched off.

In this lesson

  • Splitting a program into small functions
  • A function that returns an answer
  • Measuring time with millis()
  • Saving a number so it survives switching off

Stick: drag the pad or use the arrow keys. Buttons: the X and Y keys. In the browser the record is kept in this browser.

A browser copy of the same program, written in JavaScript, so you can try it before uploading. On Kodeck the C++ code below runs.

On the console: in the Arduino IDE open File > Examples > Kodeck > 06_HighScore and press Upload.

First time? Setting up the Arduino IDE

The code, step by step

The whole program, from top to bottom. The comment at the top of the file repeats what this page says. The file on GitHub

#include <Kodeck.h>

const int BLOCKS = 6;
float blockX[BLOCKS], blockY[BLOCKS], blockSpeed[BLOCKS];
float playerX = 150;
const int PLAYER_Y = 210;
uint32_t startTime;
int seconds = 0;
int best = 0;
bool playing = true;
bool newRecord = false;

What the game remembers

Six blocks, the player, the time and the record. uint32_t is a large whole number without a sign: the right type for milliseconds.

void placeBlock(int i) {
  blockX[i] = random(0, 290);
  blockY[i] = -random(20, 240);  // start above the screen, at different heights
  blockSpeed[i] = 2 + random(0, 20) / 10.0;
}

void resetGame() {
  for (int i = 0; i < BLOCKS; i++) placeBlock(i);
  playerX = 150;
  startTime = millis();
  seconds = 0;
  playing = true;
  newRecord = false;
}

Starting positions

placeBlock(i) puts block number i above the screen, at a random height between 20 and 240 pixels up, so the blocks do not all arrive at once.

resetGame() places all blocks and remembers when the game started: millis() is the number of milliseconds since the console was switched on.

// Moves every block; returns true if one of them hit the player
bool moveBlocks() {
  bool hit = false;
  float extra = seconds * 0.08;  // it gets harder with time
  for (int i = 0; i < BLOCKS; i++) {
    blockY[i] = blockY[i] + blockSpeed[i] + extra;
    if (blockY[i] > 240) placeBlock(i);
    if (blockX[i] < playerX + 20 && playerX < blockX[i] + 30 && blockY[i] + 20 > PLAYER_Y && blockY[i] < PLAYER_Y + 16) hit = true;
  }
  return hit;
}

A function with an answer

bool moveBlocks() moves the blocks and then answers a question: did any block hit the player? return hit; gives that answer back to the line that called the function.

The blocks fall a little faster every second: seconds * 0.08 is added to each block's speed.

void endGame() {
  playing = false;
  kodeck.sound.noise(400, 0.6);
  if (seconds > best) {
    best = seconds;
    newRecord = true;
    kodeck.save("best", best);  // written to flash memory
  }
}

Saving the record

If this game lasted longer than the best one, the new record is saved: kodeck.save("best", best) writes the number into the console's flash memory under the name “best”. Flash memory keeps its contents without power.

void drawGame() {
  auto& g = kodeck.screen;
  g.fillScreen(BLACK);
  for (int i = 0; i < BLOCKS; i++) g.fillRect(blockX[i], blockY[i], 30, 20, RED);
  g.fillRoundRect(playerX, PLAYER_Y, 20, 16, 4, CYAN);

  g.setTextColor(WHITE);
  g.setCursor(4, 4);
  g.printf("TIME %d   BEST %d", seconds, best);
  if (!playing) {
    g.setTextDatum(middle_center);
    g.setTextSize(2);
    g.setTextColor(newRecord ? YELLOW : WHITE);
    g.drawString(newRecord ? "NEW RECORD!" : "HIT!", 160, 100);
    g.setTextSize(1);
    g.setTextColor(WHITE);
    g.drawString("Y: play again", 160, 130);
    g.setTextDatum(top_left);
  }
}

Drawing

All drawing is in one function. The message after the game depends on newRecord: “NEW RECORD!” in yellow or “HIT!” in white.

void setup() {
  kodeck.begin();
  best = kodeck.load("best", 0);  // 0 if nothing has been saved yet
  resetGame();
}

Reading the record

kodeck.load("best", 0) reads the saved number. The 0 is the answer for the very first start, when nothing has been saved yet.

void loop() {
  if (playing) {
    playerX = constrain(playerX + kodeck.stick.x * 6 / 100.0, 0, 300);
    seconds = (millis() - startTime) / 1000;
    if (moveBlocks()) endGame();
  } else if (kodeck.pressed(BUTTON_Y)) {
    if (kodeck.held(BUTTON_X)) {  // X + Y: erase the record
      best = 0;
      kodeck.save("best", 0);
      kodeck.sound.slide(1200, 200, 300);
    }
    resetGame();
  }
  drawGame();
  kodeck.show();
}

A short loop

Because the work is in functions, loop() reads almost like a description: move the player, count the seconds, move the blocks, end the game on a hit, draw, show.

Dividing milliseconds by 1000 gives whole seconds. Holding X while pressing Y erases the record.

Try it yourself

  • Harder faster

    Make the game speed up twice as fast.

    Hint

    In moveBlocks(), change 0.08 to 0.16.

  • Games played

    Count how many games were played on this console, and keep the count when it is switched off.

    Hint

    Load the count in setup() with kodeck.load("games", 0), add one in endGame() and save it with kodeck.save("games", games).

  • Record in sight

    Show BEST in yellow while the current game is beating the record.

    Hint

    In drawGame(), choose the colour with seconds > best ? YELLOW : WHITE before printing.