List<Int>数组访问不允许报错:战舰游戏AI回合函数问题求助
Hey there! Let's break down the error you're hitting and fix up your tourIA function step by step.
What's Causing the Error?
In Haxe (the language your code is written in), the List<Int> type doesn't support array-style access with square brackets []. That's exactly why you're getting the "Array access is not allowed on Listposition[pos]—you need to use the get() method instead to pull elements from a List.
Let's Fix Your Code
First, let's spot the issues in your current snippet:
- There's a syntax error in the
Std.randomcall—you're missing a closing parenthesis, and you should useposition.lengthto get the List's size (notlength(position)). - You're trying to access the List with
position[pos]instead of the correctposition.get(pos). - Your
ycalculation looks off—right now you're just flooringcellule, which would give you the same value ascellule(since it's an integer). You probably wantMath.floor(cellule / dimensions)to get the proper y-coordinate from your flattened cell index.
Here's the corrected version of your function:
private function tourIA() { var position = new List<Int>(); // Fill the list with all cell indices for(i in 0...Std.parseInt(Math.pow(dimensions, 2))) { position.add(i); } // Fix: Properly generate a random index for the List var pos = Std.random(position.length); // Fix: Use get() to access the List element var cellule = position.get(pos); var x = cellule % dimensions; // Fix: Calculate y-coordinate correctly var y = Math.floor(cellule / dimensions); var n : Navire = mer.chercherNav... // Rest of your code here }
Extra Tip
If you find yourself needing frequent random access to elements, consider using an Array<Int> instead of a List<Int>. Arrays support square bracket access directly, which can be more convenient for this use case:
var position = []; // Array<Int> for(i in 0...Std.parseInt(Math.pow(dimensions, 2))) { position.push(i); } var pos = Std.random(position.length); var cellule = position[pos]; // This works perfectly with arrays!
内容的提问来源于stack exchange,提问作者Fabien Power

