I am making a game where cars can move however they cannot go through each other or go out of the map. I am not sure how to make it so that firstly the objects will stop at the edge of the map, and secondly that they cannot go through each other (make the user not be able to move them towards each other when they're touching). Any help would be appreciated. Thank you.
Here's my code:
import pygame, random, time
pygame.init()
class Point(pygame.sprite.Sprite):
def __init__(self,x,y):
super().__init__()
self.rect=pygame.Rect(x, y, 1, 1)
class Car(pygame.sprite.Sprite):
def __init__(self,hv,image,spawnx,spawny):
super().__init__()
self.image= pygame.Surface((100,100))
self.image = image
self.type = hv
self.rect = self.image.get_rect()
self.rect.x = spawnx
self.rect.y = spawny
cars.add(self)
def move(self, dx, dy):
self.rect.x += dx
self.rect.y += dy
h="horizontal"
v="vertical"
horizontal=[]
vertical=[]
screen = pygame.display.set_mode((1150, 650))
background_image = pygame.image.load("carpark2.jpg")
cars=pygame.sprite.Group()
clock = pygame.time.Clock()
done = False
red=Car(h,pygame.image.load("redcar.png").convert_alpha(),100,100)
blue=Car(v,pygame.image.load("bluecar.png").convert_alpha(),700,100)
yellow=Car(h,pygame.image.load("yellowcar.png").convert_alpha(),100,200)
purple=Car(v,pygame.image.load("purplecar.png").convert_alpha(),500,100)
orange=Car(h,pygame.image.load("orangecar.png").convert_alpha(),100,300)
white=Car(v,pygame.image.load("whitecar.png").convert_alpha(),900,100)
green=Car(h,pygame.image.load("greencar.png").convert_alpha(),100,400)
brown=Car(v,pygame.image.load("browncar.png").convert_alpha(),600,400)
pink=Car(h,pygame.image.load("pinkcar.png").convert_alpha(),100,500)
black=Car(v,pygame.image.load("blackcar.png").convert_alpha(),800,400)
for car in cars:
if car.type==h:
horizontal.append(car)
for car in cars:
if car.type==v:
vertical.append(car)
current_car=red
while done==False:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
x,y = event.pos
for car in cars:
if car.rect.collidepoint(x, y):
current_car = car
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if current_car in horizontal:
current_car.move(-50,0)
if event.key == pygame.K_RIGHT:
if current_car in horizontal:
current_car.move(50,0)
if event.key == pygame.K_UP:
if current_car in vertical:
current_car.move(0,-50)
if event.key == pygame.K_DOWN:
if current_car in vertical:
current_car.move(0,50)
screen.blit(background_image, [0, 0])
cars.draw(screen)
pygame.display.flip()
pygame.quit()