game.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. function createSound(name, url) {
  2. var deferred = Q.defer();
  3. soundManager.createSound({
  4. id: name,
  5. url: url,
  6. autoLoad: true,
  7. onload: function() {
  8. deferred.resolve(this);
  9. }
  10. });
  11. return deferred.promise;
  12. }
  13. function sign(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }
  14. function lerp(from, to, p) {
  15. return to * p + from * (1 - p);
  16. }
  17. function ease(v) { return v * v * (3 - 2 * v); }
  18. function easeOutExpo(t, b, c, d) {
  19. return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  20. }
  21. function color(r,g,b,a) {
  22. return 'rgba('+r+','+g+','+b+','+a.toFixed(5)+')';
  23. }
  24. var SoundSafari = function(canvas, beatInfo, pSoundManager) {
  25. var ctx = canvas.getContext('2d');
  26. // Constants
  27. var RADIUS = 8;
  28. var LEAF_SIZE = 8;
  29. var LEVEL_SIZE = 800;
  30. var ALLOWANCE = (LEVEL_SIZE - canvas.width)/2;
  31. var METER_WIDTH = 120;
  32. var METER_HEIGHT = 40;
  33. var METER_SPEED = 10;
  34. var PLAYER_SPEED = 50;
  35. var STAGE_SPEED = 25;
  36. var RIPPLE_SIZE = 10;
  37. var RIPPLE_SPEED = 10;
  38. var DOT_SIZE = 3;
  39. var DOT_DISTANCE = 4 * 5;
  40. var state = StateMachine.create({
  41. initial: 'waiting',
  42. events: [
  43. {name: 'play', from: 'waiting', to: 'playing'},
  44. {name: 'point', from: 'playing', to: 'waiting'}
  45. ],
  46. callbacks: {
  47. onpoint: function() {
  48. ++points;
  49. soundManager.play('get');
  50. switchBeat(points % beats.length);
  51. }
  52. }
  53. });
  54. var starColors = [
  55. 'maroon',
  56. 'red',
  57. 'orange',
  58. 'yellow',
  59. 'olive',
  60. 'green',
  61. 'teal',
  62. 'blue',
  63. 'navy',
  64. 'purple'
  65. ];
  66. var paused = false;
  67. var debug = false;
  68. var beats = [];
  69. var gameTime = 0;
  70. var currentBeats = [];
  71. var switchBeat = function(index) {
  72. var currentBeat = beats[index];
  73. currentBeats.push(currentBeat);
  74. if(currentBeats.length > 4) {
  75. currentBeats.splice(0, 1);
  76. }
  77. activeTarget = new Target(currentBeat);
  78. entities.push(activeTarget);
  79. };
  80. var soundPromise = pSoundManager.then(function() {
  81. var soundPromises = beatInfo.map(function(elem, index) {
  82. var beat = { info: elem, rounds: 0 };
  83. var promise = createSound('beat'+index, elem.url).then(function(sound) {
  84. beat.sound = sound;
  85. });
  86. beats.push(beat);
  87. return promise;
  88. });
  89. soundPromises.push(createSound('get', 'sound/get.mp3'));
  90. return Q.all(soundPromises);
  91. });
  92. // Input handling
  93. var keysDown = {};
  94. addEventListener('keydown', function(e) {
  95. keysDown[e.keyCode] = true;
  96. }, false);
  97. addEventListener('keyup', function(e) {
  98. if(e.keyCode == 68) {
  99. debug = !debug;
  100. }
  101. if(e.keyCode == 80) {
  102. pause();
  103. }
  104. delete keysDown[e.keyCode];
  105. }, false);
  106. addEventListener('blur', function() {
  107. if(!paused) pause();
  108. });
  109. // Drawing functions
  110. function drawCircle(point, r, w, color) {
  111. ctx.beginPath();
  112. ctx.arc(point.x, point.y, r, 0, 2*Math.PI, false);
  113. ctx.lineWidth = w;
  114. ctx.strokeStyle = color;
  115. ctx.stroke();
  116. }
  117. function drawLeafV(point, h, w) {
  118. ctx.beginPath();
  119. ctx.moveTo(point.x, point.y);
  120. ctx.quadraticCurveTo(point.x + w, point.y + h/2, point.x, point.y + h);
  121. ctx.quadraticCurveTo(point.x - w, point.y + h/2, point.x, point.y);
  122. ctx.fill();
  123. }
  124. function drawLeafH(point, w, h) {
  125. ctx.beginPath();
  126. ctx.moveTo(point.x, point.y);
  127. ctx.quadraticCurveTo(point.x + w/2, point.y + h, point.x + w, point.y);
  128. ctx.quadraticCurveTo(point.x + w/2, point.y - h, point.x, point.y);
  129. ctx.fill();
  130. }
  131. function drawPlayer(point) {
  132. drawCircle(point, RADIUS, 5, "#FFFFFF");
  133. }
  134. function drawSpectrum() {
  135. var barHeight = 30;
  136. var barWidth = 6;
  137. var barSpacing = 2;
  138. var margin = 5;
  139. ctx.strokeStyle = 'white';
  140. ctx.lineWidth = 2;
  141. ctx.beginPath();
  142. ctx.rect(
  143. margin - ctx.lineWidth,
  144. canvas.height - barHeight - ctx.lineWidth - margin,
  145. activeTarget.spectrum.length * (barWidth+barSpacing) + 2 * ctx.lineWidth - barSpacing,
  146. barHeight + 2 * ctx.lineWidth
  147. );
  148. ctx.stroke();
  149. for(var i = 0; i < activeTarget.spectrum.length; ++i) {
  150. var height = activeTarget.spectrum[i]*20;
  151. ctx.fillStyle = starColors[i];
  152. ctx.fillRect(i * (barWidth + barSpacing) + margin, canvas.height - height - margin, barWidth, height);
  153. }
  154. }
  155. function distX(a, b) {
  156. var dx = a.x - b.x;
  157. if(dx > LEVEL_SIZE / 2) dx -= LEVEL_SIZE;
  158. if(dx < -LEVEL_SIZE / 2) dx += LEVEL_SIZE;
  159. return dx;
  160. }
  161. function distSq(a, b) {
  162. var c = distX(a, b);
  163. var d = a.y - b.y;
  164. return c * c + d * d;
  165. }
  166. function colliding(a, b) {
  167. return distSq(a, b) <= 4 * RADIUS * RADIUS;
  168. }
  169. // "Entities"
  170. function Meter() {
  171. this.offset = 10;
  172. this.amp = 0;
  173. this.percentage = 0;
  174. this.direction = METER_SPEED;
  175. }
  176. Meter.prototype.draw = function() {
  177. var left = (canvas.width - METER_WIDTH) / 2;
  178. var vmid = this.offset + METER_HEIGHT / 2;
  179. var third = METER_WIDTH / 3;
  180. var peak = METER_HEIGHT / 2;
  181. ctx.fillStyle = 'black';
  182. ctx.rect(left, this.offset, METER_WIDTH, METER_HEIGHT);
  183. ctx.fill();
  184. var cpUp = lerp(vmid, vmid + peak * this.amp, this.percentage);
  185. var cpDown = lerp(vmid, vmid - peak * this.amp, this.percentage);
  186. ctx.lineWidth = 2;
  187. ctx.strokeStyle = 'red';
  188. ctx.beginPath();
  189. var pos = left;
  190. ctx.moveTo(left, vmid);
  191. ctx.quadraticCurveTo(pos+third/2, cpUp, pos+third, vmid);
  192. pos += third;
  193. ctx.quadraticCurveTo(pos+third/2, cpDown, pos+third, vmid);
  194. pos += third;
  195. ctx.quadraticCurveTo(pos+third/2, cpUp, pos+third, vmid);
  196. ctx.stroke();
  197. ctx.lineWidth = 3;
  198. ctx.strokeStyle = 'white';
  199. ctx.beginPath();
  200. ctx.rect(left, this.offset, METER_WIDTH, METER_HEIGHT);
  201. ctx.stroke();
  202. };
  203. Meter.prototype.onUpdate = function(dt) {
  204. if(this.percentage > 1) {
  205. this.direction = -METER_SPEED;
  206. }
  207. if(this.percentage < -1) {
  208. this.direction = METER_SPEED;
  209. }
  210. this.percentage += this.direction * dt;
  211. this.amp = 0.5 + lerp(0, 1, activeTarget.shimmerFactor);
  212. };
  213. function Star(x, y) {
  214. this.x = x;
  215. this.y = y;
  216. this.alpha = 0;
  217. this.randomize();
  218. }
  219. Star.prototype.randomize = function() {
  220. this.type = Math.floor(Math.random()*starColors.length);
  221. this.color = starColors[this.type];
  222. };
  223. Star.prototype.draw = function() {
  224. ctx.fillStyle = this.color;
  225. ctx.globalAlpha = this.alpha;
  226. var adjPosition = translatePoints(this);
  227. ctx.fillRect(adjPosition.x, adjPosition.y, DOT_SIZE, DOT_SIZE);
  228. var top = {x: adjPosition.x + DOT_SIZE/2, y: adjPosition.y - DOT_SIZE/2 };
  229. var bottom = {x: adjPosition.x + DOT_SIZE/2, y: adjPosition.y + DOT_SIZE/2*3};
  230. var left = {x: adjPosition.x - DOT_SIZE/2, y: adjPosition.y + DOT_SIZE/2 };
  231. var right = {x: adjPosition.x + DOT_SIZE/2*3, y: adjPosition.y + DOT_SIZE/2 };
  232. drawLeafH(left, -LEAF_SIZE, LEAF_SIZE/2);
  233. drawLeafH(right, LEAF_SIZE, LEAF_SIZE/2);
  234. drawLeafV(top, -LEAF_SIZE, LEAF_SIZE/2);
  235. drawLeafV(bottom, LEAF_SIZE, LEAF_SIZE/2);
  236. ctx.globalAlpha = 1;
  237. };
  238. Star.prototype.onUpdate = function() {
  239. if(this.y > canvas.height + DOT_DISTANCE * 2) {
  240. this.y -= canvas.height + DOT_DISTANCE * 4;
  241. this.randomize();
  242. }
  243. if(state.current == 'playing') {
  244. var newAlpha = 1.5 * activeTarget.spectrum[this.type];
  245. var a = 0.9;
  246. if(newAlpha > this.alpha) {
  247. a = 0.9;
  248. }
  249. this.alpha = Math.min(1, activeTarget.shimmerFactor * (this.alpha * (1-a) + newAlpha * a));
  250. }
  251. else if(state.current == 'waiting') {
  252. this.alpha = this.alpha * 0.95;
  253. }
  254. };
  255. function Dot(x, y) {
  256. this.x = x;
  257. this.y = y;
  258. }
  259. Dot.prototype.draw = function() {
  260. ctx.fillStyle = 'gray';
  261. var adjPosition = translatePoints(this);
  262. ctx.fillRect(adjPosition.x, adjPosition.y, DOT_SIZE, DOT_SIZE);
  263. };
  264. Dot.prototype.onUpdate = function() {
  265. if(this.y > canvas.height + DOT_DISTANCE * 2) {
  266. this.y -= canvas.height + DOT_DISTANCE * 4;
  267. }
  268. };
  269. function Target(beat) {
  270. this.beat = beat;
  271. this.alpha = 0;
  272. if(points < 4) {
  273. this.alpha = ease(1-points/4);
  274. }
  275. this.rippleCounter = 0;
  276. this.reset();
  277. }
  278. Target.prototype.reset = function() {
  279. this.y = -20;
  280. this.x = Math.random()*LEVEL_SIZE;
  281. };
  282. Target.prototype.color = function(p) {
  283. return color(0, 255, 0, p*this.alpha);
  284. };
  285. Target.prototype.draw = function() {
  286. var adjPosition = translatePoints(this);
  287. drawCircle(adjPosition, RADIUS, 3, this.color(1));
  288. drawCircle(adjPosition, 2, 3, this.color(1));
  289. // ripples
  290. var p = lerp(1, 0, ease(this.rippleCounter/RIPPLE_SIZE));
  291. drawCircle(adjPosition, RADIUS+7+this.rippleCounter, 1, this.color(p));
  292. drawCircle(adjPosition, RADIUS+4+this.rippleCounter, 1, this.color(p*0.8));
  293. drawCircle(adjPosition, RADIUS+1+this.rippleCounter, 1, this.color(p*0.5));
  294. };
  295. Target.prototype.onUpdate = function(dt, t) {
  296. this.rippleCounter += RIPPLE_SPEED * dt;
  297. if(this.rippleCounter > RIPPLE_SIZE) {
  298. this.rippleCounter = 0;
  299. }
  300. if(colliding(player, this)) {
  301. state.point();
  302. this.beat.sound.setPan(0);
  303. this.beat.sound.setVolume(100);
  304. this.shouldDelete = true;
  305. return;
  306. }
  307. if(this.y > canvas.height + 20) {
  308. this.reset();
  309. }
  310. var xDist = distX(this, player);
  311. var s = sign(xDist);
  312. var xDistAbs = easeOutExpo(Math.abs(xDist), 0, 100, LEVEL_SIZE/2);
  313. var yDist = this.y - player.y;
  314. var angle = 0;
  315. if(yDist != 0) {
  316. angle = easeOutExpo(Math.abs(Math.atan2(Math.abs(yDist), xDist) - Math.PI/2), 0, 100, Math.PI);
  317. }
  318. else {
  319. angle = s * 100;
  320. }
  321. this.beat.sound.setPan(Math.max(xDistAbs, angle) * s);
  322. var rDist = xDist*xDist + yDist*yDist;
  323. if(rDist >= 250000) {
  324. rDist = 250000;
  325. }
  326. rDist = 250000 - rDist;
  327. rDist /= 2500;
  328. this.beat.sound.setVolume(rDist);
  329. this.shimmerFactor = easeOutExpo(Math.abs(xDist), 1, -1, LEVEL_SIZE/2) * rDist / 100;
  330. if(isNaN(this.shimmerFactor) || this.shimmerFactor < 0) {
  331. this.shimmerFactor = 0;
  332. }
  333. this.spectrum = this.beat.sound.getSpectrum(t%this.beat.info.duration);
  334. };
  335. var player = {
  336. x: 0,
  337. y: canvas.height - 20,
  338. dx: PLAYER_SPEED
  339. };
  340. var meter = new Meter();
  341. var points;
  342. var entities;
  343. var activeTarget;
  344. var reset = function() {
  345. points = 0;
  346. entities = [];
  347. for(var j = 0; j < canvas.height / DOT_DISTANCE + 4; ++j) {
  348. for(var i = 0; i < LEVEL_SIZE / DOT_DISTANCE; ++i) {
  349. var x = i * DOT_DISTANCE;
  350. var y = (j-4) * DOT_DISTANCE;
  351. if(j % 2 == 0 && i % 2 == 0) {
  352. entities.push(new Dot(x, y));
  353. }
  354. if(j % 4 == 1) {
  355. if(i % 4 == 0) {
  356. entities.push(new Star(x, y));
  357. }
  358. else {
  359. entities.push(new Dot(x, y));
  360. }
  361. }
  362. if(j % 4 == 3) {
  363. if(i % 4 == 2) {
  364. entities.push(new Star(x, y));
  365. }
  366. else {
  367. entities.push(new Dot(x, y));
  368. }
  369. }
  370. }
  371. }
  372. };
  373. // Update
  374. var update = function(delta) {
  375. if(paused) return;
  376. var dt = delta / 1000;
  377. currentBeats.map(function(beat) {
  378. if(beat.repeat) {
  379. beat.repeat = false;
  380. }
  381. else {
  382. if(gameTime + delta > Math.ceil(gameTime / beat.info.duration) * beat.info.duration) {
  383. beat.repeat = true;
  384. }
  385. }
  386. });
  387. currentBeats.map(function(beat) {
  388. if(beat.repeat) {
  389. if(beat == activeTarget.beat && state.current == 'waiting') {
  390. state.play();
  391. }
  392. beat.sound.play();
  393. }
  394. });
  395. if(37 in keysDown) {
  396. player.x -= player.dx * dt;
  397. }
  398. if(39 in keysDown) {
  399. player.x += player.dx * dt;
  400. }
  401. player.x = (player.x + LEVEL_SIZE) % LEVEL_SIZE;
  402. for(var i = entities.length - 1; i >= 0; --i) {
  403. var entity = entities[i];
  404. entity.y += STAGE_SPEED * dt;
  405. entity.onUpdate(dt, gameTime);
  406. if(entity.shouldDelete) {
  407. entities.splice(i, 1);
  408. }
  409. }
  410. meter.onUpdate(dt);
  411. gameTime += delta;
  412. };
  413. // Render
  414. var translatePoints = function(point) {
  415. var x = point.x - player.x + canvas.width/2;
  416. if(x < -ALLOWANCE) x += LEVEL_SIZE;
  417. if(x > LEVEL_SIZE - ALLOWANCE) x -= LEVEL_SIZE;
  418. return {x:x, y:point.y};
  419. };
  420. var render = function() {
  421. ctx.fillStyle = "black";
  422. ctx.fillRect(0, 0, canvas.width, canvas.height);
  423. entities.map(function(elem) {
  424. elem.draw();
  425. });
  426. drawPlayer(translatePoints(player));
  427. meter.draw();
  428. ctx.fillStyle = "white";
  429. ctx.fillText(points+"", 5, 15);
  430. if(debug) {
  431. drawSpectrum();
  432. }
  433. if(paused) {
  434. ctx.fillStyle = 'white';
  435. ctx.textAlign = 'center';
  436. ctx.fillText("Paused (P to unpause)", canvas.width / 2, canvas.height / 2);
  437. ctx.textAlign = 'start';
  438. }
  439. };
  440. var then;
  441. var main = function() {
  442. var now = Date.now();
  443. var delta = (now - then);
  444. update(delta);
  445. render();
  446. then = now;
  447. };
  448. var start = function() {
  449. reset();
  450. switchBeat(0);
  451. then = Date.now();
  452. setInterval(main, 10);
  453. };
  454. var pause = function() {
  455. paused = !paused;
  456. if(paused) {
  457. currentBeats.map(function(beat) {beat.sound.pause()});
  458. }
  459. else {
  460. currentBeats.map(function(beat) {beat.sound.resume()});
  461. }
  462. };
  463. ctx.textAlign = 'center';
  464. ctx.fillText("Loading...", canvas.width / 2, canvas.height / 2);
  465. ctx.textAlign = 'start';
  466. Q.all([soundPromise]).done(function() {
  467. start();
  468. });
  469. };
  470. var canvas = document.getElementById('game');
  471. var beats = [
  472. {url: 'sound/b1.mp3', duration: 4000},
  473. {url: 'sound/b2.mp3', duration: 4000},
  474. {url: 'sound/b3.mp3', duration: 4000},
  475. {url: 'sound/b4.mp3', duration: 4000},
  476. {url: 'sound/b5.mp3', duration: 4000}
  477. ];
  478. var soundDeferred = Q.defer();
  479. var pSoundManager = soundDeferred.promise;
  480. soundManager.setup({
  481. url: 'swf/',
  482. flashVersion: 9,
  483. onready: function() {
  484. soundDeferred.resolve(this);
  485. }
  486. });
  487. SoundSafari(canvas, beats, pSoundManager);