Game for OLC Code Jam 2022
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

game.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. const $ = (s) => document.querySelector(s);
  2. const $$ = (s) => Array.from(document.querySelectorAll(s));
  3. const ROOT = $('#root');
  4. const X_BOUND = 0.05;
  5. const clouds = new Set();
  6. const bullets = new Set();
  7. let shootingPad = new ShootingPad();
  8. let running = true;
  9. let direction = 1;
  10. const initCloudField = () => {
  11. for (let y = 0; y < 6; y++) {
  12. for (let x = 0; x < 11; x++) {
  13. const cloud = new Cloud(X_BOUND + 0.06 * x, 0.04 + 0.04 * y, 0.03, 0.02);
  14. clouds.add(cloud);
  15. }
  16. }
  17. }
  18. const start = () => {
  19. $('.result')?.remove();
  20. shootingPad?.destroy();
  21. shootingPad = new ShootingPad();
  22. bullets.forEach(c => c.destroy());
  23. bullets.clear();
  24. clouds.forEach(c => c.destroy());
  25. clouds.clear();
  26. Cloud.reset();
  27. initCloudField();
  28. running = true;
  29. loop();
  30. }
  31. const gameOver = (result) => {
  32. const resultLabel = document.createElement('div');
  33. resultLabel.className = 'result';
  34. resultLabel.textContent = result;
  35. ROOT.appendChild(resultLabel);
  36. running = false;
  37. }
  38. const loop = () => {
  39. if (!running) return;
  40. let directionUpdated = false;
  41. let isOver = false;
  42. Array.from(clouds).forEach(c => {
  43. c.update(direction);
  44. c.draw();
  45. if (c.x < X_BOUND - 0.01 || c.x > 1.01 - X_BOUND) {
  46. directionUpdated = true;
  47. }
  48. if (c.y >= 0.95) {
  49. isOver = true;
  50. }
  51. if (!c.alive) {
  52. clouds.delete(c);
  53. }
  54. });
  55. if (directionUpdated) {
  56. direction = -direction;
  57. }
  58. if (isOver) {
  59. gameOver('Game over');
  60. }
  61. Array.from(bullets).forEach(b => {
  62. b.update();
  63. b.draw();
  64. if (!b.alive) {
  65. bullets.delete(b);
  66. }
  67. });
  68. shootingPad.update();
  69. shootingPad.draw();
  70. if (clouds.size === 0) {
  71. gameOver('WIN');
  72. }
  73. requestAnimationFrame(loop);
  74. };
  75. document.addEventListener('keypress', () => {
  76. if (!running) {
  77. start();
  78. }
  79. });
  80. start();