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
place: x, yputs a container's middle at x across and y down, out of 100. Change x and y in the step function and it moves.on_touchreacts the moment a finger lands: better thanon_tapfor "tap to jump".on_hitnotices when two containers start to overlap:
main field:
on_hit:
ball, wall: bounce()
ball, goal:
score()
play(@cheer.mp3)
flip: 180turns a container over (a card flip) andtilt: 20leans it back, in degrees.- Edit the code while a game runs and the old timers stop by themselves.
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
- Screensgo_to, go_back, transitions, and phone / tablet / desktop.
- Containers that take valuescard(task): one container, many values.
- Repeating thingsrepeat: task in tasks, grids, index, x, y and .at().
- Reaching other containersInside names, parent.name and top-level names.
- Changing the screenA dot for one change, a block for several; wait and animate.
- Sound and videoplay, loop, stop_sounds, audio and video.
- Files and projectssrc/, every file sees every name, one name in one file.
- The config blockApp name, store id, version, icon and splash screen.
- Errors and good habitsThe real error messages and their fixes; how to organise a project.
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.