Skip to content

Instantly share code, notes, and snippets.

@CodingDino
Created May 2, 2024 17:17
Show Gist options
  • Save CodingDino/d5d3721dfc609a6aa7445885919d9245 to your computer and use it in GitHub Desktop.
Save CodingDino/d5d3721dfc609a6aa7445885919d9245 to your computer and use it in GitHub Desktop.
Python script using pygame, illustrating how to use coordinates and create a relative draw function based on alignment with parts of the screen
# Libraries to use. Pygame and the system library.
import pygame, sys
from pygame.locals import *
# Set up pygame
pygame.init()
#Set up the window size and title text
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 500
PAD = 10
window = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("UI Example")
#load images
gemCount = pygame.image.load("GemCount.png")
keyCount = pygame.image.load("KeyCount.png")
crosshair = pygame.image.load("Crosshair.png")
doomGuy = pygame.image.load("DoomGuy.png")
healthBar = pygame.image.load("HealthBar.png")
def draw_relative(image, offset, align):
pos = (0,0)
if align == "TL":
pos = offset
elif align == "T":
pos = (SCREEN_WIDTH/2 - image.get_width()/2 + offset[0], offset[1])
elif align == "TR":
pos = (SCREEN_WIDTH - image.get_width() + offset[0], offset[1])
if align == "L":
pos = (offset[0], SCREEN_HEIGHT/2 - image.get_height()/2 + offset[1])
elif align == "C":
pos = (SCREEN_WIDTH/2 - image.get_width()/2 + offset[0], SCREEN_HEIGHT/2 - image.get_height()/2 + offset[1])
elif align == "R":
pos = (SCREEN_WIDTH - image.get_width() + offset[0], SCREEN_HEIGHT/2 - image.get_height()/2 + offset[1])
if align == "BL":
pos = (offset[0], SCREEN_HEIGHT - image.get_height() + offset[1])
elif align == "B":
pos = (SCREEN_WIDTH/2 - image.get_width()/2 + offset[0], SCREEN_HEIGHT - image.get_height() + offset[1])
elif align == "BR":
pos = (SCREEN_WIDTH - image.get_width() + offset[0], SCREEN_HEIGHT - image.get_height() + offset[1])
window.blit(image, pos)
# The game loop
while True:
#Draw the background
window.fill((255,255,255))
#draw the stuff in the scene
draw_relative(gemCount, (PAD,PAD), "TL")
draw_relative(crosshair, (0,0), "T")
draw_relative(keyCount, (-PAD,PAD), "TR")
draw_relative(crosshair, (0,0), "L")
draw_relative(crosshair, (0,0), "C")
draw_relative(crosshair, (0,0), "R")
draw_relative(crosshair, (0,0), "BL")
draw_relative(doomGuy, (0,0), "B")
draw_relative(crosshair, (0,0), "BR")
#put it all on the screen
pygame.display.update()
#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