Try to create a hitbox around the player box. This can be accomplished if you use a png image that is one pixel thick. And you place four of these pictures as hitbox around the player. And when there is a collision detected between the hitbox and the barrier, you can make the character stop moving. For example, if there is a collision of barrier with upper hitboxline and the player is still pressing the up key, it shouldn't do y-=speed. Hope that was helpful.