3

I am creating a 2d tile game, and am wondering what the best way to generate a cluster of a certain tile type within. For example, say I have a 2d array that is my map. Grass is represented by 0.

{{0, 0, 0, 0, 0, 0}
 {0, 0, 0, 0, 0, 0}
 {0, 0, 0, 0, 0, 0}
 {0, 0, 0, 0, 0, 0}
 {0, 0, 0, 0, 0, 0}
 {0, 0, 0, 0, 0, 0}}

Now, what I want to do is randomly create a cluster of trees (represented by 1) in my array. I want it to look something like this:

{{0, 0, 0, 0, 0, 0}
 {0, 0, 0, 0, 0, 0}
 {0, 1, 1, 1, 0, 0}
 {0, 1, 1, 1, 1, 0}
 {0, 0, 1, 1, 1, 0}
 {0, 0, 1, 1, 0, 0}}

What would be the best way to do this?

elaid
  • 351
  • 1
  • 10
  • And you want to have random trees or predefined trees? – Ya Wang Feb 09 '15 at 23:23
  • It's not clear what the problem is. Where are you stuck? – Oliver Charlesworth Feb 09 '15 at 23:23
  • I don't know how to randomly generate the trees. – elaid Feb 09 '15 at 23:24
  • Well the question is, do you know how to get a random and how random do you need it to be... So read this http://stackoverflow.com/questions/8236125/get-random-integer-in-range-x-y then do if (x == 4) 2darray[i][j] = 1; when you generate the 2d array how ever you are generating it you can make some trees – Ya Wang Feb 09 '15 at 23:26
  • Any reason you can't simply make a large chunk of terrains, with stands of trees and then sample from a random location and rotation from that? Blur it out to a grayscale image, and you might be able to use that with a randomized threshold to get different overall densities of trees, too. – Mike Housky Feb 09 '15 at 23:38
  • Do you really want to specifically create clusters of tiles or are you rather looking for ways to generate some natural distributions of these tiles? – happymoep Feb 09 '15 at 23:46
  • I want to generate clusters of tiles. They shouldn't look too un-natural, but it shouldn't be specifically based upon that. – elaid Feb 10 '15 at 11:58

1 Answers1

1

Implement a method M which does this: for a given set of positions S, it takes their neighboring positions N but only those that don't have trees inside themselves; puts trees in some of these neighboring positions N, and calls itself recursively passing in only the neighboring positions K in which it put trees (K is sub-set of N).

Now to trigger the whole thing: place a tree randomly in one point p, and call M passing in a set/list of just the position p to the method M.

This algorithm guarantees you'll generate a cluster (I mean a set of trees where each two trees are connected by other trees).

Make sure your recursion stops at some point (you can implement this by introducing certain thresholds or by using other heuristics as appropriate).

peter.petrov
  • 38,363
  • 16
  • 94
  • 159