Touch Lua's Draw Library Basics - random

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.

Related

speed up loop in matlab

I'm very new in MATLAB (this is my first script).
I wonder how may I speed up this loop, I don't know any toolbox or 'tricks' as I'm a newbie on it. I tried to code it with instinct, it works, but it is really long.
All are variables get with fread or integer manually entered, so this is basically simple math, but I have no clue on why is it so long (maybe nested loops ?) and how to improve, as I am more familiar with Python and for example multiprocess.
Thanks a lot
X = 0;
Points = [0,0,0];
for i=1:nbLines
for j=1:nbPositions-1
if lDate(i)>posDate(j) && lDate(i)<=posDate(j+1)
weight = (lDate(i) - posDate(j)) / (posDate(j+1)- posDate(j));
X = posX(j)*(1-weight) + posX(j+1) * weight;
end
end
if X ~= 0
for j=1:nbScans
Y = - distance(i,j) / tan(angle(i,j));
Points = [Points;X, Y, distance(i,j)];
end
end
end
X = 0;
Points = cell([],1) ;
Points{1} = [0,0,0];
count = 1 ;
for i=1:nbLines
id = find(lDate(i)>posDate & lDate(i)<=posDate) ;
if length(id) > 1
weight = (lDate(i) - posDate(id(1))) / (posDate(id(end))- posDate(id(1)));
X = posX(id(1))*(1-weight) + posX(id(end)) * weight;
end
if X ~= 0
j=1:nbScans ;
count = count+1 ;
Y = - distance(i,j)./tan(angle(i,j));
Points{count} = [repelem(X,size(Y,2),size(Y),1), Y, distance(i,j)'];
end
end
You have one issue with the given code. The blow line:
Points = [Points; X, Y, distance(i,j)];
This will definitely slow up your code. You need to initialize this array to store the numbers. If you initialize it, you will find good difference in speed.
X = 0;
Points = zeros([],3) ;
Points(1,:) = [0,0,0];
count = 1 ;
for i=1:nbLines
for j=1:nbPositions-1
if lDate(i)>posDate(j) && lDate(i)<=posDate(j+1)
weight = (lDate(i) - posDate(j)) / (posDate(j+1)- posDate(j));
X = posX(j)*(1-weight) + posX(j+1) * weight;
end
end
if X ~= 0
for j=1:nbScans
count = count+1 ;
Y = - distance(i,j) / tan(angle(i,j));
Points(count,:) = [X, Y, distance(i,j)];
end
end
end
Note that, you code only saves the last value of X, is this what you want?
try using parallelization- "parfor" instead of "for" that uses all available processors.
parfor i=1:nbLines
rest of code here
end

Diamond-Square algorithm: How do I determine what tiles I need to run a diamond function and what tiles I need to run a square function on?

I'm working on a diamond-square heightmap generator and I've been stuck on a certain part for a while now.
I'm having trouble determining which tiles I need to run a square() function on and which tiles I need to run a diamond() function on.
I took a look at this guide: http://www.playfuljs.com/realistic-terrain-in-130-lines/ and I took their for loop they're using as an example, but it didn't seem to work at all.
The preferred language for the answer is Lua (or just kindly point me in the right direction). I just need someone to tell me what I need to do to get a for loop that works for both diamond and square functions.
-- height constraints
local min_height = 10
local max_height = 100
-- the grid
local K = 4
local M = 2^K -- the field is cyclic integer grid 0 <= x,y < M (x=M is the same point as x=0)
local heights = {} -- min_height <= heights[x][y] <= max_height
for x = 0, M-1 do
heights[x] = {}
end
-- set corners height (all 4 corners are the same point because of cyclic field)
heights[0][0] = (min_height + max_height) / 2
local delta_height = (max_height - min_height) * 0.264
local side = M
local sqrt2 = 2^0.5
repeat
local dbl_side = side
side = side/2
-- squares
for x = side, M, dbl_side do
for y = side, M, dbl_side do
local sum =
heights[(x-side)%M][(y-side)%M]
+ heights[(x-side)%M][(y+side)%M]
+ heights[(x+side)%M][(y-side)%M]
+ heights[(x+side)%M][(y+side)%M]
heights[x][y] = sum/4 + (2*math.random()-1) * delta_height
end
end
delta_height = delta_height / sqrt2
-- diamonds
for x = 0, M-1, side do
for y = (x+side) % dbl_side, M-1, dbl_side do
local sum =
heights[(x-side)%M][y]
+ heights[x][(y-side)%M]
+ heights[x][(y+side)%M]
+ heights[(x+side)%M][y]
heights[x][y] = sum/4 + (2*math.random()-1) * delta_height
end
end
delta_height = delta_height / sqrt2
until side == 1
-- draw field
for x = 0, M-1 do
local s = ''
for y = 0, M-1 do
s = s..' '..tostring(math.floor(heights[x][y]))
end
print(s)
end

Kaczmarz animation

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:

"Tic Tac Toe" Touch Lua random squares getting filled in?

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.

Jython (JES) - Function for rotating a picture [duplicate]

I need to write a function spin(pic,x) where it will take a picture and rotate it 90 degrees counter clockwise X amount of times. I have just the 90 degree clockwise rotation in a function:
def rotate(pic):
width = getWidth(pic)
height = getHeight(pic)
new = makeEmptyPicture(height,width)
tarX = 0
for x in range(0,width):
tarY = 0
for y in range(0,height):
p = getPixel(pic,x,y)
color = getColor(p)
setColor(getPixel(new,tarY,width-tarX-1),color)
tarY = tarY + 1
tarX = tarX +1
show(new)
return new
.. but I have no idea how I would go about writing a function on rotating it X amount of times. Anyone know how I can do this?
You could call rotate() X amount of times:
def spin(pic, x):
new_pic = duplicatePicture(pic)
for i in range(x):
new_pic = rotate(new_pic)
return new_pic
a_file = pickAFile()
a_pic = makePicture(a_file)
show(spin(a_pic, 3))
But this is clearly not the most optimized way because you'll compute X images instead of the one you are interested in. I suggest you try a basic switch...case approach first (even if this statement doesn't exists in Python ;):
xx = (x % 4) # Just in case you want (x=7) to rotate 3 times...
if (xx == 1):
new = makeEmptyPicture(height,width)
tarX = 0
for x in range(0,width):
tarY = 0
for y in range(0,height):
p = getPixel(pic,x,y)
color = getColor(p)
setColor(getPixel(new,tarY,width-tarX-1),color)
tarY = tarY + 1
tarX = tarX +1
return new
elif (xx == 2):
new = makeEmptyPicture(height,width)
# Do it yourself...
return new
elif (xx == 3):
new = makeEmptyPicture(height,width)
# Do it yourself...
return new
else:
return pic
Then, may be you'll be able to see a way to merge those cases into a single (but more complicated) double for loop... Have fun...

Resources