main.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * 小球消除方块游戏 - 入口文件
  3. * 初始化模式选择、创建 Game 实例、启动游戏循环
  4. */
  5. import { Game } from './Game.js';
  6. import { ModeSelector } from './ui/ModeSelector.js';
  7. document.addEventListener('DOMContentLoaded', () => {
  8. // DOM elements
  9. const canvas = document.getElementById('can');
  10. const modeSelectorEl = document.getElementById('mode-selector');
  11. const gameOverOverlay = document.getElementById('game-over');
  12. const finalScoreEl = document.getElementById('final-score');
  13. const restartBtn = document.getElementById('restart-btn');
  14. const levelDisplay = document.getElementById('level');
  15. const ballCountDisplay = document.getElementById('ball-count');
  16. // Canvas sizing
  17. const header = document.getElementById('header');
  18. const footer = document.getElementById('footer');
  19. const contain = document.getElementById('contain');
  20. const dpr = window.devicePixelRatio || 1;
  21. const logicalWidth = Math.min(window.innerWidth, 500);
  22. const logicalHeight = window.innerHeight - header.offsetHeight - footer.offsetHeight;
  23. canvas.style.width = logicalWidth + 'px';
  24. canvas.style.height = logicalHeight + 'px';
  25. canvas.width = logicalWidth * dpr;
  26. canvas.height = logicalHeight * dpr;
  27. // Mode selector
  28. const modeSelector = new ModeSelector(modeSelectorEl);
  29. let game = null;
  30. let animFrameId = null;
  31. let lastTime = 0;
  32. function gameLoop(timestamp) {
  33. const deltaTime = lastTime ? Math.min(timestamp - lastTime, 50) : 16;
  34. lastTime = timestamp;
  35. game.update(deltaTime);
  36. game.render();
  37. // Update level display
  38. levelDisplay.textContent = game.round;
  39. ballCountDisplay.textContent = '×' + game.ballCount;
  40. animFrameId = requestAnimationFrame(gameLoop);
  41. }
  42. function startGame(mode) {
  43. modeSelector.hide();
  44. // Cancel any existing loop
  45. if (animFrameId) {
  46. cancelAnimationFrame(animFrameId);
  47. animFrameId = null;
  48. }
  49. game = new Game(canvas, mode);
  50. game.setGameOverUI(gameOverOverlay, finalScoreEl, restartBtn);
  51. game.start();
  52. lastTime = 0;
  53. animFrameId = requestAnimationFrame(gameLoop);
  54. }
  55. modeSelector.onSelect(startGame);
  56. modeSelector.show();
  57. });