2014-11-01 3 views
3

친구이자 LOW 프레임 워크를 사용하여 루아에서 광산 스위퍼 프로그램을 작성하려고합니다. 지금까지 코드는 상자 (셀)가 선택되어 있는지 확인한 다음 그려야합니다. 우리는 루아를 처음 접했고, 프로그램은 이제 오른쪽 하단 상자에서만 작동한다는 결점이 있습니다.루아에서 테이블을 사용하여 테이블을 초기화하는 방법은 무엇입니까?

업데이트 : 초기화 된 GameBoard의 값은 모두 동일한 값 (즉, GameBoard[1]까지 GameBoard[150]까지 모두 동일한 셀임)이 표시됩니다.

conf.lua 정의 일부 글로벌 변수가 :

여기 코드의 다음 main.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 

(그것은 GameBoardCell들로 가득 부하 방법에 잘못.

-- 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 

결과적으로 모든 상자의 값은 lo wer 상자에 인덱스 150 (NUM_ROWS * NUM_COLS = 150부터 최신). 테이블 (Gameboard)의 모든 요소 (Cells)는 Cell:new 메서드에서 설정된 x 및 y 값과 같습니다.

누군가가 테이블을 올바르게 초기화하고 액세스하는 방법을 알려 주시면 감사하겠습니다.

+0

style : cell [ "checked"]'대신에'cell.checked'에 대한 설명입니다. – lhf

+0

@inf 조언을 해주셔서 감사합니다. 이것은 언어의 첫날이었습니다. 코드가 오른쪽 하단에서만 작동하는 이유를 알고 있습니까? 변수 범위를 가지고 뭔가를 가질 수 있습니까? –

답변

3

Cell:new의 경우 self은 테이블 Cell이므로 매번 같은 테이블을 반환합니다. 자세한 내용은

function Cell:new(i, j) 
    local o = {} 
    setmetatable(o, self) 
    self.__index = self 

    self.x_min = (i-1) * CELL_SIZE 
    --omits rest 

    return o; 
end 

읽기 PiL: Object-Oriented Programming : 당신이 프로토 타입을 구현하는 또 다른 방법에 관심이있을 수

function Cell:new(i, j) 
    local t = {} 

    t.x_min = (i-1) * CELL_SIZE 
    --omit the rest 

    return t; 
end 

향후 개선을 위해 :

간단한 수정하는 대신 새 테이블을 만드는 것입니다 .

+0

감사합니다. 이제 보드가 작동합니다. :-) –

관련 문제