Skip to content

Latest commit

 

History

History
97 lines (68 loc) · 3.99 KB

7-keeping-the-score.md

File metadata and controls

97 lines (68 loc) · 3.99 KB

7. Keeping the Score

To skip this chapter use the following link

How many cherries did I pick up?

Lets add a global variable for the state telling how many cherries the player has picked up. So lets initiate a SCORE variable in _INIT and start with zero.

FUNCTION _INIT()
 SCORE=0
 FOR I=1,5 DO
  ADD_CHERRY()
 END
END

Increasing the score can be done when the game removes the cherry in the _UPDATE. You can increase it with I=I+1, but you may also use the shorthand += in PICO-8 (which isn't part of standard LUA).

FUNCTION _UPDATE()
 PLAYER:UPDATE()
 FOR CHERRY IN ALL(CHERRIES) DO
  IF DIST(PLAYER, CHERRY)<4 THEN
   DEL(CHERRIES, CHERRY)
   SCORE+=1
  END
 END
END

The last piece of the puzzle is to draw the score on the screen. Which we will do with PRINT again. So in our _DRAW function lets do this and use color 10 (yellow):

PRINT(SCORE,0,0,10)

Run the game with CTRL+R and it should look like this with the score printed out in the top left corner:

First score system

Respawn those cherries

After you've picked up all five cherries, there are no more to pick up! Lets add more cherries as you pick them up. In the _UPDATE function after updating all the cherries, add a cherry if there are less than five cherries available.

FUNCTION _UPDATE()
  -- SNIP SNIP
  IF #CHERRIES < 5 THEN
   ADD_CHERRY()
  END
END

When running the game it should look like this:

Respawning cherries

Feel free to remove the initialization of five cherries in the _INIT function.

Center the score!

In order to keep the score centered we need to know the width of the string. It will change once you've picked the tenth cherry and the 100th cherry. Thankfully we do know that the font is 4 pixels wide (including the 1 pixel space between characters).

We also need to know is how many characters the number has. This can be done by coercing the number to a string (w. PICO-8's TOSTR function or concatenating the number with a string) and get the length of that string.

Middle of the screen is at 64 pixels (i.e. half of 128 pixels). We can print the string with an offset away from 64 pixels based on the information above. Lets write a function that prints the text in the center:

FUNCTION PRINTC(VAL,Y,COL)
 LOCAL STR=TOSTR(VAL)
 PRINT(VAL,64-(#STR * 2),Y,COL)
END

Lets use that function to print the score, and concatenate a label to the number. E.g. SCORE: like this:

FUNCTION _DRAW()
 -- SNIP SNIP
 PRINTC("SCORE: "..SCORE,0,10)
END

Running the game should look like this, and the score should center together with the label:

Center the score

Points to review

  • There are shorthands in PICO-8 that don't exist in LUA. E.g. +=, -= etc.
  • Get the string from anything with TOSTR
  • Concatenate strings with .., also coerces number to a string