They’re intentionally put in by the developers, often for testing purposes. Sometimes, they leave them in, and players find out in some way. As for how cheat codes do what they do, they just send commands to the game to change particular variables (like the time of day, the player’s money, etc) or spawn objects into the world.
Latest Answers