You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

List<Int>数组访问不允许报错:战舰游戏AI回合函数问题求助

Fixing "Array access is not allowed on List" in Your Battleship AI Function

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 List" error when you try position[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:

  1. There's a syntax error in the Std.random call—you're missing a closing parenthesis, and you should use position.length to get the List's size (not length(position)).
  2. You're trying to access the List with position[pos] instead of the correct position.get(pos).
  3. Your y calculation looks off—right now you're just flooring cellule, which would give you the same value as cellule (since it's an integer). You probably want Math.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:07:21