# Script of card "chess" of stack "array_exercises"
global gBoard_currentState
# completely clear off the board
on clearBoard
# create an empty array
repeat for each character tColumn in "abcdefgh"
repeat with tRow = 1 to 8
put empty into board_array[tColumn][tRow]
end repeat
end repeat
# set current state to empty array
put board_array into gBoard_currentState
updateBoard
end clearBoard
# set up the board to the beginning state
on resetGame
put empty into board_beginState
put "RNBQKBNR" into tPieceOrder
put "abcdefgh" into tColumns
repeat with x = 1 to 8
put char x of tColumns into tCol
# place first row pieces
put char x of tPieceOrder & "_white" into tPieceName
put tPieceName into board_beginState[tCol][1]
put char x of tPieceOrder & "_black" into tPieceName
put tPieceName into board_beginState[tCol][8]
# place pawns
put "P_white" into board_beginState[tCol][2]
put "P_black" into board_beginState[tCol][7]
end repeat
# save the beginning state in the global current state variable
put board_beginState into gBoard_currentState
updateBoard
end resetGame
# given square references in the form B2, D5, etc.,
# update the current board state array
on makeMove pOriginSquare, pDestSquare
# determine what piece is in the start square
# if none, abort
put gBoard_currentState[char 1 of pOriginSquare][char 2 of pOriginSquare] into tOriginPiece
if tOriginPiece is empty then
beep
updateBoard
exit makeMove
end if
# determine color of origin piece
# determine what's in destination square
# if a piece of the same color, abort
# if dest square is empty, move piece there
# if dest square has enemy color there, remove attacked piece from board
# update destination square with moved piece
# delete piece from starting square
put gBoard_currentState[char 1 of pDestSquare][char 2 of pDestSquare] into tDestPiece
set the itemDelimiter to "_"
if item -1 of tOriginPiece = item -1 of tDestPiece then
beep
updateBoard
exit makeMove
else
put tOriginPiece into gBoard_currentState[char 1 of pDestSquare][char 2 of pDestSquare]
put empty into gBoard_currentState[char 1 of pOriginSquare][char 2 of pOriginSquare]
end if
updateBoard
end makeMove
# this handler updates the visual state of the board using the contents of the array
on updateBoard
lock screen
repeat for each character tColumn in "abcdefgh"
repeat with tRow = 1 to 8
put tColumn & tRow into tBtnName
if there is an image gBoard_currentState[tColumn][tRow] then
set the icon of btn tBtnName to the id of img gBoard_currentState[tColumn][tRow]
else
set the icon of btn tBtnName to 0
end if
end repeat
end repeat
unlock screen
end updateBoard