Python and Turtle python Asteroids Tutorial- Spaceship

Asteroids Tutorial- Spaceship

This game is written with an object-oriented approach. The spaceship, bullets, asteroids, and explosions are all classes.

Creating the Spaceship

The spaceship requires some variables: the initial x location, the initial y location, and the initial direction. The spaceship also needs to be able to move, so you will need a x-speed and a y-speed. As we know, in order to change velocity, you will need acceleration, so also include a thrust variable; however, we don’t want to spaceship to accelerate forever. Finally, players typically have several lives in video games, so include a lives variable as well. There is a self.alive variable, but don’t worry about that until later, self.lines is for future collision detection, and self.tipx and self.tipy are variables to assist in drawing the ship. 

Drawing the Spaceship

As you can see, the function was called draw_one. That is because we want the spaceship to wrap around the screen if it flies off. A simple way to implement this is by drawing five spaceships, but only one of them is visible at a time. When that one spaceship touches a border, one of its clones will be visible on the opposite edge. Note that if your game window changes, the numbers below must be changes as well. This will take some trial and error.

A screenshot of a cell phone

Description automatically generated
A screen shot of a computer

Description automatically generated

Moving the Spaceship

Moving the spaceship is easy enough. We simply need to multiply the speed the spaceship is going in the x and the y direction by the time it has been moving and add those values to the original x and y locations. Since we limited the thrust, the thrust life variable must be updated as well.  We want to change direction, so when the left and right arrow keys are pressed, let’s update the direction instance variable. Finally, we need to implement the actual thrust mechanism. Whenever the thrust key is pressed, we want to give the thrust some life to begin with as well as the direction we are thrusting in. We will update the x speed and the y speed accordingly. If you wish to limit the max speed of the spaceship, don’t allow the thrust from exceeding that limit.

A close up of a logo

Description automatically generated
A close up of a sign

Description automatically generated
A black sign with white text

Description automatically generated

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

Related Post