index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import * as wasm from "fourteen-screws";
  2. import { Cluiche } from "fourteen-screws";
  3. const cluiche = Cluiche.new();
  4. let canvas = document.getElementById("canvas");
  5. let context = canvas.getContext("2d");
  6. let keystate = {}
  7. document.addEventListener('keydown', (event) => { keystate[event.key] = true; }, false);
  8. document.addEventListener('keyup', (event) => { keystate[event.key] = false; }, false);
  9. const fps = new class {
  10. constructor() {
  11. this.fps = document.getElementById("fps");
  12. this.frames = [];
  13. this.lastFrameTimestamp = performance.now();
  14. }
  15. render () {
  16. // Convert the delta time since the last frame render into a measure
  17. // of frames per second
  18. const now = performance.now();
  19. const delta = now - this.lastFrameTimeStamp;
  20. this.lastFrameTimeStamp = now;
  21. const fps = 1 / delta * 1000;
  22. // Save only the latest 100 timings.
  23. this.frames.push(fps);
  24. if (this.frames.length > 100) {
  25. this.frames.shift();
  26. }
  27. // find the max, min, and mean of our 100 latest timings
  28. let min = Infinity;
  29. let max = -Infinity;
  30. let sum = 0;
  31. for (let i = 0; i < this.frames.length; i++) {
  32. sum += this.frames[i];
  33. min = Math.min(this.frames[i], min);
  34. max = Math.max(this.frames[i], max);
  35. }
  36. let mean = sum / this.frames.length;
  37. this.fps.textContent = `
  38. Frames per Second:
  39. latest = ${Math.round(fps)} |
  40. avg of last 100 = ${Math.round(mean)} |
  41. min of last 100 = ${Math.round(min)} |
  42. max of last 100 = ${Math.round(max)}
  43. `.trim();
  44. }
  45. }
  46. function render() {
  47. context.clearRect(0, 0, 320, 200);
  48. var image = context.getImageData(0, 0, 320, 200);
  49. cluiche.render(image.data);
  50. context.putImageData(image, 0, 0);
  51. }
  52. function events() {
  53. if (keystate['w']) {
  54. cluiche.player_forward();
  55. }
  56. if (keystate['s']) {
  57. cluiche.player_back();
  58. }
  59. if (keystate['a']) {
  60. cluiche.player_strafe_left();
  61. }
  62. if (keystate['d']) {
  63. cluiche.player_strafe_right();
  64. }
  65. if (keystate['ArrowLeft']) {
  66. cluiche.player_turn_left();
  67. }
  68. if (keystate['ArrowRight']) {
  69. cluiche.player_turn_right();
  70. }
  71. }
  72. function tick() {
  73. fps.render();
  74. events();
  75. render();
  76. requestAnimationFrame(tick);
  77. }
  78. requestAnimationFrame(tick);