Flow Free类游戏开发:点击非白色圆形仍触发错误提示问题排查
First, let's address the immediate issue: why clicking non-white circles is triggering the "error" message.
Root Cause
Your colors list is 0-indexed (starts at 0), but when you calculate index1 and index2, you're adding +1 to make them 1-based. Then you use this 1-based index to access colors, which means you're checking the color of the next circle in the list, not the one you clicked.
For example:
- If you click the second circle (0-based index 1, color blue),
index1becomes1+1=2. colors.get(2)is white, so your code incorrectly prints "error".
Fix Option 1: Use 0-based Indices Everywhere
Remove the +1 when setting index1 and index2, so they match the 0-based indices of both circles and colors:
if(counter % 2 == 1) { index1 = circles.indexOf(shape); // No +1 if(Color.WHITE.equals(colors.get(index1))) { counter--; System.out.println("error"); } } else { index2 = circles.indexOf(shape); // No +1 if(checkLinearity(index1, index2)) { // Draw your rectangle here } }
Adjust the checkLinearity Function
Since we're now using 0-based indices, update the function to correctly check for same row (the original logic had a bug even for 1-based):
public static boolean checkLinearity(int index1, int index2){ // Check if same column if((index1 % 5) == (index2 % 5)) { return true; } // Check if same row (0-based: integer division by 5 gives row number) if((index1 / 5) == (index2 / 5)) { return true; } return false; }
Fix Option 2: Keep 1-based Indices (Adjust Color Access)
If you prefer to keep index1 and index2 as 1-based, subtract 1 when accessing the colors list:
if(counter % 2 == 1) { index1 = circles.indexOf(shape) + 1; if(Color.WHITE.equals(colors.get(index1 - 1))) { // Subtract 1 here counter--; System.out.println("error"); } }
Note: The original checkLinearity function still has a bug for same-row checks—Math.abs(index1-index2) <5 isn't reliable (e.g., indices 5 and 6 would incorrectly return true). Use the adjusted version from Option 1 if you go this route.
Bonus: Improve Efficiency with Indexed Loop
Instead of using circles.indexOf(shape) (which scans the entire list each time), loop with an index directly to get the position of the clicked shape:
public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); for (int i = 0; i < circles.size(); i++) { Shape shape = circles.get(i); if (shape.contains(x, y)) { counter++; if(counter % 2 == 1) { index1 = i; // Directly use the loop index if(Color.WHITE.equals(colors.get(i))) { counter--; System.out.println("error"); } } else { index2 = i; if(checkLinearity(index1, index2)) { // Draw rectangle logic here } } break; // Exit loop after finding the clicked shape } } }
This is faster and avoids any potential issues with indexOf (though in your case, since each shape is unique, it works—but indexed loops are better practice here).
内容的提问来源于stack exchange,提问作者shuryu sd

