Help with preventing pygame player going off the screen

Help with preventing pygame player going off the screen

Postby dboxall123 » Sun Jul 21, 2013 11:33 pm

Hello everyone. I'm quite new to programming and was hoping somebody here could help me out. I am trying to mae my first ever game, just a simple game where a blue block collects some black blocks. However, I'm having a lot of trouble preventing the blue block from going off the edge of the screen. The best I can do is have it so that the block goes off the screen, and as soon as you let go of the left key it resets to position 0. Here is my code:
Code: Select all
import pygame
import random


#----colours----#

black=(0,0,0)
white=(255,255,255)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)

#---sprites---#

class Block(pygame.sprite.Sprite):

    def __init__(self,color,width,height):
        pygame.sprite.Sprite.__init__(self)
        self.image=pygame.Surface([width,height])
        self.image.fill(color)
        self.rect=self.image.get_rect()

    def reset_pos(self):
        self.rect.y=random.randrange(-100,-10)
        self.rect.x=random.randrange(0,580)
           
    def update(self):
        self.rect.y+=1
        if self.rect.y > screen_height:
            self.reset_pos()
   
   
                 
pygame.init()

screen_width=600
screen_height=400
screen=pygame.display.set_mode([screen_width,screen_height])
pygame.display.set_caption('BLOCKS!!!')
clock=pygame.time.Clock()


block_list=pygame.sprite.Group()
all_sprites_list=pygame.sprite.Group()

for i in range(50):
    block=Block(black,20,15)
    block.rect.x=random.randrange(screen_width-20)
    block.rect.y=random.randrange(screen_height-15)
    block_list.add(block)
    all_sprites_list.add(block)

player=Block(blue,20,15)
player.rect.y=200
player.rect.x=200
player_x_speed=0
player_y_speed=0


all_sprites_list.add(player)
   
####main loop####
done=False
while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT :
                player_x_speed= -5
            if event.key == pygame.K_RIGHT:
                player_x_speed= 5
            if event.key == pygame.K_UP:
                player_y_speed= -5
            if event.key == pygame.K_DOWN:
                player_y_speed= 5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player_x_speed= 0
            if event.key == pygame.K_RIGHT:
                player_x_speed= 0
            if event.key == pygame.K_UP:
                player_y_speed= 0
            if event.key == pygame.K_DOWN:
                player_y_speed= 0

########### here is the problem part. I'm not really sure how else to do it!!!! #######
       
        if player.rect.x < 0:
            player.rect.x=0
       
    player.rect.y+=player_y_speed
    player.rect.x+=player_x_speed
   

    screen.fill(white)
    pos=pygame.mouse.get_pos()
    #player.rect.x=pos[0]
    #player.rect.y=pos[1]

    block_hit_list=pygame.sprite.spritecollide(player,block_list,False)

    for i in block_hit_list:
        i.reset_pos()

                   
    all_sprites_list.draw(screen)
    block_list.update()
   
    pygame.display.flip()
    clock.tick(20)

pygame.quit()


Hopefully someone here can offer me some advice. Not necessarily looking for someone to solve it for me, just some hints would be nice. Would really appreciate it if someone could help me.

Thanks!
Dan
dboxall123
 
Posts: 108
Joined: Fri Jul 12, 2013 5:28 pm

Re: Help with preventing pygame player going off the screen

Postby dboxall123 » Sun Jul 21, 2013 11:43 pm

What a fool!!! I simply changed
Code: Select all
   if player.rect.x < 0:
        player.rect.x=0   
    player.rect.y+=player_y_speed
    player.rect.x+=player_x_speed


to

Code: Select all
    player.rect.y+=player_y_speed
    player.rect.x+=player_x_speed
    if player.rect.x < 0:
            player.rect.x=0

Wow, I feel silly! Thanks anyway!
dboxall123
 
Posts: 108
Joined: Fri Jul 12, 2013 5:28 pm

Re: Help with preventing pygame player going off the screen

Postby metulburr » Sun Jul 21, 2013 11:44 pm

you could of also done it with
Code: Select all
Rect.clamp_ip()

http://www.pygame.org/docs/ref/rect.htm ... t.clamp_ip

PS i moved your thread to the appropriate forums "game development"
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1500
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Help with preventing pygame player going off the screen

Postby Mekire » Mon Jul 22, 2013 2:44 am

+1 for Rect.clamp_ip(rect)

Also... Keep that namespace clean. Zero global variables.

Code: Select all
import sys,os
import random
import pygame


SCREEN_SIZE = (SCREEN_WIDTH,SCREEN_HEIGHT) = (600,400)

BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)

DIRECT_DICT = {pygame.K_UP    : ( 0,-1),
               pygame.K_DOWN  : ( 0, 1),
               pygame.K_LEFT  : (-1, 0),
               pygame.K_RIGHT : ( 1, 0)}


class Block(pygame.sprite.Sprite):
    def __init__(self,color,size):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface(size).convert()
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.fall_speed = 1
        self.rect.x = random.randrange(SCREEN_WIDTH-self.rect.width)
        self.rect.y = random.randrange(SCREEN_HEIGHT-self.rect.height)

    def reset_pos(self):
        self.rect.y = random.randrange(-100,-10)
        self.rect.x = random.randrange(0,580)

    def update(self,surface):
        self.rect.y += self.fall_speed
        if self.rect.y > SCREEN_HEIGHT:
            self.reset_pos()

    def draw(self,surface):
        surface.blit(self.image,self.rect)


class Player(pygame.sprite.Sprite):
    def __init__(self,color,location,size):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface(size).convert()
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft=location)
        self.speed = 5

    def update(self,surface):
        keys = pygame.key.get_pressed()
        for key in DIRECT_DICT:
            if keys[key]:
                self.rect.x += DIRECT_DICT[key][0]*self.speed
                self.rect.y += DIRECT_DICT[key][1]*self.speed
        self.rect.clamp_ip(surface.get_rect())

    def draw(self,surface):
        surface.blit(self.image,self.rect)


class Control(object):
    def __init__(self):
        os.environ["SDL_VIDEO_CENTERED"] = '1'
        pygame.init()
        pygame.display.set_caption('BLOCKS!!!')
        self.screen = pygame.display.set_mode(SCREEN_SIZE)
        self.clock = pygame.time.Clock()
        self.block_list=pygame.sprite.Group()
        self.all_sprites_list=pygame.sprite.Group()
        self.spawn_blocks()
        self.player = Player(BLUE,(200,200),(20,15))
        self.all_sprites_list.add(self.player)
        self.done = False

    def spawn_blocks(self):
        for i in range(50):
            block = Block(BLACK,(20,15))
            self.block_list.add(block)
            self.all_sprites_list.add(block)

    def collissions(self):
        collide = pygame.sprite.spritecollide(self.player,self.block_list,False)
        for block in collide:
            block.reset_pos()

    def event_loop(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True

    def main_loop(self):
        while not self.done:
            self.event_loop()
            self.all_sprites_list.update(self.screen)
            self.collissions()
            self.screen.fill(WHITE)
            self.all_sprites_list.draw(self.screen)
            pygame.display.flip()
            self.clock.tick(20)


if __name__ == "__main__":
    run_it = Control()
    run_it.main_loop()
    pygame.quit();sys.exit()

-Mek
User avatar
Mekire
 
Posts: 1011
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to Game Development

Who is online

Users browsing this forum: No registered users and 2 guests