local function spawnPiece( xPos, yPos, pieceType ) if pieceType ~= "red" and pieceType ~= "white" then print( "Invalid piece type", pieceType ) return nil end if xPos \< 1 or xPos \> GRID\_WIDTH or yPos \< 1 or yPos \> GRID\_HEIGHT then print( "Position out of range:", xPos, yPos ) return nil end local piece = display.newImageRect( mainGroup, "token\_" .. pieceType .. ".png", CELL\_WIDTH-5, CELL\_HEIGHT-5 ) -- record the piece's logical position on the board piece.xPos = xPos piece.yPos = yPos -- Position the piece piece.x = (xPos - 1) \* CELL\_WIDTH + (CELL\_WIDTH \* 0.5) + gbOffsetX piece.y = (yPos - 1) \* CELL\_HEIGHT + (CELL\_HEIGHT \* 0.5) + gbOffsetY return piece end -- local function startPieces() local countr = 1 for i = 1, 8 do local xPos = countr local yPos = 1 local color = "red" pieceName = "r"..countr grid[yPos][xPos] = spawnPiece(xPos, yPos, color, checkerBoard) print( pieceName ) countr = countr + 1 if i == 1 then redPiece1 = grid[yPos][xPos] print("redPiece1") print(redPiece1) end end local countw = 1 for i = 1, 8 do local xPos = countw local yPos = 8 local color = "white" pieceName = "w"..countw print( pieceName ) grid[yPos][xPos] = spawnPiece(xPos, yPos, color, checkerBoard) countw = countw + 1 end return true end local function movePiece(piece, xPos, yPos ) -- check to see if the position is occupied. You can do either: -- 1. "Capture the piece". This would involve removing the piece that is there before moving to the spot or -- 2. "Reject the move" because the spot is occupied. For the purpose of this tutorial we will reject the move. -- if xPos \< 1 or xPos \> GRID\_WIDTH or yPos \< 1 or yPos \> GRID\_HEIGHT then return false end if grid[yPos][xPos] == nil then -- got an empty spot, move into it -- get the screen x, y for where we are moving to local x = (xPos - 1) \* CELL\_WIDTH + (CELL\_WIDTH \* 0.5) + gbOffsetX local y = (yPos - 1) \* CELL\_HEIGHT + (CELL\_HEIGHT \* 0.5) + gbOffsetY -- save the old grid x, y local oldXPos = piece.xPos local oldYPos = piece.yPos -- Move the object in the table grid[yPos][xPos] = piece grid[yPos][xPos].xPos = xPos grid[yPos][xPos].yPos = yPos grid[oldYPos][oldXPos] = nil -- Now move the physical graphic transition.to(grid[yPos][xPos], { time = 500, x = x, y = y}) return true end end
Trying again to submit my code. Here’s the functions part of my code (Above).
Here’s the ways I’ve tried to call the piece to move, in the ‘did’ phase of ‘show event’. None of them have worked.
Runtime:addEventListener( “touch”, movePiece )
r1:addEventListener( “touch”, movePiece )
piece:addEventListener( “tap”, movePiece )
pieceName:addEventListener( “touch”, movePiece )
pieceName.addEventListener(“touch”,movePiece(pieceName,2,2))
Is anyone able to shed some light on my problem? How do I tell a piece that I don’t know the name of, that I want it to move when I click it? Even if I know it’s called r1 I still don’t know how to tell it to move.
Thanks,
Rodayan