/
example.js
executable file
·78 lines (62 loc) · 1.44 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var createGame = require('./index')
var Mouse = require('crtrdg-mouse')
var game = createGame()
var mouse = new Mouse(game)
var clicked = false
mouse.on('click', function () {
if (clicked) {
game.resume()
clicked = false
} else {
game.pause()
clicked = true
}
})
var box = {
size: { x: 10, y: 10 },
position: { x: game.width / 2 - 5, y: game.height / 2 - 5 }
}
box.update = function () {
box.position.x += rand(-3, 3)
box.position.y += rand(-3, 3)
}
box.boundaries = function () {
if (box.position.x <= 0) {
box.position.x = 0
}
if (box.position.x >= game.width - box.size.x) {
box.position.x = game.width - box.size.x
}
if (box.position.y <= 0) {
box.position.y = 0
}
if (box.position.y >= game.height - box.size.y) {
box.position.y = game.height - box.size.y
}
}
box.draw = function (context) {
context.fillStyle = '#fff'
context.fillRect(box.position.x, box.position.y, box.size.x, box.size.y)
}
game.on('start', function () {
console.log('started')
})
game.on('update', function (interval) {
box.update()
box.boundaries()
})
game.on('draw', function (context) {
context.fillStyle = '#f4d3a2'
context.fillRect(0, 0, game.width, game.height)
box.draw(context)
})
game.on('pause', function () {
console.log('paused')
})
game.on('resume', function () {
console.log('resumed')
})
function rand (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
game.start()