Skip to content

Instantly share code, notes, and snippets.

@CodeMaster7000
Last active December 19, 2021 21:57
Show Gist options
  • Save CodeMaster7000/68a6c089a7b9e49a03ce303b605a08ec to your computer and use it in GitHub Desktop.
Save CodeMaster7000/68a6c089a7b9e49a03ce303b605a08ec to your computer and use it in GitHub Desktop.
Space Invaders coded in Python 3 (with Pygame). I hope you enjoy playing it!
import pygame
class Game:
screen = None
aliens = []
rockets = []
lost = False
def __init__(self, width, height):
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode((width, height))
self.clock = pygame.time.Clock()
done = False
hero = Hero(self, width / 2, height - 15)
generator = Generator(self)
rocket = None
while not done:
if len(self.aliens) == 0:
self.displayText("YOU HAVE DEFEATED THE ALIENS!")
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
hero.x -= 2 if hero.x > 15 else 0
elif pressed[pygame.K_RIGHT]:
hero.x += 2 if hero.x < width - 15 else 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and not self.lost:
self.rockets.append(Rocket(self, hero.x, hero.y))
pygame.display.flip()
self.clock.tick(60)
self.screen.fill((0, 0, 0))
for alien in self.aliens:
alien.draw()
alien.checkCollision(self)
if (alien.y > height):
self.lost = True
self.displayText("THE ALIENS HAVE DEFEATED YOU")
for rocket in self.rockets:
rocket.draw()
if not self.lost: hero.draw()
def displayText(self, text):
pygame.font.init()
font = pygame.font.SysFont('Arial', 30)
textsurface = font.render(text, False, (100, 40, 40))
self.screen.blit(textsurface, (110, 160))
class Alien:
def __init__(self, game, x, y):
self.x = x
self.game = game
self.y = y
self.size = 30
def draw(self):
pygame.draw.rect(self.game.screen,
(81, 43, 88),
pygame.Rect(self.x, self.y, self.size, self.size))
self.y += 0.2
def checkCollision(self, game):
for rocket in game.rockets:
if (rocket.x < self.x + self.size and
rocket.x > self.x - self.size and
rocket.y < self.y + self.size and
rocket.y > self.y - self.size):
game.rockets.remove(rocket)
game.aliens.remove(self)
class Hero:
def __init__(self, game, x, y):
self.x = x
self.game = game
self.y = y
def draw(self):
pygame.draw.rect(self.game.screen,
(210, 250, 251),
pygame.Rect(self.x, self.y, 8, 5))
class Generator:
def __init__(self, game):
margin = 30
width = 50
for x in range(margin, game.width - margin, width):
for y in range(margin, int(game.height / 2), width):
game.aliens.append(Alien(game, x, y))
class Rocket:
def __init__(self, game, x, y):
self.x = x
self.y = y
self.game = game
def draw(self):
pygame.draw.rect(self.game.screen,
(254, 52, 110),
pygame.Rect(self.x, self.y, 2, 4))
self.y -= 2
if __name__ == '__main__':
game = Game(600, 400)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment