Set a Time Limit

To make the game competitive, let’s give the player 100 seconds to play. That way, a higher score indicates more skill, not just more patience.

Gosu has a class method Gosu.milliseconds that returns the number of milliseconds since the game started. You use this method to calculate how many seconds the player has been playing, and subtract that from 100. In the update method, you figure out how many seconds remain and convert it to a string:

WhackARuby/WhackARuby_1/whack_a_ruby.rb
 
def​ update
 
@x += @velocity_x
 
@y += @velocity_y
 
@velocity_x *= -1 ​if​ @x + @width / 2 > 800 || @x - @width / 2 < 0
 
@velocity_y *= -1 ​if​ @y + @height / 2 > 600 || @y - @height / 2 < 0
 
@visible -= 1
 
@visible = 30 ​if​ @visible < -10 ...

Get Learn Game Programming with Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.