I wanted to fill a grid with about 50% true and 50% false. This I do with random(100). Then I draw the grid on the screen, so I think the grid was filled nearly with same amount of false and true, but every time I tested the code the amount of true was giant compared with the amount of false.
I tried very long to fix the problem, but I found no solution.
Strange cell values in 2d array with the help of random
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
Strange cell values in 2d array with the help of random
- Attachments
-
- main.love
- (408 Bytes) Downloaded 90 times
@pixelwar_studio on twitter
- Ranguna259
- Party member
- Posts: 911
- Joined: Tue Jun 18, 2013 10:58 pm
- Location: I'm right next to you
Re: Strange cell values in 2d array with the help of random
Everything looks alright except two things:
You don't need to do
There's no need to do that. And second, the problem is in your draw code, you are multiplying the sides of your rectangle by x and y, replace:
with:
FYI: You don't realy need to do math.random(100), all you need to do is math.random(0,1) this will output 0 or 1.
Here's a fixed love file:
You don't need to do
Code: Select all
return grid
Code: Select all
love.graphics.rectangle("fill", 7 * (x - 1), 7 * (y - 1), 7 * x, 7 * y)
Code: Select all
love.graphics.rectangle("fill", 7 * (x - 1), 7 * (y - 1), 7, 7)
Here's a fixed love file:
- Attachments
-
- randomsqrs.love
- (362 Bytes) Downloaded 87 times
Re: Strange cell values in 2d array with the help of random
You can control the amount of random values using "shuffle" of pre-generated values. For example if you want 50% true and 50% false values you can achieve it like this:
Code: Select all
local rnd = {}
function shuffle(t)
local n = #t
while n >= 2 do
-- n is now the last pertinent index
local k = love.math.random(n) -- 1 <= k <= n
-- Quick swap
t[n], t[k] = t[k], t[n]
n = n - 1
end
end
function love.load()
for i = 1, 50 do
rnd[i] = true
end
for i = 51, 100 do
rnd[i] = false
end
end
function love.keypressed(key, isRepeat)
if key == "escape" then
love.event.quit()
elseif key == " " then
shuffle(rnd)
print("*****************************")
for i = 1, #rnd do
print(i, rnd[i])
end
end
end
Re: Strange cell values in 2d array with the help of random
Thanks, I'm stupid , because I thought that the love.graphics.rectangle works after the pattern x1,y1,x2,y2 and not after x,y,width,height.
EDIT: And thanks for the tip @arampl
EDIT: And thanks for the tip @arampl
@pixelwar_studio on twitter
Who is online
Users browsing this forum: Ahrefs [Bot], Amazon [Bot], Bing [Bot] and 9 guests