Score activated when button is pressed does not work, Corona sdk - button

I would like the score to increase only when this button is pressed. However when I tried running my code the score did not change... Any ideas?
thanks in advance!
here is my code:
score = 0
local scoreNumber = display.newText(score, 200, 30, nil, 20)
scoreNumber.xScale = 1.2
scoreNumber.yScale = 1.2
local scoreText = display.newText("score:", 150, 30, nil, 20)
scoreText.xScale = 1.2
scoreText.yScale = 1.2
local buttonPressed = false
local myButton = display.newRect(50,50,100,100)
local function scoretimer(event)
if buttonPressed then
score = score + 1
scoreNumber.text = score
end
end
local function buttonPressed(event)
if event.phase == "began" then
buttonPressed = true
elseif event.phase == "ended" then
buttonPressed = false
end
return true
end
myButton:addEventListener("touch", buttonPressed)
Runtime:addEventListener("enterFrame", scoretimer)

First you declare:
local buttonPressed = false
end then you declare it again as a function:
local function buttonPressed(event)
Rename your function and everything should go fine

Related

The buttons in my pygame menu only work on hold and not on push [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
Closed 5 days ago.
i am working through a pygame code and am in the process of creating a second menu sequentially, however unlike the first menu the second one differs in that it only works when holding down on the position of the button.
i am wondering if anyone can help differentiate what makes the two work and if there is a fix for it.
import random
import time
import pygame
pygame.init()
WIDTH = 500
HEIGHT = 500
screen = pygame.display.set_mode([WIDTH, HEIGHT])
fps = 60
timer = pygame.time.Clock()
main_menu = False
font = pygame.font.Font('freesansbold.ttf', 24)
menu_command = 0
p1score = 0
p2score = 0
class Button:
def __init__(self, txt, pos):
self.text = txt
self.pos = pos
self.button = pygame.rect.Rect((self.pos[0], self.pos[1]), (200, 40))
def draw(self):
pygame.draw.rect(screen, 'light gray', self.button, 0, 5)
pygame.draw.rect(screen, 'dark gray', self.button, 5, 5)
text = font.render(self.text, True, 'black')
screen.blit(text, (self.pos[0] + 15, self.pos[1] + 7))
def check_clicked(self):
if self.button.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
return True
else:
return False
def draw_game():
button = Button('Main Menu', (120, 450))
button.draw()
menu = button.check_clicked()
return menu
def draw_menu():
command = -1
pygame.draw.rect(screen, 'black', [100, 100, 300, 300])
#exit menu button
menu_button = Button('Exit Menu', (120, 350))
btn1 = Button('Local Match', (120, 180))
btn2 = Button('Online Match', (120, 240))
btn3 = Button('Settings', (120, 300))
menu_button.draw()
btn1.draw()
btn2.draw()
btn3.draw()
if menu_button.check_clicked():
command = 0
if btn1.check_clicked():
command = 1
if btn2.check_clicked():
command = 2
if btn3.check_clicked():
command = 3
return command
def turndecide():
time.sleep(0.1)
firstturn = -1
p1button = Button('player 1', (120, 120))
p2button = Button('player 2', (120, 180))
ranbutton = Button('Random', (120, 240))
firstturntext = font.render(f'please select who will take the first turn', True, 'black')
screen.blit(firstturntext, (20, 20))
p1button.draw()
p2button.draw()
ranbutton.draw()
if p1button.check_clicked():
firstturn = 1
if p2button.check_clicked():
firstturn = 2
if ranbutton.check_clicked():
firstturn = random.randint(1, 2)
return firstturn
def localgame():
screen.fill('white')
turn = turndecide()
if turn > 0:
screen.fill('red')
outputtext = font.render(f'player {turn} will move first', True, 'black')
screen.blit(outputtext, (20, 20))
run = True
while run:
screen.fill('white')
timer.tick(fps)
if main_menu:
menu_command = draw_menu()
if menu_command != -1:
main_menu = False
else:
main_menu = draw_game()
if menu_command > 0:
if menu_command == 1:
localgame()
if menu_command == 2:
onlinegame()
if menu_command == 3:
settings()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.flip()
pygame.quit()
i tried adding a while loop to ensure the code does not move backward as it does
def localgame():
screen.fill('white')
turn = turndecide()
testvariable = True
while testvariable:
if turn > 0:
screen.fill('red')
outputtext = font.render(f'player {turn} will move first', True, 'black')
screen.blit(outputtext, (20, 20))
but this causes the program to crash.
In your check_clicked function, it will return True only if the user is actively clicking on the button. Whether or not you show the menu is, therefore, also linked to whether or not the user is actively clicking/holding the button.
Instead, each time the button is clicked, toggle the menu option. Only toggle the menu again once the player releases the mouse and presses it again. This avoids the menu being toggled really quickly constantly while holding the button down.
Perhaps, have a can_click variable that is set to False every time a click is registered and reset to True when the mouse is released.

Object Shell.Application Open Folder In Same Explorer Window

I want to ask you a question regarding Shell.Application COM Object. The programming language I work in is AutoIT. I would like to know, how can I open a folder in the exact same Window a previous folder has been opened.
For instance, if I open the C:\Folder in a Window and it has a subfolder, then how can I make the Script open that subfolder in the same window the "parent folder" has been opened, without creating a new window for that. The only way I can open a Folder is like this:
global $ShellApplication = ObjCreate("Shell.Application")
$ShellApplication.Explore("C:\Folder")
Sleep(100)
$ShellApplication.Explore("C:\Folder\Subfolder")
but this way is the wrong way. I hope someone has got any idea about how this could be achieved.
I don't know whether this is what you want, but you can automate the current window like this:
#include <Array.au3>
Opt("SendKeyDelay", 1) ;5 milliseconds
Opt("SendKeyDownDelay", 1) ;1 millisecond
$pid = ShellExecute("explorer.exe ", #DesktopDir)
Sleep(300)
;~ $aWinList=WinList("[REGEXPCLASS:(Explore|Cabinet)WClass]")
;~ _ArrayDisplay($aWinList)
ConsoleWrite($pid & #CRLF)
$handle = _WinGetHandleByPID($pid)
Sleep(2000)
SendKeepActive($handle)
Send('{F4}')
Send('^a')
Send(#AppDataCommonDir & "{ENTER}")
Func _WinGetHandleByPID($vProcess, $nShow = 1)
; Get Window Handle by PID
; Author Hubertus
; derived from Smoke_N's script with the same name,
; but to handle more than one process with the same name
; and to return handle of newest window ($nShow = 2).
;
; $vProcess = Processname(e.g. "Notepad.exe") or Processnumber(e.g. 4711 )
; $nShow = -1 "All (Visble or not)", $nShow = 0 "Not Visible Only", $nShow = 1 "Visible Only", $nShow = 2 "return handle of newest window "
; #error = 0 Returns array of matches. Array[0][0] and #extended shows number of matches.
; #error = 0 and $nShow = 2 return handle of newest window
; Array[n][0] shows windows title. Array[n][1] shows windows handle. n = 1 to #extended
; #error = 1 Process not found.
; #error = 2 Window not found.
If Not ProcessExists($vProcess) Then Return SetError(1, 0, 0) ; no matching process
Local $iWinList, $aWinList = WinList()
Local $iResult, $aResult[UBound($aWinList)][2]
Local $iProcessList, $aProcessList = ProcessList($vProcess)
If $aProcessList[0][0] = 0 Then Local $aProcessList[2][2] = [[1, 0], ["", $vProcess]]
For $iWinList = 1 To $aWinList[0][0]
For $iProcessList = 1 To $aProcessList[0][0]
If WinGetProcess($aWinList[$iWinList][1]) = $aProcessList[$iProcessList][1] Then
If $nShow > -1 And Not $nShow = (2 = BitAND(WinGetState($aWinList[$iWinList][1]), 2)) Then ContinueLoop
$iResult += 1
$aResult[$iResult][0] = $aWinList[$iWinList][0]
$aResult[$iResult][1] = $aWinList[$iWinList][1]
EndIf
Next
Next
If $iResult = 0 Then Return SetError(2, 0, 0) ; no window found
ReDim $aResult[$iResult + 1][2]
$aResult[0][0] = $iResult
If $nShow = 2 Then Return SetError(0, $iResult, $aResult[1][1])
Return SetError(0, $iResult, $aResult)
EndFunc ;==>_WinGetHandleByPID

Displaying image buttons to replicate app icons - Corona SDK

I need to display images so that they mimic the layout of iOS app icons on the various "home" pages. I have the code written to display the various images; however, I cannot figure out how to return a value which corresponds with each individual image on a click event.
Here's my code so far:
plates = {
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png"
}
-- The PlateId will have corosponding indexes with the plates array. It will be used to query plate information
plateId = {1,2,3,4}
plateIdRef = {}
index = 1
platesIsh = {1,2,3,4,5,6,7,8}
local anX = 20
local anY = 120
for i=1, #plates do
local bufferY = 20
if index == 4 then
bufferY = 110
anX = 20
elseif index > 4 then
bufferY = 110
end
if index == 7 then
bufferY = 200
anX = 20
elseif index > 7 then
bufferY = 200
if index == 10 then
bufferY = 290
anX = 20
elseif index > 10 then
bufferY = 290
end
end
local dummyVar = math.random()
dummyVar = display.newImageRect(plates[index],80, 80)
sceneGroup:insert(dummyVar)
dummyVar.x = anX + 30
dummyVar.y = anY + bufferY
table.insert(plateIdRef, index)
function dummyVar:touch( event )
if event.phase == "began" then
local alert = native.showAlert( "Corona", event.target, { "OK", "Learn More" } )
--print( "You touched "..dummyVar)
return true
end
end
dummyVar:addEventListener( "touch", dummyVar )
anX = anX + 110
index = index + 1
end
Any ideas?
Ok, an example to see how it works:
local plates = {}
local function plateTouch( self, event )
local phase = event.phase
if phase == "ended" then
print( "You touched ".. self.id)
end
return true
end
for i=1, 3 do
plates[i] = display.newImageRect("test.png",80, 80)
plates[i].id = "plate " .. i
plates[i].x = 90 * i
plates[i].y = 90
plates[i].touch = plateTouch
plates[i]:addEventListener( "touch", plates[i] )
end
When you create each plate you can define an id property to know what button was pressed, also you can add any other properties you need.
You can see the API docs for touch event and see the example with table listeners.
Other approach could be object oriented solution, where you define a class to create new plates, but maybe first you need to understand the example.

why does the Director class make my global variables not visible to external modules in corona?

I'm doing basic stuff to understand using external classes/modules with global variables, and now I'm trying to add director. But when I added the director class, my global variables such as applyThrust then became not visible in the external class.
It worked fine before refactoring for Director. Before using director, I only had 2 files, rocket.lua and the mainScreen.lua file below was simply main.lua. I used the same globals, applyThrust and thrustForceY, and it worked.
By the way, the director functionality of switching screens appears to work fine, other than this odd side effect of making the global variables not visible.
I asked this on the corona director forums and got no response so I thought I'd try reliable STO.
Here's the files I'm using with the director stuff :
main.lua
display.setStatusBar (display.HiddenStatusBar)
local director = require ("director")
local mainGroup = display.newGroup()
local function main()
mainGroup:insert(director.directorView)
director:changeScene("menu")
return true
end
main()
menu.lua
module(..., package.seeall)
function new()
local localGroup = display.newGroup()
------------------------------------------------------------------------------
local playText = display.newText("Play",160, 100, "Arial", 32)
playText:setTextColor(0, 0, 255)
localGroup:insert(playText)
local function pressPlay (event)
if event.phase == "ended" then
director:changeScene ("mainScreen")
end
end
playText:addEventListener ("touch", pressPlay)
------------------------------------------------------------------------------
return localGroup
end
mainScreen.lua
local Rocket = require( "rocket" )
local physics = require( "physics" )
module(..., package.seeall)
function new()
local localGroup = display.newGroup()
------------------------------------------------------------------
score = 100
physics.start()
local ground = display.newRect( 60, 170, 60, 60 )
physics.addBody( ground, "static", { density=3.0, friction=0.5, bounce=0.2 } )
rocket = Rocket.new(80, 110)
local upText = display.newText("Up",160, 300, "Arial", 32)
upText:setTextColor(0, 0, 255)
------------- my global variables -----------
thrustForceY = -100
applyThrust = false
local function pressUp (event)
local t = event.target
local phase = event.phase
if( "began" == phase ) then
display.getCurrentStage():setFocus( t )
t.isFocus = true
if( not applyThrust ) then
rocket:addThrust()
end
rocket:applyForce(0, thrustForceY, rocket.x, rocket.y)
applyThrust = true
elseif "ended" == phase or "cancelled" == phase then
rocket:removeThrust()
display.getCurrentStage():setFocus( nil )
t.isFocus = false
applyThrust = false
end
return true
end
upText:addEventListener ("touch", pressUp)
----------------------------------------------
return localGroup
end
rocket.lua
module(..., package.seeall)
local physics = require( "physics" )
--constructor--------------------
function new(x, y)
rocket = display.newGroup()
local body = display.newRect( x, y, 25, 60 )
physics.addBody( body, { density=1.5, friction=0.5, bounce=0.2 } )
body.isFixedRotation = true
rocket:insert(body)
local thrust = {}
function rocket:addThrust()
thrust = display.newRect( body.x, body.y + (body.height / 2) , 10, 10 )
thrust.y = body.y + (body.height / 2) + (thrust.height / 2)
physics.addBody( thrust, { density=1.5, friction=0.5, bounce=0.2 } )
rocket:insert(thrust)
end
function rocket:removeThrust()
rocket:remove(thrust)
end
function rocket:applyForce( xForce, yForce, atPointX, atPointY )
body:applyForce( xForce, yForce, atPointX, atPointY )
end
----------------------------------------------------------------------
-- enterFrame listener for rocket
----------------------------------------------------------------------
function rocket:enterFrame (event)
if( applyThrust ) then
body:applyForce(0, thrustForceY, body.x, body.y)
thrust.y = body.y + (body.height / 2) + (thrust.height / 2)
thrust.x = body.x
else
print("applyThrust is nil")
end
end
Runtime:addEventListener("enterFrame", rocket)
return rocket
end
A global variable in Corona is as simple as using "_G." before your variable.
For example:
lives = 3
Would become:
_G.lives = 3
But Director already has functionality to pass parameters to another scene.... there is no need to use globals.
scene1.lua
local params = {
param1= "http://github.com/",
param2 = "bla-bla"
}
director:changeScene( params, "screen2", "moveFromRight" )
screen2.lua
new = function ( params )
local url = params.param1
local bla = params.param2
...
end
Good point.
Also, you can put all your variables in a file you created and access it from any module.

Lua recursive scrolling menu not working?

Hey guys, just wondering why ain't my menu working, I've been coding it for like 8 hours now and just can't figure out what's wrong.
Menu = {
label = "Mahin Menu",
current = current or true,
open = open or true,
subMenus = {}
}
function Menu.newSubMenu()
return {
setup = Menu.setup,
print = Menu.print,
toggleOpen = Menu.toggleOpen,
getCurrentMenu = Menu.getCurrentMenu,
getLastMenu = Menu.getLastMenu,
getNextMenu = Menu.getNextMenu,
getPrevMenu = Menu.getPrevMenu
}
end
function Menu:setup(m_parent, m_label, m_action)
self.parent = m_parent
self.label = m_label
self.action = m_action
self.subMenus = {}
self.current = false
self.open = false
table.insert(m_parent.subMenus, self)
end
function Menu:print(indent)
io.write(string.rep(" ", indent))
if #self.subMenus>0 then
if self.open == true then
io.write("[-]")
else
io.write("[+]")
end
else
io.write(" ")
end
if self.current == true then
io.write("<" .. self.label .. ">")
else
io.write(" " .. self.label)
end
io.write("\n")
if #self.subMenus>0 and self.open == true then
for i=1,#self.subMenus do
self.subMenus[i]:print(indent+1)
end
end
end
function Menu:toggleOpen()
if self.open == true then
self.open = false
else
self.open = true
end
end
function Menu:getCurrentMenu()
if self.current == true then
return self
else
for k=1,#self.subMenus do
local v = self.subMenus[k]:getCurrentMenu()
if v ~= nil then
return v
end
end
end
end
function Menu:getLastMenu()
if self.open == true and #self.subMenus > 0 then
return self.subMenus[#self.subMenus]:getLastMenu()
else
return self
end
end
function Menu:getNextMenu(bool)
bool = bool or false
if bool == false then
if #self.subMenus > 0 and self.open == true then
return self.subMenus[1]
end
end
if self.parent then
if self.parent.subMenus[#self.parent.subMenus] == self then
self.parent:getNextMenu(true)
else
for i=1,#self.parent.subMenus do
if self.parent.subMenus[i] == self then
print(self.parent.subMenus[i+1].label)
return self.parent.subMenus[i+1]
end
end
end
else
return self
end
end
function Menu:getPrevMenu()
if self.parent then
for k=1,#self.parent.subMenus do
if self.parent.subMenus[k] == self then
if k == 1 then
return self.parent
elseif #self.parent.subMenus[k-1].subMenus > 0 and self.parent.subMenus[k-1].open == true then
local x = self.parent.subMenus[k-1]
while #x.subMenus > 0 and x.open == true do
x = x.subMenus[#x.subMenus]
end
return x
else
return self.parent.subMenus[k-1]
end
end
end
else
return self
end
end
Test = Menu.newSubMenu()
Test:setup(Menu, "Test item")
Mahi = Menu.newSubMenu()
Mahi:setup(Menu, "Mahi item")
Mahi.open = true
Testx = Menu.newSubMenu()
Testx:setup(Mahi, "Lalall")
Testx.open= true
Sadmad = Menu.newSubMenu()
Sadmad:setup(Testx, "Woot")
Asd = Menu.newSubMenu()
Asd:setup(Menu, "Asd menu")
Asd.current = true
Menu.current = false
repeat
print(string.rep("\n",2))
Menu:print(0)
x=io.read()
if x == "z" then
x = Menu:getCurrentMenu()
print(Menu:getCurrentMenu().label)
print(Menu:getCurrentMenu():getNextMenu().label)
y = Menu:getCurrentMenu():getNextMenu()
x.current = false
y.current = true
elseif x == "a" then
x = Menu:getCurrentMenu()
y = Menu:getCurrentMenu():getPrevMenu()
x.current = false
y.current = true
end
until x == "sad"
"
there's the code, and when ever i try to move my current from "Asd menu" downwards, it'll error:
menu.lua:150: attempt to index a nil value
which doesn't make any sense, it's clearly declared, and I've tried adding prints and they always give me Asd menu O.o
Same goes for if I'll try to move from Woot to Asd menu, same exact error, and I have no idea why, since I added those prints
print(Menu:getCurrentMenu().label)
print(Menu:getCurrentMenu():getNextMenu().label)
and they do give me Asd menu, but then it says that trying to index a nil value at the second print line, but it sill does print? I'm out of ideas, any help out here?
You are missing a return statement in line 92.
Note that this line does not actually return anything, so the function is returning nil.
After changing it to return self.parent:getNextMenu(true) it seems to be working.

Resources