2

I'm working on my first game, Catch the cat. I'm new to pygame so don't expect a lot from me.

It is simple game, where you need to click on a cat. As the score goes higher, the cat will go faster.

I need to make hitbox for the cat. Can anyone help?

Here is the code:

    #IMPORTS FOR THE GAME
import pygame, sys
from pygame.locals import *
pygame.init()
#game speed settings
FPS = 5
fpsClock = pygame.time.Clock()
#Display settings
DISPLAY = pygame.display.set_mode((600, 600))
pygame.display.set_caption('Catch the cat')
#background music settings
pygame.mixer.music.load('backmusic.wav')
pygame.mixer.music.play(-1, 0.0)
#COLORS
WHITE = (255, 255, 255)
AQUA = (0, 255, 255)
BLACK = (0, 0, 0)
HITBOXCOLOR = (0, 255, 255, 255)
#CAT IMAGE SETUP
catImg = pygame.image.load('cat.png')
catx = 10
caty = 20
direction = 'right'
# SCORE DISPLAY SETUP
fontObj = pygame.font.Font('freesansbold.ttf', 20)
score = 0
textSurfaceObj = fontObj.render(str(score), True, AQUA, BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (10, 10)
while True:
    DISPLAY.fill(WHITE)
    DISPLAY.blit(textSurfaceObj, textRectObj)
    if direction == 'right':
        catx += 5
        if catx == 300:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 300:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 20:
            direction = 'right'
    DISPLAY.blit(catImg, (catx, caty))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    fpsClock.tick(FPS)
nivanda
  • 23
  • 3
  • The simplest one is to make `rect` around the cat(using picture dimensions) and then use `rect.collidepoint()` – kaktus_car May 11 '20 at 12:19

1 Answers1

4

Use pygame.Rect objects. You can get a rectangle with the size of the cat by get_rect from the cat surface. Set the position of the cat by the key word attribute topleft. Use the MOUSEBUTTONDOWN event and collidepoint() to test if the mouse is on the cat when it is clicked:

while True:
    # [...]

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            cat_rect = catImg.get_rect(topleft = (catx, caty))
            if cat_rect.collidepoint(event.pos):
                print("hit")
Rabbid76
  • 202,892
  • 27
  • 131
  • 174