vi studio

Lessons · Building apps · 22 of 36

Timers and games

every(), stop(), on_touch, place: x, y and on_hit.

every(seconds, action) runs an action again and again and gives back a timer; stop(timer) ends it. A game is a step function that every runs about 30 times a second.

ball_y = 10
speed = 0
loop = 0

step():
  speed = speed + 0.3
  ball_y = ball_y + speed
  if (ball_y > 90):
    ball_y = 90
    speed = 0 - speed * 0.7

drop():
  stop(loop)
  ball_y = 10
  speed = 0
  loop = every(0.03 seconds, step())

main court:
  color: slate[900]
  on_touch: drop()
  children:
    ball:
      place: 50, ball_y
      size: 10
      shape: circle
      color: orange[400]
    hint:
      place: 50, 96
      text: "Tap to drop the ball"
      text_style: 14, white
main field:
  on_hit:
    ball, wall: bounce()
    ball, goal:
      score()
      play(@cheer.mp3)

The Comet Glide template is a whole game built this way.

Every example here runs in Vi Studio: open it in your browser (phones too) and press Start learning on the welcome page. Each code block there has a Try it button that runs it in the phone preview.

More in Building apps

About Vi. Vi is a free, open-source programming language for building real mobile apps. You describe each screen in plain words, and Vi compiles it to React Native (Expo) for Android, iOS and the web. Its editor, Vi Studio, runs on Windows, in any browser and on your phone, with the app running live as you type. Read more about Vi.