common.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const gameTiles = [
  2. ".", // Empty
  3. "█", // Wall
  4. "▪", // Block
  5. "_", // Paddle
  6. "°", // Ball
  7. ];
  8. /**
  9. * Render the arcade screen
  10. *
  11. * @param {number[]} screenState An array of numbers represent the state of the arcade screen
  12. * @param {boolean} autoplay If true, the game will autoplay itself
  13. * @returns {void}
  14. */
  15. function _render(screenState, autoplay = false) {
  16. if (screenState.length % 3 != 0) {
  17. console.warn("screenState length is not divisible by three!");
  18. }
  19. /** @type {number[][]} */
  20. let board = [];
  21. let boardWidth = -1;
  22. let boardHeight = -1;
  23. let blockTileCount = 0;
  24. let gameScore = 0;
  25. let ballX = 0;
  26. let paddleX = 0;
  27. for (let i = 0; i < screenState.length; i += 3) {
  28. const x = screenState[i];
  29. const y = screenState[i + 1];
  30. const tile = screenState[i + 2];
  31. if (x == -1) { gameScore = tile; }
  32. // Track the board dimensions
  33. if (x > boardWidth) { boardWidth = x; }
  34. if (y > boardHeight) { boardHeight = y; }
  35. // create a row for the y dimension if it doesn't already exist
  36. if (!board[y]) { board[y] = []; }
  37. // If the current tile is the ball, store the x coord for autoplay
  38. if (tile == 3) { paddleX = x; }
  39. else if (tile == 4) { ballX = x; }
  40. board[y][x] = tile;
  41. }
  42. board = normalizeBoard(board, boardWidth, boardHeight);
  43. let boardString = "";
  44. for (const row of board) {
  45. for (const tile of row) {
  46. if (tile == 2) {
  47. blockTileCount++;
  48. }
  49. boardString += gameTiles[tile];
  50. }
  51. boardString += "\n";
  52. }
  53. return [boardString, gameScore, blockTileCount, ballX, paddleX];
  54. }
  55. function renderToConsole(screenState) {
  56. const [boardState, gameScore, blockTileCount, ballX, paddleX] = _render(screenState, false, true);
  57. console.clear();
  58. console.log("Score: ", gameScore);
  59. console.log(boardState);
  60. console.log("Block Tile Count: ", blockTileCount);
  61. return [ballX, paddleX];
  62. }
  63. function normalizeBoard(board, width, height) {
  64. for (let h = 0; h <= height; h++) {
  65. if (!board[h]) { board[h] = []; }
  66. for (let w = 0; w <= width; w++) {
  67. if (board[h][w] == undefined) { board[h][w] = 0; }
  68. }
  69. }
  70. return board;
  71. }
  72. module.exports = {
  73. render: renderToConsole,
  74. };