Yes, you are correct that planets, moons, and stars generally have a spherical shape. This is primarily a result of the force of gravity acting on their mass over long periods of time. The process by which celestial bodies become spherical is called "hydrostatic equilibrium."
When a celestial body forms, such as a planet or moon, it begins as a collection of gas, dust, and other materials. These materials come together due to gravitational attraction, forming a protoplanetary disk. Over time, the particles in the disk collide and stick together, forming larger bodies called planetesimals. Through further accretion and collisions, these planetesimals grow into protoplanets or moons.
As a protoplanet or moon gains mass, its gravitational pull becomes stronger. The force of gravity pulls material inward and causes it to compress. With sufficient mass, the body's own gravity overcomes the structural strength of the material, causing it to collapse under its own weight and assume a spherical shape.
This process is also observed in stars. Stars form from massive clouds of gas and dust called nebulae. As the cloud collapses under gravity, it forms a protostar. As the protostar continues to contract, it heats up and eventually reaches a point where nuclear fusion ignites in its core, becoming a star. The star's gravity and the outward pressure from nuclear fusion push against each other, resulting in a state of hydrostatic equilibrium, where the star maintains a roughly spherical shape.
It's important to note that not all celestial bodies are perfectly spherical. Factors such as rotation, tidal forces, and impacts can cause deviations from a perfect sphere. Additionally, smaller bodies like asteroids or irregularly shaped moons may not have enough mass to achieve a fully spherical shape. Nonetheless, the force of gravity is a significant contributor to the spherical shape observed in celestial bodies.