Python and Turtle python Asteroids Tutorial- Asteroids

Asteroids Tutorial- Asteroids

Creating the Asteroids

The asteroids in this game are 12-sided polygons (dodecagons). The asteroid class should have five parameters (its size, x location, y location, speed, and tilt). The latter two parameters are default parameters. You will need to initialize the variables for each instance. After that, add 12 side lengths to a list that makes the dodecagon. 

A screenshot of a cell phone

Description automatically generated

Drawing the Asteroids

The asteroids are tilted in different directions. Also, you cannot just randomly connect consecutive points; this could lead to lines crossing and thus your shape is no longer a dodecagon. Start at the initial x and y position of the asteroid and increment that by the first side length multiplied by the tilt variable. Since a dodecagon has 12 points, there are 12 rays from the center of the dodecagon to each point; these 12 rays divide a circle of 360 degrees; thus, before you draw the line to the next point, you must increment the angle by 30 degrees (π/6). Take the next side length, multiply it by the cosine of the angle to get the x component of the vector and similarly multiply it by the sine of the angle to get the y component of the vector. Increment the x and y locations and add the values to the list of points.

A screenshot of a cell phone

Description automatically generated

Movement Off Screen

When the asteroids inevitably go beyond the screen, you want the asteroid to wrap around from the opposite side that it came from. Similar to the approach taken by the spaceship, simply draw five copies of the asteroid, four of them invisible (off-screen) and one in the middle. Whenever one goes off the screen, adjust which asteroid is in the middle.

A picture containing text

Description automatically generated

Animation

The animation process is simple. Move the asteroid a bit, draw the new asteroid, then update the screen.

A close up of a black background

Description automatically generated

Independent Runs

When this file is run independent of the main game file, just animate a singular asteroid moving around in space, wrapping around the edges.

A black sign with white text

Description automatically generated

View this link for the full code: https://github.com/HaimingXu679/Asteroids/blob/master/asteroid.py

View this link for the full repository: https://github.com/HaimingXu679/Asteroids

Related Post