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
const BALL_W = 5, RACKET_W = 35, RACKET_Y = 300, SPEED = 10; const FIELD_W = 270, FIELD_H = 370; const LEFT = BALL_W, TOP = BALL_W, BORDER = RACKET_Y - BALL_W, RIGHT = FIELD_W - BALL_W, BOTTOM = FIELD_H - BALL_W; var timer = null; var ball, racket; var ball_x, ball_y, racket_x; var dx = 0, dy = 0; var touch_event, move_event; var acc_x = 0; window.onload = function() { ball = get("ball"); racket = get("racket"); field = get("field"); if (window.ontouchstart === null) { touch_event = "touchstart"; move_event= "touchmove"; } else { touch_event = "mousedown"; move_event = "mousemove"; } field.addEventListener(touch_event, field_touch, false); field.addEventListener(move_event, racket_move, false); window.addEventListener("devicemotion", acc_change); init_game(); }; function field_touch(e) { if (timer != null) return; init_game(); timer = setInterval(move_ball, 30); get("message").style.display = "none"; } function racket_move(e) { if (timer == null) return; var rc = field.getBoundingClientRect(); var x; if (e.type == "touchmove") { x = e.touches[0].clientX; } else if (e.type == "mousemove") { x = e.clientX; } adjust_racket_pos(x - rc.left); draw(); } function acc_change(e) { acc_x = e.accelerationIncludingGravity.x; } function init_game() { ball_x = racket_x = FIELD_W / 2; ball_y = BORDER; get_move_dir(); draw(); } function get_move_dir() { var a = Math.random() * Math.PI / 4; if (dx < 0) a = -a; dx = Math.sin(a) * SPEED; dy = -Math.cos(a) * SPEED; } function move_ball() { ball_x += dx; ball_y += dy; if (acc_x > 0.5) adjust_racket_pos(racket_x + 5); if (acc_x < -0.5) adjust_racket_pos(racket_x - 5); if (ball_x < LEFT) { ball_x = 2 * LEFT - ball_x; dx = -dx; } if (ball_x > RIGHT) { ball_x = 2 * RIGHT - ball_x; dx = -dx; } if (ball_y < TOP) { ball_y = 2 * TOP - ball_y; dy = -dy; } if (ball_y > BOTTOM) { ball_x -= dx / dy * (ball_y - BOTTOM); ball_y = BOTTOM; clearInterval(timer); timer = null; } if (ball_y > BORDER) { var k = (ball_y - BORDER) / dy; if (k < 1) { var x = ball_x - dx * k; if (Math.abs(x - racket_x) < RACKET_W) { get_move_dir(); ball_x = x + dx * (1 - k); ball_y = BORDER + dy * (1 - k); } } } draw(); } function draw() { set_ball_pos(ball_x - BALL_W, ball_y - BALL_W); set_racket_pos(racket_x - RACKET_W); } function set_ball_pos(x, y) { ball.style.left = (x + "px"); ball.style.top = (y + "px"); } function adjust_racket_pos(x) { racket_x = Math.min(Math.max(x, RACKET_W), FIELD_W - RACKET_W); } function set_racket_pos(x) { racket.style.left = (x + "px"); } function get(id) { return document.getElementById(id); }