Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Бонус #2

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "qunit"]
path = qunit
url = git://github.com/jquery/qunit.git
123 changes: 123 additions & 0 deletions Ball.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* Created with JetBrains WebStorm.
* User: yunnii
* Date: 12/1/12
* Time: 3:35 AM
* To change this template use File | Settings | File Templates.
*/
/*global R: true*/

(function (exports) {
"use strict";

/**
* Конструктор, принимает координаты центра шара, радиус и объект на котором необходимо его разместить
*
* @param {object} paper
* @param {double}x
* @param {double}y
* @param {double}r
*
* @example
* item.set({title: "March 20", content: "In his eyes she eclipses..."});
*/
var Ball = function (paper, x, y, r) {
this.r = r;
this.circle = paper.circle(x, y, r).attr({fill: "#66e", "stroke-width": 2});
this.areaRadius = r + 30;
};

/** Отдает поле circle в виде строки типа Raphael.path
*
* @return {string} Cтроковое представление.
*/
function getCircleToPath(x, y, r) {
var s = "M";
s = s + (x) + "," + (y - r) + "A" + r + "," + r + ",0,1,1," + (x - 0.1) + "," + (y - r) + "z";
return s;
}

exports.Ball = Ball;

/** Изменяет положение объекта
*
* @param {double}x - новая координата х центра
* @param {double}y - новая координат у центра
*/
Ball.prototype.SetXY = function (x, y) {
this.circle.attrs.cx = x;
this.circle.attrs.cy = y;
};

Ball.prototype.X = function () { return this.circle.attrs.cx; };
Ball.prototype.Y = function () { return this.circle.attrs.cy; };
Ball.prototype.circleString = function () { return getCircleToPath(this.X(), this.Y(), this.r); };

var speed = 50;

/** Перемещение в указанном направлении
*
* @param {double}x - координата x, откуда по отношению к центру был толчок
* @param {double}y - координата y, откуда по отношению к центру был толчок
*/

Ball.prototype.moveBall = function (x, y) {

var center = {X : this.X(), Y: this.Y()},
tangens = (x - center.X === 0) ? 0 : (y - center.Y) / (x - center.X),
nextX,
nextY;

if (x - center.X === 0) {
nextX = center.X;
nextY = (y - center.Y > 0) ? center.Y - speed :
center.Y + speed;
} else {
nextX = (x - center.X > 0) ? center.X - speed :
center.X + speed;
nextY = tangens * nextX + (center.Y - tangens * center.X);
if (Math.abs(tangens) > 1.1) {
nextY = (y - center.Y > 0) ? center.Y - speed :
center.Y + speed;
}
}

this.circle.animate({cx: nextX, cy: nextY}, 1000);
this.SetXY(nextX, nextY);
};

/** Принадлежит ли точка, переданная в параметре окрестности радиуса this.areaRadius шара
*
* @param {double}x - координата x
* @param {double}y - координата y
*/
Ball.prototype.isNearBall = function (x, y) {
return (Math.abs(this.X() - x) < this.areaRadius &&
Math.abs(this.Y() - y) < this.areaRadius);
};

/** Перемещение в указанном направлении
* ищем уравнение прямой, перпендикулярной стенке, о которую ударились
* находим точку, симметричную центру относительно данной прямой
*
* @param {double}hitX - координата x столкновения со стенкой
* @param {double}hitY - координата y столкновения со стенкой
* @param {double}tangens - тангенс угла наклона стенки
*/

Ball.prototype.findReflectionPoint = function (hitX, hitY, tangens) {
var center = {X : this.X(), Y: this.Y()},
revertTangens = (tangens === 0) ? 0 : 1 / tangens;

var x = (tangens === 0) ? hitX : (tangens / (tangens * tangens + 1)) * (hitY - center.Y + tangens * center.X + hitX * revertTangens);
var y = (tangens === 0) ? center.Y : tangens * x + (center.Y - tangens * center.X);

var resultX = 2 * x - center.X,
resultY = 2 * y - center.Y;

var pushX = 2 * hitX - resultX,
pushY = 2 * hitY - resultY;

return {x : pushX, y: pushY};
};
}(window));
130 changes: 130 additions & 0 deletions animate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* Created by .
* User: yunnii
* Date: 11/29/12
* Time: 2:47 PM
* To change this template use File | Settings | File Templates.
*/
/*global $: true*/
/*global alert: true*/
/*global Raphael: true*/
/*global model: true*/
/*global Ball: true*/
/*global tmpl: true*/
(function (exports) {
"use strict";

// exports.R = R;
var template = "M <%= x1 %>,<%= y1 %> L <%= x2 %>, <%= y2 %> L <%= x1 %>,<%= y1 %>",
el,
start = null,
idInterval,
pathArray,
borderArray;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

        pathArray = [],
        borderArray = [];

Иначе не работает


function intersectChecker() {
setInterval(function () {
var i,
bbox,
intersect,
hit,
nextPoint,
tan;

for (i = 0; i < pathArray.length; i += 1) {

intersect = Raphael.pathIntersection(pathArray[i], el.circleString());
if (intersect.length > 0) {
clearInterval(idInterval);

hit = { x: 0, y: 0};
intersect.forEach(function (el) {
hit.x += el.x;
hit.y += el.y;
});
hit.x /= intersect.length;
hit.y /= intersect.length;

bbox = borderArray[i].getBBox();
tan = (bbox.x - bbox.x2 === 0) ? 0 : (bbox.y - bbox.y2) / (bbox.x - bbox.x2);

nextPoint = el.findReflectionPoint(hit.x, hit.y, tan);

el.moveBall(nextPoint.x, nextPoint.y);
idInterval = setInterval(function () {
el.moveBall(nextPoint.x, nextPoint.y);
}, 1000);
}
}
}, 100);
}

function moveBall(e) {
if (start === null) {
start = 1;
intersectChecker();
}
e = e || window.event;

if (el.isNearBall(e.pageX, e.pageY)) {
clearInterval(idInterval);
el.moveBall(e.pageX, e.pageY);
idInterval = setInterval(function () {
el.moveBall(e.pageX, e.pageY);
}, 1000);

e.isImmediatePropagationStopped();
}
}

/**
* инициализируем шар
*/
function load() {

var colour = "r(0.5,0.5)hsb(4.8, 1, 1)-hsb(4.8, 1, .3)",
canvas = Raphael("main", 1000, 1000);

pathArray.forEach(function (path) {
canvas.path(path)
.attr({fill: "#ddd", "fill-opacity": 1, stroke: "#fff", "stroke-width": 16});
borderArray.push(canvas.path(path)
.attr({fill: "#ddd", "fill-opacity": 1, stroke: "#333", "stroke-width": 12}));
});

el = new Ball(canvas, 260, 350, 30);

$("#main").mousemove(moveBall);
}

/** Загружаем координаты стенки
*/
function initialise() {

$.getJSON('data.json')
.error(function () { alert("Попробуйте позже, сервер недоступен =)"); })
.success(function (result) {
if (result.length === 0) {
return;
}

var i;

for (i = 0; i < result.length - 1; i += 1) {
pathArray.push(tmpl(template, { x1: result[i].x,
y1: result[i].y,
x2: result[i + 1].x,
y2: result[i + 1].y}));
}
pathArray.push(tmpl(template, { x1: result[result.length - 1].x,
y1: result[result.length - 1].y,
x2: result[0].x,
y2: result[0].y}));

load();
});
}

$(document).ready(initialise);

}(window));
42 changes: 42 additions & 0 deletions data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[
{
"x": "26",
"y": "290"
},
{
"x": "94",
"y": "120"
},
{
"x": "204",
"y": "100"
},
{
"x": "410",
"y": "280"
},
{
"x": "478",
"y": "212"
},
{
"x": "448",
"y": "86"
},
{
"x": "610",
"y": "34"
},
{
"x": "686",
"y": "200"
},
{
"x": "680",
"y": "478"
},
{
"x": "234",
"y": "478"
}
]
22 changes: 22 additions & 0 deletions demo.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
body {
background: #ccc;
color: #ccc;
font: 300 100.1% "Helvetica Neue", Helvetica, "Arial Unicode MS", Arial, sans-serif;
}
#holder {
left: 20%;
position: absolute;
top: 10%;
height: 540px;
width: 740px;
}
#copy {
bottom: 0;
font: 300 .7em "Helvetica Neue", Helvetica, "Arial Unicode MS", Arial, sans-serif;
position: absolute;
right: 1em;
text-align: right;
}
#copy a {
color: #fff;
}
19 changes: 19 additions & 0 deletions main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>Бонусное дз</title>
<link rel="stylesheet" href="demo.css"media="screen">
<style media="screen">

</style>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="raphael.js"></script>
<script src="Ball.js"></script>
<script src="templating.js"></script>
<script src="animate.js"></script>
</head>
<body id="main">
<div id="holder"></div>
</body>
</html>
18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"x": "dz-bonus",
"y": "Simple ball game",
"author": {
"name": "Yunnii"
},
"version": "1.0.0",
"scripts": {
"test": "make test"
},
"dependencies": {
"connect": "1.1.4"
},
"engines": {
"node": ">=0.6.12",
"npm": ">=1.1.4"
}
}
Loading