I'm currently trying to create brick breaker using love2d but the problem is whenever is used math.random() to generate random bricks the love application keeps running it multiple times and the brick moves constantly.
EDIT: So I want to generate bricks at particular column but the rows should be randomly selected. My basic idea was to do math.random(2) == 1 then drawing bricks using for loop but the problem is that it gets updated/drawn at every second and the bricks keeps on flickering/moving. I just want to randomly(only randomly select the y co-ordinate my x co-ordinate is fixed) to draw it once when you execute the code but its keep on flickering
The issue I'm facing - https://youtu.be/AJB5vH7yfHc
My code
for y = 0, VIRTUAL_HEIGHT- 4, 10 do
if math.random(2) == 1 then
love.graphics.rectangle('line', VIRTUAL_WIDTH - 10, y, 5, 10)
end
end
Alright, after you edited the question, this sounds more like what you're talking about. Just take out that #column loop, and set it to create cells on the last column.
love.load()
--VIRTUAL_WIDTH, VIRTUAL_HEIGHT = love .graphics .getDimensions()
block_pos = {} -- table to store block positions
rows, columns = 30, 20 -- you decide how many
chance_of_block = 33 -- % chance of placing a block
block_width = math .floor( VIRTUAL_WIDTH /columns )
block_height = math .floor( VIRTUAL_HEIGHT /rows )
col = columns -1 -- don't loop through columns, just use final column
for row = 0, rows -1 do
if love .math .random() *100 <= chance_of_block then
local xpos = col *block_width
local ypos = row *block_height
block_pos[ #block_pos +1 ] = { x = xpos, y = ypos }
end -- rand
end -- #columns
r, g, b = 0.5, 0.5, 0.0
love .graphics .setColor( r, g, b )
love.draw()
for b = 1, #block_pos do
local block = block_pos[b]
love .graphics .rectangle( 'line', block.x, block.y, block_width, block_height )
end -- #block_pos
generate block positions in love.load()
--VIRTUAL_WIDTH, VIRTUAL_HEIGHT = love .graphics .getDimensions( )
block_pos = {} -- table to store block positions
rows, columns = 5, 8 -- you decide how many
chance_of_block = 75 -- % chance of placing a block
block_width = math .floor( VIRTUAL_WIDTH /columns )
block_height = math .floor( VIRTUAL_HEIGHT /rows )
for row = 0, rows -1 do
for col = 0, columns -1 do
if love .math .random() *100 <= chance_of_block then
local xpos = col *block_width
local ypos = row *block_height
local red = love .math .random()
local green = love .math .random()
local blue = love .math .random()
block_pos[ #block_pos +1 ] = { x = xpos, y = ypos, r = red, g = green, b = blue }
end -- rand
end -- #columns
end -- #rows
(edited: realized row & column should start from 0 index, so they line up on the screen)
then draw them with love.draw()
for b = 1, #block_pos do
local block = block_pos[b]
love .graphics .setColor( block.r, block.g, block.b )
love .graphics .rectangle( 'fill', block.x, block.y, block_width, block_height )
end -- #block_pos
Related
i am asking for help.. I want to animate the Kaczmarz method on Matlab. It's method allows to find solution of system of equations by the serial projecting solution vector on hyperplanes, which which is given by the eqations of system.
And i want make animation of this vector moving (like the point is going on the projected vectors).
%% System of equations
% 2x + 3y = 4;
% x - y = 2;
% 6x + y = 15;
%%
A = [2 3;1 -1; 6 1];
f = [4; 2; 15];
resh = pinv(A)*f
x = -10:0.1:10;
e1 = (1 - 2*x)/3;
e2 = (x - 2);
e3 = 15 - 6*x;
plot(x,e1)
grid on
%
axis([0 4 -2 2])
hold on
plot(x,e2)
hold on
plot(x,e3)
hold on
precision = 0.001; % точность
iteration = 100; % количество итераций
lambda = 0.75; % лямбда
[m,n] = size(A);
x = zeros(n,1);
%count of norms
for i = 1:m
nrm(i) = norm(A(i,:));
end
for i = 1:1:iteration
j = mod(i-1,m) + 1;
if (nrm(j) <= 0), continue, end;
predx = x;
x = x + ((f(j) - A(j,:)*x)*A(j,:)')/(nrm(j))^2;
p = plot(x);
set(p)
%pause 0.04;
hold on;
if(norm(predx - x) <= precision), break, end
end
I wrote the code for this method, by don't imagine how make the animation, how I can use the set function.
In your code there are a lot of redundant and random pieces. Do not call hold on more than once, it does nothing. Also set(p) does nothing, you want to set some ps properties to something, then you use set.
Also, you are plotting the result, but not the "change". The change is a line between the previous and current, and that is the only reason you'd want to have a variable such as predx, to plot. SO USE IT!
Anyway, this following code plots your algorithm. I added a repeated line to plot in green and then delete, so you can see what the last step does. I also changed the plots in the begging to just plot in red so its more clear what is each of the things.
Change your loop for:
for i = 1:1:iteration
j = mod(i-1,m) + 1;
if (nrm(j) <= 0), continue, end;
predx = x;
x = x + ((f(j) - A(j,:)*x)*A(j,:)')/(nrm(j))^2;
plot([predx(1) x(1)],[predx(2) x(2)],'b'); %plot line
c=plot([predx(1) x(1)],[predx(2) x(2)],'g'); %plot it in green
pause(0.1)
children = get(gca, 'children'); %delete the green line
delete(children(1));
drawnow
% hold on;
if(norm(predx - x) <= precision), break, end
end
This will show:
WARNING: This question is only for Touch Lua users who have purchased and have knowledge of the Draw Library.
PLEASE REFER TO THE BOTTOM PORTION OF THIS QUESTION TO SEE THE FULL PROGRAM. THE SNIPPETS I USE IN THE BEGINNING ARE PART OF THAT PROGRAM (NUMPAD.LUA)
Okay, so now for the questions:
•What's the use of "." between "b" and "x"? Or "b" and "draw"? Etc...
•How does the table set up the button? Please be super specific?
•Why is there a "+", "*", and "(j-1)" in lines 7 and 8?
•What's height and width doing in there? I thought there were only x and y.
function createButtons()
buttons = { }
local c = 1
for i = 1, 4 do
for j = 1, 3 do
local b = { }
b.x = 80 + 60 * (j-1)
b.y = 160 + 60 * (i-1)
b.width = 40
b.height = 40
b.color = draw.blue
b.draw = drawButton
b.action = digitAction
buttons[c] = b
c = c + 1
end
end
buttons[1].title = '7'
buttons[2].title = '8'
buttons[3].title = '9'
buttons[4].title = '4'
buttons[5].title = '5'
buttons[6].title = '6'
buttons[7].title = '1'
buttons[8].title = '2'
buttons[9].title = '3'
buttons[10].title = '0'
buttons[11].title = '.'
buttons[11].action = dotAction
buttons[12].title = 'C'
buttons[12].color = draw.orange
buttons[12].action = clearAction
end
Lastly, referencing the program as a whole...
•How does the button know when you tap on it? Specifically what are the lines of code and how does it work? (I have a very faint understanding of track touches btw)
function digitAction(button)
if string.len(display.title) < 16 then
sys.alert('tock')
if display.started then
display.title = display.title .. button.title
else
if button.title ~= '0' then
display.title = button.title
display.started = true
end
end
else
sys.alert('tink')
end
end
function dotAction(button)
if string.find(display.title, '.', 1, true) then
sys.alert('tink')
else
display.title = display.title .. '.'
display.started = true
sys.alert('tock')
end
end
function clearAction(button)
sys.alert('tock')
display.title = '0'
display.started= false
end
function createDisplay()
display = { }
display.x = 60
display.y = 100
display.width = 200
display.height = 40
display.title = '0'
display.color = draw.red
display.started = false
end
function createButtons()
buttons = { }
local c = 1
for i = 1, 4 do
for j = 1, 3 do
local b = { }
b.x = 80 + 60 * (j-1)
b.y = 160 + 60 * (i-1)
b.width = 40
b.height = 40
b.color = draw.blue
b.draw = drawButton
b.action = digitAction
buttons[c] = b
c = c + 1
end
end
buttons[1].title = '7'
buttons[2].title = '8'
buttons[3].title = '9'
buttons[4].title = '4'
buttons[5].title = '5'
buttons[6].title = '6'
buttons[7].title = '1'
buttons[8].title = '2'
buttons[9].title = '3'
buttons[10].title = '0'
buttons[11].title = '.'
buttons[11].action = dotAction
buttons[12].title = 'C'
buttons[12].color = draw.orange
buttons[12].action = clearAction
end
function drawDisplay()
draw.setfont('Helvetica', 20)
draw.setlinestyle(2, 'butt')
local x1, y1 = display.x, display.y
local x2, y2 = x1 + display.width, y1 + display.height
draw.roundedrect(x1, y1, x2, y2, 10, display.color)
local w, h = draw.stringsize(display.title)
local x = x2 - 10 - w
local y = y1 + (display.height - h)/2
draw.string(display.title, x, y, draw.black)
end
function drawButton(b)
draw.setfont('Helvetica', 18)
draw.setlinestyle(2, 'butt')
local x1, y1 = b.x, b.y
local x2, y2 = x1+b.width, y1+b.height
draw.roundedrect(x1, y1, x2, y2, 10, b.color)
local w, h = draw.stringsize(b.title)
local x = b.x + (b.width - w)/2
local y = b.y + (b.height - h)/2
draw.string(b.title, x, y, draw.black)
end
function drawButtons()
for i = 1, #buttons do
buttons[i].draw(buttons[i])
end
end
function lookupButton(x, y)
for i = 1, #buttons do
local b = buttons[i]
if x > b.x and x < b.x+b.width and y > b.y and y < b.y+b.height then
return b
end
end
return nil
end
function drawScreen()
draw.beginframe()
draw.clear()
drawDisplay()
drawButtons()
draw.endframe()
end
function touchBegan(x, y)
local b = lookupButton(x, y)
if b then
b.action(b)
end
end
function touchMoved(x, y)
end
function touchEnded(x, y)
end
function init()
draw.setscreen(1)
draw.settitle('Num Pad')
draw.clear()
draw.tracktouches (touchBegan, touchMoved, touchEnded)
createButtons()
createDisplay()
end
function mainloop()
while true do
draw.doevents()
drawScreen()
draw.sleep(30)
end
end
function main()
init()
mainloop()
end
-- start program
main()
Thank you so much for any help you can offer! I know this is a lot of questions, but this knowledge can really help propel me forward!
WARNING: This question is only for Touch Lua users who have purchased
and have knowledge of the Draw Library
Since when do you have to purchase something to answer programming questions? All your questions are on absolute Lua basics anyway.
What's the use of "." between "b" and "x"? Or "b" and "draw"? Etc...
The dot operator is used to index table members. So b.x will give you the value that belongs to key "x" in table b. Its syntactic sugar for b["x"].
How does the table set up the button? Please be super specific?
The function createButtons creates an empty table and fills it with buttons represented by a table b that stores various button properties.
Why is there a "+", "*", and "(j-1)" in lines 7 and 8?
Because the author of that program wants to add and multiply. Here the coordinates b.x and b.y are calculated. (j-1) is used because j starts at 1, but he needs it to start at 0 for this calculation.
The 2 for loops will create 4 rows of buttons, each containing 3 buttons as the x coordinate depends on parameter j while y depends on parameter i.
What's height and width doing in there? I thought there were only x
and y.
The button needs dimensions, not only a location. As b is created as a local variable within the for loop all its properties are set here. They may be changed later.
How does the button know when you tap on it? Specifically what are the
lines of code and how does it work?
Your mainloop will call draw.doevents() every cycle. So at some point there will be an event that will cause touchBegan to be called.
The button itself does not know that it was tapped. function touchBegan(x,y) will search if one of the buttons was hit at x,y by calling lookupButton(x,y) and call its action function. action is either one of dotAction, digitAction or clearAction. So if you tap on a digit button digitAction() will be called e.g.
Do yourself a favour and read a book on Lua or at least do a Lua tutorial. Befor diving into third party libraries. If you don't know how to index the most common Lua type or that + and * are arrithmetic operators, you will have a very hard time understanding code and you will not be productive in any way.
This program in particular uses tables to represent buttons, it does this to make it more manageable. The height and width are the same way. If you are new to the draw library, reviewing code like this is only going to confuse you. Most of your questions are actually about OOP honestly
Also this question probably isn't suitable for Stack Overflow right now. If you want help/a small tutorial on the subject feel free to PM me on the Touch Lua forum, my username is warspyking, but as it stands you need to either revise or delete this question.
I'm writing a "Peak finder" in Matlab. I've never used Matlab or anything similar before this project, so I'm new to "vectorizing" my code. Essentially, the program needs to take a video of molecules and plot circles on the molecules present in each frame of the video. If a molecule is crowded then it gets a red circle, but if it is not crowded it gets a green circle.
My problem is that some of these videos have 2000 frames and my program takes up to ~25 seconds to process a single frame, which is not practical.
Using tic and toc I've found the trouble maker: A for-loop which calls a function that contains a for-loop.
function getPeaks( orgnl_img, processed_img, cut_off, radius )
% find large peaks peaks by thresholding, i.e. you accept a peak only
% if its more than 'threshold' higher than its neighbors
threshold = 2*std2(orgnl_img);
peaks = (orgnl_img - processed_img) > threshold;
% m and n are dimensions of the frame, named peaks
[m, n] = size(peaks);
cc_centroids = regionprops(peaks, 'centroid');
% Pre-allocate arrays
x_centroid = zeros(1, length(cc_centroids));
y_centroid = zeros(1, length(cc_centroids));
for i = 1:length(cc_centroids)
% Extract the x and y components from cc_centroids struct
x_centroid(i) = cc_centroids(i).Centroid(1);
y_centroid(i) = cc_centroids(i).Centroid(2);
row = int64(x_centroid(i));
col = int64(y_centroid(i));
% Assure that script doesnt attempt to exceed frame
if col-2 > 0 && row-2 > 0 && col+2 < m && row+2 < n
region_of_interest = orgnl_img(col-2:col+2,row-2:row+2);
local_intensity = max(region_of_interest(:));
% Do not plot circle when intensity is 'cut off' or lower
if local_intensity > cut_off
dist_bool = findDistance(cc_centroids, x_centroid(i), y_centroid(i), radius);
if dist_bool == 1
color = 'g';
else
color = 'r';
end
plotCircle(color, x_centroid(i), y_centroid(i), radius)
end
end
end
end
And here is the findDistance function which contains another for-loop and determines if the circles overlap:
function dist_bool = findDistance( all_centroids, x_crrnt, y_crrnt, radius )
x_nearby = zeros(1, length(all_centroids));
y_nearby = zeros(1, length(all_centroids));
for i = 1:length(all_centroids)
if all_centroids(i).Centroid(1) < (x_crrnt+2*radius) &&...
all_centroids(i).Centroid(1) > (x_crrnt-2*radius) &&...
all_centroids(i).Centroid(2) < (y_crrnt+2*radius) &&...
all_centroids(i).Centroid(2) > (y_crrnt-2*radius)
x_nearby(i) = all_centroids(i).Centroid(1);
y_nearby(i) = all_centroids(i).Centroid(2);
pts_of_interest = [x_nearby(i),y_nearby(i);x_crrnt,y_crrnt];
dist = pdist(pts_of_interest);
if dist == 0 || dist > 2*radius
dist_bool = 1;
else
dist_bool = 0;
break
end
end
end
end
I think that there must be much improvement to be done here. I would appreciate any advice.
Thanks! :)
UPDATE: Here are the profiler results. The first section of code is the "getPeaks" function
http://i.stack.imgur.com/VaLdH.png
The hold comes from the plot circle function:
function plotCircle( color, x_centroid, y_centroid, radius )
hold on;
th = 0:pi/50:2*pi;
xunit = radius * cos(th) + x_centroid;
yunit = radius * sin(th) + y_centroid;
plot(xunit, yunit, color);
hold off;
end
So I recently purchased the draw library on Touch Lua! I've started trying to make a simple Tic Tac Toe game. I'm using a simple setup they used to detect clicks on the NumPad default program, so the buttons should work.
The problem is that when you tap a square, the O fills into seemingly-random squares, sometimes more than 1, up to 4+ squares may get filled.
I suspect the problem is the function Picked, which sets the title to X/O and then updates the board.
local Turn = nil
local Move = "O"
local Mode = nil
::ModePick::
print("1 player mode? (y/n)")
local plrs = io.read()
if plrs == "y" then
Mode = 1
goto TurnChoice
elseif plrs == "n" then
Mode = 2
goto Game
else
goto ModePick
end
::TurnChoice::
print("Would you like to go first? (Be O) (y/n)")
do
local pick = io.read()
if pick == "y" then
Turn = 1
elseif pick == "n" then
Turn = 2
else
goto TurnChoice
end
end
::Game::
local Buttons = {}
draw.setscreen(1)
draw.settitle("Tic Tac Toe")
draw.clear()
width, height = draw.getport()
function Picked(b)
for i,v in pairs(Buttons) do
if v == b then
b.title = Move
UpdateBoard()
end
end
--Fill in X/O details
--Detect if there's a tic/tac/toe
--Set winning screen
if Move == "O" then
--Compute Move (1 player)
--Move = "X" (2 player)
else
Move = "O"
end
end
function DrawButton(b)
draw.setfont('Helvetica', 50)
draw.setlinestyle(2, 'butt')
local x1, y1 = b.x, b.y
local x2, y2 = x1+b.width, y1+b.height
draw.rect(x1, y1, x2, y2, b.color)
local w, h = draw.stringsize(b.title)
local x = b.x + (b.width - w)/2
local y = b.y + (b.height - h)/2
draw.string(b.title, x, y, draw.black)
return b
end
function Button(x, y, x2, y2, title, color, action)
local action = action or function() end
local button = {x = x, y = y, width = x2, height = y2, color = color, title = title, action = action}
table.insert(Buttons, button)
return button
end
function LookUpButton(x, y)
for i = 1, #Buttons do
local b = Buttons[i]
if x > b.x and x < b.x+b.width and y > b.y and y < b.y+b.height then
return b
end
end
return nil
end
function TouchBegan(x, y)
local b = LookUpButton(x, y)
if b then
b.action(b)
end
end
function TouchMoved(x, y)
end
function TouchEnded(x, y)
end
draw.tracktouches(TouchBegan, TouchMoved, TouchEnded)
function CreateButton(x,y,x2,y2,txt,col,func)
return DrawButton(Button(x, y, x2, y2, txt, col, func))
end
function UpdateBoard()
draw.clear()
for i = 1,3 do
for ii = 1,3 do
CreateButton(100 * (ii - 1) + 7.5, 100 * (i - 1) + 75, 100, 100, Buttons[i + ii].title, draw.blue, Picked)
end
end
end
for i = 1,3 do
for ii = 1,3 do
CreateButton(100 * (ii - 1) + 7.5, 100 * (i - 1) + 75, 100, 100, "", draw.blue, Picked)
end
end
while true do
draw.doevents()
sleep(1)
end
Note: Sorry if the indention came out wrong, I pasted all this code in on my iPod, so I had to manually put in 4 spaces starting each line.
If anybody could help me out with this small setback I have, I'd love the help, if there's anything I'm missing I'd gladly edit it in just reply in the comments :D
EDIT: I've modified some of the code to fix how the table keeps getting new buttons, this is the code I have now, same problem, buttons are added in wrong place (and getting removed now):
function Button(x, y, x2, y2, title, color, action, prev)
local action = action or function() end
local button = {x = x, y = y, width = x2, height = y2, color = color, title = title, action = action}
if prev then
for i,v in pairs(Buttons) do
if v == prev then
table.remove(Buttons, i)
end
end
end
table.insert(Buttons, button)
return button
end
function CreateButton(x,y,x2,y2,txt,col,func, prev)
return DrawButton(Button(x, y, x2, y2, txt, col, func, prev))
end
function UpdateBoard()
draw.clear()
for i = 1,3 do
for ii = 1,3 do
CreateButton(100 * (ii - 1) + 7.5, 100 * (i - 1) + 75, 100, 100, Buttons[i + ii].title, draw.blue, Picked, Buttons[i + ii])
end
end
end
EDIT: Thanks to Etan I've fixed UpdateBoard, squares are still random:
function UpdateBoard()
draw.clear()
local n = 1
for i = 1,3 do
for ii = 1,3 do
CreateButton(100 * (ii - 1) + 7.5, 100 * (i - 1) + 75, 100, 100, Buttons[n].title, draw.blue, Picked, Buttons[n])
n = n + 1
end
end
end
It's been a while since I've got around to post the finished code, but this is what it looks like:
function UpdateBoard(ended)
local ended = ended or false
local Act = nil
if ended == true then
Act = function() end
else
Act = Picked
end
draw.clear()
local Buttons2 = {}
for i,v in pairs(Buttons) do
Buttons2[i] = v
end
Buttons = {}
local n = 1
for i = 1,3 do
for ii = 1,3 do
CreateButton(100 * (ii - 1) + 7.5, 100 * (i - 1) + 75, 100, 100, Buttons2[n].title, draw.blue, Act, Buttons2[n], i, ii)
n = n + 1
end
end
OpenButtons = {}
ClosedButtons = {}
for i,v in pairs(Buttons) do
if v.title == "" then
table.insert(OpenButtons, v)
else
table.insert(ClosedButtons, v)
end
end
end
It may seem a bit complicated for the question, but this is the code after multiple other things.
The main difference you should note here, is that it's recreating the table of buttons, so it does not recount new buttons, and it uses n to count up, instead of using i and ii.
I have a set of pre-declared values to set specific rotations for an object.
local rotations = {900,-900}
And want my spawn function for the blocks to randomly pick one or the other from this function:
local blocks = {}
timerSrc = timer.performWithDelay(1200, createBlock, -1)
function createBlock(event)
b = display.newImageRect("images/block8.png", 20, 150)
b.x = 500
b.y = math.random(100,250)
b.name = 'block'
physics.addBody(b, "static")
transition.to( b, { rotation = math.random(rotations), time = math.random(2700,3700)} )
blocks:insert(b)
end
When I use:
rotation = math.random(-900,900)
it just chooses any values between the 2 numbers rather than 1 or the other. How can I do this correctly ?
If m is an integer value, math.random(m) returns integers in range [1, m] randomly. So math.random(2) returns integers 1 or 2 randomly.
To generate random numbers either 900 or -900, use:
rotation = math.random(2) == 1 and 900 or -900