2

How do I add some sort of collision detection between the rectangle and the circles? and how do I make it to where every time a circle is collided with, it gives me 1 point? I'm trying to get familiar with coding and Python, I know I probably shouldn't be doing all of this when I'm relatively new and should be learning actual Python instead, but I'm stuck on this and it's just bugging me.

import pygame
import random


pygame.init()
y = 0
x = 0
point = 0
is_blue = True
WHITE = (255, 255, 255)
clock = pygame.time.Clock()
screen = pygame.display.set_mode([500, 500])
food_pos = random.randint(1, 400)

food_list = []
time_interval = 3000
next_food_time = pygame.time.get_ticks()

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            is_blue = not is_blue

    pygame.display.set_caption("Collect the balls to win!")

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]:
        y -= 3
    if pressed[pygame.K_DOWN]:
        y += 3
    if pressed[pygame.K_LEFT]:
        x -= 3
    if pressed[pygame.K_RIGHT]:
        x += 3

    if x <= -1:
        x = 0
    if x >= 471:
        x = 470
    if y <= -1:
        y = 0
    if y >= 471:
        y = 470

    current_time = pygame.time.get_ticks()
    if current_time > next_food_time and len(food_list) < 10:
        next_food_time += time_interval
        food_list.append((random.randint(1, 400), random.randint(1, 400)))

    screen.fill((0, 0, 0))
    if is_blue:
        color = (0, 128, 255)
    else:
        color = (255, 100, 0)

    pygame.draw.rect(screen, color, pygame.Rect(x, y, 30, 30))
    for food_pos in food_list:
        pygame.draw.circle(screen, WHITE, food_pos, 5)
    pygame.display.flip()
    clock.tick(144)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
bruh3436
  • 49
  • 3

1 Answers1

2

See How do I detect collision in pygame?

Create pygame.Rect objects for the player and the food. Use pygame.Rect.colliderect to detect collision between the player and the food. If a collision is detected, remove the food from the list and increase the points:

while not done:
    # [...]

    player_rect = pygame.Rect(x, y, 30, 30)
    for food_pos in food_list[:]:
        food_rect = pygame.Rect(0, 0, 10, 10)
        food_rect.center = food_pos
        if player_rect.colliderect(food_rect):
            food_list.remove(food_pos)
            point += 1
            print(point)

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174