Collision Code
Completion requirements
# pip install pygame
import pygame
import os # needed to get paths to images
import math
#get path to our game
myPath = os.path.dirname( os.path.realpath( __file__ ) )
screen = pygame.display.set_mode( (800, 600) )
# Title
pygame.display.set_caption("Space Invaders")
#background
background = pygame.image.load( os.path.join( myPath, "images\\background.png") )
# player
playerImg = pygame.image.load( os.path.join( myPath, "images\\player.png" ) )
playerX = 368
playerY = 480
playerX_change = 0 # how far to move the player
score = 0
# Enemy
enemyImg = pygame.image.load( os.path.join( myPath, "images\\enemy.png" ) )
enemyX = 368
enemyY = 30
enemyX_change = 2 # how far to move the enemy
enemyY_change = 40
# Bullet
bulletImg = pygame.image.load( os.path.join( myPath, "images\\bullet.png" ) )
bulletX = 0
bulletY = 0
bulletY_change = -3
bullet_state = "ready"
def draw_sprite( sprite, x, y ):
x = int(x)
y = int
screen.blit( sprite, ( x, y ) ) # blit basically means draw
def fire_bullet( x, y ):
global bullet_state, bulletX, bulletY
bullet_state = "fire"
bulletX = x
bulletY = y
def isCollision(x1, y1, x2, y2):
hypotenuse = math.sqrt( math.pow(x1 - x2, 2 ) + math.pow(y1 - y2, 2) ) # pythagoras theorum
if hypotenuse < 64 :
return True
else:
return False
# game loop
running = True
while running:
for event in pygame.event.get(): # get all python events and loop through them
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -2
if event.key == pygame.K_RIGHT:
playerX_change = 2
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
fire_bullet( playerX + 64 / 2 - 32 / 2, playerY )
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <= 0: # if player tries to move too far left
playerX = 0
if playerX >= 800 - 64: # if the player moves too far right
playerX = 800 - 64
enemyX += enemyX_change
if enemyX <= 0: # if player tries to move too far left
enemyX_change = 1
enemyY += enemyY_change
if enemyX >= 800 - 64: # if the player moves too far right
enemyX_change = -1
enemyY += enemyY_change
#bullet movement
if bullet_state == "fire":
bulletY += bulletY_change
if bulletY <= 0:
bullet_state = "ready"
#test collisions
collision = isCollision(enemyX + 64 / 2, enemyY + 64 / 2, bulletX + 32 / 2, bulletY + 32 /2 )
if collision and bullet_state == "fire":
bullet_state = "ready"
score += 1
print( score )
enemyX = 368
enemyY = 30
screen.fill((0,0,0))
screen.blit( background, (0,0) )
draw_sprite(playerImg, playerX, playerY) # draw the player
draw_sprite(enemyImg, enemyX, enemyY)
if bullet_state == "fire":
draw_sprite(bulletImg, bulletX, bulletY)
pygame.display.update() # needed to apply the change
Last modified: Thursday, 19 November 2020, 3:08 PM