我和一位朋友正在尝试使用Löve框架用Lua语言编写扫雷游戏程序。目前,代码需要查看一个方格(一个单元格)是否被选中然后进行绘制。我们对Lua不是很熟悉,现在程序存在的问题是它只能在右下角的方格上工作。
更新:现在我看到初始化的GameBoard所有值都相同(即GameBoard[1]到GameBoard[150]都是相同的单元格)。
以下是代码:
conf.lua定义了一些全局变量:
这里是
结果是所有的方框都具有索引为150的较低方框的值(最新的,因为 NUM_ROWS * NUM_COLS = 150)。表格(Gameboard)的所有元素(Cells)都具有在Cell:new方法中设置的相同的x和y值。
如果有人能告诉我们如何正确地初始化和访问一个表格,那将不胜感激。
更新:现在我看到初始化的GameBoard所有值都相同(即GameBoard[1]到GameBoard[150]都是相同的单元格)。
以下是代码:
conf.lua定义了一些全局变量:
function love.conf(t)
-- Global variables.
CELL_SIZE = 40
NUM_ROWS = 15
NUM_COLS = 10
STATS_HEIGHT = 100
AMOUNT_OF_CELLS = NUM_ROWS * NUM_COLS
GRID_WIDTH = 400
GRID_HEIGHT = 700
end
这里是
main.lua
中相关失败的代码(在加载方法中填充 GameBoard
与 Cell
时出错)。-- The Cell table is used for every individual square on
-- the gameboard
Cell = {}
-- The Gameboard (150 Cell objects)
GameBoard = {}
-- The function new belongs to Cell and spawns a new object (a table)
-- with the same attributes as Cell.
function Cell:new(i, j)
-- each cell knows:
-- its x- and y-coordinates.
self.x_min = (i-1) * CELL_SIZE
self.x_max = (CELL_SIZE-1) + (i-1) * CELL_SIZE
self.y_min = STATS_HEIGHT + (j-1) * CELL_SIZE
self.y_max = STATS_HEIGHT + (CELL_SIZE-1) + (j-1) * CELL_SIZE
-- if it is a mine (determined with random number generator)
isMine = (math.random(1, 8) % 8 == 0) -- Roughly 0.15 (1/7) times true (is a mine)
self.isMine = isMine
-- do not check the mine initially
self.checked = false
-- return the cell object
return self;
end
-- love.load is a love-function that is called once when the game
-- starts.
function love.load()
-- The index of the cell on the GameBoard (ranging from 1 to 150)
local index = 1
-- Build a two dimensional table of Cell-objects
for i = 1, NUM_COLS, 1 do
for j = 1, NUM_ROWS, 1 do
GameBoard[ index ] = Cell:new( i, j )
index = index + 1
end
end
end
结果是所有的方框都具有索引为150的较低方框的值(最新的,因为 NUM_ROWS * NUM_COLS = 150)。表格(Gameboard)的所有元素(Cells)都具有在Cell:new方法中设置的相同的x和y值。
如果有人能告诉我们如何正确地初始化和访问一个表格,那将不胜感激。
cell.checked
而不是cell["checked"]
等等。 - lhf