浏览代码

Refactor render function

Refactored to have the rendering just return the string visualization of
the board state, as well as some optional information about the state of
the screen. This information is then passed to a higher level rendering
function that renders it to the caller's choice. Presently, only
rendering to the console is possible.
ApisNecros 2 月之前
父节点
当前提交
24d2ae6754
共有 1 个文件被更改,包括 24 次插入7 次删除
  1. 24 7
      13/common.js

+ 24 - 7
13/common.js

@@ -10,10 +10,10 @@ const gameTiles = [
  * Render the arcade screen
  *
  * @param {number[]} screenState An array of numbers represent the state of the arcade screen
- * @param {boolean} countBlocks Display a count of block tiles on the screen
+ * @param {boolean} autoplay If true, the game will autoplay itself
  * @returns {void}
  */
-function render(screenState, countBlocks = false) {
+function _render(screenState, autoplay = false) {
     if (screenState.length % 3 != 0) {
         console.warn("screenState length is not divisible by three!");
     }
@@ -23,12 +23,17 @@ function render(screenState, countBlocks = false) {
     let boardWidth = -1;
     let boardHeight = -1;
     let blockTileCount = 0;
+    let gameScore = 0;
+    let ballX = 0;
+    let paddleX = 0;
 
     for (let i = 0; i < screenState.length; i += 3) {
         const x = screenState[i];
         const y = screenState[i + 1];
         const tile = screenState[i + 2];
 
+        if (x == -1) { gameScore = tile; }
+
         // Track the board dimensions
         if (x > boardWidth) { boardWidth = x; }
         if (y > boardHeight) { boardHeight = y; }
@@ -36,6 +41,10 @@ function render(screenState, countBlocks = false) {
         // create a row for the y dimension if it doesn't already exist
         if (!board[y]) { board[y] = []; }
 
+        // If the current tile is the ball, store the x coord for autoplay
+        if (tile == 3) { paddleX = x; }
+        else if (tile == 4) { ballX = x; }
+
         board[y][x] = tile;
     }
 
@@ -52,11 +61,17 @@ function render(screenState, countBlocks = false) {
         boardString += "\n";
     }
 
+    return [boardString, gameScore, blockTileCount, ballX, paddleX];
+}
+
+function renderToConsole(screenState) {
+    const [boardState, gameScore, blockTileCount, ballX, paddleX] = _render(screenState, false, true);
     console.clear();
-    console.log(boardString);
-    if (countBlocks) {
-        console.log("\n", "Block tiles: ", blockTileCount);
-    }
+    console.log("Score: ", gameScore);
+    console.log(boardState);
+    console.log("Block Tile Count: ", blockTileCount);
+
+    return [ballX, paddleX];
 }
 
 function normalizeBoard(board, width, height) {
@@ -70,4 +85,6 @@ function normalizeBoard(board, width, height) {
     return board;
 }
 
-module.exports = { render };
+module.exports = {
+    render: renderToConsole,
+};