New programmer with three months of Python under my belt (only a few weeks of pygame)...
I'm designing a 2-D, top-down game and have been trying to get obstacles to break sprite LOS. My current attempt is for each sprite to cast a single ray toward every other sprite in visual range, stopping if the ray collides with a LOS blocker's rect, and adding only visible sprites to a list.
So far, the sprites always see one another through the wall. I thought it was an iteration/indentation/too-many-loops issue. I've tried boolean-type breaks and putting the code in a function with return (at several different points in the code), but it didn't help -- the monster always head straight for the player until they hit the wall.
Picture: X-Ray Vision
It's been a few days of Google research and trial and error, but no joy. Any solves or nudges in the right direction much appreciated!
Relevant code follows.
Wall Class
Implementation
wall = GraphBoxSprite('wall', (WIDTH // 2 - 25, HEIGHT // 2 - 10), 50, 20, BLACK, False, walls, obstacles, losBlockers, allSprites)
Code
class GraphBoxSprite(pygame.sprite.Sprite):
# Creates a sprite the size and shape of supplied graph size
def __init__(self, ID, position, squareWidth, squareHeight, colour, transparent=False, *groups):
super().__init__(*groups)
self.ID = ID
self.position = position
self.image = pygame.Surface((squareWidth, squareHeight)) # Blank surface
self.rect = self.image.get_rect(topleft=position)
self.image.fill(colour)
if transparent is True:
self.image.set_colorkey(colour) # Transparent background
Creature Class
Implementation
character = CreatureSprite('character', (WIDTH // 2, HEIGHT // 2 - 50), MEDIUM, QUICK, QUIET, BLUE_LINE, CANDLELIGHT, None, None, characters, allCreatures, allSprites)
Code
class CreatureSprite(pygame.sprite.Sprite):
# Creates a sprite to order
def __init__(self, ID, position, size, speed, noiseLevel=None, colour=GREY, lightRadius=None, infravision=None, image=None, *groups):
super().__init__(*groups)
self.image = pygame.Surface(size) # Blank surface for image
self.image.fill(WHITE)
self.image.set_colorkey(WHITE) # Transparent background
self.rect = self.image.get_rect(topleft=position)
self.ID = ID
self.size = size
self.colour = colour
self.lightRadius = lightRadius
self.losLength = 600 # view distance
self.losWidth = 150 # degrees
self.position = Vector2(position)
self.speed = int(speed / (GRID_SCALE * 10))
self.velocity = Vector2(0, 0)
self.destination = Vector2(position)
self.destinationRadius = 40
self.heading = self.destination - self.position
def update(self, walls, dungeonDressings, obstacles, losBlockers, monsters, characters, allCreatures, dungeonLights, creatureLights, allLights, allSprites):
# Draw the creature
pygame.draw.circle(self.image, self.colour, (self.size[0] // 2, self.size[1] // 2), self.size[0] // 2)
pygame.draw.line(self.image, WHITE, (self.size[0] // 2, self.size[1] // 2), (self.size[0] // 2, self.size[1] - 20), 1)
# Draw light over darkness and colour over light
if self.lightRadius:
spritePosition = (int(self.position[0]), int(self.position[1])) # syntactic sugar
pygame.draw.circle(DARKNESS, (COLOURKEY), spritePosition, self.lightRadius * GRID_SCALE)
pygame.draw.circle(LIGHTNESS, (GOLDENROD), spritePosition, self.lightRadius * GRID_SCALE)
# Movement
self.position += self.velocity # Update the position vector first
self.rect.center = self.position # Update the rect afterwards
# This vector points to the destination
self.heading = self.destination - self.position
distance = self.heading.length()
# Normalize heading for scale to desired length/speed below
if self.heading: # Cannot normalize a zero vector
self.heading.normalize_ip()
# Sprite rotation to heading
#self.image = pygame.transform.rotate(self.image, self.heading) --- won't accept Vector2, only real number ---
# Slow down when approaching destination
if distance > self.destinationRadius:
self.velocity = self.heading * self.speed
elif distance <= 15:
for sprite in allSprites:
if sprite in allCreatures or sprite in obstacles: # Creatures maintain personal space
self.velocity = Vector2(0, 0)
else:
self.velocity = self.heading * (distance / self.destinationRadius * self.speed)
# Line of Sight
targets = []
visible = []
seen = []
for target in allSprites:
if target != self:
targets.append(target.ID)
lineOfSight = target.position - self.position
lineOfSightDist = lineOfSight.length()
if lineOfSightDist < self.losLength: # Target in range
#if self.heading < self.losWidth: # Target in field of view --- need to convert to comparable format ---
x = self.position[0]
y = self.position[1]
for i in range(int(lineOfSightDist)): # Try to reach target with a cast ray
x += lineOfSight[0]
y += lineOfSight[1]
for sprite in allSprites:
if sprite.rect.collidepoint(int(round(x)), int(round(y))):
if sprite in losBlockers: # Stop ray
seen.append(sprite)
visible.append(target.ID)
break
else:
seen.append(sprite)
visible.append(target.ID)
break
print('{} sees {} out of {} in range'.format(self.ID, visible, targets))
# Creature AI
if self.ID == 'monster':
if seen:
for sprite in seen:
if sprite.ID == 'character':
self.destination = sprite.position
# When sprites collide
for sprite in allSprites:
if self.rect.colliderect(sprite):
if self in allCreatures and sprite in obstacles:
self.velocity = Vector2(0, 0)
def changeColour(self, colour):
self.colour = colour
Full Code
import os, sys, ctypes, random, math, copy, time, pickle, shelve, pprint, pygame # Inbuilt functions
import charReference, equipment # Reference material
from pygame.locals import *
from pygame.math import Vector2
pygame.init()
pygame.display.set_caption('LOOT OR DIE!')
directory = 'C:\\Users\\user\\OneDrive\\LootOrDie\\'
pygame.font.init()
# Main fonts
font = pygame.font.Font(directory + 'fonts\\Cour.ttf', 18)
fontB = pygame.font.Font(directory + 'fonts\\Courbd.ttf', 18)
fontI = pygame.font.Font(directory + 'fonts\\Couri.ttf', 18)
fontBI = pygame.font.Font(directory + 'fonts\\Courbi.ttf', 18)
smallFont = pygame.font.Font(directory + 'fonts\\Cour.ttf', 16)
smallFontB = pygame.font.Font(directory + 'fonts\\Courbd.ttf', 16)
smallFontI = pygame.font.Font(directory + 'fonts\\Couri.ttf', 16)
smallFontBI = pygame.font.Font(directory + 'fonts\\Courbi.ttf', 16)
bigFont = pygame.font.Font(directory + 'fonts\\Cour.ttf', 24)
bigFontB = pygame.font.Font(directory + 'fonts\\Courbd.ttf', 24)
bigFontI = pygame.font.Font(directory + 'fonts\\Couri.ttf', 24)
bigFontBI = pygame.font.Font(directory + 'fonts\\Courbi.ttf', 24)
# Colours
COLOURKEY = (127, 33, 33) # Transparent colour key
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
DARKGREY = ( 64, 64, 64)
GREY = (128, 128, 128)
LIGHTGREY = (200, 200, 200)
PINK_LINE = (238, 106, 167)
RED = (179, 0, 0)
BLOOD = (138, 3, 3)
ORANGE = (255, 185, 0)
GOLD = (100, 84, 0)
GOLDENROD = (212, 175, 55)
GREEN = ( 0, 130, 0)
FOREST_GREEN = ( 11, 102, 35)
BLUE_LINE = (100, 149, 237)
BLUE_INK = ( 0, 0, 128)
DARK_BLUE = ( 0, 60, 120)
""" Define Screen """
# Prevent screen stretching
preventStretch = True
if preventStretch is True:
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
SCREEN_SIZE = WIDTH, HEIGHT = (1440, 900)
SCREEN = pygame.display.set_mode(SCREEN_SIZE, pygame.RESIZABLE) # FULLSCREEN
LEFT_MARGIN = 40
TOP_MARGIN = 26
LINE_HEIGHT = 22
COL1 = LEFT_MARGIN
COL2 = int(SCREEN.get_width() / 4 + (LEFT_MARGIN * 2))
COL3 = int(((SCREEN.get_width() / 4) + (LEFT_MARGIN * 2)) * 2)
COL4 = int(((SCREEN.get_width() / 4) + (LEFT_MARGIN * 2)) * 3)
# Timing and FPS
clock = pygame.time.Clock()
FPS = 60
# Double mouse-click half second delay
doubleClickClock = pygame.time.Clock()
DOUBLE_MOUSE_CLICK_TIME = 500
""" Define Buttons """
MENU_BUTTON_WIDTH = 150
MENU_BUTTON_HEIGHT = 30
LINE_BUTTON_WIDTH = int(SCREEN.get_width() / 4 - (LEFT_MARGIN * 2))
LINE_BUTTON_HEIGHT = LINE_HEIGHT - 2
EQUIP_BUTTON_WIDTH = int(SCREEN.get_width() / 2 - (LEFT_MARGIN * 2))
BODY_BUTTON_WIDTH = 255
# TextLine Buttons
col_1_textLines = []
col_2_textLines = []
col_3_textLines = []
lineNo = 0
for line in range(40): # The maximum number of lines per screen
line = COL1, TOP_MARGIN + LINE_HEIGHT * lineNo
col_1_textLines.append(line)
lineNo += 1
col_2_textLines = []
lineNo = 0
for line in range(40):
line = COL2, TOP_MARGIN + LINE_HEIGHT * lineNo
col_2_textLines.append(line)
lineNo += 1
col_2_textLines = []
lineNo = 0
for line in range(40):
line = COL2, TOP_MARGIN + LINE_HEIGHT * lineNo
col_2_textLines.append(line)
lineNo += 1
""" Dungeon Settings """
# Graph paper coordinates
GRID_SCALE = 5 # feet per square
SQUARE_WIDTH = 20
SQUARE_HEIGHT = 20
GRID_MARGIN = 1 # between squares
# Creature Sizes
TINY = (5, 5)
SMALL = (10, 10)
MEDIUM = (15, 15)
LARGE = (20, 20)
HUGE = (40, 40)
# Creature Speeds and Noise Levels
""" Run is * 10 """
STATIONARY = SILENT = 0
SHAMBOLIC = STEALTHY = 15
SLUGGISH = QUIET = 30
SLOW = NOISY = 60
PLODDING = LOUD = 90
QUICK = CACOPHONOUS = 120
# Light Source Radii
CANDLELIGHT = 10
SMALL_ITEMLIGHT = 10
MEDIUM_ITEMLIGHT = 15
LONG_ITEMLIGHT = 20
LANTERNLIGHT = 30
TORCHLIGHT = 40
# Cloak screen in darkness
DARKNESS = pygame.Surface(SCREEN_SIZE)
DARKNESS.set_colorkey(COLOURKEY)
# Mask for light colour
LIGHTNESS = pygame.Surface(SCREEN_SIZE)
LIGHTNESS.set_colorkey(COLOURKEY)
def dungeon():
# Window for testing
windowSize = windowWidth, windowHeight = WIDTH, HEIGHT
window = pygame.Surface(windowSize)
""" Sprite Groups """
# Dungeon
walls = pygame.sprite.Group()
dungeonDressings = pygame.sprite.Group()
obstacles = pygame.sprite.Group() # Anything that blocks movement
losBlockers = pygame.sprite.Group() # Anything that blocks line of sight (LOS)
# Creatures
characters = pygame.sprite.Group()
monsters = pygame.sprite.Group()
allCreatures = pygame.sprite.Group()
# Lights
dungeonLights = pygame.sprite.Group()
creatureLights = pygame.sprite.Group()
allLights = pygame.sprite.Group()
# Everything
allSprites = pygame.sprite.Group()
""" Sprites """
# Character sprites
character = CreatureSprite('character', (WIDTH // 2, HEIGHT // 2 - 50), MEDIUM, QUICK, QUIET, BLUE_LINE, CANDLELIGHT, None, None, characters, allCreatures, allSprites)
# Enemy sprites
for monster in range(1):
orc = CreatureSprite('monster', (WIDTH // 2, HEIGHT // 2 + 50), MEDIUM, PLODDING, NOISY, BLOOD, TORCHLIGHT, None, None, monsters, allCreatures, allSprites)
# The Wall
wall = GraphBoxSprite('wall', (WIDTH // 2 - 25, HEIGHT // 2 - 10), 50, 20, BLACK, False, walls, obstacles, losBlockers, allSprites)
selectedObject = None
destinationPoint = None
while True: # Main Loop
clock.tick(FPS) # Set framerate
# Capture mouse coordinates on screen and in window
mousePos = x, y = pygame.mouse.get_pos()
mouseWindowPos = (x - int(WIDTH / 2 - windowWidth / 2), y - int(HEIGHT / 2 - windowHeight / 2))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
if selectedObject:
if selectedObject in characters:
selectedObject.changeColour(BLUE_LINE)
elif selectedObject in monsters:
selectedObject.changeColour(BLOOD)
selectedObject = None
else:
quitGame()
# Set destination with mouse-click
if event.type == MOUSEBUTTONDOWN:
# Check for double click event
doubleClick = False
if doubleClickClock.tick() < DOUBLE_MOUSE_CLICK_TIME:
doubleClick = True
if event.button == 1:
if selectedObject: # Single-click to de-select sprite
if selectedObject in characters:
selectedObject.changeColour(BLUE_LINE)
elif selectedObject in monsters:
selectedObject.changeColour(BLOOD)
selectedObject = None
elif not selectedObject: # Single-click to select new sprite
for sprite in allCreatures:
if sprite.rect.collidepoint(mouseWindowPos):
selectedObject = sprite
selectedObject.changeColour(GOLDENROD)
elif event.button == 3:
if selectedObject: # Send selected sprite to destination
selectedObject.destination = mouseWindowPos
# Arrange dark and light sources
DARKNESS.fill(0)
LIGHTNESS.fill(COLOURKEY)
# Draw squares on coloured background to mimic graph paper
window.fill(BLUE_LINE)
for column in range(SQUARE_WIDTH + GRID_MARGIN, windowWidth, SQUARE_WIDTH + GRID_MARGIN):
for row in range(SQUARE_HEIGHT + GRID_MARGIN, windowHeight, SQUARE_HEIGHT + GRID_MARGIN):
pygame.draw.rect(window, WHITE, [column, row, SQUARE_WIDTH, SQUARE_HEIGHT])
# Update Sprites
allSprites.update(window, walls, dungeonDressings, obstacles, losBlockers, monsters, characters, allCreatures, dungeonLights, creatureLights, allLights, allSprites)
# Draw items
walls.draw(window)
allCreatures.draw(window)
# Draw screen overlaid with darkness overlaid by lit areas
SCREEN.blit(window, (WIDTH // 2 - windowWidth // 2, HEIGHT // 2 - windowHeight // 2))
# Make LIGHTNESS surface partially transparent
LIGHTNESS.set_alpha(75)
SCREEN.blit(LIGHTNESS, (0, 0))
SCREEN.blit(DARKNESS, (0, 0))
pygame.display.update()
class GraphBoxSprite(pygame.sprite.Sprite):
# Creates a sprite the size and shape of supplied graph size
def __init__(self, ID, position, squareWidth, squareHeight, colour, transparent=False, *groups):
super().__init__(*groups)
self.ID = ID
self.position = position
self.image = pygame.Surface((squareWidth, squareHeight)) # Blank surface
self.rect = self.image.get_rect(topleft=position)
self.image.fill(colour)
if transparent is True:
self.image.set_colorkey(colour) # Transparent background
class CreatureSprite(pygame.sprite.Sprite):
# Creates a sprite to order
def __init__(self, ID, position, size, speed, noiseLevel=None, colour=GREY, lightRadius=None, infravision=None, image=None, *groups):
super().__init__(*groups)
self.image = pygame.Surface(size) # Blank surface for image
self.image.fill(WHITE)
self.image.set_colorkey(WHITE) # Transparent background
self.rect = self.image.get_rect(topleft=position)
self.ID = ID
self.size = size
self.colour = colour
self.lightRadius = lightRadius
self.losLength = 600 # view distance
self.losWidth = 150 # degrees
self.position = Vector2(position)
self.speed = int(speed / (GRID_SCALE * 10))
self.velocity = Vector2(0, 0)
self.destination = Vector2(position)
self.destinationRadius = 40
self.heading = self.destination - self.position
def update(self, walls, dungeonDressings, obstacles, losBlockers, monsters, characters, allCreatures, dungeonLights, creatureLights, allLights, allSprites):
# Draw the creature
pygame.draw.circle(self.image, self.colour, (self.size[0] // 2, self.size[1] // 2), self.size[0] // 2)
pygame.draw.line(self.image, WHITE, (self.size[0] // 2, self.size[1] // 2), (self.size[0] // 2, self.size[1] - 20), 1)
# Draw light over darkness and colour over light
if self.lightRadius:
spritePosition = (int(self.position[0]), int(self.position[1])) # syntactic sugar
pygame.draw.circle(DARKNESS, (COLOURKEY), spritePosition, self.lightRadius * GRID_SCALE)
pygame.draw.circle(LIGHTNESS, (GOLDENROD), spritePosition, self.lightRadius * GRID_SCALE)
# Movement
self.position += self.velocity # Update the position vector first
self.rect.center = self.position # Update the rect afterwards
# This vector points to the destination
self.heading = self.destination - self.position
distance = self.heading.length()
# Normalize heading for scale to desired length/speed below
if self.heading: # Cannot normalize a zero vector
self.heading.normalize_ip()
# Sprite rotation to heading
#self.image = pygame.transform.rotate(self.image, self.heading) --- won't accept Vector2, only real number ---
# Slow down when approaching destination
if distance > self.destinationRadius:
self.velocity = self.heading * self.speed
elif distance <= 15:
for sprite in allSprites:
if sprite in allCreatures or sprite in obstacles: # Creatures maintain personal space
self.velocity = Vector2(0, 0)
else:
self.velocity = self.heading * (distance / self.destinationRadius * self.speed)
# Line of Sight
targets = []
visible = []
seen = []
for target in allSprites:
if target != self:
targets.append(target.ID)
lineOfSight = target.position - self.position
lineOfSightDist = lineOfSight.length()
if lineOfSightDist < self.losLength: # Target in range
#if self.heading < self.losWidth: # Target in field of view --- need to convert to comparable format ---
x = self.position[0]
y = self.position[1]
for i in range(int(lineOfSightDist)): # Try to reach target with a cast ray
x += lineOfSight[0]
y += lineOfSight[1]
for sprite in allSprites:
if sprite.rect.collidepoint(int(round(x)), int(round(y))):
if sprite in losBlockers: # Stop ray
seen.append(sprite)
visible.append(target.ID)
break
else:
seen.append(sprite)
visible.append(target.ID)
break
print('{} sees {} out of {} in range'.format(self.ID, visible, targets))
# Creature AI
if self.ID == 'monster':
if seen:
for sprite in seen:
if sprite.ID == 'character':
self.destination = sprite.position
# When sprites collide
for sprite in allSprites:
if self.rect.colliderect(sprite):
if self in allCreatures and sprite in obstacles:
self.velocity = Vector2(0, 0)
def changeColour(self, colour):
self.colour = colour
def quitGame():
pygame.quit()
sys.exit()
def waitForKeyPress():
# Pause program until a key is pressed
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:
return
""" Start Game """
if __name__ == '__main__':
dungeon()
