This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
legokingmi's profile picture

Draw to the Screen Until User Presses key?

Started by legokingmi, 29 August 2014 - 02:09 PM
legokingmi #1
Posted 29 August 2014 - 04:09 PM
Hello, I am making a screen saver type program and I want the program to place pixels randomly all over the computer screen while waiting for a keypress.

I am having trouble at the part where it repeats until the key is pressed. It will draw one pixel, then wait for a key without drawing other pixels.



shell.run("pastebin","get","sZTVBCue","VEIos") --Get the background image program.

clear=0
iAmAway = paintutils.loadImage("VEIos")
paintutils.drawImage(iAmAway,1,1)

repeat
   x = math.random(1,51)
   y = math.random(1,19)
   paintutils.drawPixel(x,y,8) -- Draw the random pixel in light blue.
   clear=1+1
   sleep(0.5)

   if clear == 60 then -- Clear screen every 60 runs.
	  paintutils.drawImage(iAmAway,1,1)
	  clear = 0
   end

until os.pullEvent("key") -- SUPPOSED to repeat until the user presses a key but only does one round then just waits.

sleep(1)

term.setBackgroundColor(32768)
term.clear()
term.setCursorPos(1,1)


Thanks much! :)/>

-Lego
Bomb Bloke #2
Posted 29 August 2014 - 04:20 PM
Timers are the key here. We use them to replace the use of "sleep", then set up an event listening loop that waits for timer or keypress events.

Something along these lines:

local myEvent
local myTimer = os.startTimer(0)

while true do
   myEvent = {os.pullEvent()}  -- Grab any event, stick the details in a table.

   -- Now, depending on the type of event that occurred:
   if myEvent[1] == "timer" and myEvent[2] == myTimer then
	  x = math.random(1,51)
	  y = math.random(1,19)
	  paintutils.drawPixel(x,y,8) -- Draw the random pixel in light blue.
	  clear=clear+1
	  
	  if clear == 60 then -- Clear screen every 60 runs.
			 paintutils.drawImage(iAmAway,1,1)
			 clear = 0
	  end
	  
	  myTimer = os.startTimer(1)
   elseif myEvent[1] == "key" then
	  break
   end
end
Edited on 29 August 2014 - 02:21 PM
legokingmi #3
Posted 29 August 2014 - 04:35 PM
Thank you very much :)/>

-Lego