web/keys
Keyboard state for browser games.
import web.keys
On this page
In a game you usually ask once per frame which keys are down, rather than taking an event for every press. This package listens to the keyboard events for you and keeps the state. Call Init once, then ask for the state inside the EveryFrame function from dom.
Functions
Track
func Track(k: str)Adds a key to the list of tracked keys; the key name is the browser
key value, such as a. Up to 32 keys.import dom
import web.canvas
import web.keys
mut x := 160.0
mut score := 0
func main:
el := dom.Create("canvas")
dom.SetAttr(el, "id", "game")
dom.Append(dom.Body(), el)
c := canvas.Get("game")
keys.Init()
keys.Track("a")
keys.Track("d")
dom.EveryFrame((now: f64):
if keys.Down("ArrowLeft") or keys.Down("a"):
x -= 4
end
if keys.Down("ArrowRight") or keys.Down("d"):
x += 4
end
if keys.Pressed(" "):
score += 1
end
canvas.ClearRect(c, 0, 0, canvas.Width(c), canvas.Height(c))
canvas.FillRect(c, x - 10, 100, 20, 20)
canvas.FillText(c, "score: " + score, 10, 20)
end)
endInit
func Init()Starts tracking and adds the arrow keys, Enter and the space bar. Those keys no longer scroll the page.
The example for this item is shown with the ones above: web-keys-Game.salam
Down
func Down(k: str): boolThe key is being held right now; for continuous movement.
The example for this item is shown with the ones above: web-keys-Game.salam
Pressed
func Pressed(k: str): boolThe key has been pressed since the last time you asked; every press returns true exactly once. For jumping or shooting.
The example for this item is shown with the ones above: web-keys-Game.salam