I am making a little game where you can push some boxes around.
Right now I am trying to figure out an issue;
When a box is pushed to the edge of the screen, it is stopped so it can't be pushed off screen. But this allows other boxes and the player sprite to overlap the edge.
I am trying to avoid this while making sure that the player and all the boxes can still move and be moved away from the edge eventually, I also plan on adding many more boxes and with so many variables I have no idea how do this.
I have spent a lot of time just looking in the pygame documentation using different collides and whatnot but I can't seem to find something that would fit.
import pygame, sys
from pygame.locals import QUIT
from pygame import *
# Predefined some colors
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
pygame.init()
DISPLAYSURF = pygame.display.set_mode((750, 500))
DISPLAYSURF.fill(WHITE)
SCREEN_WIDTH=750
SCREEN_HEIGHT=500
pygame.display.set_caption('Puzzle Game')
FPS=20
FramesPerSecond=pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Player1.png")
self.rect = self.image.get_rect()
self.rect.center=(75,425)
def update(self):
pressed_keys=pygame.key.get_pressed()
if self.rect.top > 0:
if pressed_keys[K_UP]:
self.rect.move_ip(0, -5)
if self.rect.bottom < SCREEN_HEIGHT:
if pressed_keys[K_DOWN]:
self.rect.move_ip(0,5)
if self.rect.left > 0:
if pressed_keys[K_LEFT]:
self.rect.move_ip(-5, 0)
if self.rect.right < SCREEN_WIDTH:
if pressed_keys[K_RIGHT]:
self.rect.move_ip(5, 0)
def draw(self, surface):
surface.blit(self.image, self.rect)
class Box(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.image.load("Box.jpg")
self.rect = self.image.get_rect()
self.rect.center = (x, y)
def update(self):
pressed_keys=pygame.key.get_pressed()
for item in sprites:
if pygame.sprite.collide_rect(self, item):
if self.rect.right < SCREEN_WIDTH:
if item.rect.x < self.rect.x and pressed_keys[K_RIGHT]:
self.rect.move_ip(5,0)
if self.rect.left > 0:
if item.rect.x > self.rect.x and pressed_keys[K_LEFT]:
self.rect.move_ip(-5,0)
if self.rect.top > 0:
if item.rect.y > self.rect.y and pressed_keys[K_UP]:
self.rect.move_ip(0,-5)
if self.rect.bottom < SCREEN_HEIGHT:
if item.rect.y < self.rect.y and pressed_keys[K_DOWN]:
self.rect.move_ip(0,5)
def draw(self, surface):
surface.blit(self.image, self.rect)
P1 = Player()
B1 = Box(100, 100)
B2 = Box(200, 200)
boxes = pygame.sprite.Group()
boxes.add(B1, B2)
sprites = pygame.sprite.Group()
sprites.add(P1, boxes)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
sprites.update()
DISPLAYSURF.fill(WHITE)
sprites.draw(DISPLAYSURF)
pygame.display.update()
FramesPerSecond.tick(FPS)