Create SPACE INVADER 2D GAME with 168 lines of Pygame (Python 3.9) Code – Complete Code

Hi,

Creating games of your own and being able to modify the code as per your own desires can be quite a confidence booster. I realized it when I created this Space Invader 2D game using the Pygame module of Python. Apart from the lines of code that I have written below you will need to download few other necessary files. These files are images or audio files. For example, we use two spaceship images, one yellow and the other red, for showing the spaceships. The space.png file is used to show our background as of space. Download these files and put them in a folder titled ‘Assets’. Then put this folder in the same directory/folder where your python file is.

Also read:

Tic-Tac-Toe Game only in 95 lines of Python Code– Function Based

Tic-Tac-Toe Game in 77 lines – Class based

Pygame Python Code for the game SPACE INVADERS in 2D

There are two audio files too, one creates the sound of firing gun, and other creates the sound of being-hit whenever a ship is caught between the fire from the other ship. I want to thank Tech With Tim (YoutTube Channel) for the guidance. Please copy the code as it is given below, change it only if you know what you are doing. Please note that left and right Ctrl buttons are used as the firing buttons, hence make sure that your Keyboard has two such buttons, else you need to change the code accordingly.

Download these files, put them in a folder with name ‘Assets’ and then put the folder in the same directory/folder where you would create your python file.

Please keep these files in the same directory /folder where your python file will be created.

Code Starts here:

import pygame
import os
pygame.font.init()
pygame.mixer.init()

# initialize pygame

pygame.init()
WIDTH, HEIGHT = 800, 500
# Create the Screen
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("SPACE INVADERS __ SANISHA")
WHITE = (255, 255, 255)
BLACK = (200, 100, 20)
RED = (255, 0, 0)
YELLOW = (255, 200, 100)

BORDER = pygame.Rect(WIDTH//2-5, 0, 10, HEIGHT)

HEALTH_font = pygame.font.SysFont('Ariel', 20)
WINNER_font = pygame.font.SysFont('Ariel', 120)

BULLET_HIT_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'Grenade+1.mp3'))
BULLET_FIRE_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'Gun+Silencer.mp3'))

fps = 60
VEL = 2

BULLET_VEL = 7
MAX_BULLETS = 3
SPSHIP_WIDTH = 50
SPSHIP_HEIGHT = 38

YELLOW_HIT = pygame.USEREVENT + 1
RED_HIT = pygame.USEREVENT + 2

YELLOW_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_yellow.png'))
YELLOW_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPSHIP_WIDTH, SPSHIP_HEIGHT)), 90)
RED_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_red.png'))
RED_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(RED_SPACESHIP_IMAGE, (SPSHIP_WIDTH, SPSHIP_HEIGHT)), 270)

SPACE = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'space.png')), (WIDTH, HEIGHT))

def draw_window(red, yellow, red_bullets, yellow_bullets, red_health, yellow_health):
WIN.blit(SPACE, (0, 0))
pygame.draw.rect(WIN, BLACK, BORDER)

red_health_text = HEALTH_font.render("Health : " + str(red_health), 1, WHITE)
yellow_health_text = HEALTH_font.render("Health : " + str(yellow_health), 1, WHITE)

WIN.blit(red_health_text, (WIDTH - red_health_text.get_width() -10, 10))
WIN.blit(yellow_health_text, (10, 10))

WIN.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y))
WIN.blit(RED_SPACESHIP, (red.x, red.y))

for bullet in red_bullets:
pygame.draw.rect(WIN, RED, bullet)
for bullet in yellow_bullets:
pygame.draw.rect(WIN, YELLOW, bullet)

pygame.display.update()


def yellow_handle_movement(keys_pressed, yellow):
if keys_pressed[pygame.K_a] and yellow.x - VEL > 0: # LEFT
yellow.x -= VEL
if keys_pressed[pygame.K_d] and yellow.x + VEL + yellow.width< BORDER.x: # RIGHT
yellow.x += VEL
if keys_pressed[pygame.K_w] and yellow.y - VEL > 0: # UP
yellow.y -= VEL
if keys_pressed[pygame.K_s] and yellow.y + VEL + yellow.height < HEIGHT - 15: # DOWN
yellow.y += VEL


def red_handle_movement(keys_pressed, red):
if keys_pressed[pygame.K_LEFT] and red.x - VEL > BORDER.x + BORDER.width + 10: # LEFT # LEFT
red.x -= VEL
if keys_pressed[pygame.K_RIGHT] and red.x + VEL + red.width < WIDTH: # LEFT
red.x += VEL
if keys_pressed[pygame.K_UP] and red.y - VEL > 0: # UP
red.y -= VEL
if keys_pressed[pygame.K_DOWN] and red.y + VEL + red.height < HEIGHT - 15: # DOWN
red.y += VEL

def handle_bullets(yellow_bullets, red_bullets, yellow, red):
for bullet in yellow_bullets:
bullet.x += BULLET_VEL
if red.colliderect(bullet):
pygame.event.post(pygame.event.Event(RED_HIT))
yellow_bullets.remove(bullet)
elif bullet.x > WIDTH:
yellow_bullets.remove(bullet)

for bullet in red_bullets:
bullet.x -= BULLET_VEL
if yellow.colliderect(bullet):
pygame.event.post(pygame.event.Event(YELLOW_HIT))
red_bullets.remove(bullet)
elif bullet.x < 0:
red_bullets.remove(bullet)

def draw_winner(text):
draw_text = WINNER_font.render(text, 1, WHITE)
WIN.blit(draw_text, (WIDTH//2 - draw_text.get_width()/2, HEIGHT/2 - draw_text.get_height()/2))
pygame.display.update()

pygame.time.delay(5000)

def main():
red = pygame.Rect(700, 300, SPSHIP_WIDTH, SPSHIP_HEIGHT)
yellow = pygame.Rect(100, 300, SPSHIP_WIDTH, SPSHIP_HEIGHT)
clock = pygame.time.Clock()

red_bullets = []
yellow_bullets = []

red_health = 10
yellow_health = 10

run = True
while run:
clock.tick(fps)
keys_pressed = pygame.key.get_pressed()

for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LCTRL and len(yellow_bullets) < MAX_BULLETS:
bullet = pygame.Rect(yellow.x + yellow.width - 20, yellow.y + yellow.height//2 + 5, 10, 5)
yellow_bullets.append(bullet)
BULLET_FIRE_SOUND.play()

if event.key == pygame.K_RCTRL and len(red_bullets) < MAX_BULLETS:
bullet = pygame.Rect(red.x, red.y + red.height//2 + 5, 10, 5)
red_bullets.append(bullet)
BULLET_FIRE_SOUND.play()

if event.type == RED_HIT:
red_health -= 1
BULLET_HIT_SOUND.play()

if event.type == YELLOW_HIT:
yellow_health -= 1
BULLET_HIT_SOUND.play()

winner_text = ""
if red_health <= 0:
winner_text = "Yellow Wins!"
if yellow_health <= 0:
winner_text = "Red Wins!"
if winner_text != "":
draw_winner(winner_text)
break

yellow_handle_movement(keys_pressed, yellow)
red_handle_movement(keys_pressed, red)

handle_bullets(yellow_bullets, red_bullets, yellow, red)

draw_window(red, yellow, red_bullets, yellow_bullets, red_health, yellow_health)
main()

if __name__ == "__main__":
main()

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com