0

I have been trying to make boundaries so that the character cant go through but I can't find a way to do it. basically I am trying to make something like Pacman so when I try to bump into the boundaries in doesn't work and I go off the map/window. Should I try to make the arrays into something else or is there something else that I have to do cuz I really don't know. this is the code on the bottom can you guys help me

import pygame
from pygame.locals import *

import random 

pygame.init()
width, height = 640,480
hbox = 20
vbox = 20
controls =[False, False, False, False]
playerpos =[100,100]
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)


screen=pygame.display.set_mode((width, height))
rect = pygame.Rect(300, 220, hbox, vbox)
player = pygame.image.load("resources/images/pac.png")
grass = pygame.image.load("resources/images/grass.png")
coin = pygame.image.load("resources/images/coin.png")
player = pygame.transform.scale(player, (30,30))
coin = pygame.transform.scale(coin, (20,20))
l = random.randint(0,480)
k = random.randint(0,640)
n = random.randint(480,640)
walls = (
    pygame.Rect(0, 0, 640, 10),
    pygame.Rect(0, 0, 10, 480),
    pygame.Rect(630, 0, 10, 480),
    pygame.Rect(0, 470, 640, 10),
    )
bar = (
    pygame.Rect(230, 170, 160, 10),
    pygame.Rect(230, 170, 10, 140),
    pygame.Rect(230, 310, 160, 10),
    pygame.Rect(390, 170, 10, 150),
    )

while 1:

    screen.fill(0)
    moved = None
    for x in range(width//grass.get_width()+1):
        for y in range(height//grass.get_height()+1):
            screen.blit(grass,(x*100,y*100))
    screen.blit(player, playerpos)

    screen.blit(coin, (l,k))



    for wall in walls:
        pygame.draw.rect(screen, pygame.Color("red"), wall)
    for bars in bar:
        pygame.draw.rect(screen, pygame.Color("red"), bars)
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key==K_w:
                controls[0]=True
            elif event.key==K_a:
                controls[1]=True
            elif event.key==K_s:
                controls[2]=True
            elif event.key==K_d:
                controls[3]=True
        if event.type == pygame.KEYUP:
            if event.key==pygame.K_w:
                controls[0]=False
            elif event.key==pygame.K_a:
                controls[1]=False
            elif event.key==pygame.K_s:
                controls[2]=False
            elif event.key==pygame.K_d:
                controls[3]=False
    if controls[0]:
        playerpos[1]-=2
        #sleep(1)
    elif controls[2]:
        playerpos[1]+=2
    if controls[1]:
        playerpos[0]-=2
    elif controls[3]:
        playerpos[0]+=2

    if playerpos>[610,0] and playerpos>[0,430]:
        controls =[False, False, False, False]


        if event.type==pygame.QUIT:
            pygame.quit() 
            exit(0) 

0 Answers0