質問

I'm new to javascript and canvas, but not entirely new to programming (I have some HTML/PHP experience).

I've always had an interest in web games that use grids, so after taking a few javascript courses online, I found some javascript code that dynamically created hexagonal grids of canvas objects.

I've been playing around with the code, adding click events to highlight the hex you're on, trying to put random numbers on the hexes to depict numbers of "units" etc. Sort of mocking up what a game might look like, just for the learning experience.

One thing that I've been trying to do, and I can't seem to figure out, is how to define canvas objects in an array, so that I can reference them by row/column. It seems like it would be much easier, in the context of a game, to reference a grid cell by row/column so that you can do actions based on that location.

I'm using ocanvas.js to create canvas objects, so ideally I'd love to be able to define a grid cell as:

hex[row][col] = canvas.display.polygon({
    x: x0,
    y: y0,
    sides: 6,
    radius: this.radius,
    rotation: 0,
    fill: fillColor,
    stroke: "outside 1px #000",
    row: row,
    col: col,
    zIndex: "back",
    selected: false
});
hex[row][col].add();    

However, I've noticed that mutlidimensional arrays don't work in javascript like they do in PHP. In PHP, you don't have to predefine the scope of an array. You can just do:

$array = [];
$array[1][5] = "foo";

And it'll put that value in the [1][5] position. In my hex code here: http://tny.cz/14282e49 about 3/4 down I have a comment showing that I want to call my hex[col][row] object... but I'm always getting "Uncaught TypeError: Cannot read property '5' of undefined" errors, where '5' is the column its trying to access.

So, this is a 2 part question: 1) Am I not defining my hex array correctly to access the canvas objects like that? 2) Is there a better way that I'm just not seeing, to access specific canvas objects in a column/row grid format?

役に立ちましたか?

解決

Part I:

Before assigning a value to hex[row][col], you need to make sure that hex[row] exists.

hex[row] = hex[row] || [];
hex[row][col] = canvas.display.polygon({
    x: x0,
    y: y0,
    sides: 6,
    radius: this.radius,
    rotation: 0,
    fill: fillColor,
    stroke: "outside 1px #000",
    row: row,
    col: col,
    zIndex: "back",
    selected: false
});
hex[row][col].add();

The line hex[row] = hex[row] || []; says "if hex[row] exists, use it. otherwise create a new array. Assign the result to hex[row]." The || "or" operator is used as a "default" here. See this page as a reference: http://seanmonstar.com/post/707078771/guard-and-default-operators


Part II:

http://www.redblobgames.com/grids/hexagons/#coordinates

I recommend using the "axial coordinate" system used at that resource. Read the entire thing. It's a long post and is way too much information for a SO answer here.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top