# Random generation question

+13 votes

The actual art for my final is coming together but I cannot get my random generation to work. I want it so that each of the hills, thesky, the background, and the extra objects have a one in three chance of being selected when generating. Here's the code.

``````to gen-hills
if random 3 = 0 [
grassy-hills
]
if random 3 = 1 [
sandy-hills
]
if random 3 = 2 [
snowy-hills
]
end

to gen-sky
if random 3 = 0 [
morning
]
if random 3 = 1 [
sunset
]
if random 3 = 2 [
nighttime
]
end

to gen-back
if random 3 = 0 [
town
]
if random 3 = 1 [
forest
]
if random 3 = 2 [
ocean
]
end

to gen-extras
if random 3 = 0 [
birds
]
if random 3 = 1 [
clouds
]
if random 3 = 2 [
planes
]
end
``````

My logic is that each option will have a one in three chance in being created which is why I have them reach doing "random 3." But sometimes when I run the code I get multiple things overlapping or not being drawn correctly or nothing being drawn at all. What steps should I take to remedy this problem?

asked

## 3 Answers

+3 votes

Best answer

You should declare a variable before your if statements like this:

let check random 3

and then your if statements should look like this:

if check = 0 [ option1 ]
if check = 1 [ option2 ]
if check = 2 [ option3 ]

answered by (918 points)
selected
0

Thank you. This works

+3 votes

using ifelse instead of if will work!

answered by (8 points)
0 votes

I try to change your code. They are the same. I use ifelse statements and take caution on using random.

``````  to gen-hills
ifelse (random 3 )= 0 [
grassy-hills
] [
ifelse (random 3) = 1 [
sandy-hills
] [
if (random 3) = 2 [
snowy-hills
]
]
end

to gen-sky
ifelse (random 3) = 0 [
morning
] [
ifelse (random 3) = 1 [
sunset
] [
if (random 3) = 2 [
nighttime
]
]
end
``````
answered by (1.1k points)