Java控制台10x10网格开发:反转奇数行及玩家显示咨询
Hey there! Let's break down your two requirements step by step and get you sorted out properly.
Solution for Your 10x10 Grid Needs
1. Implementing Odd-Row Reversal with Correct Top-to-Bottom Row Order
First, let's align on the goal: the grid should display rows starting from 91-100 at the top, down to 1-10 at the bottom. On top of that, only the odd-indexed rows (original grid's rows 1,3,5,7,9) should have their element order reversed (so 11-20 becomes 20-11, 31-40 becomes 40-31, etc.).
Core Logic Breakdown
- Initialize the grid in natural order: row 0 holds 1-10, row 1 holds 11-20, ..., row 9 holds 91-100. This makes row reversal logic easier to manage.
- When rendering to the console, iterate from the last row to the first (so 91-100 shows up at the top, 1-10 at the bottom).
- For each row during rendering: if it's an odd-indexed row in the original grid, reverse its elements before printing (we'll use a copy to avoid modifying the original grid data).
Modified Code for Requirement 1
import java.util.Arrays; public class Board { private static final int rows = 10; private static final int cols = 10; private static final int numOfObstacles = 5; private static final int numOfFuelUps = 4; private int[][] gameBoard; public Board() { initializeBoard(); renderBoard(); } // Set up the grid with numbers 1-100 in natural row order private void initializeBoard() { gameBoard = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { gameBoard[i][j] = i * cols + j + 1; } } } // Render the grid with reversed top-to-bottom order and odd rows reversed private void renderBoard() { for (int i = rows - 1; i >= 0; i--) { // Start from last row (91-100) for correct top-to-bottom order System.out.println(); int[] currentRow = gameBoard[i]; // Reverse odd-indexed rows (original grid's rows 1,3,5,7,9) if (i % 2 != 0) { currentRow = Arrays.copyOf(currentRow, currentRow.length); reverseArray(currentRow); } // Print each element with consistent spacing for (int num : currentRow) { System.out.printf("%3d\t", num); } } } // Helper to reverse an array of integers private void reverseArray(int[] arr) { for (int left = 0, right = arr.length - 1; left < right; left++, right--) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } } public static void main(String[] args) { new Board(); } }
2. Using StringBuilder for Dynamic Grid Updates & Player Position Replacement
Is This a Good Approach?
Absolutely! StringBuilder is perfect for this scenario:
- It's way more efficient than string concatenation with
+(which creates unnecessary new String objects every time). - It lets you build each row's content dynamically, making it super easy to replace specific positions with player markers, obstacles, or fuel-ups.
Implementation Steps & Code
Here's how to integrate this into your board class, with support for player position markers:
- Track Player Coordinates: Add class variables to store where each player is located.
- Build Rows with StringBuilder: For each row, create a
StringBuilderto construct the row's text. Check each position—if it's a player's spot, append their identifier; otherwise, append the grid number. - Handle Reversed Rows: When dealing with reversed odd rows, map the rendered column back to the original grid's column to correctly identify player positions.
Integrated Code Example
import java.util.Arrays; public class Board { private static final int rows = 10; private static final int cols = 10; private static final int numOfObstacles = 5; private static final int numOfFuelUps = 4; private int[][] gameBoard; // Track player positions (example starting spots) private int[] player1Pos = {2, 3}; // Original grid row 2, column 3 → number 24 private int[] player2Pos = {7, 5}; // Original grid row7, column5 → number76 public Board() { initializeBoard(); renderBoardWithPlayers(); } private void initializeBoard() { gameBoard = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { gameBoard[i][j] = i * cols + j + 1; } } } private void renderBoardWithPlayers() { StringBuilder fullGrid = new StringBuilder(); for (int renderRow = rows - 1; renderRow >= 0; renderRow--) { int originalRow = renderRow; int[] currentRow = gameBoard[originalRow]; // Reverse odd original rows if needed if (originalRow % 2 != 0) { currentRow = Arrays.copyOf(currentRow, currentRow.length); reverseArray(currentRow); } StringBuilder rowText = new StringBuilder(); for (int col = 0; col < cols; col++) { // Map rendered column back to original column for reversed rows int originalCol = (originalRow % 2 != 0) ? cols - 1 - col : col; // Check if current spot is a player's position if (originalRow == player1Pos[0] && originalCol == player1Pos[1]) { rowText.append("P1\t"); } else if (originalRow == player2Pos[0] && originalCol == player2Pos[1]) { rowText.append("P2\t"); } else { rowText.append(String.format("%3d\t", currentRow[col])); } } fullGrid.append(rowText).append("\n"); } // Clear console (optional, for cleaner updates) and print the grid System.out.print("\033[H\033[2J"); System.out.flush(); System.out.println(fullGrid.toString()); } private void reverseArray(int[] arr) { for (int left = 0, right = arr.length - 1; left < right; left++, right--) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } } // Call this method when a player moves to update their position and re-render public void updatePlayerPosition(int playerNum, int newRow, int newCol) { if (playerNum == 1) { player1Pos[0] = newRow; player1Pos[1] = newCol; } else if (playerNum == 2) { player2Pos[0] = newRow; player2Pos[1] = newCol; } renderBoardWithPlayers(); } public static void main(String[] args) { Board board = new Board(); // Example: Move Player1 to original row 5, column 2 try { Thread.sleep(2000); // Wait 2 seconds to show the initial grid board.updatePlayerPosition(1, 5, 2); } catch (InterruptedException e) { e.printStackTrace(); } } }
Key Details
- Console Clearing: The
System.out.print("\033[H\033[2J");line clears the console before re-rendering, which makes updates look cleaner (works on most terminals). - Position Mapping: For reversed rows, we calculate
originalColto ensure we're checking the correct spot in the original grid for player positions. - Flexibility: You can easily add obstacles or fuel-ups by adding more condition checks in the row-building loop (e.g., append
"XXX\t"for obstacles).
内容的提问来源于stack exchange,提问作者stef
相关产品推荐
相关产品推荐

