-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame-example.js
111 lines (100 loc) · 2.35 KB
/
game-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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class Player {
constructor (pos, speed, color) {
this.pos = pos
this.startx = pos[0]
this.starty = pos[1]
this.speed = speed
this.color = color
}
move (dir) {
if (dir === 'up') {
this.pos[1] -= this.speed
} else if (dir === 'down') {
this.pos[1] += this.speed
} else if (dir === 'left') {
this.pos[0] -= this.speed
} else {
this.pos[0] += this.speed
}
}
boundCheck (width, height) {
if (this.pos[0] < 0) {
this.pos[0] = 0
} else if (this.pos[0] > 230) {
this.pos[0] = 230
}
if (this.pos[1] < 0) {
this.pos[1] = 0
} else if (this.pos[1] > 230) {
this.pos[1] = 230
}
}
render (ctx) {
ctx.fillStyle = this.color
ctx.fillRect(this.pos[0], this.pos[1], 20, 20)
}
playerCollide (player) {
return ((this.pos[0] < player.pos[0] + 20) &&
(player.pos[0] < this.pos[0] + 20) &&
(this.pos[1] < player.pos[1] + 20) &&
(player.pos[1] < this.pos[1] + 20))
}
reset () {
this.pos[0] = this.startx
this.pos[1] = this.starty
}
}
const VIEWPORT_WIDTH = 250
const VIEWPORT_HEIGHT = 250
let keys = []
const c = document.getElementById('c')
c.width = VIEWPORT_WIDTH
c.height = VIEWPORT_HEIGHT
const ctx = c.getContext('2d')
document.body.addEventListener('keydown', function (e) {
keys[e.keyCode] = true
})
document.body.addEventListener('keyup', function (e) {
keys[e.keyCode] = false
})
let player1 = new Player([0, 0], 2, '#0000FF')
let player2 = new Player([220, 220], 4, 'FF0000')
function GameLoop () {
ctx.clearRect(0, 0, VIEWPORT_WIDTH, VIEWPORT_HEIGHT)
// player 1
if (keys[38]) {
player1.move('up')
}
if (keys[40]) {
player1.move('down')
}
if (keys[37]) {
player1.move('left')
}
if (keys[39]) {
player1.move('right')
}
// player 2
if (keys[87]) {
player2.move('up')
}
if (keys[83]) {
player2.move('down')
}
if (keys[65]) {
player2.move('left')
}
if (keys[68]) {
player2.move('right')
}
player1.boundCheck(VIEWPORT_WIDTH, VIEWPORT_HEIGHT)
player2.boundCheck(VIEWPORT_WIDTH, VIEWPORT_HEIGHT)
player1.render(ctx)
player2.render(ctx)
if (player1.playerCollide(player2) || player2.playerCollide(player1)) {
player1.reset()
player2.reset()
}
window.requestAnimationFrame(GameLoop)
}
window.requestAnimationFrame(GameLoop)