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
|
<center>
<canvas id="canvas"></canvas>
</center>
<script>
var WIDTH = 300
var HEIGHT = 400
window.onload = function(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.width = WIDTH;
canvas.height = HEIGHT;
document.addEventListener("keydown",keyDown);
document.addEventListener("keyup",keyUp);
setInterval(game, 1000/10);
}
var tileCountWidth = 30;
var tileCountHeight = 40;
var tileWidth = WIDTH/tileCountWidth;
var tileHeight = HEIGHT/tileCountHeight;
var ballX = WIDTH/2;
var ballY = 10;
var leftUp = false;
var rightUp = false;
var vx = randomInt(20)-10;
var vy = 0;
var ay = 2;
var ymax = 20;
var length = 5;
var paddleWidth = 11;
function game(){
update()
color("black");
// BACKGROUND
ctx.fillRect(0,0,WIDTH, HEIGHT);
// SIDES
color("blue");
ctx.fillRect(0,0,tileWidth, HEIGHT);
// console.log(WIDTH, tileWidth, tileCountWidth)
ctx.fillRect(WIDTH-tileWidth, 0, tileWidth, HEIGHT);
ctx.beginPath();
// DRAW BALL
color("white");
ctx.fillRect(ballX, ballY, tileWidth, tileHeight);
// DRAW PADDLES
color("red");
ctx.lineWidth=10;
ctx.moveTo(1*tileWidth, 33*tileHeight);
if(leftUp){
ctx.lineTo((1+paddleWidth)*tileWidth, 33*tileHeight);
} else {
ctx.lineTo((1+paddleWidth)*tileWidth, 35*tileHeight);
}
ctx.stroke();
var t = tileCountWidth - 1
ctx.moveTo(t*tileWidth, 33*tileHeight);
if(rightUp){
ctx.lineTo((t-paddleWidth)*tileWidth, 33*tileHeight);
} else {
ctx.lineTo((t-paddleWidth)*tileWidth, 35*tileHeight);
}
ctx.stroke();
}
function update(){
if(((leftUp && ballX/tileWidth <=8) || (rightUp && ballX/tileWidth >=13))
&& ballY/tileHeight <= 35 && ballY/tileHeight >= 32){
console.log("Hit!")
vy=-20
}
vy += ay
vy = Math.min(vy, ymax)
ballY += vy
ballX += vx
if(ballX <= tileWidth){
ballX = tileWidth
vx = -vx
}
if(ballX >= WIDTH-(2*tileWidth)){
ballX = WIDTH-(2*tileWidth)
vx = -vx
}
}
function keyUp(e){
switch(e.keyCode){
case 37:
leftUp = false;
break;
case 39:
rightUp = false;
break;
}
}
function keyDown(e){
switch(e.keyCode){
case 37:
leftUp = true;
break;
case 39:
rightUp = true;
break;
}
}
function setRandomCoords(item){
item.x = randomInt(tileWidth);
item.y = randomInt(tileHeight);
}
function randomInt(max){
return Math.floor(Math.random()*max);
}
function font(size){
ctx.font=size+"px Courier";
}
function color(c){
ctx.strokeStyle=c;
ctx.fillStyle=c;
}
</script>
|