Currently I've been spending around half an hour trying to figure out how to implement this script better. I've tried a few methods, but they didn't quite work. When running the script, the player glitches a bit, and sometimes the player can only move in the blocks once it comes in contact.
x = 64*3
y = 0
xvel = 0
yvel = 0
grounded = True
playerRect = pygame.Rect ((x, y, 64, 64))
collidelist = []
level = ["#=======##=========================",
"#=======#==========================",
"#==###############=========###=====",
"#===============#####==============",
"#==================================",
"###################################"]
def makelevel (level):
x = y = 0
def checkline (line, x, y):
for character in line:
if character == "#":
block = pygame.draw.rect (screen, (50, 50, 255), (x * 64, y * 64, 64, 64))
collidelist.append (block)
x += 1
for line in level:
checkline (line, x, y)
y += 1
def move (xvel, yvel):
global x
global y
global playerRect
global collideList
x += xvel
y += yvel
for block in collidelist:
if playerRect.colliderect(block):
x += -xvel * 2
y += -yvel * 2
break
makelevel (level)
while True:
screen.fill ([0, 0, 0])
makelevel (level)
playerRect = pygame.Rect ((x, y, 64, 64))
pygame.draw.rect (screen, (255, 255, 255), playerRect)
for event in pygame.event.get ():
if event.type == pygame.QUIT:
pygame.quit ()
sys.exit ()
exit ()
pressed = pygame.key.get_pressed ()
if pressed [pygame.K_RIGHT]:
move (5, 0)
if pressed [pygame.K_LEFT]:
move (-5, 0)
if pressed [pygame.K_UP]:
move (0, -5)
if pressed [pygame.K_DOWN]:
move (0, 5)
pygame.display.update ()