Pygame Boundary Not Working

Pygame Boundary Not Working

Postby J4awesome » Tue Apr 26, 2016 10:53 pm

I'm a kid in middle school and hope to be a programmer when I grow up.I'm going to a summer school coding class and learning python and pygame.I already knew enough python but just got my hands wet in pygame.I was adding trying to add a boundary for my game but it's able to block the left and top of the screen here is my code:

Code: Select all
import pygame,sys
from pygame.locals import *

WIDTH = 400
HEIGHT = 400

pg = "player.gif"
bg = "y.gif"
background = pygame.image.load(bg)
player = pygame.image.load(pg)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
        x,y = pygame.mouse.get_pos()
        if x <= WIDTH:
         x = 0
        if y <= HEIGHT:
         y = 0
Last edited by micseydel on Tue Apr 26, 2016 10:58 pm, edited 1 time in total.
Reason: Moved to Game Development.
Posts: 5
Joined: Thu Apr 21, 2016 7:36 pm

Re: Pygame Boundary Not Working

Postby Ofnuts » Wed Apr 27, 2016 7:45 am

You have to do some test on all four sides and you have to take in account the size of the player icon, the x,y coordinates you get are those of its top left corner.... so from the x,y position you get, you compute the positions of the top/bottom,right/left edges of the player, and compare these to the minimum/maximum X,Y (left edge against minimum X, right edge against maximum X...). Another solution is to compute a bounding rectangle for the top left corner using width and height of the player image (minX,minY,maxX-width,maxY-height) and just compare x,y to these values.

Also you have to constrain x,y before you redraw. in you code, nothing uses x,y after they have been "corrected".
This forum has been moved to See you there.
User avatar
Posts: 2659
Joined: Thu May 14, 2015 9:46 am
Location: Paris, France, EU, Earth, Solar system, Milky Way, Local Cluster, Universe #32987440940987

Return to Game Development

Who is online

Users browsing this forum: Yahoo [Bot] and 2 guests