Robert after looking trough your code I belive I found solution for your bug.

To get rid of your bug you need to manualy set the height of your figure after detecting colision with the celing so that the figure would be just below the celing. This would prevent colision with your figure and wall in the nex pas as it's happeneing now becouse the figure's head literaly gets into the celing. It seems that the same bug happens when detecting colision with ground.

Also for specifying direction of movment don't use strings like 'up'. Why? String comparison is quite slow. While now it doesn't affect much the overal speed of your game but if you intend to have some enemies in future wich would also obey the same physics that your character does it will be quite noticable.
So instead of using strings for specifying direction off movments use colection off available directions like:
Code:
type
TDirection = (dirUp, dirDown, dirLeft, dirRight)