2

As you can see in the code there is a trash can and a square that I can move. My goal is to make a game so they have to make the square go to the trash can. But I have no idea how.

Code:

    import pygame
    from pygame.locals import *
    pygame.init
    red = (255,0,0)
    blue = (0,0,255)
    clock = pygame.time.Clock()
    x = 100
    y = 100
    screen = pygame.display.set_mode((500,500))
    pygame.display.set_caption("recycling game!")
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                exit()
        keyPressed = pygame.key.get_pressed()
        screen.fill((0,0,0))
        if keyPressed[pygame.K_UP]:
            y-=3;
        keyPressed = pygame.key.get_pressed()
        if keyPressed[pygame.K_DOWN]:
            y+=3;
        keyPressed = pygame.key.get_pressed()
        if keyPressed[pygame.K_LEFT]:
            x-=3;
        keyPressed = pygame.key.get_pressed()
        if keyPressed[pygame.K_RIGHT]:
            x+=3;
        rect = pygame.draw.rect(screen,red,(x,y,50,50))
        imagevariable = pygame.image.load("recycle.png")
        imagevariable = pygame.transform.scale(imagevariable,(100,100))
        screen.blit(imagevariable,(380,380))
        pygame.display.update()
        clock.tick(60) 

Also, I want to make a timer in the top of the pygame screen so please help with collision and timer!

Qiu YU
  • 517
  • 4
  • 20
Ravishankar D
  • 131
  • 10
  • 1
    Hi and welcome to Stack Overflow :-). A little tip: sometimes asking too many questions makes it harder to answer any single one of them. Asking a single question keeps the post focused. I recommend [editing](https://stackoverflow.com/posts/63094400/edit) your question to focus on collision. Once you get that working, you can open another question for the timer. – ggorlen Jul 25 '20 at 22:58
  • ok thanks a lot. Will do(:. Also can you answer my question about how to make a timer then. Because I really do need help – Ravishankar D Jul 25 '20 at 23:44

2 Answers2

2

I will answer to get you started on some simple collision.

Collision in PyGame is mainly done with pygame.Rect rectangles. The code defines a rectangle that goes around edge of the images, and when one rectangle overlaps another, that means they've hit (collided).

A pygame Rect is just a simple x and y co-ordinate of the top-left corner, along with a width and a height. You already have a red square, to make this into a pygame Rect, we just combine the x,y and the 50,50:

# Create the moveable item 
x = 100
y = 100
rubbish_rect = pygame.Rect( x, y, 50, 50 )

The image for the recycling bit requires a few more steps. This is because we want the rectangle to be the same size as the image. Your code loads the image, scales it, and then draws it at 380,380. One of the useful properties of pygame Surfaces, that they have a .get_rect() member function, which will automatically give you a rectangle that is the same size as the image. We can then move the rect to 380,380 and use it for image-drawing position:

# Create the recycling-bin object
recycling_image = pygame.image.load("recycle.png")                                # Load the image 
recycling_image = pygame.transform.smoothscale( recycling_image, ( 100, 100 ) )   # Scale to size
recycling_rect  = recycling_image.get_rect()                                      # Make a Rect for it
recycling_rect.topleft = ( 380, 380 )  

So now there is a Rect for both the rubbish item, and the recycling bin. We can use the Rect member function Rect.colliderect( other_rect ), which will return True if the rectangles Rect and other_rect overlap.

This allows us to check for the item entering the recycling quite simply:

if ( rubbish_rect.colliderect( recycling_rect ) ):
    print( "*rubbish has been recycled*" )

Obviously this is true even if the rubbish hits the side of the bin, so you really want a "bounce off" when the item does not enter at the top.

I hope this answer gives you a start on object collision.

Reference Code:

import pygame
from pygame.locals import *
pygame.init()                   # <<-- Added '()'

# Create the recycling-bin object
recycling_image = pygame.image.load("recycle.png")                                # Load the image 
recycling_image = pygame.transform.smoothscale( recycling_image, ( 100, 100 ) )   # Scale to size
recycling_rect  = recycling_image.get_rect()                                      # Make a Rect for it
recycling_rect.topleft = ( 380, 380 )                                             # Position the Rect

# Create the moveable item 
x = 100
y = 100
rubbish_rect = pygame.Rect( x, y, 50, 50 )

red = (255,0,0)
blue = (0,0,255)
clock = pygame.time.Clock()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("recycling game!")
while True:
    # handle user input
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
    keyPressed = pygame.key.get_pressed()
    if keyPressed[pygame.K_UP]:
        rubbish_rect.y -= 3;
    keyPressed = pygame.key.get_pressed()
    if keyPressed[pygame.K_DOWN]:
        rubbish_rect.y += 3;
    keyPressed = pygame.key.get_pressed()
    if keyPressed[pygame.K_LEFT]:
        rubbish_rect.x -= 3;
    keyPressed = pygame.key.get_pressed()
    if keyPressed[pygame.K_RIGHT]:
        rubbish_rect.x += 3;

    # Draw the screen
    screen.fill((0,0,0))
    pygame.draw.rect( screen, red, rubbish_rect )
    #imagevariable = pygame.image.load("recycle.png")
    #imagevariable = pygame.transform.scale(imagevariable,(100,100))
    #screen.blit(imagevariable,(380,380))
    screen.blit( recycling_image, recycling_rect )

    # Did the rubbish enter the bin?
    if ( rubbish_rect.colliderect( recycling_rect ) ):
        print( "*rubbish has been recycled*" )
        # move the rubbich back to the start
        rubbish_rect.topleft = ( x, y )  # starting x,y

    pygame.display.update()
    clock.tick(60)
Kingsley
  • 14,398
  • 5
  • 31
  • 53
  • THANKS SO MUCH I HAVE LITERALLY BEEN WATCHING EVER VIDEO ON YOUTUBE!!! YOU HELPED SO MUCH. ok seriously thanks a lot you saved my life. i made some chnges so that when the ball touched the trash can i quit pygame. and thats about it – Ravishankar D Jul 26 '20 at 00:41
0

You wrote:

screen.blit(imagevariable,(380,380))

Let's change those Magic Numbers:

trash_x, trash_y = 380, 380
screen.blit(imagevariable, (trash_x, trash_y))
inc = 3  # the increment that player moves on each keypress

Now we're in a good position to assess whether player is near trash:

is_near = ((trash_x - inc < x < trash_x + inc)
       and (trash_y - inc < y < trash_y + inc))

Armed with that is_near boolean, you can decide what should be displayed next.

J_H
  • 17,926
  • 4
  • 24
  • 44