ArcBasicDocs
Chapter 10

Collisions, scores and time

Games are about things touching: catching a coin, getting hit by a rock, reaching the exit. In this chapter you'll learn to spot when two things touch, keep score, and race the clock.

10_coins.absOpen in editor
; Catch the coins: collisions, a score and a time limitGraphics 640, 480SetBuffer BackBuffer()SeedRnd MilliSecs()basketX = 290coinX = Rand(20, 600) : coinY = 0score = 0endTime = MilliSecs() + 30000       ; MilliSecs counts in thousandths of a second: this is 30 seconds awayWhile Not KeyHit(1)	timeLeft = (endTime - MilliSecs()) / 1000	If timeLeft < 0 Then timeLeft = 0	If timeLeft > 0		; move the basket		If KeyDown(203) And basketX > 0 Then basketX = basketX - 7		If KeyDown(205) And basketX < 580 Then basketX = basketX + 7		; the coin falls		coinY = coinY + 4		; caught it? Do the basket's and the coin's rectangles overlap?		If RectsOverlap(basketX, 440, 60, 20, coinX, coinY, 20, 20)			score = score + 1			coinX = Rand(20, 600) : coinY = 0		EndIf		; missed it: a new coin starts at the top		If coinY > 480 Then coinX = Rand(20, 600) : coinY = 0	EndIf	Cls	Color 255, 210, 0	Oval coinX, coinY, 20, 20	Color 120, 200, 255	Rect basketX, 440, 60, 20	Color 255, 255, 255	Text 10, 10, "Score: " + score	Text 560, 10, "Time: " + timeLeft	If timeLeft = 0 Then Text 320, 220, "Time's up! You caught " + score + " coins.", True, True	FlipWendEnd
A coin falling towards a blue basket

Did they touch?

Almost every game cheats a little: it treats each thing as a rectangle, even when it's drawn as a circle or a ship. RectsOverlap takes two rectangles, each as x, y, width and height, and says whether they overlap. Here one is the basket and the other is the box around the coin. If they overlap, the coin was caught: add a point and send a new coin from the top.

Rectangles that are a little smaller than the drawing feel fairer to players. Nobody likes being hit by something that clearly missed them.

Keeping score

A score is just a variable you add to, and Text shows it, joined to some words. Draw it last, so it sits on top of everything else.

Keeping time

MilliSecs() is a clock that counts thousandths of a second. On its own the number means nothing, but the difference between two readings is a length of time. The program works out when the game should end (now, plus 30,000 thousandths) and each frame divides what's left by 1000 to get whole seconds. When it reaches 0, the basket stops moving and the final score shows.

Timing with MilliSecs() means 30 seconds is 30 seconds on any computer. Counting frames instead is simpler, but the time would depend on how fast the screen refreshes.

Try this

  • Make the coin fall faster as the score goes up. (Hint: coinY = coinY + 4 + score / 5.)
  • Add a red bomb that falls too. Catching it costs 3 points.
  • Keep a best score, and press Space after time's up to play again.