You could add a field that holds the height. When a counter is added to a square you do a check to count how many others are already on it and then add 1 and store it as the height. Then when you click on a square the first one to be picked will be the one with the highest height (LIFO = last in first out).
Hope that helps.
Hope that helps.