Hamlet says early in the play that, in order to remain in Elsinore while he plans his revenge against Claudius, he may pretend to be crazy. People who might otherwise be suspcious of his motives will merely assume that the grief over his father's death is the cause of his erratic behavior.