Skip to content

Instantly share code, notes, and snippets.

@CodingDino
Created May 17, 2024 15:06
Show Gist options
  • Save CodingDino/5c2c3a6b045ea06d1bfd165ba96c5dc1 to your computer and use it in GitHub Desktop.
Save CodingDino/5c2c3a6b045ea06d1bfd165ba96c5dc1 to your computer and use it in GitHub Desktop.
Screensaver loading screen demo showing vectors in pygame
# Libraries to use. Pygame and system library
import pygame, sys, random, time, math
from pygame.locals import *
#-----------------------------------------------
# INITIALISATION
#-----------------------------------------------
# Set up pygame
pygame.init()
# Set up the window size and title text
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 500
window = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("Hello Pygame")
#load images
sanic = pygame.image.load("sanic.png")
#sanic position
randX = random.randint(0,SCREEN_WIDTH-sanic.get_width())
randY = random.randint(0,SCREEN_HEIGHT-sanic.get_height())
pos = (randX, randY)
speed = 10
randVelX = random.randint(-10,10)
randVelY = random.randint(-10,10)
mag = math.sqrt(randVelX*randVelX+randVelY*randVelY)
direction = (randVelX/mag, randVelY/mag)
velocity = (direction[0]*speed, direction[1]*speed)
#-----------------------------------------------
# THE GAME LOOP
#-----------------------------------------------
while True:
#-----------------------------------------------
# LOGIC
#-----------------------------------------------
# target
if pygame.mouse.get_pressed()[0]:
target = pygame.mouse.get_pos()
diff = (target[0]-pos[0], target[1]-pos[1])
mag = math.sqrt(diff[0]*diff[0]+diff[1]*diff[1])
direction = (diff[0]/mag, diff[1]/mag)
velocity = (direction[0]*speed, direction[1]*speed)
# movement
pos = (pos[0]+velocity[0],pos[1]+velocity[1])
# bouncing
if pos[0] < 0:
pos = (0, pos[1])
velocity = (-velocity[0], velocity[1])
elif pos[0] > SCREEN_WIDTH - sanic.get_width():
pos = (SCREEN_WIDTH - sanic.get_width(), pos[1])
velocity = (-velocity[0], velocity[1])
if pos[1] < 0:
pos = (pos[0], 0)
velocity = (velocity[0], -velocity[1])
elif pos[1] > SCREEN_HEIGHT - sanic.get_height():
pos = (pos[0], SCREEN_HEIGHT - sanic.get_height())
velocity = (velocity[0], -velocity[1])
#-----------------------------------------------
# RENDER
#-----------------------------------------------
# Draw the background
window.fill((97, 255, 231))
# Draw objects
window.blit(sanic, pos)
# Put it all on the screen
pygame.display.update()
time.sleep(0.02)
#-----------------------------------------------
# EVENTS
#-----------------------------------------------
# check for events (user input)
for event in pygame.event.get():
#if they closed the window...
if event.type == QUIT:
#quit!
pygame.quit()
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment