Space Invaders Mini Project in Python(Turtle) with Source Code

Introduction

The Logo programming language is frequently linked to turtle graphics. In the late 1960s, Seymour Papert added turtle graphics support to Logo to support his version of the turtle robot, which is a simple robot controlled from the user’s workstation and designed to carry out the drawing functions assigned to it using a small retractable pen set into or attached to the robot’s body.

The standard library of the Python programming language now contains a Turtle graphics module. Turtle in Python, like its Logo ancestor, allows programmers to manipulate one or more turtles in a two-dimensional space.

Overview of the syntax

A location, an orientation (or direction), and a pen are the three qualities of the turtle. Color, width, and on/off state are all properties of the pen (also called down and up).

“Move ahead 10 spaces” and “turn left 90 degrees” are orders that the turtle responds to based on its current location. The turtle’s pen can also be managed by enabling it, changing its color, and adjusting its breadth. By visualizing what they would do if they were the turtle, a pupil may comprehend (and forecast and reason about) the turtle’s motion. This is referred to as “body syntonic” reasoning by Seymour Papert.

Basic syntax:

import turtle // start of the program
     //body
    //of the main
   //code
turtle.done() //end of the program

Inorder to understand the codes to draw various shapes given below, Getting Started with Powerful yet Easy Python Graphics Module, Turtle.

Methods

Python is an object-oriented programming language, as we all know. This implies it can simulate the real world using classes and objects. A Python method is a label that can be applied to an object and is a piece of code that may be run on that object. But before we go any further, let’s have a look at some classes and objects.

A Python method is a label that can be applied to an object and is a piece of code that may be run on that object.

The most frequently, used turtle methods are:

MethodParameterDescription
Turtle()NoneCreates and returns a new turtle object
forward()amountMoves the turtle forward by the specified amount
backward()amountMoves the turtle backward by the specified amount
right()angleTurns the turtle clockwise
left()angleTurns the turtle counterclockwise
penup()NonePicks up the turtle’s Pen
pendown()NonePuts down the turtle’s Pen
up()NonePicks up the turtle’s Pen
down()NonePuts down the turtle’s Pen
color()Color nameChanges the color of the turtle’s pen
fillcolor()Color nameChanges the color of the turtle will use to fill a polygon
heading()NoneReturns the current heading
position()NoneReturns the current position
goto()x, yMove the turtle to position x,y
begin_fill()NoneRemember the starting point for a filled polygon
end_fill()NoneClose the polygon and fill with the current fill color
dot()NoneLeave the dot at the current position
stamp()NoneLeaves an impression of a turtle shape at the current location
shape()shapenameShould be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Downloads

Download the .gif files given below:

Download this gif from here. Rename it as background.gif. Now lets get coding!!

Space Invaders Game

The best way to learn is to do. Hence, what better way to learn python programming language (if you know the basics) than to code your first mini project. For this blog we are going to build a space invaders game mini project using python programming language.

# importing turtle, math and random python modules
import turtle
import math
import random

# Set up the game window screen
window = turtle.Screen()
window.bgcolor("green")
window.title("Space Invaders game made by ABK for Follow tuts")
window.bgpic("background.gif")

# Register the shape
turtle.register_shape("invader.gif")
turtle.register_shape("player.gif")

# Draw border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
    border_pen.fd(600)
    border_pen.lt(90)
border_pen.hideturtle()

# Set the score to 0
score = 0

# Draw the pen
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 280)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align="left", font=("Arial", 14, "normal"))
score_pen.hideturtle()

# Create the player turtle
player = turtle.Turtle()
#player.color("blue")
player.shape("player.gif")
player.penup()
player.speed(0)
player.setposition(0,-250)
player.setheading(90)

playerspeed = 15

# Choose a number of enemies
number_of_enemies = 10
# Creat an empty list of enemies
enemies = []

# Add enemies to the list
for i in range(number_of_enemies):
    # create the enemy
    enemies.append(turtle.Turtle())

for enemy in enemies:
    #enemy.color("Red")
    enemy.shape("invader.gif")
    enemy.penup()
    enemy.speed(0)
    x = random.randint(-200, 200)
    y =  random.randint(100, 250)
    enemy.setposition(x, y)

enemyspeed = 5

# Creat the player's bullet
bullet = turtle.Turtle()
bullet.color("yellow")
bullet.shape("triangle")
bullet.penup()
bullet.speed(0)
bullet.setheading(90)
bullet.shapesize(0.5,0.5)
bullet.hideturtle()

bulletspeed = 30

# define bullet state
# ready - ready to fire
# fire - bullet is firing
bulletstate = "ready"


# Move the player left and right
def move_left():
    x = player.xcor()
    x -= playerspeed
    if x < -280:
        x = -280
    player.setx(x)

def move_right():
    x = player.xcor()
    x += playerspeed
    if x > 280:
        x = 280
    player.setx(x)

def fire_bullet():
    # Declare bulletstate as a global if it needs changed
    global bulletstate
    if bulletstate == "ready":
        bulletstate = "fire"
        # Move the bullet to the just above the player
        x = player.xcor()
        y = player.ycor() + 10
        bullet.setposition(x,y)
        bullet.showturtle()

# For collision between enemy and bullet
def isCollision_enemy_bullet(t1, t2):
    distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
    if distance < 25:
        return True
    else:
        return False

# For collision between enemy and player
def isCollision_enemy_player(t1, t2):
    distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
    if distance < 30:
        return True
    else:
        return False

# Create keyboard bindings
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(fire_bullet, "space")

# Main game loop
Game_Over = False
missed_enemies = 0
while True:

    for enemy in enemies:
        # Move the enemy
        x = enemy.xcor()
        x += enemyspeed
        enemy.setx(x)


        # Move the enemy back and down
        if enemy.xcor() > 270:
            # Move all enemies down
            for e in enemies:
                y = e.ycor()
                y -= 40
                e.sety(y)
                if e.ycor() < -285 and Game_Over == False:
                    e.hideturtle()
                    missed_enemies += 1
                    if missed_enemies == 5:
                        Game_Over = True
                    x = random.randint(-200, 200)
                    y = random.randint(100, 250)
                    e.setposition(x, y)
                    e.showturtle()
            # Change enemy direction
            enemyspeed *= -1

        if enemy.xcor() < -270:
            # Move all enemies down
            for e in enemies:
                y = e.ycor()
                y -= 40
                e.sety(y)
                if e.ycor() < -285 and Game_Over == False:
                    e.hideturtle()
                    missed_enemies += 1
                    if missed_enemies ==5:
                        Game_Over = True
                    x = random.randint(-200, 200)
                    y = random.randint(100, 250)
                    e.setposition(x, y)
                    e.showturtle()
            # Change enemy direction
            enemyspeed *= -1

        # check for a collision between the bullet and the enemy
        if isCollision_enemy_bullet(bullet, enemy):
            # Reset the bullet
            bullet.hideturtle()
            bulletstate = "ready"
            bullet.setposition(0, -400)
            # Reset the enemy
            x = random.randint(-200, 200)
            y = random.randint(100, 250)
            enemy.setposition(x, y)
            enemyspeed += 0.5
            # update the score
            score += 10
            scorestring = "Score: %s" %score
            score_pen.clear()
            score_pen.write(scorestring, False, align="left", font=("Arial", 14, "normal"))
        # check for a collision between the player and enemy
        if isCollision_enemy_player(player, enemy):
            Game_Over = True
        if Game_Over == True:
            player.hideturtle()
            bullet.hideturtle()
            for e in enemies:
                e.hideturtle()
            window.bgpic("end.gif")
            break

    # Move the bullet
    if bulletstate == "fire":
        y = bullet.ycor()
        y += bulletspeed
        bullet.sety(y)

    # Check to see if the bullet has gone to the top
    if bullet.ycor() > 275:
        bullet.hideturtle()
        bulletstate = "ready"

turtle.done()

Output

The below is the output screenshot for the above code:

SHARE Space Invaders Mini Project in Python(Turtle) with Source Code

You may also like...

Leave a Reply

Your email address will not be published.

Share