Difficult with some code learning.

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
Strelok
Prole
Posts: 18
Joined: Thu Sep 08, 2011 6:44 pm
Location: Brazil - Amazonas

Difficult with some code learning.

Post by Strelok »

Hello, guys,

So I was studying today, rearranging some code that I learned yesterday and I got stuck in this part.

Code: Select all

function love.load()
	Tileset = love.graphics.newImage('sprite0003.png')

	tileW, tileH = 16, 16
	tilesetW, tilesetH = Tileset:getWidth(), Tileset:getHeight()

	
end
-- Aqui o tileset é dividido.
quadInfo = {
	{' ', 0, 0	 },	-- = chão
	{'0', 16, 0	 },	-- = alçapão fechado
	{',', 32, 0	 },	-- = borda superior-esquerda
	{'-', 48, 0	 },	-- = borda superior
	{'*', 64, 0	 },	-- = borda superior-direita
	{'#', 0, 16  },	-- = chão gradeado
	{'X', 0, 32	 },	-- = caixa
	{'C', 0, 48  }, -- = caixa superior-parede
	{'c', 0, 64	 },	-- = caixa inferior-chão
	{'O', 16, 16 },	-- = alçapão aberto
	{'<', 16, 32 }, -- = mesa esquerda
	{'B', 16, 48 },	-- = caixa2 superior-parede
	{'b', 16, 64 },	-- = caixa2 inferior-chão
	{'e', 32, 16 },	-- = borda esquerda
	{'>', 32, 32 }, -- = mesa direita
	{'T', 32, 48 },	-- = caixa3 superior
	{'t', 32, 64 }, -- = caixa3 inferior-chão
	{'p', 48, 16 }, -- = borda inferior esquerda
	{'P', 48, 32 }, -- = borda inferior
	{'D', 48, 48 }, -- = porta aberta superior
	{'d', 48, 64 },	-- = porta aberta inferior
	{'r', 64, 16 },	-- = borda direita
	{'R', 64, 32 }, -- = borda inferior direita
	{'u', 64, 48 },	-- = parede superior
	{'U', 64, 64 }  -- = parede inferior
}

Quads = {}
for _, info in ipairs(quadInfo) do
	Quads[info[1]] = love.graphics.newQuad(info[2], info[3], tileW, tileH, tilesetW, tilesetH) -- POINTS ERROR HERE (LINE 40)
end
-- ///////////////////////////////////Mapa vai aqui///////////////////////////////////////


-- Mapa para testes.

TileTable = {} -- inicializa a variavel TileTable com uma string vazia.

local tileString = [[
X#######################X
X                    0  X
X  0                    X
X              0        X
X                       X
X    XX  XX   XXX X X   X
X   X  X X  X X   X X   X
X   X  X X  X X   X X   X
X   X  X XXX  XXX X X   X
X   X  X X  X X    X  0 X
X 0 X  X X  X X    X    X
X   X  X X  X X  X X    X
X    XX  XXX  XXX  X    X
X                       X
X   <><><><><><><><>    X
X                       X
X  0                  0 X
X#######################X
]]
	
local width = #(tileString:match("[^\n]+")) -- calcula o número de caracteres na primeira linha com o operador # e o atribui à variavel local width.
-- após essa linha nós sabemos o quão grande nosso mapa é.

for x = 1, width, 1 do TileTable[x] = {} end -- esta linha está iniciando TileTable com um número de tabelas vazias que depende do variável width.
-- por exemplo, se width = 3, então TileTable teria 3x { {}, {}, {}}
-- O objetivo aqui é criar a coluna primeiro, então temos que ter certeza que TileTable está sendo primeiro indexado por x e depois y.

local rowIndex, columnIndex = 1, 1 -- inicializa duas variáveis: rowIndex e columnIndex e atribui-lhes o valor 1.

for row in tileString:gmatch("[^\n]") do -- inicia um loop genérico que usa string.gmatch como função iteradora (VER TUTORIAL DE LOOPS)
-- em cada iteração string:gmatch(padrão) retorna duas substrings correspondidas pelo padrão. O padrão que estamos usando aqui é ("[^\n]"), o mesmo de antes.
-- ela retorna todos os caracteres entre dois caracteres de nova linha. O efeito visual é que em cada iteração a variável row contem uma linah de tileString, começando da primeira linha.
	assert(#row == width, 'Map is not aligned: width of row ' .. tostring(rowIndex) .. ' should be ' .. tostring(width) .. ', but it is ' .. tostring(row))
	-- essas linha acima checa se o mapa está propriamente "alinhado", se todas as fileiras possuem a mesma largura da primeira. Se este não for o caso o jogo irá mostrar um erro.
	columnIndex = 1 -- resetando a variável columnIndex para 1.
	for character in row:gmatch(".") do -- dessa vez iterando sobre os valores de row o padrão "."(significa qualquer caractere). Dentro do corpo desse segundo loop nós teremos
	-- iterativamente todos os caracteres que row possui, em ordem.
		TileTable[columnIndex][RowIndex] = character -- uma vez que nós temos um caractere(na variável character) e as coordenadas x e y, nós podemos colocálos em TileTable. 
		columnIndex = columnIndex + 1 -- nós também precisamos aumentar manualmente o valor de x(string:match não possui uma variável "contador" para fazer isso mais automaticamente).
	end -- fecha o loop que está analizando as células em uma linha
	rowIndex=rowIndex + 1 -- aumenta manualmente o valor de y, assim como foi feito com x.
end -- fecha o loop externo, o que esta analizando as linhas do mapa.

function love.draw()

	for columnIndex, column in ipairs(TileTable) do
		for rowIndex, char in ipairs(column) do
			local x, y = (clomunIndex-1)*tileW, (rowIndex-1)*tileH
			love.graphics.draw(Tileset, Quads[char], x, y)
		end
	end

end




-- ///////////////////////////////////Mapa termina aqui///////////////////////////////////////
Don't mind the comments, I was using them for studying. The error is in the line 40 of code.

Here is a screenshot of it:
http://prntscr.com/2rysql

I am using this tutorial to learn, it is a bit outdated, but I managed to work on the outdated code(mostly):
https://github.com/kikito/love-tile-tut ... 1d-strings
User avatar
Inny
Party member
Posts: 652
Joined: Fri Jan 30, 2009 3:41 am
Location: New York

Re: Difficult with some code learning.

Post by Inny »

The love.load function runs after the global chunk runs. tileW is nil until then. Move the code that creates the quads into your love.load function.
User avatar
Strelok
Prole
Posts: 18
Joined: Thu Sep 08, 2011 6:44 pm
Location: Brazil - Amazonas

Re: Difficult with some code learning.

Post by Strelok »

Wow, that was fast! Thank you, mr. Inny. I should have paid more attention. There were more errors in the code, but I managed to repair them.

Here is the result of the code. I am happy with it. I can understand the code fairly well.
http://prntscr.com/2ryyyw

I am a bit unconfortable with using chars for declaring the tiles, because the more tiles I have in my tileset the more complicated it will be to draw the entine map... I will try to learn more and improve the code.

Also, is there any "hero/object moving-per-pixel tutorial" out there?

Ps.: Your avatar reminds me of Sifl and Olly.
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 4 guests