-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.ts
132 lines (117 loc) · 2.84 KB
/
game.ts
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
function triggerGame() {
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);
setInterval(game, 8);
}
let pos1: number, pos2: number, speed: number, baseSpeed: number, score1: number, score2: number, bx: number, by: number, bs: number, vx: number,
vy: number, sh: number, sw: number, pw1: number, pw2: number;
score1 = score2 = 0;
bx = by = 150;
bs = 10;
speed = 1;
baseSpeed = 1;
vx = vy = 1;
sh = 300;
sw = 400;
pw1 = pw2 = 50;
pos1 = pos2 = (sh / 2) - pw1;
function game(event: Event) {
let c = <HTMLCanvasElement>document.getElementById('game');
let ctx: CanvasRenderingContext2D = c.getContext('2d');
// do black background
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, sw, sh);
// score point
if (bx <= 10) {
score2++;
bx = (sw / 2) - bs / 2;
by = (sh / 2) - bs / 2;
speed = baseSpeed;
}
if (bx >= sw - 10) {
score1++;
bx = (sw / 2) - bs / 2;
by = (sh / 2) - bs / 2;
speed = baseSpeed;
}
// collide top and bottom
if (by < bs) {
vy = speed;
}
if (by > sh - bs) {
vy = speed * -1;
}
// collide w players
if (bx <= 21 && by + bs >= pos1 && by < pos1 + pw1) {
speed += 0.25;
vx = speed;
}
if (bx + bs >= sw - 21 && by + bs >= pos2 && by < pos2 + pw2) {
speed += 0.25;
vx = speed * -1;
}
// move players
if (wDown && pos1 >= 9) {
pos1 -= 2;
}
if (sDown && pos1 < sh - 9 - pw1) {
pos1 += 2;
}
if (upDown && pos2 >= 9) {
pos2 -= 2;
}
if (downDown && pos2 < sh - 9 - pw2) {
pos2 += 2;
}
// draw players
ctx.fillStyle = '#ffffff';
ctx.fillRect(10, pos1, 10, pw1);
ctx.fillRect(sw - 20, pos2, 10, pw2);
// move ball
bx += vx;
by += vy;
// draw ball
ctx.fillRect(bx, by, bs, bs);
// draw score
ctx.font = "20px Courier New";
ctx.fillText(String(score1), (sw / 2) - 40, 20);
ctx.fillText(String(score2), (sw / 2) + 40, 20);
}
let wDown: boolean, sDown: boolean, upDown: boolean, downDown: boolean;
wDown = sDown = upDown = downDown = false;
function keyDown(event: KeyboardEvent) {
if (event.keyCode === 87) {
// w
wDown = true;
}
if (event.keyCode === 83) {
// s
sDown = true;
}
if (event.keyCode === 38) {
// up
upDown = true;
}
if (event.keyCode === 40) {
// down
downDown = true;
}
}
function keyUp(event: KeyboardEvent) {
if (event.keyCode === 87) {
// w
wDown = false;
}
if (event.keyCode === 83) {
// s
sDown = false;
}
if (event.keyCode === 38) {
// up
upDown = false;
}
if (event.keyCode === 40) {
// down
downDown = false;
}
}