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

Creating a loop to make a pattern background

Started by Crazypkr, 30 August 2014 - 02:54 AM
Crazypkr #1
Posted 30 August 2014 - 04:54 AM
Heres my problem, I want to make a list that sets the background to red and then blue everytime I ask.

for example, I want the following

BoxList = (xmin,xmax,ymin,ymax,color1,color2,rows)

color1 = red
color2 = blue

then I want it to print out like this

red——-
blue——
red———


ect. ect.

current code pastebin.com/mWfb6Tjg

Please help, I tried doing it but I can't get it right :(/>
Edited on 30 August 2014 - 02:56 AM
Bomb Bloke #2
Posted 30 August 2014 - 06:46 AM
You've got a bit of a misunderstanding in regards to "for" loops there: There's no need to manually increment the counter variables, for starters.

Here's another version of your function which should be a bit closer to what you intended:

Spoiler
mon = peripheral.wrap("top")
mon.setBackgroundColor(colors.black)
mon.clear()

function BoxL (xmin,xmax,ymin,ymax,color1,color2)
  local currColor = color1
  for i = xmin,xmax do
    for j = ymin,ymax do
      if currColor == color1 then
        currColor = color2
        mon.setBackgroundColor(currColor)
      else
        currColor = color1
        mon.setBackgroundColor(currColor)
      end

      mon.setCursorPos(i,j)
      mon.write(" ")
    end
  end
  mon.setBackgroundColor(colors.black)
end

BoxL(1,20,1,2,colors.red,colors.blue)

Using string.rep() you can cut that down a little:

Spoiler
mon = peripheral.wrap("top")
mon.setBackgroundColor(colors.black)
mon.clear()

function BoxL (xmin,xmax,ymin,ymax,color1,color2)
  local currColor = color1
  for j = ymin,ymax do
    if currColor == color1 then
      currColor = color2
      mon.setBackgroundColor(currColor)
    else
      currColor = color1
      mon.setBackgroundColor(currColor)
    end

    mon.setCursorPos(xmin,j)
    mon.write(string.rep(" ",xmax-xmin+1))
  end
  mon.setBackgroundColor(colors.black)
end

BoxL(1,20,1,2,colors.red,colors.blue)
KingofGamesYami #3
Posted 30 August 2014 - 06:49 AM
If I am reading this correctly, the closest I can get to what you want is this:

local bColors = {
	b = colors.blue,
	r = colors.red,
}
local function doPattern( pattern, minx, miny, maxx, maxy )
	local xinc = #( pattern:match( "[^\r\n]+" ) )
	local _, yinc = pattern:gsub( "[\r\n]", "\n" )
	yinc = yinc + 1
	for x = minx, maxx, xinc do
		for y = miny, maxy, yinc do
			local l = y
			for line in pattern:gmatch( "[^\r\n]+" ) do
				for i = 1, #line do
					term.setCursorPos( i + x - 1, l )
					term.setBackgroundColor( bColors[ line:sub( i, i ) ] )
					term.write( " " )
				end
				l = l + 1
			end
		end
	end
end

local pattern = "br\nrb"
doPattern( pattern, 1, 1, term.getSize() )

Edit: Updated code (it'll work with [almost] any pattern you throw at it )
Edited on 30 August 2014 - 05:00 AM